diff --git a/FCLTDWF.Doc b/FCLTDWF.Doc new file mode 100644 index 0000000..20622d0 Binary files /dev/null and b/FCLTDWF.Doc differ diff --git a/Mouse.doc b/Mouse.doc new file mode 100644 index 0000000..ec298db Binary files /dev/null and b/Mouse.doc differ diff --git a/Redistribute/.gitignore b/Redistribute/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/Redistribute/Dirinfo b/Redistribute/Dirinfo new file mode 100644 index 0000000..d14f142 --- /dev/null +++ b/Redistribute/Dirinfo @@ -0,0 +1,29 @@ +Programma's gemaakt met Visual C++ 2005 zijn afhankelijk van + + MSVCR80.DLL en + MSVCP80.DLL + +Daarvan zijn mij twee versies bekend + 8.0.50608.0 + 8.0.50727.762 + +De originele Visual C++ 2005 genereert afhankelijkheid naar de 8.0.50608.0 versie van de DLL's. +Na Servicepack 1 is er een afhankelijkheid naar versie 8.0.50727.762 + +De versienummer afhankelijkheid wordt geforceerd door de Manifest die embedded +wordt in DLL's en of EXE's. + +'Zo maar' de goede DLL's in C:\Windows\System32 zetten werkt niet en vooral: hoort niet. +Je wordt geacht (de goede) vcredist_86.exe te draaien die de DLL's installeert op de goede plek. + +Onder Windows 2000 doet hij dat inderdaad ook nog in C:\Windows\System32 + +Onder Windows 2003 en XP worden ze netjes volgens de side-by-side methode +geinstalleerd onder C:\Windows\WinSxS + +Als je de nieuwste van de twee installeert dan komt er onder c:\WINdows\winsxs\Policies +nog een bestandje wat versie 8.0.50608.0 redirect naar 8.0.50727.762 + +"c:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\vcredist_x86\vcredist_x86.exe" + +gdiplus.dll is included in Windows XP and Windows Server 2003 \ No newline at end of file diff --git a/Redistribute/vcredist_x86.exe b/Redistribute/vcredist_x86.exe new file mode 100644 index 0000000..1421c29 Binary files /dev/null and b/Redistribute/vcredist_x86.exe differ diff --git a/Redistribute/vcredist_x86_SP1_8.0.50727.762.exe b/Redistribute/vcredist_x86_SP1_8.0.50727.762.exe new file mode 100644 index 0000000..47f87a0 Binary files /dev/null and b/Redistribute/vcredist_x86_SP1_8.0.50727.762.exe differ diff --git a/RemoveAbout/.gitignore b/RemoveAbout/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/RemoveAbout/RemoveAbout.vcproj b/RemoveAbout/RemoveAbout.vcproj new file mode 100644 index 0000000..52c304c --- /dev/null +++ b/RemoveAbout/RemoveAbout.vcproj @@ -0,0 +1,188 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/RemoveAbout/RemoveAbout.vcproj.DIJKORAAD.jgl.user b/RemoveAbout/RemoveAbout.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..c1bd4d5 --- /dev/null +++ b/RemoveAbout/RemoveAbout.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SLNKDWF.sln b/SLNKDWF.sln new file mode 100644 index 0000000..9b28c61 --- /dev/null +++ b/SLNKDWF.sln @@ -0,0 +1,95 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SLNKDWFViewer", "Standalone\SLNKDWFViewer.vcproj", "{B2601E72-4FF4-4B9C-A89F-C2E7DACF36FD}" + ProjectSection(ProjectDependencies) = postProject + {6DFC9788-904C-4724-A734-06634061EF00} = {6DFC9788-904C-4724-A734-06634061EF00} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Viewer", "Viewer\Viewer.vcproj", "{6DFC9788-904C-4724-A734-06634061EF00}" + ProjectSection(ProjectDependencies) = postProject + {CF524F70-4DDD-4040-803B-41B5DE7B1CF9} = {CF524F70-4DDD-4040-803B-41B5DE7B1CF9} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WincmdViewer", "WincmdViewer\WINCDMDWF.vcproj", "{92F5EB69-069C-43EA-97E7-2F6507AA5873}" + ProjectSection(ProjectDependencies) = postProject + {6DFC9788-904C-4724-A734-06634061EF00} = {6DFC9788-904C-4724-A734-06634061EF00} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WincmdContent", "WincmdContent\filesys.vcproj", "{2F492A95-A23D-45C9-BBD9-E5B9325B22C1}" + ProjectSection(ProjectDependencies) = postProject + {CF524F70-4DDD-4040-803B-41B5DE7B1CF9} = {CF524F70-4DDD-4040-803B-41B5DE7B1CF9} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WincmdPacker", "WincmdPacker\WincmdPacker.vcproj", "{18EC7157-E263-458C-A41C-52E9538A642F}" + ProjectSection(ProjectDependencies) = postProject + {6EA5FCEC-1DB0-4542-8E41-9423021BD460} = {6EA5FCEC-1DB0-4542-8E41-9423021BD460} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SLNKDWFStaticRO", "SlnkDWFImpl\SLNKDWFStaticRO.vcproj", "{CF524F70-4DDD-4040-803B-41B5DE7B1CF9}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SLNKDWFCom", "SlnkDWFCom\SLNKDWF.vcproj", "{7F9F1060-C14D-4DD5-91D3-FA7263FECF5E}" + ProjectSection(ProjectDependencies) = postProject + {89BE476D-6C02-4514-BFCE-256106D98713} = {89BE476D-6C02-4514-BFCE-256106D98713} + {6EA5FCEC-1DB0-4542-8E41-9423021BD460} = {6EA5FCEC-1DB0-4542-8E41-9423021BD460} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SLNKDWFStaticRW", "SlnkDWFImpl\SLNKDWFStaticRW.vcproj", "{6EA5FCEC-1DB0-4542-8E41-9423021BD460}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tiff", "SlnkDWFImpl\CxImage\tiff\Tiff.vcproj", "{B61F3CD8-D974-4127-8335-557650DA8B5E}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B0573FCD-8E98-421C-8BA3-F47CEB1F1047}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RemoveAbout", "RemoveAbout\RemoveAbout.vcproj", "{89BE476D-6C02-4514-BFCE-256106D98713}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B2601E72-4FF4-4B9C-A89F-C2E7DACF36FD}.Debug|Win32.ActiveCfg = Debug|Win32 + {B2601E72-4FF4-4B9C-A89F-C2E7DACF36FD}.Debug|Win32.Build.0 = Debug|Win32 + {B2601E72-4FF4-4B9C-A89F-C2E7DACF36FD}.Release|Win32.ActiveCfg = Release|Win32 + {B2601E72-4FF4-4B9C-A89F-C2E7DACF36FD}.Release|Win32.Build.0 = Release|Win32 + {6DFC9788-904C-4724-A734-06634061EF00}.Debug|Win32.ActiveCfg = Debug|Win32 + {6DFC9788-904C-4724-A734-06634061EF00}.Debug|Win32.Build.0 = Debug|Win32 + {6DFC9788-904C-4724-A734-06634061EF00}.Release|Win32.ActiveCfg = Release|Win32 + {6DFC9788-904C-4724-A734-06634061EF00}.Release|Win32.Build.0 = Release|Win32 + {92F5EB69-069C-43EA-97E7-2F6507AA5873}.Debug|Win32.ActiveCfg = Debug|Win32 + {92F5EB69-069C-43EA-97E7-2F6507AA5873}.Debug|Win32.Build.0 = Debug|Win32 + {92F5EB69-069C-43EA-97E7-2F6507AA5873}.Release|Win32.ActiveCfg = Release|Win32 + {92F5EB69-069C-43EA-97E7-2F6507AA5873}.Release|Win32.Build.0 = Release|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Debug|Win32.ActiveCfg = Debug|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Debug|Win32.Build.0 = Debug|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Release|Win32.ActiveCfg = Release|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Release|Win32.Build.0 = Release|Win32 + {18EC7157-E263-458C-A41C-52E9538A642F}.Debug|Win32.ActiveCfg = Debug|Win32 + {18EC7157-E263-458C-A41C-52E9538A642F}.Debug|Win32.Build.0 = Debug|Win32 + {18EC7157-E263-458C-A41C-52E9538A642F}.Release|Win32.ActiveCfg = Release|Win32 + {18EC7157-E263-458C-A41C-52E9538A642F}.Release|Win32.Build.0 = Release|Win32 + {CF524F70-4DDD-4040-803B-41B5DE7B1CF9}.Debug|Win32.ActiveCfg = Debug|Win32 + {CF524F70-4DDD-4040-803B-41B5DE7B1CF9}.Debug|Win32.Build.0 = Debug|Win32 + {CF524F70-4DDD-4040-803B-41B5DE7B1CF9}.Release|Win32.ActiveCfg = Release|Win32 + {CF524F70-4DDD-4040-803B-41B5DE7B1CF9}.Release|Win32.Build.0 = Release|Win32 + {7F9F1060-C14D-4DD5-91D3-FA7263FECF5E}.Debug|Win32.ActiveCfg = Debug|Win32 + {7F9F1060-C14D-4DD5-91D3-FA7263FECF5E}.Debug|Win32.Build.0 = Debug|Win32 + {7F9F1060-C14D-4DD5-91D3-FA7263FECF5E}.Release|Win32.ActiveCfg = Release|Win32 + {7F9F1060-C14D-4DD5-91D3-FA7263FECF5E}.Release|Win32.Build.0 = Release|Win32 + {6EA5FCEC-1DB0-4542-8E41-9423021BD460}.Debug|Win32.ActiveCfg = Debug|Win32 + {6EA5FCEC-1DB0-4542-8E41-9423021BD460}.Debug|Win32.Build.0 = Debug|Win32 + {6EA5FCEC-1DB0-4542-8E41-9423021BD460}.Release|Win32.ActiveCfg = Release|Win32 + {6EA5FCEC-1DB0-4542-8E41-9423021BD460}.Release|Win32.Build.0 = Release|Win32 + {B61F3CD8-D974-4127-8335-557650DA8B5E}.Debug|Win32.ActiveCfg = Debug|Win32 + {B61F3CD8-D974-4127-8335-557650DA8B5E}.Debug|Win32.Build.0 = Debug|Win32 + {B61F3CD8-D974-4127-8335-557650DA8B5E}.Release|Win32.ActiveCfg = Release|Win32 + {B61F3CD8-D974-4127-8335-557650DA8B5E}.Release|Win32.Build.0 = Release|Win32 + {89BE476D-6C02-4514-BFCE-256106D98713}.Debug|Win32.ActiveCfg = Debug|Win32 + {89BE476D-6C02-4514-BFCE-256106D98713}.Debug|Win32.Build.0 = Debug|Win32 + {89BE476D-6C02-4514-BFCE-256106D98713}.Release|Win32.ActiveCfg = Release|Win32 + {89BE476D-6C02-4514-BFCE-256106D98713}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/SlnkDWFCom/.gitignore b/SlnkDWFCom/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFCom/About.cpp b/SlnkDWFCom/About.cpp new file mode 100644 index 0000000..0565d49 --- /dev/null +++ b/SlnkDWFCom/About.cpp @@ -0,0 +1,96 @@ +// About.cpp : Implementation of CAbout + +#include "stdafx.h" +#include "About.h" +#include "SLNKDWFVersion.h" + +#define SECURITY_WIN32 +#include "Security.h" + +// CAbout +extern HINSTANCE g_hInstance; + +// In release mode verwijderen we altijd About.obj om hercompile te forceren +CString buildDATE(__DATE__); +CString buildTIME(__TIME__); + +STDMETHODIMP CAbout::get_All(BSTR* pVal) +{ + char module[_MAX_PATH]; // HMODULE + GetModuleFileName(g_hInstance, module, sizeof(module)/sizeof(char)); + char name[_MAX_PATH]; // HMODULE + ULONG cnt = sizeof(name)/sizeof(char); + if (!GetUserNameEx(NameSamCompatible, name, &cnt)) + { + myTRACE("\nGetUserNameEx failed (%d): %s", GetLastError(), myGetLastErrorMsg()); + } + + CString result; + result.Format(" SLNKDWF: built on %s, %s" + "\n DLL: %s" + "\nUsercontext: %s", buildDATE, buildTIME, module, name); + (*pVal) = result.AllocSysString(); + + return S_OK; +} + +STDMETHODIMP CAbout::get_DLLPath(BSTR* pVal) +{ + char module[_MAX_PATH]; // HMODULE + GetModuleFileName(g_hInstance, module, sizeof(module)); + + CString result; + result.Format("%s", module); + (*pVal) = result.AllocSysString(); + + return S_OK; +} + +STDMETHODIMP CAbout::get_Buildtime(BSTR* pVal) +{ + CString result; + result.Format("%s, %s", buildDATE, buildTIME); + (*pVal) = result.AllocSysString(); + + return S_OK; +} + +STDMETHODIMP CAbout::get_UserContext(BSTR* pVal) +{ + char name[_MAX_PATH]; // HMODULE + ULONG cnt = sizeof(name)/sizeof(char); + CString result; + if (!GetUserNameEx(NameSamCompatible, name, &cnt)) + { + myTRACE("\nGetUserNameEx failed (%d): %s", GetLastError(), myGetLastErrorMsg()); + result = "Unable to detect user"; + } + else + result = name; + + (*pVal) = result.AllocSysString(); + + return S_OK; +} + +STDMETHODIMP CAbout::get_VersionMajor(LONG* pVal) +{ + (*pVal) = SLNK_MAJOR_VERSION; + + return S_OK; +} + +STDMETHODIMP CAbout::get_VersionMinor(LONG* pVal) +{ + (*pVal) = SLNK_MINOR_VERSION; + + return S_OK; +} + +STDMETHODIMP CAbout::get_VersionString(BSTR* pVal) +{ + CString result = SLNK_BUILDVERSION; + (*pVal) = result.AllocSysString(); + + return S_OK; +} diff --git a/SlnkDWFCom/About.h b/SlnkDWFCom/About.h new file mode 100644 index 0000000..f1dadc5 --- /dev/null +++ b/SlnkDWFCom/About.h @@ -0,0 +1,52 @@ +// About.h : Declaration of the CAbout + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" + + +// CAbout + +class ATL_NO_VTABLE CAbout : + public CComObjectRootEx, + public CComCoClass, + public IDispatchImpl +{ +public: + CAbout() + { + } + +DECLARE_REGISTRY_RESOURCEID(IDR_ABOUT) + + +BEGIN_COM_MAP(CAbout) + COM_INTERFACE_ENTRY(IAbout) + COM_INTERFACE_ENTRY(IDispatch) +END_COM_MAP() + + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + return S_OK; + } + + void FinalRelease() + { + } + +public: + + STDMETHOD(get_All)(BSTR* pVal); + STDMETHOD(get_DLLPath)(BSTR* pVal); + STDMETHOD(get_Buildtime)(BSTR* pVal); + STDMETHOD(get_UserContext)(BSTR* pVal); + STDMETHOD(get_VersionMajor)(LONG* pVal); + STDMETHOD(get_VersionMinor)(LONG* pVal); + STDMETHOD(get_VersionString)(BSTR* pVal); +}; + +OBJECT_ENTRY_AUTO(__uuidof(About), CAbout) diff --git a/SlnkDWFCom/About.rgs b/SlnkDWFCom/About.rgs new file mode 100644 index 0000000..1b1e966 --- /dev/null +++ b/SlnkDWFCom/About.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.About.1 = s 'About Class' + { + CLSID = s '{2BA64B82-1A96-4F15-9815-40B291B505EB}' + } + SLNKDWF.About = s 'About Class' + { + CLSID = s '{2BA64B82-1A96-4F15-9815-40B291B505EB}' + CurVer = s 'SLNKDWF.About.1' + } + NoRemove CLSID + { + ForceRemove {2BA64B82-1A96-4F15-9815-40B291B505EB} = s 'About Class' + { + ProgID = s 'SLNKDWF.About.1' + VersionIndependentProgID = s 'SLNKDWF.About' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/BoundingBox.cpp b/SlnkDWFCom/BoundingBox.cpp new file mode 100644 index 0000000..45907ef --- /dev/null +++ b/SlnkDWFCom/BoundingBox.cpp @@ -0,0 +1,17 @@ +// BoundingBox.cpp : Implementation of CBoundingBox + +#include "stdafx.h" +#include "BoundingBox.h" + + +// CBoundingBox + +STDMETHODIMP CBoundingBox::get_min(IDWGPoint** pVal) +{ + return m_minPoint->QueryInterface(IID_IDWGPoint, (void**)pVal); +} + +STDMETHODIMP CBoundingBox::get_max(IDWGPoint** pVal) +{ + return m_maxPoint->QueryInterface(IID_IDWGPoint, (void**)pVal); +}; diff --git a/SlnkDWFCom/BoundingBox.h b/SlnkDWFCom/BoundingBox.h new file mode 100644 index 0000000..7e60835 --- /dev/null +++ b/SlnkDWFCom/BoundingBox.h @@ -0,0 +1,75 @@ +// BoundingBox.h : Declaration of the CBoundingBox + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" +#include "DWGPoint.h" + + +// CBoundingBox + +class ATL_NO_VTABLE CBoundingBox : + public CComObjectRootEx, + public CComCoClass, + public IDispatchImpl +{ +public: + CBoundingBox() + { + } + +//REMOVED DECLARE_REGISTRY_RESOURCEID(IDR_BOUNDINGBOX) + + +BEGIN_COM_MAP(CBoundingBox) + COM_INTERFACE_ENTRY(IBoundingBox) + COM_INTERFACE_ENTRY(IDispatch) +END_COM_MAP() + + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + // + // Maak object m_minPoint + // + CComObject *pDWGPoint; + HRESULT hr = CComObject::CreateInstance(&pDWGPoint); + if(FAILED(hr)) return hr; + + pDWGPoint->AddRef(); + hr = pDWGPoint->QueryInterface(IID_IDWGPoint, (void **)&m_minPoint); + pDWGPoint->Release(); + if(FAILED(hr)) return hr; + + // + // Maak object m_maxPoint + // + hr = CComObject::CreateInstance(&pDWGPoint); + if(FAILED(hr)) return hr; + + pDWGPoint->AddRef(); + hr = pDWGPoint->QueryInterface(IID_IDWGPoint, (void **)&m_maxPoint); + pDWGPoint->Release(); + if(FAILED(hr)) return hr; + + return S_OK; + } + + void FinalRelease() + { + } + +private: + CComQIPtr m_minPoint; + CComQIPtr m_maxPoint; + +public: + STDMETHOD(get_min)(IDWGPoint** pVal); + STDMETHOD(get_max)(IDWGPoint** pVal); + +}; + +//REMOVED OBJECT_ENTRY_AUTO(__uuidof(BoundingBox), CBoundingBox) diff --git a/SlnkDWFCom/BoundingBox.rgs b/SlnkDWFCom/BoundingBox.rgs new file mode 100644 index 0000000..f406ac5 --- /dev/null +++ b/SlnkDWFCom/BoundingBox.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.BoundingBox.1 = s 'BoundingBox Class' + { + CLSID = s '{FCEF1E56-36FF-4F66-BEA5-FD08D860524F}' + } + SLNKDWF.BoundingBox = s 'BoundingBox Class' + { + CLSID = s '{FCEF1E56-36FF-4F66-BEA5-FD08D860524F}' + CurVer = s 'SLNKDWF.BoundingBox.1' + } + NoRemove CLSID + { + ForceRemove {FCEF1E56-36FF-4F66-BEA5-FD08D860524F} = s 'BoundingBox Class' + { + ProgID = s 'SLNKDWF.BoundingBox.1' + VersionIndependentProgID = s 'SLNKDWF.BoundingBox' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/DWFFile.cpp b/SlnkDWFCom/DWFFile.cpp new file mode 100644 index 0000000..330c4bf --- /dev/null +++ b/SlnkDWFCom/DWFFile.cpp @@ -0,0 +1,83 @@ +// DWFFile.cpp : Implementation of CDWFFile + +#include "stdafx.h" +#include "assert.h" +#include "DWFFile.h" + +#include "myEPlotSection.h" + +// CDWFFile + +STDMETHODIMP CDWFFile::InterfaceSupportsErrorInfo(REFIID riid) +{ + static const IID* arr[] = + { + &IID_IDWFFile + }; + + for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) + { + if (InlineIsEqualGUID(*arr[i],riid)) + return S_OK; + } + return S_FALSE; +} + +//CDWFFile::~CDWFFile() +//{ +// // It seems we never get here? Use FinalRelease +//}; + +HRESULT CDWFFile::FinalConstruct() +{ + m_EPlotSections.SetParent(this); + m_EPlotSections.SetOuterUnknown(GetControllingUnknown()); + return m_EPlotSections.FinalConstruct(); +} + +// Omdat de tellingen gekoppeld zijn weten we zeker dat de refcount van +// onze eigen objecten ook 0 zal zijn en is het dus veilig ze weg te gooien (toch...?) +void CDWFFile::FinalRelease() +{ + m_EPlotSections.FinalRelease(); +} + +STDMETHODIMP CDWFFile::Open(BSTR DWFPath) +{ + try + { + if (CDWFFileImpl::Open(CString(DWFPath))) + { + return S_OK; + } + else + return E_FAIL; + } + catch (CString& e) + { + return myAtlReportError (GetObjectCLSID(), e); + } + +} + +STDMETHODIMP CDWFFile::get_PropertiesXML(BSTR* pVal) +{ + CString s; + if (CDWFFileImpl::get_PropertiesXML(s)) + { + CComBSTR bstrString(s); + return bstrString.CopyTo(pVal); + } + else + return E_FAIL; + + return S_OK; +} + +STDMETHODIMP CDWFFile::get_EPlotSections(IEPlotSections **ppEPlotSections) +{ +// if (!m_isOpen) +// return myAtlReportError (GetObjectCLSID(), "\nDWF File is not opened"); + + return m_EPlotSections.QueryInterface(ppEPlotSections); +} diff --git a/SlnkDWFCom/DWFFile.h b/SlnkDWFCom/DWFFile.h new file mode 100644 index 0000000..f37d368 --- /dev/null +++ b/SlnkDWFCom/DWFFile.h @@ -0,0 +1,55 @@ +// DWFFile.h : Declaration of the CDWFFile + +#pragma once +#include "resource.h" // main symbols + +#include "DWFFileImpl.h" + +#include "ComObjectEmbed.h" +#include "EPlotSections.h" + +#include "SLNKDWF.h" + +// CDWFFile + +class ATL_NO_VTABLE CDWFFile : + public CComObjectRootEx, + public CComCoClass, + public ISupportErrorInfo, + public IDispatchImpl, + public CDWFFileImpl +{ +public: + CDWFFile() + { + m_EPlotSections.InitImpl(&(CDWFFileImpl::m_EPlotSections)); + } + +DECLARE_REGISTRY_RESOURCEID(IDR_DWFFILE) +DECLARE_GET_CONTROLLING_UNKNOWN() //ADDED + +BEGIN_COM_MAP(CDWFFile) + COM_INTERFACE_ENTRY(IDWFFile) + COM_INTERFACE_ENTRY(IDispatch) + COM_INTERFACE_ENTRY(ISupportErrorInfo) +END_COM_MAP() + +// ISupportsErrorInfo + STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct(); + + void FinalRelease(); + +protected: + CComObjectEmbed m_EPlotSections; + +public: + STDMETHOD(Open)(BSTR DWFPath); + STDMETHOD(get_PropertiesXML)(BSTR* pVal); + STDMETHOD(get_EPlotSections)(IEPlotSections **ppEPlotSections); +}; + +OBJECT_ENTRY_AUTO(__uuidof(myDWFFile), CDWFFile) diff --git a/SlnkDWFCom/DWFFile.rgs b/SlnkDWFCom/DWFFile.rgs new file mode 100644 index 0000000..a70ad9a --- /dev/null +++ b/SlnkDWFCom/DWFFile.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.DWFFile.1 = s 'DWFFile Class' + { + CLSID = s '{BE2BCD58-4971-49E6-9A70-CDDD5C01224D}' + } + SLNKDWF.DWFFile = s 'DWFFile Class' + { + CLSID = s '{BE2BCD58-4971-49E6-9A70-CDDD5C01224D}' + CurVer = s 'SLNKDWF.DWFFile.1' + } + NoRemove CLSID + { + ForceRemove {BE2BCD58-4971-49E6-9A70-CDDD5C01224D} = s 'DWFFile Class' + { + ProgID = s 'SLNKDWF.DWFFile.1' + VersionIndependentProgID = s 'SLNKDWF.DWFFile' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/DWGPoint.cpp b/SlnkDWFCom/DWGPoint.cpp new file mode 100644 index 0000000..eb163a6 --- /dev/null +++ b/SlnkDWFCom/DWGPoint.cpp @@ -0,0 +1,32 @@ +// DWGPoint.cpp : Implementation of CDWGPoint + +#include "stdafx.h" +#include "DWGPoint.h" + + +// CDWGPoint + +STDMETHODIMP CDWGPoint::get_DwgX(DOUBLE* pVal) +{ + (*pVal) = m_DwgX; + return S_OK; +} + +STDMETHODIMP CDWGPoint::put_DwgX(DOUBLE newVal) +{ + m_DwgX = newVal; + return S_OK; +} +STDMETHODIMP CDWGPoint::get_DwgY(DOUBLE* pVal) +{ + (*pVal) = m_DwgY; + return S_OK; +} + +STDMETHODIMP CDWGPoint::put_DwgY(DOUBLE newVal) +{ + m_DwgY = newVal; + return S_OK; +} + + diff --git a/SlnkDWFCom/DWGPoint.h b/SlnkDWFCom/DWGPoint.h new file mode 100644 index 0000000..000de15 --- /dev/null +++ b/SlnkDWFCom/DWGPoint.h @@ -0,0 +1,51 @@ +// DWGPoint.h : Declaration of the CDWGPoint + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" + + +// CDWGPoint + +class ATL_NO_VTABLE CDWGPoint : + public CComObjectRootEx, + public CComCoClass, + public IDispatchImpl +{ +public: + CDWGPoint() + { + } + +//REMOVED DECLARE_REGISTRY_RESOURCEID(IDR_DWGPOINT) + + +BEGIN_COM_MAP(CDWGPoint) + COM_INTERFACE_ENTRY(IDWGPoint) + COM_INTERFACE_ENTRY(IDispatch) +END_COM_MAP() + + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + return S_OK; + } + + void FinalRelease() + { + } + +protected: + double m_DwgX, m_DwgY; + +public: + STDMETHOD(get_DwgX)(DOUBLE* pVal); + STDMETHOD(put_DwgX)(DOUBLE newVal); + STDMETHOD(get_DwgY)(DOUBLE* pVal); + STDMETHOD(put_DwgY)(DOUBLE newVal); +}; + +//REMOVED OBJECT_ENTRY_AUTO(__uuidof(DWGPoint), CDWGPoint) diff --git a/SlnkDWFCom/DWGPoint.rgs b/SlnkDWFCom/DWGPoint.rgs new file mode 100644 index 0000000..e96e4b3 --- /dev/null +++ b/SlnkDWFCom/DWGPoint.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.DWGPoint.1 = s 'DWGPoint Class' + { + CLSID = s '{96301A8D-1DC9-4900-B89D-C745C4CAEFF4}' + } + SLNKDWF.DWGPoint = s 'DWGPoint Class' + { + CLSID = s '{96301A8D-1DC9-4900-B89D-C745C4CAEFF4}' + CurVer = s 'SLNKDWF.DWGPoint.1' + } + NoRemove CLSID + { + ForceRemove {96301A8D-1DC9-4900-B89D-C745C4CAEFF4} = s 'DWGPoint Class' + { + ProgID = s 'SLNKDWF.DWGPoint.1' + VersionIndependentProgID = s 'SLNKDWF.DWGPoint' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/EPlotSection.rgs b/SlnkDWFCom/EPlotSection.rgs new file mode 100644 index 0000000..88cbf71 --- /dev/null +++ b/SlnkDWFCom/EPlotSection.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.EPlotSection.1 = s 'EPlotSection Class' + { + CLSID = s '{F2599AE6-8A08-4B5E-9C68-BD975229F0D1}' + } + SLNKDWF.EPlotSection = s 'EPlotSection Class' + { + CLSID = s '{F2599AE6-8A08-4B5E-9C68-BD975229F0D1}' + CurVer = s 'SLNKDWF.EPlotSection.1' + } + NoRemove CLSID + { + ForceRemove {F2599AE6-8A08-4B5E-9C68-BD975229F0D1} = s 'EPlotSection Class' + { + ProgID = s 'SLNKDWF.EPlotSection.1' + VersionIndependentProgID = s 'SLNKDWF.EPlotSection' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/EPlotSections.h b/SlnkDWFCom/EPlotSections.h new file mode 100644 index 0000000..9f9cc67 --- /dev/null +++ b/SlnkDWFCom/EPlotSections.h @@ -0,0 +1,59 @@ +// EPlotSections.h : Declaration of the CEPlotSections + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" + +#include "EPlotSectionsImpl.h" + +#include "ComObjectEmbed.h" +#include "myEPlotSection.h" + +// CEPlotSections + +class ATL_NO_VTABLE CEPlotSections : + public CComObjectRootEx, + public CComCoClass, + public ISupportErrorInfo, + public IDispatchImpl +{ +public: + CEPlotSections() + { + } + +DECLARE_GET_CONTROLLING_UNKNOWN() //ADDED + +BEGIN_COM_MAP(CEPlotSections) + COM_INTERFACE_ENTRY(IEPlotSections) + COM_INTERFACE_ENTRY(IDispatch) + COM_INTERFACE_ENTRY(ISupportErrorInfo) +END_COM_MAP() + +// ISupportsErrorInfo + STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + return S_OK; + } + + void FinalRelease() ; + +protected: + IDWFFile *m_pParent; // Non-addreffed! + CEPlotSectionsImpl *m_pSectionsImpl; // Pointer naar onderliggende sections + CAtlArray> m_EPlotSections; + +public: + void InitImpl(CEPlotSectionsImpl *epl); + void SetParent(IDWFFile *pParent); + BOOL ProcessManifest(DWFToolkit::DWFManifest& rManifest, CString sourceDescription); + + STDMETHODIMP get_Parent(IDWFFile **ppParent); + STDMETHOD(get_Count)(LONG* pVal); + STDMETHOD(get_Item)(LONG i, IDispatch** pVal); +}; diff --git a/SlnkDWFCom/EPlotSections.rgs b/SlnkDWFCom/EPlotSections.rgs new file mode 100644 index 0000000..793ce05 --- /dev/null +++ b/SlnkDWFCom/EPlotSections.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.EPlotSections.1 = s 'EPlotSections Class' + { + CLSID = s '{7B2E7661-9B9A-4217-A19E-745EFFF8E86D}' + } + SLNKDWF.EPlotSections = s 'EPlotSections Class' + { + CLSID = s '{7B2E7661-9B9A-4217-A19E-745EFFF8E86D}' + CurVer = s 'SLNKDWF.EPlotSections.1' + } + NoRemove CLSID + { + ForceRemove {7B2E7661-9B9A-4217-A19E-745EFFF8E86D} = s 'EPlotSections Class' + { + ProgID = s 'SLNKDWF.EPlotSections.1' + VersionIndependentProgID = s 'SLNKDWF.EPlotSections' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/Metafile.cpp b/SlnkDWFCom/Metafile.cpp new file mode 100644 index 0000000..3856b7b --- /dev/null +++ b/SlnkDWFCom/Metafile.cpp @@ -0,0 +1,135 @@ +/****************************************************************************** + * File : Metafile.cpp (c) 1997-2002, Furix + * + * Author : J. Groot Lipman + * Project : BetterWMF + * Version : 4.00 + * + * Function : Core file of BetterWMF. Contains all functions to convert a + * WMF-file or Clipboard object to a better one + *****************************************************************************/ + +#include "stdafx.h" + +#include "metafile.h" + +/***************************************************************************** + * Static variables for CMetafile. Only temporary used for/in static playback + * procedures + */ + +// ========================================================================== +/* + + FUNCTION : WriteMetaFileAsPlaceable + + PARAMETERS : HMETAFILE - a handle to the metafile + LPCSTR lpstrOutFileName - filename to write to + + PURPOSE : Write a metafile in placeable format + + RETURNS : BOOL - TRUE is Success, FALSE is failure + + COMMENTS : Fills out and writes a placeable header, followed by the + metafile bits, to the file. + + HISTORY : 4/17/95 - Created + +*/ +BOOL CMetafile::WriteMetaFileAsPlaceable( HMETAFILE hOld, CSize Size, double Inch, LPCSTR lpstrOutFileName) +{ + FILE *OutFile; + //OFSTRUCT outof; + + DWORD dwSize; + LPBYTE pBits; + + ALDUSMFHEADER pAldusMFHdr; + // Fill out the placeable header + pAldusMFHdr.key = ALDUS_KEY; + pAldusMFHdr.hmf = NULL; + pAldusMFHdr.inch = (unsigned short)Inch; +; + pAldusMFHdr.reserved = 0; + pAldusMFHdr.bbox.left = (short)0; + pAldusMFHdr.bbox.top = (short)0; + pAldusMFHdr.bbox.right = (short)Size.cx; + pAldusMFHdr.bbox.bottom = (short)Size.cy; + pAldusMFHdr.checksum = CalculateAPMCheckSum( pAldusMFHdr ); + + // Get the bits + if( (dwSize = GetMetaFileBitsEx( hOld, 0, NULL )) == 0 ) + { + DeleteMetaFile( hOld ); +// myErrorBox(NULL, "Failed to Get MetaFile Bits Size"); + return NULL; + } + // Allocate that much memory + if( (pBits = (LPBYTE) malloc( dwSize )) == NULL ) + { + DeleteMetaFile( hOld ); +// myErrorBox(NULL, "Failed to Allocate Memory for Metafile Bits"); + return NULL; + } + // Get the metafile bits + if( GetMetaFileBitsEx( hOld, dwSize, pBits ) == 0 ) + { + free( pBits ); + DeleteMetaFile( hOld ); +// myErrorBox(NULL, "Failed to Get MetaFile Bits"); + return NULL; + } + + // TODO: Error checking + // Open the file + OutFile = fopen( lpstrOutFileName, "wb" ); + + // Write the header + fwrite(&pAldusMFHdr, 1, sizeof( APMFILEHEADER ), OutFile); + + // Write the bits + fwrite(pBits, 1, dwSize, OutFile ); + + // Close the file + fclose(OutFile); + + // Clean up + free( pBits ); + return TRUE; +} +// End WriteMetaFileAsPlaceable +// ========================================================================== + + +// ========================================================================== +/* + + FUNCTION : CalculateAPMCheckSum + + PARAMETERS : APMFILEHEADER apmfh - A placeable header + + PURPOSE : Calculates the checksum for a placeable header + + RETURNS : WORD - the checksum + + COMMENTS : The checksum is derived by XORing each word. + + HISTORY : 4/17/95 - Created + +*/ +WORD CMetafile::CalculateAPMCheckSum( ALDUSMFHEADER pAldusMFHdr ) +{ + LPWORD lpWord; + WORD wResult, i; + + // Start with the first word + wResult = *(lpWord = (LPWORD)(&pAldusMFHdr)); + // XOR in each of the other 9 words + for(i=1;i<=9;i++) + { + wResult ^= lpWord[i]; + } + return wResult; +} +// End CalculateAPMCheckSum +// ========================================================================== diff --git a/SlnkDWFCom/Metafile.h b/SlnkDWFCom/Metafile.h new file mode 100644 index 0000000..e0ec88f --- /dev/null +++ b/SlnkDWFCom/Metafile.h @@ -0,0 +1,39 @@ +#ifndef __METAFILE_H_ +#define __METAFILE_H_ + +#pragma pack(1) +// +//placeable metafile data definitions +// +typedef struct tagOLDRECT +{ + short left; + short top; + short right; + short bottom; +} OLDRECT; + +typedef struct +{ + DWORD key; + WORD hmf; + OLDRECT bbox; + WORD inch; + DWORD reserved; + WORD checksum; +} ALDUSMFHEADER, * LPALDUSMFHEADER, APMFILEHEADER; +#pragma pack() + +#define OFFSET_TO_META sizeof (ALDUSMFHEADER) +#define METAHEADER_SIZE sizeof (METAHEADER) +#define ALDUS_KEY 0x9AC6CDD7 + +class CMetafile +{ +// Operations +public: + static BOOL WriteMetaFileAsPlaceable( HMETAFILE hOld, CSize Size, double Inch, LPCSTR lpstrOutFileName); + static WORD CalculateAPMCheckSum( ALDUSMFHEADER pAldusMFHdr ); +}; + +#endif // __METAFILE_H_ diff --git a/SlnkDWFCom/Options.cpp b/SlnkDWFCom/Options.cpp new file mode 100644 index 0000000..75437d0 --- /dev/null +++ b/SlnkDWFCom/Options.cpp @@ -0,0 +1,50 @@ +// Options.cpp : Implementation of COptions + +#include "stdafx.h" +#include "Options.h" + +CSLNKOptions g_SLNKOptions; // The one and only + +// Set all default values +CSLNKOptions::CSLNKOptions() +{ + m_MinContSize = 0.20e6; // Minimale grootte voor een contour om herkend te worden + m_SkipContLeader = FALSE; // ARKEY tekeningen hebben een leading lijntje voor de contour +} +// COptions + +STDMETHODIMP COptions::InterfaceSupportsErrorInfo(REFIID riid) +{ + static const IID* arr[] = + { + &IID_IOptions + }; + + for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) + { + if (InlineIsEqualGUID(*arr[i],riid)) + return S_OK; + } + return S_FALSE; +} + +STDMETHODIMP COptions::SetOption(BSTR optionName, VARIANT OptionValue) +{ + CComVariant val(OptionValue); + CString nm(optionName); + nm.MakeUpper(); + + if (nm=="MINCONTSIZE") + { + HRESULT hr = val.ChangeType(VT_R8); + if (FAILED(hr)) return hr; + g_SLNKOptions.m_MinContSize = val.dblVal; + } + if (nm=="SKIPCONTLEADER") + { + HRESULT hr = val.ChangeType(VT_BOOL); + if (FAILED(hr)) return hr; + g_SLNKOptions.m_SkipContLeader = val.boolVal; + } + return S_OK; +} diff --git a/SlnkDWFCom/Options.h b/SlnkDWFCom/Options.h new file mode 100644 index 0000000..81422b8 --- /dev/null +++ b/SlnkDWFCom/Options.h @@ -0,0 +1,66 @@ +// Options.h : Declaration of the COptions + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" + + +#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) +#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." +#endif + + +class CSLNKOptions +{ +public: + CSLNKOptions(); + + double m_MinContSize; // In DWG Units + BOOL m_SkipContLeader; // +}; +extern CSLNKOptions g_SLNKOptions; // The one and only + +// COptions + +class ATL_NO_VTABLE COptions : + public CComObjectRootEx, + public CComCoClass, + public ISupportErrorInfo, + public IDispatchImpl +{ +public: + COptions() + { + } + +DECLARE_REGISTRY_RESOURCEID(IDR_OPTIONS) + + +BEGIN_COM_MAP(COptions) + COM_INTERFACE_ENTRY(IOptions) + COM_INTERFACE_ENTRY(IDispatch) + COM_INTERFACE_ENTRY(ISupportErrorInfo) +END_COM_MAP() + +// ISupportsErrorInfo + STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); + + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + return S_OK; + } + + void FinalRelease() + { + } + +public: + + STDMETHOD(SetOption)(BSTR optionName, VARIANT OptionValue); +}; + +OBJECT_ENTRY_AUTO(__uuidof(Options), COptions) diff --git a/SlnkDWFCom/Options.rgs b/SlnkDWFCom/Options.rgs new file mode 100644 index 0000000..a6a3f14 --- /dev/null +++ b/SlnkDWFCom/Options.rgs @@ -0,0 +1,26 @@ +HKCR +{ + SLNKDWF.Options.1 = s 'Options Class' + { + CLSID = s '{168678A9-6FA7-49C3-B839-DFDF07E0A79A}' + } + SLNKDWF.Options = s 'Options Class' + { + CLSID = s '{168678A9-6FA7-49C3-B839-DFDF07E0A79A}' + CurVer = s 'SLNKDWF.Options.1' + } + NoRemove CLSID + { + ForceRemove {168678A9-6FA7-49C3-B839-DFDF07E0A79A} = s 'Options Class' + { + ProgID = s 'SLNKDWF.Options.1' + VersionIndependentProgID = s 'SLNKDWF.Options' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/SLNKContour.cpp b/SlnkDWFCom/SLNKContour.cpp new file mode 100644 index 0000000..68e25a1 --- /dev/null +++ b/SlnkDWFCom/SLNKContour.cpp @@ -0,0 +1,138 @@ +// SLNKContour.cpp : Implementation of CSLNKContour + +#include "stdafx.h" +#include "SLNKContour.h" +#include "Whipfile.h" + +// Merk op dat sommige functies ook nog in WhipFile zijn gedefinieerd. Die moeten daar weg omdat we +// tegenwoordig (mei 2007) via WhipFile.Contour("label") een Contour object opleveren waar je alles +// maar op doet, of beter nog mettertijd WhipFile.Contours.Item("label") +// Voor backward compatibiliteit laten we de Whipfile nog maar even intact + +// CSLNKContour + +void CSLNKContour::SetImpl(CSLNKContourImpl * pSLNKContour) +{ + m_SLNKContour = pSLNKContour; + if (m_SLNKContour->m_fromSymbol) return; // Die zijn vast nog niet getransformeerd + + WT_Logical_Box bx = pSLNKContour->bounds(); + + WT_Point3D dwgPt; + CComQIPtr pt; + + dwgPt = pSLNKContour->m_parentWhipFileState->m_contunits.transform(bx.minpt()); + m_dwgBounding->get_min(&pt); + pt->put_DwgX(dwgPt.m_x); + pt->put_DwgY(dwgPt.m_y); + pt.Release(); + + dwgPt = pSLNKContour->m_parentWhipFileState->m_contunits.transform(bx.maxpt()); + m_dwgBounding->get_max(&pt); + pt->put_DwgX(dwgPt.m_x); + pt->put_DwgY(dwgPt.m_y); + pt.Release(); + + WT_Logical_Point lp = CSLNKContourImpl::Centroid(*pSLNKContour); + dwgPt = pSLNKContour->m_parentWhipFileState->m_contunits.transform(lp); + m_dwgCenter->put_DwgX(dwgPt.m_x); + m_dwgCenter->put_DwgY(dwgPt.m_y); +}; + +STDMETHODIMP CSLNKContour::SetColor(ULONG rgb, BYTE Alpha /*=0*/) +{ + int b=rgb%256; + int g=(rgb>>8)%256; + int r=(rgb>>16)%256; + m_SLNKContour->m_Color.set(r, g, b, Alpha); + + return S_OK; +} + +// De FriendlyName verschijnt uiteindelijk als tooltip +STDMETHODIMP CSLNKContour::SetUrl(BSTR Url, BSTR FriendlyName) +{ + CString fName(FriendlyName); + if (fName=="") + fName=m_SLNKContour->m_contLabel.ascii(); + + // Merk op: \n lijkt \012 te zijn? + fName.Replace("\012", "\\n"); // Anders corrupte (ascii?) DWF + fName.Replace("\015", "\\n"); // Anders corrupte (ascii?) DWF + + if (WT_String::is_ascii(fName.GetLength(), fName)) + m_SLNKContour->m_Url.set( WD_URL_Optimize, (LPCSTR)CString(Url), (LPCSTR)fName); + else + { // Use UNICODE for example for Michaël + CStringW s(fName); + m_SLNKContour->m_Url.set( WD_URL_Optimize, Url, s); + } + + return S_OK; +} + +STDMETHODIMP CSLNKContour::get_Area(DOUBLE* pVal) +{ + *pVal = m_SLNKContour->m_DWGArea; + + return S_OK; +} + +STDMETHODIMP CSLNKContour::get_Extents(IBoundingBox** pVal) +{ + if (m_SLNKContour->m_fromSymbol) + return E_NOTIMPL; // (nog) niet op symbolen + + return m_dwgBounding->QueryInterface(IID_IBoundingBox, (void**)pVal); +} + +STDMETHODIMP CSLNKContour::get_Center(IDWGPoint** pVal) +{ + if (m_SLNKContour->m_fromSymbol) + return E_NOTIMPL; // (nog) niet op symbolen + return m_dwgCenter->QueryInterface(IID_IDWGPoint, (void**)pVal); +} + +STDMETHODIMP CSLNKContour::get_Key(BSTR* pVal) +{ + CComBSTR bstrString(m_SLNKContour->m_Key); + + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CSLNKContour::put_Key(BSTR newVal) +{ + CString key(newVal); + m_SLNKContour->m_Key = key; + + return S_OK; +} + +STDMETHODIMP CSLNKContour::get_Label(BSTR* pVal) +{ + CComBSTR bstrString(m_SLNKContour->m_ExtraLabel); + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CSLNKContour::put_Label(BSTR newVal) +{ + CString key(newVal); + m_SLNKContour->m_ExtraLabel = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKContour::get_Hatch(BYTE* pVal) +{ + (*pVal) = m_SLNKContour->m_Pattern; + + return S_OK; +} + +STDMETHODIMP CSLNKContour::put_Hatch(BYTE newVal) +{ + WT_Fill_Pattern patt = WT_Fill_Pattern((WT_Fill_Pattern::WT_Pattern_ID)newVal); + m_SLNKContour->m_Pattern.set(patt); + //contour->m_Pattern.pattern_scale() = 1.0; + + return S_OK; +} diff --git a/SlnkDWFCom/SLNKContour.h b/SlnkDWFCom/SLNKContour.h new file mode 100644 index 0000000..c68e730 --- /dev/null +++ b/SlnkDWFCom/SLNKContour.h @@ -0,0 +1,104 @@ +// SLNKContour.h : Declaration of the CSLNKContour + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" +#include "SLNKContourImpl.h" +#include "BoundingBox.h" + +#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) +#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." +#endif + + + +// CSLNKContour + +class ATL_NO_VTABLE CSLNKContour : + public CComObjectRootEx, + public CComCoClass, + public IDispatchImpl +{ +public: + CSLNKContour() + { + } + +//REMOVED DECLARE_REGISTRY_RESOURCEID(IDR_SLNKCONTOUR) + + +BEGIN_COM_MAP(CSLNKContour) + COM_INTERFACE_ENTRY(ISLNKContour) + COM_INTERFACE_ENTRY(IDispatch) +END_COM_MAP() + + + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + // + // Maak object m_dwgBounding + // + CComObject *pBoundingBox; + HRESULT hr = CComObject::CreateInstance(&pBoundingBox); + if(FAILED(hr)) return hr; + + pBoundingBox->AddRef(); + hr = pBoundingBox->QueryInterface(IID_IBoundingBox, (void **)&m_dwgBounding); + pBoundingBox->Release(); + if(FAILED(hr)) return hr; + + // + // Maak object m_dwgCenter + // + CComObject *pDWGPoint; + hr = CComObject::CreateInstance(&pDWGPoint); + if(FAILED(hr)) return hr; + + pDWGPoint->AddRef(); + hr = pDWGPoint->QueryInterface(IID_IDWGPoint, (void **)&m_dwgCenter); + pDWGPoint->Release(); + if(FAILED(hr)) return hr; + return S_OK; + } + + void FinalRelease() + { + } + + // Deze SLNKContour wijst naar een CSLNKContourImpl in een WhipFile object. We moeten voorkomen + // dat deze te snel uit de scope wegvalt. Dat doen we mbv SetParent + // Omgekeerd is geen probleem: de WhipFile verwijst niet(!) naar de CSLNKContour en heeft er dus + // geen last van dat die wegvalt (van zijn SLNKContourImpl objecten is hij gewoon eigenaar) + + void SetParent(IWhipFile *pParent) + { + HRESULT hr = pParent->QueryInterface(IID_IWhipFile, (void **)&m_parent_iWhipFile); + }; + void SetImpl(CSLNKContourImpl * pSLNKContour); + +private: + CSLNKContourImpl * m_SLNKContour; + CComQIPtr m_dwgCenter; + CComQIPtr m_dwgBounding; + CComQIPtr m_parent_iWhipFile; // Om scope levend te houden + +public: + + STDMETHOD(SetColor)(ULONG rgb, BYTE Alpha); + STDMETHOD(SetUrl) (BSTR Url, BSTR FriendlyName); + STDMETHOD(get_Area)(DOUBLE* pVal); + STDMETHOD(get_Extents)(IBoundingBox** pVal); + STDMETHOD(get_Center)(IDWGPoint** pVal); + STDMETHOD(get_Key)(BSTR* pVal); + STDMETHOD(put_Key)(BSTR newVal); + STDMETHOD(get_Label)(BSTR* pVal); + STDMETHOD(put_Label)(BSTR newVal); + STDMETHOD(get_Hatch)(BYTE* pVal); + STDMETHOD(put_Hatch)(BYTE newVal); +}; + +//REMOVED OBJECT_ENTRY_AUTO(__uuidof(SLNKContour), CSLNKContour) diff --git a/SlnkDWFCom/SLNKContour.rgs b/SlnkDWFCom/SLNKContour.rgs new file mode 100644 index 0000000..9063bce --- /dev/null +++ b/SlnkDWFCom/SLNKContour.rgs @@ -0,0 +1,26 @@ +HKCR +{ + SLNKDWFCom.SLNKContour.1 = s 'SLNKContour Class' + { + CLSID = s '{476C0F28-5860-485D-BEBD-D03F68E1C930}' + } + SLNKDWFCom.SLNKContour = s 'SLNKContour Class' + { + CLSID = s '{476C0F28-5860-485D-BEBD-D03F68E1C930}' + CurVer = s 'SLNKDWFCom.SLNKContour.1' + } + NoRemove CLSID + { + ForceRemove {476C0F28-5860-485D-BEBD-D03F68E1C930} = s 'SLNKContour Class' + { + ProgID = s 'SLNKDWFCom.SLNKContour.1' + VersionIndependentProgID = s 'SLNKDWFCom.SLNKContour' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/SLNKDWF.cpp b/SlnkDWFCom/SLNKDWF.cpp new file mode 100644 index 0000000..8fb3240 --- /dev/null +++ b/SlnkDWFCom/SLNKDWF.cpp @@ -0,0 +1,115 @@ +// SLNKDWF.cpp : Implementation of DLL Exports. + +#include "stdafx.h" + +#include "resource.h" +#include "SLNKDWF.h" +#include "dlldatax.h" + +// Detect Memory Leaks +#ifdef _DEBUG +//CMemLeakDetect memLeakDetect; +#endif + +HINSTANCE g_hInstance; +extern CString buildDATE; +extern CString buildTIME; + +class CSLNKDWFModule : public CAtlDllModuleT< CSLNKDWFModule > +{ +public : + DECLARE_LIBID(LIBID_SLNKDWFLib) + DECLARE_REGISTRY_APPID_RESOURCEID(IDR_SLNKDWF, "{71B32202-1B68-4E92-9C86-8F53FB298011}") +}; + +CSLNKDWFModule _AtlModule; + + +// DLL Entry Point +extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) +{ + g_hInstance = hInstance; + char module[_MAX_PATH]; // HMODULE + + GetModuleFileName(g_hInstance, module, sizeof(module)); + + char *txt; + switch (dwReason) + { + case DLL_PROCESS_ATTACH: txt = "DLL_PROCESS_ATTACH"; break; + case DLL_PROCESS_DETACH: txt = "DLL_PROCESS_DETACH"; break; + case DLL_THREAD_ATTACH: txt = "DLL_THREAD_ATTACH"; break; + case DLL_THREAD_DETACH: txt = "DLL_THREAD_DETACH"; break; + default: txt = "UNKNOWN reason"; + } + + DWORD pid = GetCurrentProcessId(); + if (dwReason == DLL_PROCESS_ATTACH) + myDoTRACE("\nLoading SLNKDWF: built on %s, %s" + "\n DLL: %s" + "\n PID: %d" +// "\n Handle: %x\n" + , buildDATE, buildTIME, module, pid, hInstance); +// else +// myDoTRACE("\nUn/Loading SLNKDWF handle %x, reason %s", hInstance, txt); + +#ifdef _MERGE_PROXYSTUB + if (!PrxDllMain(hInstance, dwReason, lpReserved)) + return FALSE; +#endif + hInstance; + return _AtlModule.DllMain(dwReason, lpReserved); +} + + +// Used to determine whether the DLL can be unloaded by OLE +STDAPI DllCanUnloadNow(void) +{ +#ifdef _MERGE_PROXYSTUB + HRESULT hr = PrxDllCanUnloadNow(); + if (FAILED(hr)) + return hr; +#endif + return _AtlModule.DllCanUnloadNow(); +} + + +// Returns a class factory to create an object of the requested type +STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) +{ +#ifdef _MERGE_PROXYSTUB + if (PrxDllGetClassObject(rclsid, riid, ppv) == S_OK) + return S_OK; +#endif + return _AtlModule.DllGetClassObject(rclsid, riid, ppv); +} + + +// DllRegisterServer - Adds entries to the system registry +STDAPI DllRegisterServer(void) +{ + // registers object, typelib and all interfaces in typelib + HRESULT hr = _AtlModule.DllRegisterServer(); +#ifdef _MERGE_PROXYSTUB + if (FAILED(hr)) + return hr; + hr = PrxDllRegisterServer(); +#endif + return hr; +} + + +// DllUnregisterServer - Removes entries from the system registry +STDAPI DllUnregisterServer(void) +{ + HRESULT hr = _AtlModule.DllUnregisterServer(); +#ifdef _MERGE_PROXYSTUB + if (FAILED(hr)) + return hr; + hr = PrxDllRegisterServer(); + if (FAILED(hr)) + return hr; + hr = PrxDllUnregisterServer(); +#endif + return hr; +} diff --git a/SlnkDWFCom/SLNKDWF.def b/SlnkDWFCom/SLNKDWF.def new file mode 100644 index 0000000..0562f63 --- /dev/null +++ b/SlnkDWFCom/SLNKDWF.def @@ -0,0 +1,9 @@ +; SLNKDWF.def : Declares the module parameters. + +LIBRARY "SLNKDWF.DLL" + +EXPORTS + DllCanUnloadNow PRIVATE + DllGetClassObject PRIVATE + DllRegisterServer PRIVATE + DllUnregisterServer PRIVATE diff --git a/SlnkDWFCom/SLNKDWF.idl b/SlnkDWFCom/SLNKDWF.idl new file mode 100644 index 0000000..a0e0c7f --- /dev/null +++ b/SlnkDWFCom/SLNKDWF.idl @@ -0,0 +1,364 @@ +// SLNKDWF.idl : IDL source for SLNKDWF +// + +// This file will be processed by the MIDL tool to +// produce the type library (SLNKDWF.tlb) and marshalling code. + +#include "olectl.h" +import "oaidl.idl"; +import "ocidl.idl"; + + +interface IEPlotSection; +interface IEPlotSections; +interface ISLNKEvent; +interface IBoundingBox; +interface IDWGPoint; +//interface IChild; +//interface ISubChild; + +[ + object, + uuid(3C57EFD2-B1A1-4B70-A6B2-14D05401F458), + dual, + nonextensible, + helpstring("IDWFFile Interface"), + pointer_default(unique) +] +interface IDWFFile : IDispatch{ + [id(1), helpstring("method Open")] HRESULT Open(BSTR DWFPath); + [propget, id(9), helpstring("property PropertiesXML")] HRESULT PropertiesXML([out, retval] BSTR* pVal); + [propget, id(10), helpstring("property EPlotSections")] HRESULT EPlotSections([out,retval] IEPlotSections **ppEPlotSections); +}; +[ + object, + uuid(B0C6AC9F-3D1E-4489-9CE9-436A220ED12F), + dual, + nonextensible, + helpstring("IWhipFile Interface"), + pointer_default(unique) +] +interface IWhipFile : IDispatch{ + [id(1), helpstring("method Load")] HRESULT Load([in] BSTR WhipPath); + [id(2), helpstring("method LoadStream")] HRESULT LoadStream([in] VARIANT EPlotStream); + [id(3), helpstring("method SaveAs")] HRESULT SaveAs([in] BSTR WhipPath); + [id(4), helpstring("method SetLabel")] HRESULT SetLabel([in] BSTR IdentLabel, [in] BSTR ExtraLabel); + [id(5), helpstring("method SetColor")] HRESULT SetColor([in] BSTR IdentLabel, [in] ULONG rgb, [in, defaultvalue(0)] BYTE Alpha); + [id(8), helpstring("method SetLabelFont")] HRESULT SetLabelFont([in] BSTR FontName, [in] DOUBLE FontHeight, [in, defaultvalue(0)] DOUBLE FontHeightSymbols); + [id(9), helpstring("method SetLabelPosition")] HRESULT SetLabelPosition([in, defaultvalue(1)] BYTE LabelPos); + [propget, id(10), helpstring("method ContoursXML")] HRESULT ContoursXML([out, retval] BSTR* pVal); + [id(12), helpstring("method SetLayers")] HRESULT SetLayers([in] BSTR reContouren, [in] BSTR reLabels); + [propget, id(14), helpstring("property AddSymbol")] HRESULT AddSymbol([in] DOUBLE dwgX, [in] DOUBLE dwgY, BSTR symbolName, [out, retval] IUnknown** pVal); + [id(15), helpstring("method DefineSymbol")] HRESULT DefineSymbol([in] BSTR symbolName, [in] VARIANT EPlotStream); + [id(16), helpstring("method DefineBitmapSymbol")] HRESULT DefineBitmapSymbol([in] BSTR symbolName, [in] BSTR symbolPath, [in] DOUBLE height); + [propget, id(17), helpstring("property Contour")] HRESULT Contour([in] BSTR IdentLabel, [out, retval] IUnknown** pVal); + [id(18), helpstring("method SetFilterLayers")] HRESULT SetFilterLayers([in] BSTR reLayers); + [propget, id(19), helpstring("property hintScale")] HRESULT hintScale([out, retval] DOUBLE* pVal); + [propput, id(19), helpstring("property hintScale")] HRESULT hintScale([in] DOUBLE newVal); + [propget, id(20), helpstring("property FindInContour")] HRESULT FindInContour([in] DOUBLE dwgX, [in] DOUBLE dwgY, [out, retval] BSTR* pVal); +}; +[ + object, + uuid(FB9CAA9B-CA0A-4BF0-AA2C-47579BEFA214), + dual, + nonextensible, + helpstring("IWhip2PNG Interface"), + pointer_default(unique) +] +interface IWhip2PNG : IDispatch{ + [id(1), helpstring("method Load")] HRESULT Load([in] BSTR WhipPath); + [id(2), helpstring("method SaveAsPng")] HRESULT SaveAsPNG([in] BSTR PNGPath); + [id(3), helpstring("method SaveAsWMF")] HRESULT SaveAsWMF([in] BSTR WMFPath); + [id(4), helpstring("method Find")] HRESULT Find([in] LONG findX, [in] LONG findY, [out, retval] BSTR* foundLabel); + [id(5), helpstring("method SetDimensions")] HRESULT SetDimensions([in] LONG sizeX, + [in] LONG sizeY, [in] LONG offsetX, [in] LONG offsetY, [in] DOUBLE dScale, [in, defaultvalue(0)] LONG lRotation); + [id(6), helpstring("method GetAsMap")] HRESULT GetAsMap( [out, retval] BSTR* AsMap); +// [id(7), helpstring("method FindCoords")] HRESULT FindCoords([in] LONG findX, [in] LONG findY, [out] VARIANT* dwgX, [out] VARIANT* dwgY); + [propget, id(8), helpstring("property AtlRegExp")] HRESULT AtlRegExp([in] BSTR RegExp, [in] BSTR TestExp, [out, retval] BSTR* pVal); + [id(9), helpstring("method TextAsPNG")] HRESULT TextAsPNG(BSTR Message, [out, retval] VARIANT *ImageData); + [id(10), helpstring("property GetAsPNG")] HRESULT GetAsPNG([out, retval] VARIANT *ImageData); + [id(11), helpstring("property GetAsTransGIF")] HRESULT GetAsTransGIF([out, retval] VARIANT *ImageData); + [id(12), helpstring("method LoadStream")] HRESULT LoadStream([in] VARIANT DWFStream); + [id(13), helpstring("method SetLayers")] HRESULT SetLayers([in] BSTR RegExp); + [propget, id(14), helpstring("property forceBW2")] HRESULT forceBW([out, retval] VARIANT_BOOL* pVal); + [propput, id(14), helpstring("property forceBW2")] HRESULT forceBW([in] VARIANT_BOOL newVal); + [propget, id(15), helpstring("property SLNKEvent")] HRESULT SLNKEvent([out, retval] ISLNKEvent** pVal); + [propget, id(16), helpstring("property paperColor")] HRESULT paperColor([out, retval] LONG* pVal); + [propput, id(16), helpstring("property paperColor")] HRESULT paperColor([in] LONG newVal); + [id(17), helpstring("method ReplaceColor")] HRESULT ReplaceColor([in] LONG paperColor, [in] LONG oldColor, [in] LONG newColor); + [propget, id(18), helpstring("property Maximize")] HRESULT Maximize([out, retval] VARIANT_BOOL* pVal); + [propput, id(18), helpstring("property Maximize")] HRESULT Maximize([in] VARIANT_BOOL newVal); + [propget, id(19), helpstring("property dwgScale")] HRESULT dwgScale([out, retval] DOUBLE* pVal); + [propput, id(19), helpstring("property dwgScale")] HRESULT dwgScale([in] DOUBLE newVal); + [propget, id(21), helpstring("property forceGray")] HRESULT forceGray([out, retval] VARIANT_BOOL* pVal); + [propput, id(21), helpstring("property forceGray")] HRESULT forceGray([in] VARIANT_BOOL newVal); +}; +[ + object, + uuid(68FBB9BF-FD4C-42D4-9670-459CCF7480BE), + dual, + nonextensible, + helpstring("IAbout Interface"), + pointer_default(unique) +] +interface IAbout : IDispatch{ + [propget, id(1), helpstring("property All")] HRESULT All([out, retval] BSTR* pVal); + [propget, id(2), helpstring("property DLLPath")] HRESULT DLLPath([out, retval] BSTR* pVal); + [propget, id(3), helpstring("property Buildtime")] HRESULT Buildtime([out, retval] BSTR* pVal); + [propget, id(4), helpstring("property UserContext")] HRESULT UserContext([out, retval] BSTR* pVal); + [propget, id(5), helpstring("property VersionMajor")] HRESULT VersionMajor([out, retval] LONG* pVal); + [propget, id(6), helpstring("property VersionMinor")] HRESULT VersionMinor([out, retval] LONG* pVal); + [propget, id(7), helpstring("property VersionString")] HRESULT VersionString([out, retval] BSTR* pVal); +}; +[ + object, + uuid(99560CEF-C2CE-4CB3-AE7F-6AD6CE72CC97), + dual, + nonextensible, + helpstring("IEPlotSection Interface"), + pointer_default(unique) +] +interface IEPlotSection : IDispatch{ +// [id(1), helpstring("method Init"),hidden] HRESULT Init([in] long *ptr); +// [id(2), helpstring("method GetEPlotSection"),hidden] HRESULT GetEPlotSection([out] long **ptr); + [propget, helpstring("My Parent")] HRESULT Parent([out, retval] IEPlotSections **ppParent); + [propget, id(3), helpstring("property Name")] HRESULT Name([out, retval] BSTR* pVal); + [propget, id(4), helpstring("property Title")] HRESULT Title([out, retval] BSTR* pVal); + [local] + [id(6), helpstring("method Read")] HRESULT + Read([out, size_is(cb), length_is(*pcbRead)]void *pv, [in]ULONG cb, [out]ULONG *pcbRead); + [local] + [id(7), helpstring("method Write")] HRESULT + Write([in, size_is(cb)] const void *pv, [in]ULONG cb, [out]ULONG *pcbWritten); + [propget, id(8), helpstring("property PaperColor")] HRESULT PaperColor([out, retval] ULONG* pVal); + [id(9), helpstring("method Open")] HRESULT Open([in]BOOL bForWrite); + [id(10), helpstring("method Close")] HRESULT Close(void); + [propget, id(11), helpstring("property SourceDescription")] HRESULT SourceDescription([out, retval] BSTR* pVal); + [propget, id(12), helpstring("property PropertiesXML")] HRESULT PropertiesXML([out, retval] BSTR* pVal); + [propget, id(13), helpstring("property PaperClipWidth")] HRESULT PaperClipWidth([out, retval] DOUBLE* pVal); + [propget, id(14), helpstring("property EPlotSectionImpl"), hidden] HRESULT EPlotSectionImpl([out, retval] /*CEPlotSectionImpl*/BYTE ** pVal); + [propput, id(14), helpstring("property EPlotSectionImpl"), hidden] HRESULT EPlotSectionImpl([in] /*CEPlotSectionImpl*/ BYTE * newVal); +}; +[ + object, + uuid(32292BE4-2ACB-4BDD-AF3C-DF91ADD4EF36), + dual, + nonextensible, + helpstring("IEPlotSections Interface"), + pointer_default(unique) +] +interface IEPlotSections : IDispatch{ + [propget, helpstring("My Parent")] HRESULT Parent([out, retval] IDWFFile **ppParent); + [propget, id(1), helpstring("property Count")] HRESULT Count([out, retval] LONG* pVal); + [propget, id(2), helpstring("property Item")] HRESULT Item([in] LONG i, [out, retval] IDispatch** pVal); +}; +[ + object, + uuid(BA3EEF9F-BEB1-4478-870B-3E274AF8506A), + dual, + nonextensible, + helpstring("ISLNKEvent Interface"), + pointer_default(unique) +] +interface ISLNKEvent : IDispatch{ + [propget, id(1), helpstring("property DwgX")] HRESULT DwgX([out, retval] DOUBLE* pVal); + [propput, id(1), helpstring("property DwgX")] HRESULT DwgX([in] DOUBLE newVal); + [propget, id(2), helpstring("property DwgY")] HRESULT DwgY([out, retval] DOUBLE* pVal); + [propput, id(2), helpstring("property DwgY")] HRESULT DwgY([in] DOUBLE newVal); + [propget, id(7), helpstring("property ContourLabel")] HRESULT ContourLabel([out, retval] BSTR* pVal); + [propput, id(7), helpstring("property ContourLabel")] HRESULT ContourLabel([in] BSTR newVal); + [propget, id(8), helpstring("property ContourLayer")] HRESULT ContourLayer([out, retval] BSTR* pVal); + [propput, id(8), helpstring("property ContourLayer")] HRESULT ContourLayer([in] BSTR newVal); + [propget, id(9), helpstring("property TextLabel")] HRESULT TextLabel([out, retval] BSTR* pVal); + [propput, id(9), helpstring("property TextLabel")] HRESULT TextLabel([in] BSTR newVal); + [propget, id(10), helpstring("property TextLayer")] HRESULT TextLayer([out, retval] BSTR* pVal); + [propput, id(10), helpstring("property TextLayer")] HRESULT TextLayer([in] BSTR newVal); + [propget, id(11), helpstring("property found")] HRESULT found([out, retval] IDWGPoint** pVal); + [propget, id(12), helpstring("property dwgExtents")] HRESULT dwgExtents([out, retval] IBoundingBox** pVal); + [propget, id(13), helpstring("property viewExtents")] HRESULT viewExtents([out, retval] IBoundingBox** pVal); +}; +[ + object, + uuid(102FE53F-3C9A-47C6-9BAD-1434838FF53D), + dual, + nonextensible, + helpstring("IBoundingBox Interface"), + pointer_default(unique) +] +interface IBoundingBox : IDispatch{ + [propget, id(1), helpstring("property min")] HRESULT min([out, retval] IDWGPoint** pVal); + [propget, id(2), helpstring("property max")] HRESULT max([out, retval] IDWGPoint** pVal); +}; +[ + object, + uuid(C5678016-EF7B-4476-966E-8AFD4514DB2A), + dual, + nonextensible, + helpstring("IDWGPoint Interface"), + pointer_default(unique) +] +interface IDWGPoint : IDispatch{ + [propget, id(1), helpstring("property DwgX")] HRESULT DwgX([out, retval] DOUBLE* pVal); + [propput, id(1), helpstring("property DwgX")] HRESULT DwgX([in] DOUBLE newVal); + [propget, id(2), helpstring("property DwgY")] HRESULT DwgY([out, retval] DOUBLE* pVal); + [propput, id(2), helpstring("property DwgY")] HRESULT DwgY([in] DOUBLE newVal); +}; +[ + object, + uuid(A505B2D9-4D41-411F-B2A7-B297AA399278), + dual, + nonextensible, + helpstring("ISLNKContour Interface"), + pointer_default(unique) +] +interface ISLNKContour : IDispatch{ + [id(2), helpstring("method SetColor")] HRESULT SetColor([in] ULONG rgb, [in, defaultvalue(0)] BYTE Alpha); + [id(3), helpstring("method SetUrl")] HRESULT SetUrl([in] BSTR Url, [in] BSTR FriendlyName); + [propget, id(5), helpstring("property Area")] HRESULT Area([out, retval] DOUBLE* pVal); + [propget, id(6), helpstring("property Extents")] HRESULT Extents([out, retval] IBoundingBox ** pVal); + [propget, id(7), helpstring("property Center")] HRESULT Center([out, retval] IDWGPoint** pVal); + [propget, id(8), helpstring("property Key")] HRESULT Key([out, retval] BSTR* pVal); + [propput, id(8), helpstring("property Key")] HRESULT Key([in] BSTR newVal); + [propget, id(9), helpstring("property Label")] HRESULT Label([out, retval] BSTR* pVal); + [propput, id(9), helpstring("property Label")] HRESULT Label([in] BSTR newVal); + [propget, id(10), helpstring("property Hatch")] HRESULT Hatch([out, retval] BYTE* pVal); + [propput, id(10), helpstring("property Hatch")] HRESULT Hatch([in] BYTE newVal); +}; +[ + object, + uuid(FE75E3AB-5047-4CB6-A910-FF3156CB7946), + dual, + nonextensible, + helpstring("ISLNKSymbol Interface"), + pointer_default(unique) +] +interface ISLNKSymbol : IDispatch{ + [propget, id(2), helpstring("property Scale")] HRESULT Scale([out, retval] DOUBLE* pVal); + [propput, id(2), helpstring("property Scale")] HRESULT Scale([in] DOUBLE newVal); + [propget, id(3), helpstring("property Rotation")] HRESULT Rotation([out, retval] LONG* pVal); + [propput, id(3), helpstring("property Rotation")] HRESULT Rotation([in] LONG newVal); + [propget, id(4), helpstring("property Contour")] HRESULT Contour([out, retval] IUnknown** pVal); +}; +[ + object, + uuid(FC848365-3C85-490D-8CC0-DB66D73FA34E), + dual, + nonextensible, + helpstring("IOptions Interface"), + pointer_default(unique) +] +interface IOptions : IDispatch{ + [id(1), helpstring("method SetOption")] HRESULT SetOption([in] BSTR optionName, VARIANT OptionValue); +}; +[ + uuid(B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8), + version(1.0), + helpstring("SLNKDWF 1.0 Type Library") +] +library SLNKDWFLib +{ + importlib("stdole2.tlb"); + [ + uuid(BE2BCD58-4971-49E6-9A70-CDDD5C01224D), + helpstring("DWFFile Class") + ] + coclass myDWFFile + { + [default] interface IDWFFile; + }; + [ + uuid(C2632BD5-3157-45A6-8FFC-57063FF2B169), + helpstring("WhipFile Class") + ] + coclass WhipFile + { + [default] interface IWhipFile; + }; + [ + uuid(783AC7F0-E6E1-4CE1-A38B-FA047D44DC1C), + helpstring("Whip2PNG Class") + ] + coclass Whip2PNG + { + [default] interface IWhip2PNG; + }; + [ + uuid(2BA64B82-1A96-4F15-9815-40B291B505EB), + helpstring("About Class") + ] + coclass About + { + [default] interface IAbout; + }; + [ + uuid(F2599AE6-8A08-4B5E-9C68-BD975229F0D1), + helpstring("EPlotSection Class"), + noncreatable + ] + coclass EPlotSection + { + [default] interface IEPlotSection; + }; + [ + uuid(7B2E7661-9B9A-4217-A19E-745EFFF8E86D), + helpstring("EPlotSections Class"), + noncreatable + ] + coclass EPlotSections + { + [default] interface IEPlotSections; + }; + [ + uuid(F7226C2D-B5C7-4C72-AA43-6D5013EF7C96), + helpstring("SLNKEvent Class"), + noncreatable + ] + coclass SLNKEvent + { + [default] interface ISLNKEvent; + }; + [ + uuid(FCEF1E56-36FF-4F66-BEA5-FD08D860524F), + helpstring("BoundingBox Class"), + noncreatable + ] + coclass BoundingBox + { + [default] interface IBoundingBox; + }; + [ + uuid(96301A8D-1DC9-4900-B89D-C745C4CAEFF4), + helpstring("DWGPoint Class"), + noncreatable + ] + coclass DWGPoint + { + [default] interface IDWGPoint; + }; + [ + uuid(476C0F28-5860-485D-BEBD-D03F68E1C930), + helpstring("SLNKContour Class"), + noncreatable + ] + coclass SLNKContour + { + [default] interface ISLNKContour; + }; + [ + uuid(8CEBC89F-658A-49C8-96E4-852FFFA9B10F), + helpstring("SLNKSymbol Class"), + noncreatable + ] + coclass SLNKSymbol + { + [default] interface ISLNKSymbol; + }; + [ + uuid(168678A9-6FA7-49C3-B839-DFDF07E0A79A), + helpstring("Options Class") + ] + coclass Options + { + [default] interface IOptions; + }; +}; diff --git a/SlnkDWFCom/SLNKDWF.rgs b/SlnkDWFCom/SLNKDWF.rgs new file mode 100644 index 0000000..f191d93 --- /dev/null +++ b/SlnkDWFCom/SLNKDWF.rgs @@ -0,0 +1,11 @@ +HKCR +{ + NoRemove AppID + { + '%APPID%' = s 'SLNKDWF' + 'SLNKDWF.DLL' + { + val AppID = s '%APPID%' + } + } +} diff --git a/SlnkDWFCom/SLNKDWF.vcproj b/SlnkDWFCom/SLNKDWF.vcproj new file mode 100644 index 0000000..1fabce8 --- /dev/null +++ b/SlnkDWFCom/SLNKDWF.vcproj @@ -0,0 +1,533 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFCom/SLNKDWFVersion.h b/SlnkDWFCom/SLNKDWFVersion.h new file mode 100644 index 0000000..fb73747 --- /dev/null +++ b/SlnkDWFCom/SLNKDWFVersion.h @@ -0,0 +1,18 @@ +// Zorg dat versies alfabetisch altijd op elkaar volgen! +#define SLNK_MAJOR_VERSION 2 +#define SLNK_MINOR_VERSION 00 +#define SLNK_BUILD_VERSION 0 + +// Define resource strings +#define ECHO(a) #a +#define STRINGIZE_SLNK_BUILD(major, minor, build) ECHO(major) "," ECHO(minor) ",0," ECHO(build) +#define STRINGIZE_SLNK_FULL(major, minor) ECHO(major) "." ECHO(minor) + +// Deze wordt gebruikt in SLNKDWF.RC2 en eindigt in Version Tab van de properties +// Daar conformeren we aan de standaard(?) +#define SLNK_BUILDVERSION STRINGIZE_SLNK_BUILD(SLNK_MAJOR_VERSION, SLNK_MINOR_VERSION, SLNK_BUILD_VERSION) + +// Deze wordt in splashscherm getoond en in About-scherm +// Bovendien wordt DonShowSplashVersion hiervan afgeleid +// Ergo: Voor de eenvoud niet de BUILD_VERSION tonen aan eindgebruikers +#define SLNK_FULLVERSION STRINGIZE_SLNK_FULL(SLNK_MAJOR_VERSION, SLNK_MINOR_VERSION) diff --git a/SlnkDWFCom/SLNKEvent.cpp b/SlnkDWFCom/SLNKEvent.cpp new file mode 100644 index 0000000..737e00a --- /dev/null +++ b/SlnkDWFCom/SLNKEvent.cpp @@ -0,0 +1,95 @@ +// SLNKEvent.cpp : Implementation of CSLNKEvent + +#include "stdafx.h" +#include "SLNKEvent.h" + + +// CSLNKEvent + + +STDMETHODIMP CSLNKEvent::get_DwgX(DOUBLE* pVal) +{ + (*pVal) = m_DwgX; + return S_OK; +} + +STDMETHODIMP CSLNKEvent::put_DwgX(DOUBLE newVal) +{ + m_DwgX = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKEvent::get_DwgY(DOUBLE* pVal) +{ + (*pVal) = m_DwgY; + return S_OK; +} + +STDMETHODIMP CSLNKEvent::put_DwgY(DOUBLE newVal) +{ + m_DwgY = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKEvent::get_ContourLabel(BSTR* pVal) +{ + CComBSTR bstrString(m_ContourLabel); + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CSLNKEvent::put_ContourLabel(BSTR newVal) +{ + m_ContourLabel = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKEvent::get_ContourLayer(BSTR* pVal) +{ + CComBSTR bstrString(m_ContourLayer); + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CSLNKEvent::put_ContourLayer(BSTR newVal) +{ + m_ContourLayer = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKEvent::get_TextLabel(BSTR* pVal) +{ + CComBSTR bstrString(m_TextLabel); + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CSLNKEvent::put_TextLabel(BSTR newVal) +{ + m_TextLabel = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKEvent::get_TextLayer(BSTR* pVal) +{ + CComBSTR bstrString(m_TextLayer); + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CSLNKEvent::put_TextLayer(BSTR newVal) +{ + m_TextLayer = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKEvent::get_found(IDWGPoint** pVal) +{ + return S_OK; +} + +STDMETHODIMP CSLNKEvent::get_dwgExtents(IBoundingBox** pVal) +{ + return m_dwgBounding->QueryInterface(IID_IBoundingBox, (void**)pVal); +} + +STDMETHODIMP CSLNKEvent::get_viewExtents(IBoundingBox** pVal) +{ + return m_viewBounding->QueryInterface(IID_IBoundingBox, (void**)pVal); +} diff --git a/SlnkDWFCom/SLNKEvent.h b/SlnkDWFCom/SLNKEvent.h new file mode 100644 index 0000000..3e5e7df --- /dev/null +++ b/SlnkDWFCom/SLNKEvent.h @@ -0,0 +1,93 @@ +// SLNKEvent.h : Declaration of the CSLNKEvent + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" +#include "BoundingBox.h" + + +// CSLNKEvent + +class ATL_NO_VTABLE CSLNKEvent : + public CComObjectRootEx, + public CComCoClass, + public IDispatchImpl +{ +public: + CSLNKEvent() + { + } + +//REMOVED DECLARE_REGISTRY_RESOURCEID(IDR_SLNKEVENT) + + +BEGIN_COM_MAP(CSLNKEvent) + COM_INTERFACE_ENTRY(ISLNKEvent) + COM_INTERFACE_ENTRY(IDispatch) +END_COM_MAP() + + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + // + // Maak object m_dwgBounding + // + CComObject *pBoundingBox; + HRESULT hr = CComObject::CreateInstance(&pBoundingBox); + if(FAILED(hr)) return hr; + + pBoundingBox->AddRef(); + hr = pBoundingBox->QueryInterface(IID_IBoundingBox, (void **)&m_dwgBounding); + pBoundingBox->Release(); + if(FAILED(hr)) return hr; + + // + // Maak object m_viewBounding + // + hr = CComObject::CreateInstance(&pBoundingBox); + if(FAILED(hr)) return hr; + + pBoundingBox->AddRef(); + hr = pBoundingBox->QueryInterface(IID_IBoundingBox, (void **)&m_viewBounding); + pBoundingBox->Release(); + if(FAILED(hr)) return hr; + + return S_OK; + } + + void FinalRelease() + { + } + +private: + CComQIPtr m_dwgBounding; + CComQIPtr m_viewBounding; + + double m_DwgX, m_DwgY; + double m_minDwgX, m_maxDwgY; + double m_maxDwgX, m_minDwgY; + CString m_ContourLabel, m_ContourLayer; + CString m_TextLabel, m_TextLayer; +public: + + STDMETHOD(get_DwgX)(DOUBLE* pVal); + STDMETHOD(put_DwgX)(DOUBLE newVal); + STDMETHOD(get_DwgY)(DOUBLE* pVal); + STDMETHOD(put_DwgY)(DOUBLE newVal); + STDMETHOD(get_ContourLabel)(BSTR* pVal); + STDMETHOD(put_ContourLabel)(BSTR newVal); + STDMETHOD(get_ContourLayer)(BSTR* pVal); + STDMETHOD(put_ContourLayer)(BSTR newVal); + STDMETHOD(get_TextLabel)(BSTR* pVal); + STDMETHOD(put_TextLabel)(BSTR newVal); + STDMETHOD(get_TextLayer)(BSTR* pVal); + STDMETHOD(put_TextLayer)(BSTR newVal); + STDMETHOD(get_found)(IDWGPoint** pVal); + STDMETHOD(get_dwgExtents)(IBoundingBox** pVal); + STDMETHOD(get_viewExtents)(IBoundingBox** pVal); +}; + +//REMOVED OBJECT_ENTRY_AUTO(__uuidof(SLNKEvent), CSLNKEvent) diff --git a/SlnkDWFCom/SLNKEvent.rgs b/SlnkDWFCom/SLNKEvent.rgs new file mode 100644 index 0000000..d99bbea --- /dev/null +++ b/SlnkDWFCom/SLNKEvent.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.SLNKEvent.1 = s 'SLNKEvent Class' + { + CLSID = s '{F7226C2D-B5C7-4C72-AA43-6D5013EF7C96}' + } + SLNKDWF.SLNKEvent = s 'SLNKEvent Class' + { + CLSID = s '{F7226C2D-B5C7-4C72-AA43-6D5013EF7C96}' + CurVer = s 'SLNKDWF.SLNKEvent.1' + } + NoRemove CLSID + { + ForceRemove {F7226C2D-B5C7-4C72-AA43-6D5013EF7C96} = s 'SLNKEvent Class' + { + ProgID = s 'SLNKDWF.SLNKEvent.1' + VersionIndependentProgID = s 'SLNKDWF.SLNKEvent' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/SLNKSymbol.cpp b/SlnkDWFCom/SLNKSymbol.cpp new file mode 100644 index 0000000..49ab0e5 --- /dev/null +++ b/SlnkDWFCom/SLNKSymbol.cpp @@ -0,0 +1,75 @@ +// SLNKSymbol.cpp : Implementation of CSLNKSymbol + +#include "stdafx.h" +#include "SLNKSymbol.h" +#include "SLNKContour.h" + +// CSLNKSymbol + +STDMETHODIMP CSLNKSymbol::InterfaceSupportsErrorInfo(REFIID riid) +{ + static const IID* arr[] = + { + &IID_IWhipFile + }; + + for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) + { + if (InlineIsEqualGUID(*arr[i],riid)) + return S_OK; + } + return S_FALSE; +} + + +void CSLNKSymbol::SetImpl(CSLNKSymbolImpl * pSLNKSymbol) +{ + m_SLNKSymbol = pSLNKSymbol; +} + +STDMETHODIMP CSLNKSymbol::get_Scale(DOUBLE* pVal) +{ + (*pVal) = m_SLNKSymbol->m_Scale; + return S_OK; +} + +STDMETHODIMP CSLNKSymbol::put_Scale(DOUBLE newVal) +{ + m_SLNKSymbol->m_Scale = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKSymbol::get_Rotation(LONG* pVal) +{ + (*pVal) = m_SLNKSymbol->m_Rotation; + return S_OK; +} + +STDMETHODIMP CSLNKSymbol::put_Rotation(LONG newVal) +{ + long rotation = (newVal%360+360)%360; // Normaliseren + if (rotation%90 != 0) + return myAtlReportError (GetObjectCLSID(), "ERROR Symbol rotation must be 0/90/180/270."); + + m_SLNKSymbol->m_Rotation = newVal; + return S_OK; +} + +STDMETHODIMP CSLNKSymbol::get_Contour(IUnknown** pVal) +{ + CSLNKContourImpl *contour= &m_SLNKSymbol->m_SLNKContour; + + CComObject *theContour; + HRESULT hr = CComObject::CreateInstance(&theContour); + if(FAILED(hr)) return hr; + + theContour->AddRef(); + hr = theContour->QueryInterface(IID_ISLNKContour, (void **)pVal); + if(FAILED(hr)) return hr; + + theContour->SetParent(m_parent_iWhipFile); // Zelfde parent maar + theContour->Release(); + theContour->SetImpl(contour); // Heel belangrijk: zet de implementatie waar we een interface op bieden + + return S_OK; +} diff --git a/SlnkDWFCom/SLNKSymbol.rgs b/SlnkDWFCom/SLNKSymbol.rgs new file mode 100644 index 0000000..0f4b5e0 --- /dev/null +++ b/SlnkDWFCom/SLNKSymbol.rgs @@ -0,0 +1,26 @@ +HKCR +{ + SLNKDWFCom.SLNKSymbol.1 = s 'SLNKSymbol Class' + { + CLSID = s '{8CEBC89F-658A-49C8-96E4-852FFFA9B10F}' + } + SLNKDWFCom.SLNKSymbol = s 'SLNKSymbol Class' + { + CLSID = s '{8CEBC89F-658A-49C8-96E4-852FFFA9B10F}' + CurVer = s 'SLNKDWFCom.SLNKSymbol.1' + } + NoRemove CLSID + { + ForceRemove {8CEBC89F-658A-49C8-96E4-852FFFA9B10F} = s 'SLNKSymbol Class' + { + ProgID = s 'SLNKDWFCom.SLNKSymbol.1' + VersionIndependentProgID = s 'SLNKDWFCom.SLNKSymbol' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/SLNKSymbolDefImpl.cpp b/SlnkDWFCom/SLNKSymbolDefImpl.cpp new file mode 100644 index 0000000..6a61566 --- /dev/null +++ b/SlnkDWFCom/SLNKSymbolDefImpl.cpp @@ -0,0 +1,427 @@ +#include "StdAfx.h" +#include "myEPlotSection.h" +#include "SLNKSymbolDefImpl.h" +#include "../SLNKDWFImpl/CxImage\CxImage\ximage.h" +#include "../SLNKDWFImpl/Whip2DCImpl.h" +#include "SLNKContourImpl.h" +#include + +// Bij EPlotsection (external DWF) +CSLNKSymbolDefinition::CSLNKSymbolDefinition(CComQIPtr EPlotSection) +{ + m_iEPlotSection = EPlotSection; + + CEPlotSectionImpl *epli; + m_iEPlotSection->get_EPlotSectionImpl((BYTE **)&epli); + m_wtFile.set_eplotsection(epli); + m_AsBitmap = NULL; + m_BuiltIn = false; + calculateBoundary(); +}; + +// Bij Contour list (builtin symbol) +CSLNKSymbolDefinition::CSLNKSymbolDefinition(int count, WT_Logical_Point const *points) +{ + m_BuiltIn = true; + m_wtFile.set_eplotsection(NULL); + this->m_dwgScale = 1.0; + m_AsBitmap = NULL; + m_BoundingContour.set(count, points, false); + m_Origin = CSLNKContourImpl::Centroid(m_BoundingContour); +}; + +// By bitmap +CSLNKSymbolDefinition::CSLNKSymbolDefinition(CString const filepath, double const height) +{ + m_wtFile.set_eplotsection(NULL); + m_AsBitmap = NULL; + m_BuiltIn = false; + CxImage img; + if (!img.Load(filepath)) + { // Rood kruisje? + img.Create(32, 32, 24); + img.Clear(255); // Wit + img.DrawLine(0,31,0,31,RGB(255,0,0)); + img.DrawLine(0,31,31,0,RGB(255,0,0)); + }; + BYTE *m_Buffer=NULL; + long m_size; + img.Encode(m_Buffer, m_size, CXIMAGE_FORMAT_PNG); + + this->m_dwgScale = (double)img.GetHeight()/ height; + + //myDoTRACE("\nCreates symbol bitmap (%d,%d)->PNG %d byte (W2D was %d)", pixeldx,pixeldy,m_size, epli->size()); + + m_AsBitmap = new + WT_PNG_Group4_Image( + (int)img.GetHeight(), /*rows*/ + (int)img.GetWidth(), /*cols*/ + WT_PNG_Group4_Image::PNG, + 3, + NULL, + m_size, + (WT_Byte*)m_Buffer, + WT_Logical_Point(0,0), + WT_Logical_Point(img.GetWidth(),img.GetHeight()), + WD_False); // Geen copy, we verwijderen zelf expliciet + + WT_Logical_Point pts4[4] = { WT_Logical_Point(0, 0), + WT_Logical_Point(img.GetWidth(), 0), + WT_Logical_Point(img.GetWidth(), img.GetHeight()), + WT_Logical_Point(0, img.GetHeight())}; + m_BoundingContour.set(4, pts4, true); + m_Origin = CSLNKContourImpl::Centroid(m_BoundingContour); +}; + +CSLNKSymbolDefinition::~CSLNKSymbolDefinition(void) +{ + if (m_AsBitmap) + { + CxImage xx;xx.FreeMemory((void *)m_AsBitmap->data()); // We hebben een copy gedaan dus dit mag/moet + delete m_AsBitmap; + } +} + +// Bepaal een bounding contour van ons symbool. Die is eventueel later leuk te gebruiken voor een HitTest +// v0: bounding box +// v1: bounding octagon +// Algoritm: search google for Bounding Octagon +// http://geometryalgorithms.com/Archive/algorithm_0107/algorithm_0107.htm +// (v2: bounding convex hull waarschijnlijk overkill) +#include +WT_Result CSLNKSymbolDefinition::calculateBoundary () +{ + WT_Result result; + + m_wtFile.set_file_mode(WT_File::File_Read); + result = m_wtFile.open(); + if (result != WT_Result::Success) + return result; + + // Door de enorm grote dwf-coordinaten lopen we een integer overflow risico tijdens + // onze bepaling van Pmin en Pmax (die min en max van x+y bepalen) en in theorie + // ook van Qmin en Qmax (die over het verschil x-y gaan) hoewel dat in de praktijk rond 0 zal liggen + // Daarom rekenen we systematisch met de helft. Dat moet risico's voorkomen en de afrondfout nemen + // we voor lief + // Merk op dat de resulterende Octagon kleiner is dan de de bounding box, die zeker binnen de coordinaat + // ruimte valt dus voor het eindresultaat is er geen risico. Alleen oppassen voor tussenresultaten dus + // Ging concreet mis met 41610ev_symbols.dwf + WT_Integer32 Xmin, Xmax, Ymin, Ymax; + WT_Integer32 Pmin2, Pmax2, Qmin2, Qmax2; + // Signal invalid + Xmin = Ymin = Pmin2 = Qmin2 = INT_MAX; + Xmax = Ymax = Pmax2 = Qmax2 = INT_MIN; + + BOOL ViewportDone = FALSE; // We doen alleen de eerste viewport. + // Gaf problemen bij symbolen die vanuit paperspace waren geexporteerd + // Do the actual reading. + while ((result = m_wtFile.process_next_object()) == WT_Result::Success) + { + //myTRACE("Attribute '%s'\n", wtFile->file_stats()->descriptions()); + switch(m_wtFile.current_object()->object_type()) + { + case WT_Object::Attribute: + { + const WT_Attribute *obj = (WT_Attribute *)m_wtFile.current_object(); + if (obj->object_id() == WT_Object::Viewport_ID) + { + if (ViewportDone) + { + myTRACE("\nSkipping second viewport in symbol"); + break; + } + ViewportDone = TRUE; + WT_Viewport *viewport = (WT_Viewport *)m_wtFile.current_object(); + WT_Units symbolunits = viewport->viewport_units(); + m_dwgScale = symbolunits.application_to_dwf_transform()(0,0); // Symbol's dScale + break; + } + break; + } + case WT_Object::Drawable: + { + WT_Drawable *obj = (WT_Drawable *)m_wtFile.current_object(); + if (obj->object_id() != WT_Object::Origin_ID)// Belachelijk dat die Drawable is? + { + WT_Logical_Box bx = obj->bounds(&m_wtFile); + Xmin = min(Xmin, bx.minpt().m_x); + Ymin = min(Ymin, bx.minpt().m_y); + Xmax = max(Xmax, bx.maxpt().m_x); + Ymax = max(Ymax, bx.maxpt().m_y); + + // Voor echte (deel)cirkels gaan we de diagonaal bounding box scherper berekenen + if (obj->object_id() == WT_Object::Outline_Ellipse_ID || obj->object_id() == WT_Object::Filled_Ellipse_ID) + { + WT_Ellipse *elp = (WT_Ellipse *)obj; + if (elp->minor() == elp->major()) // Anders te ingewikkeld + { // Bepaal het ingeschreven vierkant van de cirkel + WT_Integer32 dr = myRound(elp->minor() / sqrt(2.0) + 0.5); // Altijd omhoog afronden + WT_Logical_Box bx2; + bx2.minpt() = WT_Logical_Point(elp->position().m_x - dr, elp->position().m_y - dr); + bx2.maxpt() = WT_Logical_Point(elp->position().m_x + dr, elp->position().m_y + dr); + // Houdt er wel rekening mee dat bij partiele cirkels het origineel scherper kan + // zijn omdat wij er geen rekening houden dat de cirkel misschien partieel is + Pmin2 = min(Pmin2, max(bx.minpt().m_x/2 + bx.minpt().m_y/2,bx2.minpt().m_x/2 + bx2.minpt().m_y/2)); // Linksonder + Qmax2 = max(Qmax2, min(bx.maxpt().m_x/2 - bx.minpt().m_y/2,bx2.maxpt().m_x/2 - bx2.minpt().m_y/2)); // Rechtsonder + Pmax2 = max(Pmax2, min(bx.maxpt().m_x/2 + bx.maxpt().m_y/2,bx2.maxpt().m_x/2 + bx2.maxpt().m_y/2)); // Rechtsboven + Qmin2 = min(Qmin2, max(bx.minpt().m_x/2 - bx.maxpt().m_y/2,bx2.minpt().m_x/2 - bx2.maxpt().m_y/2)); // Linksboven + break; + } + // else gewoon 'doorvallen' naar standaard Pmin2 etc. + } + + // Voor WT_Pointset gebaseerde objecten kunnen we het ook wel beter + if (obj->object_id() == WT_Object::Polygon_ID || + obj->object_id() == WT_Object::Polyline_ID || + obj->object_id() == WT_Object::Polytriangle_ID) + { + WT_Point_Set *pts; + // Rechtstreekse cast naar (WT_Point_Set *) gaf memory violations? + switch (obj->object_id()) + { + case WT_Object::Polygon_ID : pts = (WT_Polygon *)m_wtFile.current_object(); break; + case WT_Object::Polyline_ID : pts = (WT_Polyline *)m_wtFile.current_object(); break; + case WT_Object::Polytriangle_ID: pts = (WT_Polytriangle *)m_wtFile.current_object(); break; + } + + for (int i=0;icount(); i++) + { + WT_Logical_Point &pt = pts->points()[i]; + Pmin2 = min(Pmin2, pt.m_x/2 + pt.m_y/2); // Linksonder + Qmax2 = max(Qmax2, pt.m_x/2 - pt.m_y/2); // Rechtsonder + Pmax2 = max(Pmax2, pt.m_x/2 + pt.m_y/2); // Rechtsboven + Qmin2 = min(Qmin2, pt.m_x/2 - pt.m_y/2); // Linksboven + } + break; // we zijn wel klaar + } + + Pmin2 = min(Pmin2, bx.minpt().m_x/2 + bx.minpt().m_y/2); // Linksonder + Qmax2 = max(Qmax2, bx.maxpt().m_x/2 - bx.minpt().m_y/2); // Rechtsonder + Pmax2 = max(Pmax2, bx.maxpt().m_x/2 + bx.maxpt().m_y/2); // Rechtsboven + Qmin2 = min(Qmin2, bx.minpt().m_x/2 - bx.maxpt().m_y/2); // Linksboven + } + } + break; + default: + //myTRACE("Skipping '%s'\n", wtFile->file_stats()->descriptions()); + break; + } + } +// if (result == WT_Result::End_Of_DWF_Opcode_Found) +// dwfresult = DwfResult::Success; + + m_wtFile.close(); + + // Rechthoek +// WT_Logical_Point pts1[4] = { WT_Logical_Point(Xmin, Ymin), +// WT_Logical_Point(Xmax, Ymin), +// WT_Logical_Point(Xmax, Ymax), +// WT_Logical_Point(Xmin, Ymax)}; + m_BoundingBox = WT_Logical_Box(Xmin, Ymin, Xmax, Ymax); + + // Diamant heeft overflow risico +// WT_Logical_Point pts2[4] = { WT_Logical_Point(Pmin2+Qmin2, Pmin2-Qmin2), +// WT_Logical_Point(Pmin2+Qmax2, Pmin2-Qmax2), +// WT_Logical_Point(Pmax2+Qmax2, Pmax2-Qmax2), +// WT_Logical_Point(Pmax2+Qmin2, Pmax2-Qmin2)}; + + // Octagon + // Expressievolgorde is telkens belangrijk om overflow te voorkomen + WT_Logical_Point pts3[8] = { WT_Logical_Point(Pmin2-Ymin+Pmin2, Ymin), + WT_Logical_Point(Qmax2+Ymin+Qmax2, Ymin), + WT_Logical_Point(Xmax, Xmax-Qmax2-Qmax2), + WT_Logical_Point(Xmax, Pmax2-Xmax+Pmax2), + WT_Logical_Point(Pmax2-Ymax+Pmax2, Ymax), + WT_Logical_Point(Qmin2+Ymax+Qmin2, Ymax), + WT_Logical_Point(Xmin, Xmin-Qmin2-Qmin2), + WT_Logical_Point(Xmin, Pmin2-Xmin+Pmin2)}; + + m_BoundingContour.set(sizeof(pts3)/sizeof(pts3[0]), pts3, true); + m_Origin = CSLNKContourImpl::Centroid(m_BoundingContour); + + return result; +} + +#ifdef NO_BITMAPPEREN +WT_Drawable *CSLNKSymbolDefinition::asBitmap(int pixeldx, int pixeldy, long paperColor) +{ + if (m_AsBitmap) + { + // TODO: Wat als pixeldy != m_AsBitmap->rows() + // Dat dwfdx anders is is minder boeiend, dat verschaalt wel + WT_PNG_Group4_Image *newBitmap = new + WT_PNG_Group4_Image( + m_AsBitmap->rows(), /*rows*/ + m_AsBitmap->columns(), /*cols*/ + WT_PNG_Group4_Image::PNG, + 3, + NULL, + m_AsBitmap->data_size(), + (WT_Byte *)m_AsBitmap->data(), + m_BoundingBox.minpt(), + m_BoundingBox.maxpt(), + WD_False); // Don't copy + m_AsBitmap = newBitmap; + return m_AsBitmap; // Dan zijn we rap klaar. Dat is onze winst + } + + // Blijkbaar de eerste keer hier. Tijd om de bitmap te bakken + CWhip2DCImpl iWhip2DC; + HDC pDC = ::GetDC(0); + HDC myDC = CreateCompatibleDC(pDC); + //ReleaseDC(pDC); + CEPlotSectionImpl *epli = NULL; + m_iEPlotSection->get_EPlotSectionImpl((BYTE **)&epli); + iWhip2DC.Load(myDC, epli, + "", ".*", + myRound(pixeldx), myRound(pixeldy), + VARIANT_TRUE /*center*/, VARIANT_TRUE /*m_Maximize*/); + + BITMAPINFO bmInfo; + memset(&bmInfo.bmiHeader,0,sizeof(BITMAPINFOHEADER)); + bmInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); + bmInfo.bmiHeader.biWidth=pixeldx; + bmInfo.bmiHeader.biHeight=pixeldy; + bmInfo.bmiHeader.biPlanes=1; + bmInfo.bmiHeader.biCompression=BI_RGB; // Geen compressie + bmInfo.bmiHeader.biBitCount=24; + //create a new bitmap and select it in the memory dc + BYTE *pbase; + HBITMAP TmpBmp = CreateDIBSection(pDC, &bmInfo,DIB_RGB_COLORS,(void**)&pbase,0,0); + HGDIOBJ TmpObj=SelectObject(myDC,TmpBmp); + + iWhip2DC.put_paperColor(paperColor); // Op zich maken we hem transparant maar onze zwart/wit toggle moet wel kloppen + SUCCEEDED(iWhip2DC.Paint(VARIANT_FALSE /*m_forceBW*/)); + CxImage img; + img.CreateFromHBITMAP(TmpBmp); + + img.DecreaseBpp(8, FALSE); // Werkt averechts voor kleine plaatjes (pallette is groot?) + // Maar CxImage::Draw2 lijkt alleen te werken met palette achtergrond dus het moet maar + RGBQUAD back = {GetBValue(paperColor), // RGBQUAD is BGR!! + GetGValue(paperColor), + GetRValue(paperColor),0}; + ///RGBQUAD back = {0,0,0,0}; + img.SetTransIndex(img.GetNearestIndex(back)); +// img.SetTransColor(back); // Voor als we zonder pallette werken + + BYTE *m_Buffer=NULL; + long m_size; + img.Encode(m_Buffer, m_size, CXIMAGE_FORMAT_PNG); + myDoTRACE("\nCreates symbol bitmap (%d,%d)->PNG %d byte (W2D was %d)", pixeldx,pixeldy,m_size, epli->size()); + + DeleteObject(TmpBmp); + DeleteDC(myDC); + ReleaseDC( NULL, pDC ); //Do not forget! + + m_AsBitmap = new + WT_PNG_Group4_Image( + pixeldy, /*rows*/ + pixeldy, /*cols*/ + WT_PNG_Group4_Image::PNG, + 3, + NULL, + m_size, + (WT_Byte*)m_Buffer, + m_BoundingBox.minpt(), + m_BoundingBox.maxpt(), + WD_False); // Geen copy, we verwijderen zelf expliciet + + return m_AsBitmap; +} +#endif + +WT_Result CSLNKSymbolDefinition::serialize(WT_File & file) +{ + if (m_AsBitmap) + { // Wel even kopietje trekken omdat anders niet opnieuw getransformeerd wordt + WT_PNG_Group4_Image( + m_AsBitmap->rows(), /*rows*/ + m_AsBitmap->columns(), /*cols*/ + WT_PNG_Group4_Image::PNG, + 3, + NULL, + m_AsBitmap->data_size(), + (WT_Byte *)m_AsBitmap->data(), + m_AsBitmap->bounds().minpt(), + m_AsBitmap->bounds().maxpt(), + WD_False).serialize(file); + return WT_Result::Success; + } + if (m_BuiltIn) + return WT_Result::Success; + + WT_Result result; + // Open onze symbool DWF + m_wtFile.set_file_mode(WT_File::File_Read); + result = m_wtFile.open(); + if (result != WT_Result::Success) + return result; // Waarschijnlijk builtin symbol? + +// Op zich is er minder kans op overflow als we het symbool tijden het inlezen +// al richting (0,0) zetten. Dan wordt echter niet meer de definitieve transform +// uitgevoerd omdat m_transformed op WD_True staat. +// WT_Logical_Point lshift(- m_Origin.m_x,- m_Origin.m_y); +// +// m_wtFile.heuristics().set_transform(WT_Transform (lshift, 0, 0, 0)); +// m_wtFile.heuristics().set_apply_transform(true); + + // Do the actual reading. + // Een apply_transform is door de aanroeper al op file gezet. + // Dankzij set_apply_transform gaat de rest miraculeus vanzelf + while ((result = m_wtFile.process_next_object()) == WT_Result::Success) + { + //myTRACE("Attribute '%s'\n", wtFile->file_stats()->descriptions()); + switch(m_wtFile.current_object()->object_type()) + { + case WT_Object::Drawable: +#ifdef _DEBUG + if (m_wtFile.current_object()->object_id() == WT_Object::Origin_ID + && !file.heuristics().allow_binary_data() + ) + { // Origin is niet toegestaan bij ASCII + break; + } +#endif + m_wtFile.current_object()->serialize(file); + break; + case WT_Object::Attribute: + { + const WT_Attribute *obj = (WT_Attribute *)m_wtFile.current_object(); + // myTRACE("Attribute '%s'\n", my_plan_file.file_stats()->descriptions()); + // Hoewel een Attibute gaat hij toch niet via desired_rendition + // Omdat we weten dat we net uit uit een DWF komen kunnen we best + // wel rechtstreeks serializen + // Let wel: desired_rendition is dan niet meer te vertrouwen. Zie @@@ + if (obj->object_id() == WT_Object::View_ID) + { + // De view komt VOOR de Viewport dus wordt niet goed vertaald + // bovendien doen we er toch niets mee + break; + } + if (obj->object_id() == WT_Object::Layer_ID) + { + // Zou toch wel erg complex worden. Werkt ook maar matig + break; + } + if (obj->object_id() == WT_Object::Color_ID) + { // Misschien een zwart-wit toggle doorvoeren? Of zelfs highlight? + // m_iEPlotSection->get_PaperColor() + } + if (obj->object_id() == WT_Object::Viewport_ID) + { + break; // Voorkom dat het Viewport object in de DWF komt + // Dan krijgen we last omdat we er op clippen + // eigenlijk moeten we de originele viewport + // terug zetten na afloop + } + obj->serialize(file); + } + break; + default: + //myTRACE("Skipping '%s'\n", wtFile->file_stats()->descriptions()); + break; + } + } + m_wtFile.close(); + return WT_Result::Success; +} diff --git a/SlnkDWFCom/SLNKSymbolDefImpl.h b/SlnkDWFCom/SLNKSymbolDefImpl.h new file mode 100644 index 0000000..a6584f0 --- /dev/null +++ b/SlnkDWFCom/SLNKSymbolDefImpl.h @@ -0,0 +1,27 @@ +#pragma once + +#include "Whiptk/whip_toolkit.h" +#include "myWT_File.h" + +class CSLNKSymbolDefinition +{ +public: + CSLNKSymbolDefinition(CComQIPtr EPlotSection); + CSLNKSymbolDefinition(int count, WT_Logical_Point const *points) ; + CSLNKSymbolDefinition(CString const filepath, double const height); + ~CSLNKSymbolDefinition(void); + + CComQIPtr m_iEPlotSection; // Om scope levend te houden + myWT_File m_wtFile; // Beetje redundant? + WT_Logical_Box m_BoundingBox; + WT_Polygon m_BoundingContour; + WT_Logical_Point m_Origin; + double m_dwgScale; + WT_Drawable *asBitmap(int pixeldx, int pixeldy, long paperColor); + WT_Result serialize(WT_File & file); + +private: + bool m_BuiltIn; + WT_Result calculateBoundary(); + WT_PNG_Group4_Image *m_AsBitmap; +}; diff --git a/SlnkDWFCom/SLNKSymbolImpl.cpp b/SlnkDWFCom/SLNKSymbolImpl.cpp new file mode 100644 index 0000000..8fed14f --- /dev/null +++ b/SlnkDWFCom/SLNKSymbolImpl.cpp @@ -0,0 +1,188 @@ +#include "StdAfx.h" +#include "myEPlotSection.h" +#include "SLNKSymbolDefImpl.h" +#include "SLNKSymbolImpl.h" +#include "../SLNKDWFImpl/CxImage\CxImage\ximage.h" +#include "../SLNKDWFImpl/Whip2DCImpl.h" +#include + +CSLNKSymbolImpl::CSLNKSymbolImpl(void) +{ +} + +CSLNKSymbolImpl::~CSLNKSymbolImpl(void) +{ +} + +CSLNKSymbolImpl::CSLNKSymbolImpl(double dwgX, double dwgY, CWhipFileState *State) +{ + m_dwgX = dwgX; + m_dwgY = dwgY; + m_symbolName = ""; + m_Rotation = 0; + m_Scale = 1.0; + m_SLNKContour.m_parentWhipFileState = State; + m_SLNKContour.m_fromSymbol=true; +} + +WT_Result CSLNKSymbolImpl::serialize (WT_File & file, WT_Units & units, + CSLNKSymbolDefinition *symbdef, double hintScale) +{ + ATLASSERT(symbdef != NULL); + + WT_Point3D insertion(m_dwgX, m_dwgY); + //m_SLNKContour.m_parentWhipFileState->m_contunits + + double dScale = units.application_to_dwf_transform()(0,0); // Drawing's dScale + + WT_Transform wasTransform = file.heuristics().transform(); + WT_Boolean wasApplyTransform = file.heuristics().apply_transform(); + + WT_Logical_Point LPInsertion = units.transform(insertion); + // Onze file had mogelijk al een transform staan. Die moeten we wel blijven ondersteunen + // (terugzetten komt wel) + if (wasApplyTransform) + { + LPInsertion *= wasTransform; + } + // WT_Transform ondersteunt wel rotaties 0,90,180 en 270. Dat gaat echter altijd om DWF 0,0 + // terwijl wij toch echt om ons insertionpoint willen. + // Het (b)lijkt oplosbaar door ons punt te tegenroteren + WT_Transform tr0; + tr0.set_rotation((360-m_Rotation)%360); + LPInsertion *= tr0; + + WT_Result result; + +#ifdef _xDEBUG + { // Cirkel onder het symbool tekenen + WT_Logical_Point center = units.transform(insertion); + // Binnenkant cirkel + file.desired_rendition().color() = WT_Color(128, 128, 128, 0); // doorzichtig werkt (nog) niet voor ellipsen + WT_Filled_Ellipse(center, 1500, 1500).serialize(file); + // Buitenkant cirkel + file.desired_rendition().color() = WT_Color(0, 255, 0, 0); // doorzichtig werkt (nog) niet voor ellipsen + file.desired_rendition().line_weight() = WT_Line_Weight(100); + WT_Outline_Ellipse(center, 1500, 1500).serialize(file); + file.desired_rendition().line_weight() = WT_Line_Weight(0); + } +#endif +#ifdef _DEBUG + { // klein cirkeltje op insertion + WT_Logical_Point center = units.transform(insertion); + // Binnenkant cirkel + file.desired_rendition().color() = WT_Color(0, 0, 128, 0); // doorzichtig werkt (nog) niet voor ellipsen + WT_Filled_Ellipse(center, 50, 50).serialize(file); + // Buitenkant cirkel + file.desired_rendition().color() = WT_Color(0, 128, 0, 0); // doorzichtig werkt (nog) niet voor ellipsen + file.desired_rendition().line_weight() = WT_Line_Weight(10); + WT_Outline_Ellipse(center, 50, 50).serialize(file); + file.desired_rendition().line_weight() = WT_Line_Weight(0); + } +#endif + // Vertrouw de huidige rendition niet! Het eerste lijntje van een symbool kan default wit verwachten (CO206.DWF) + // Tijdens het serializen van het symbool hebben we niets met (desired)_rendition te maken + WT_Color().serialize(file); // Op de default zetten. TODO: Moet eigenlijk voor alle attributen + + double dx, dy; + + dx = dy = m_Scale * dScale / symbdef->m_dwgScale; + // PAS OP: (SDU tekening) je kunt hier in overflow problemen komen + // als dx*symbdef->m_Origin.m_x>MAXINT ofwel eigenlijk al als dx>1.0 + // ofwel als d(rawing)Scale > symbdef->m_dwgScale (en dan heb ik het nog + // niet over verschaalde symbolen). + if (dx*symbdef->m_Origin.m_x > INT_MAX || dy*symbdef->m_Origin.m_y > INT_MAX) + { + throw myCString("\nSLNKDWF symbol coordinate overflow. Possible solutions:" + "\nDecrease drawing dwf resolution (%.6f)" + "\nIncrease symbool dwf resolution (%.6f)" + "\nDecrease symbol scale (%.6f)",dScale, symbdef->m_dwgScale, m_Scale + ); + } + //myDoTRACE("\nSymbool m_Scale = %.6f, dScale = %.6f, symbdef->m_dwgScale = %.6f==>dx=%.6g", m_Scale, dScale, symbdef->m_dwgScale, dx); + // WT_Logical_Point lshift(LPInsertion); + + WT_Logical_Point lshift(LPInsertion.m_x - myRound(dx*symbdef->m_Origin.m_x), + LPInsertion.m_y - myRound(dy*symbdef->m_Origin.m_y)); + + file.heuristics().set_transform(WT_Transform (lshift, dx, dy, m_Rotation)); + file.heuristics().set_apply_transform(true); + +#ifdef NO_BITMAPPEREN + // Vooralsnog uitgeschakeld: we hebben de (hoognodige) achtergrondkleur niet + Merk op dat builtin symbols (star) geen nog geen boundingbox ingevuld hebben + int pixeldx = 1000; + int pixeldy = 1000; + if (hintScale>0) + { + WT_Logical_Box bx = symbdef->m_BoundingBox; + pixeldx = myRound((bx.maxpt().m_x - bx.minpt().m_x)*m_Scale/symbdef->m_dwgScale/hintScale); + pixeldy = myRound((bx.maxpt().m_y - bx.minpt().m_y)*m_Scale/symbdef->m_dwgScale/hintScale); + //myDoTRACE("\nbx=(%d,%d)-(%d,%d)",bx.minpt().m_x,bx.minpt().m_y,bx.maxpt().m_x,bx.maxpt().m_y); + //myDoTRACE(" makes (%d,%d) pixels",pixeldx,pixeldy); + } + if ( 0 && pixeldx < 100 && pixeldy < 100 ) // Heel weinig pixels + { // Bitmap versie van het symbool gebruiken + //double rescale = 1.0; //m_Scale/symbdef->m_dwgScale*dScale; + if (pixeldx > 0 && pixeldy > 0) + { + symbdef->asBitmap(pixeldx, pixeldy, 0xffffff)->serialize(file); + } + } + else +#endif + { //Gewone vector versie + symbdef->serialize(file); + } + +#ifdef _DEBUG + WT_Comments cmt; + CString s; s.Format("About to insert symbol contour %s", m_symbolName); + cmt.set(s); + cmt.serialize(file); +#endif + + //Cirkeltje op symbool zwaartepunt + //file.desired_rendition().color() = WT_Color(255, 0, 0, 0); + //WT_Filled_Ellipse(symbdef->m_Center, 50, 50).serialize(file); + +#ifdef _DEBUG + m_SLNKContour.m_outlineAlpha = 255; // Zichtbaar maken +#else + m_SLNKContour.m_outlineAlpha = 0; // Onzichtbaar maken +#endif + // En vervolgens nog een mooi bounding contourtje er om heen. + // Die is essentieel voor het aanwijzen. Doordat hierboven de alpha op 0 is gezet wordt hij wel transparant + WT_Color().serialize(file); // Op de default zetten. + file.desired_rendition().color() = file.rendition().color() = WT_Color(); + m_SLNKContour.serialize(file, true); + + // Nu contour aanpassen. Is handig voor later teksten bijplaatsen + // Echter: die willen we exclusief 'wasTranform' hebben. Daarvoor tegencorrigeren we + // + LPInsertion = units.transform(insertion); + WT_Transform tr1; + tr1.set_rotation((360-m_Rotation)%360); + LPInsertion *= tr1; + lshift = WT_Logical_Point(LPInsertion.m_x - myRound(dx*symbdef->m_Origin.m_x), + LPInsertion.m_y - myRound(dy*symbdef->m_Origin.m_y)); + WT_Transform tm(lshift, dx, dy, m_Rotation); + m_SLNKContour.transform(tm); // Pas op: de bounds zijn nu misschien nog verkeerd +#if 0 + // Tegencorrectie werkte niet goed met rotatie. Daarom maar zoals hierboven + WT_Transform tm(file.heuristics().transform()); + WT_Logical_Point wasT(wasTransform.m_translate); + WT_Transform tr1; + tr1.set_rotation((360-m_Rotation)%360); + wasT *= tr1; + tm.m_translate.m_x -= wasT.m_x; + tm.m_translate.m_y -= wasT.m_y; + m_SLNKContour.transform(tm); // Pas op: de bounds zijn nu misschien nog verkeerd +#endif + + // En transform weer terug + file.heuristics().set_transform(wasTransform); + file.heuristics().set_apply_transform(wasApplyTransform); + // ASSERT: Deze werkt nu ook m_SLNKContour.serialize(file, true, true); + return result; +}; diff --git a/SlnkDWFCom/SLNKSymbolImpl.h b/SlnkDWFCom/SLNKSymbolImpl.h new file mode 100644 index 0000000..60cd114 --- /dev/null +++ b/SlnkDWFCom/SLNKSymbolImpl.h @@ -0,0 +1,27 @@ +#pragma once + +#include "Whiptk/whip_toolkit.h" +#include "SLNKContourImpl.h" + +class CSLNKSymbolImpl +{ +public: + CSLNKSymbolImpl(void); + + CSLNKSymbolImpl(double dwgX, double dwgY, CWhipFileState *State); + + WT_Result serialize (WT_File & file, WT_Units & units, + CSLNKSymbolDefinition *symbdef, + double hintScale); + WT_Result calculateBoundary (myWT_File *wtFile); + + ~CSLNKSymbolImpl(void); +public: + double m_dwgX, m_dwgY; + //CString m_Label; + //CString m_Key; + CString m_symbolName; + int m_Rotation; + double m_Scale; + CSLNKContourImpl m_SLNKContour; +}; diff --git a/SlnkDWFCom/SLNKdwf.aps b/SlnkDWFCom/SLNKdwf.aps new file mode 100644 index 0000000..792bea9 Binary files /dev/null and b/SlnkDWFCom/SLNKdwf.aps differ diff --git a/SlnkDWFCom/SLNKdwf.rc b/SlnkDWFCom/SLNKdwf.rc new file mode 100644 index 0000000..e52ad05 --- /dev/null +++ b/SlnkDWFCom/SLNKdwf.rc @@ -0,0 +1,158 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "1 TYPELIB ""SLNKDWF.tlb""\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#include "SLNKDWFVersion.h" + +VS_VERSION_INFO VERSIONINFO + FILEVERSION SLNK_MAJOR_VERSION, SLNK_MINOR_VERSION, 0, SLNK_BUILD_VERSION + PRODUCTVERSION SLNK_MAJOR_VERSION, SLNK_MINOR_VERSION, 0, SLNK_BUILD_VERSION + FILEFLAGSMASK 0x1fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "Dijkoraad IT" + VALUE "FileDescription", "Superlink DWF " + VALUE "FileVersion", SLNK_BUILDVERSION "\0" + VALUE "InternalName", "SLNKDWF.dll" + VALUE "LegalCopyright", "(c) Dijkoraad IT 2005-2007. All rights reserved." + VALUE "OriginalFilename", "SLNKDWF.dll" + VALUE "ProductName", "Superlink" + VALUE "ProductVersion", SLNK_BUILDVERSION "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// REGISTRY +// + +IDR_SLNKDWF REGISTRY "SLNKDWF.rgs" + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDS_PROJNAME "SLNKDWF" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Dutch (Netherlands) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NLD) +#ifdef _WIN32 +LANGUAGE LANG_DUTCH, SUBLANG_DUTCH +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// REGISTRY +// + +IDR_DWFFILE REGISTRY "DWFFile.rgs" +IDR_WHIPFILE REGISTRY "WhipFile.rgs" +IDR_WHIP2PNG REGISTRY "Whip2PNG.rgs" +IDR_ABOUT REGISTRY "About.rgs" +IDR_EPLOTSECTION REGISTRY "EPlotSection.rgs" +IDR_EPLOTSECTIONS REGISTRY "EPlotSections.rgs" +IDR_SLNKEVENT REGISTRY "SLNKEvent.rgs" +IDR_BOUNDINGBOX REGISTRY "BoundingBox.rgs" +IDR_DWGPOINT REGISTRY "DWGPoint.rgs" +IDR_SLNKCONTOUR REGISTRY "SLNKContour.rgs" +IDR_SLNKSYMBOL REGISTRY "SLNKSymbol.rgs" +IDR_OPTIONS REGISTRY "Options.rgs" + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +#endif // Dutch (Netherlands) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +1 TYPELIB "SLNKDWF.tlb" + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/SlnkDWFCom/Whip2PNG.cpp b/SlnkDWFCom/Whip2PNG.cpp new file mode 100644 index 0000000..dc48ca9 --- /dev/null +++ b/SlnkDWFCom/Whip2PNG.cpp @@ -0,0 +1,608 @@ +// Whip2PNG.cpp : Implementation of CWhip2PNG + +#include "stdafx.h" +#include "CxImage\CxImage\ximage.h" + +#include "Whip2DCImpl.h" + +#include "Whip2PNG.h" + +#include "metafile.h" + +CWhip2PNG::CWhip2PNG() +{ + m_sizeX = 800; + m_sizeY = 600; + m_offsetX = 0; + m_offsetY = 0; + m_dScale = 1.0; + m_lRotation = 0; + m_RegExp = ".*"; + m_forcePaper = FALSE; + m_forceBW = FALSE; + m_forceGray = FALSE; + m_Maximize = FALSE; + m_dwgScale = 0.0; +} + +STDMETHODIMP CWhip2PNG::Load(BSTR WhipPath) +{ + myDoTRACE("\nCWhip2PNG::Load('%ls')", WhipPath); + + m_WhipPath = WhipPath; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::LoadStream(VARIANT EPlotStream) +{ + myDoTRACE("\nCWhip2PNG::LoadStream()"); + + if (EPlotStream.vt!=VT_ERROR) + { + VARIANT *var2 = &EPlotStream; + if (var2->vt==(VT_VARIANT|VT_BYREF)) // ByRef + var2 = (VARIANT *)var2->pvarVal; + + if (var2->vt==VT_DISPATCH) + { + m_iEPlotSection = var2->pdispVal; + if (!m_iEPlotSection) + return E_INVALIDARG; + } + else + return E_INVALIDARG; + } + + return S_OK; +} + +// Werkt nog niet echt goed? +STDMETHODIMP CWhip2PNG::SaveAsWMF(BSTR WMFPath) +{ + CmyTimer timer("CWhip2PNG::SaveAsWMF"); + +#if 0 + HDC myDC = CreateEnhMetaFile(NULL,CString(WMFPath),NULL,NULL); // In memory + InitDC(myDC); + + if (m_forcePaper) + HRESULT res = m_iWhip2DC.set_paperColor(m_paperColor); + res = m-iWhip2DC->Paint(m_forceBW); + HENHMETAFILE hMF = CloseEnhMetaFile(myDC); + DeleteEnhMetaFile(hMF); + DeleteDC(myDC); + +#endif + +#if 1 + HDC myDC = CreateMetaFile(NULL); // In memory + InitDC(myDC); + + HRESULT res; + if (m_forcePaper) + res = m_iWhip2DC.put_paperColor(m_paperColor); + res = m_iWhip2DC.Paint(m_forceBW); + + HMETAFILE hMF = CloseMetaFile(myDC); + CMetafile::WriteMetaFileAsPlaceable(hMF, CSize(m_sizeX, m_sizeY),m_sizeX/4,CString(WMFPath)); + DeleteMetaFile(hMF); + DeleteDC(myDC); + +#endif + + putDWGInfo(); // Generieke info naar het event + + return S_OK; +} + +bool CWhip2PNG::CreateCxImage(CxImage *img) +{ + CmyTimer timer("CWhip2PNG::CreateCXImage"); + + bool res = true; + + //---- + HDC pDC = ::GetDC(0); + HDC myDC = CreateCompatibleDC(pDC); + //ReleaseDC(pDC); + InitDC(myDC); // Stelt ook definitieve m_SizeX en m_SizeY vast + +#if 1 + + BITMAPINFO bmInfo; + memset(&bmInfo.bmiHeader,0,sizeof(BITMAPINFOHEADER)); + bmInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); + bmInfo.bmiHeader.biWidth=m_sizeX; + bmInfo.bmiHeader.biHeight=m_sizeY; + bmInfo.bmiHeader.biPlanes=1; + bmInfo.bmiHeader.biCompression=BI_RGB; // Geen compressie + bmInfo.bmiHeader.biBitCount=24; + + //create a new bitmap and select it in the memory dc + BYTE *pbase; + HBITMAP TmpBmp = CreateDIBSection(pDC, &bmInfo,DIB_RGB_COLORS,(void**)&pbase,0,0); + //---- +#else + // Deze werkt ook wel maar is 10% langzamer? Je zou sneller verwachten? + // Bovendien ben je nu afhankelijk van de display instellingen? + // En het converteren CreateFromHBITMAP is veel langzamer + HBITMAP TmpBmp = CreateCompatibleBitmap ( pDC, m_sizeX, m_sizeY ); + //BITMAP bm; + //GetObject(TmpBmp, sizeof(BITMAP), (LPSTR) &bm); + //als bm.bmBits nu NULL is hebben we wel een echte DFB; +#endif + if (!TmpBmp) + { + myDoTRACE("\nTmpBmp==NULL when creating (%d, %d)??", m_sizeX, m_sizeY); + return false; + } + + HGDIOBJ TmpObj=SelectObject(myDC,TmpBmp); + + if (m_forcePaper) + m_iWhip2DC.put_paperColor(m_paperColor); + + res = res && SUCCEEDED(m_iWhip2DC.Paint(m_forceBW)); + if (!res)myDoTRACE("Paint faalt??"); + + if (!img->CreateFromHBITMAP(TmpBmp)) + { + myDoTRACE("CreateFromHBITMAP faalt??"); + return false; + } + if (m_lRotation%360 == 90 || m_lRotation%360 == -270) + img->RotateLeft(); + + if (m_lRotation%360 == -90 || m_lRotation%360 == 270) + img->RotateRight(); + + if (m_lRotation == -180 || m_lRotation == 180) // Voor te draggen symbolen + img->Rotate180(); + + putDWGInfo(); // Generieke info naar het event + + DeleteObject(TmpBmp); + DeleteDC(myDC); + ReleaseDC( NULL, pDC ); //Do not forget! + + return res; +} + +// Alleen gebruikt in testscripts +STDMETHODIMP CWhip2PNG::SaveAsPNG(BSTR PNGPath) +{ + myDoTRACE("\nCWhip2PNG::SaveAsPNG('%ls')", PNGPath); + + CxImage img; + bool res = CreateCxImage(&img); + if (!res) + { + CString err; err.Format("Could not CreateCxImage: %s", img.GetLastError()); + return myAtlReportError (GetObjectCLSID(), "\nCWhip2PNG::SaveAsPNG('%ls')\n%s", (LPCSTR)m_WhipPath, err); + } + + { + CmyTimer timer("PNG Save"); + + if (!img.Save(CString(PNGPath), CXIMAGE_FORMAT_PNG)) + return myAtlReportError (GetObjectCLSID(), "\nSaveAsPNG save failed: %s", img.GetLastError()); + } + + return S_OK; +} + + +// Handig om GetIMG.asp errormessages te laten opleveren +// Ondersteunt ook m_Maximize: dan wordt de witruimte geminimaliseerd; +STDMETHODIMP CWhip2PNG::TextAsPNG(BSTR Message, VARIANT *ImageData) +{ + // Indirect via een tempDC omdat anders de CompatibleBitmap Z/W wordt + // TODO: Als de server Windows in 256 kleuren draait, wat krijg je dan? + HDC tempDC = CreateDC("DISPLAY",NULL,NULL,NULL); + HDC myDC = CreateCompatibleDC ( tempDC ); + + CString tok(Message); + tok.Replace("~", "\n"); // We ondersteunen ook ~ als newline + RECT rc = { 0, 0, m_sizeX, 0}; + DrawText(myDC, tok, tok.GetLength(), &rc, DT_CALCRECT); // Grootte bepalen + + if (m_Maximize) + { + m_sizeX = rc.right; + m_sizeY = rc.bottom; + } + HBITMAP memBM = CreateCompatibleBitmap ( tempDC, m_sizeX, m_sizeY ); + DeleteDC(tempDC); + SelectObject(myDC, memBM); + HBRUSH tempBrush = CreateSolidBrush(RGB(255,255,255)); + HBRUSH oldbrush = (HBRUSH) SelectObject(myDC,tempBrush); + FillRect(myDC,CRect(0,0,m_sizeX, m_sizeY),tempBrush); + SelectObject(myDC,oldbrush); + DeleteObject(tempBrush); + + // Nu het echte tekenen + rc.top = m_sizeY/2 - rc.bottom/2; // Vertikaal centreren + rc.bottom = m_sizeY/2 + rc.bottom/2; + DrawText(myDC, tok, tok.GetLength(), &rc, DT_TOP); + + CxImage img; + if (!img.CreateFromHBITMAP(memBM)) + return myAtlReportError (GetObjectCLSID(), "\nTextAsPNG CreateFromHBITMAP failed: %s", img.GetLastError()); + + DeleteObject(memBM); + DeleteDC(tempDC); + DeleteDC(myDC); + + return StreamPNG(img, ImageData, TRUE); +} + +// Als we dan toch door de tekening zijn gegaan is het soms +// wel handig informatie over de tekening te hebben +// Dat stoppen we grotendeels in m_SLNKEvent +void CWhip2PNG::putDWGInfo() +{ + HRESULT res; + res = m_iWhip2DC.get_paperColor((LONG*)&m_paperColor); // Weten we nu ook + + double resX, resY; + + res = m_iWhip2DC.DPtoDWG(0, m_sizeY, &resX, &resY); + CComQIPtr bbView; + m_SLNKEvent->get_viewExtents(&bbView); + CComQIPtr pt; + bbView->get_min(&pt); + pt->put_DwgX(resX); + pt->put_DwgY(resY); + pt.Release(); // Voor re-use + + res = m_iWhip2DC.DPtoDWG(m_sizeX, 0, &resX, &resY); + bbView->get_max(&pt); + pt->put_DwgX(resX); + pt->put_DwgY(resY); + pt.Release(); + + double resMX, resMY; + res = m_iWhip2DC.DWGExtents(&resX, &resY, &resMX, &resMY); + + CComQIPtr bbDWG; + m_SLNKEvent->get_dwgExtents(&bbDWG); + bbDWG->get_min(&pt); + pt->put_DwgX(resX); + pt->put_DwgY(resY); + pt.Release(); + + bbDWG->get_max(&pt); + pt->put_DwgX(resMX); + pt->put_DwgY(resMY); + pt.Release(); +} + +// Zoek een punt dat de gebruiker in de tekening geklikt heeft. +// Er wordt alleen een simpele tekst opgeleverd (hetzij aangeklikte truetype tekst +// of een Contour label). Meer details zijn via get_SLNKEvent te verkrijgen +STDMETHODIMP CWhip2PNG::Find(LONG findX, LONG findY, BSTR* foundLabel) +{ + CmyTimer timer("CWhip2PNG::Find"); + + HDC pDC = ::GetDC(0); + HDC myDC = CreateCompatibleDC(pDC); + //ReleaseDC(pDC); + // Er hoeft geen bitmap naar myDC omdat we toch niet painten + InitDC(myDC); + + CString ContourLabel, ContourLayer, TextLabel, TextLayer; + HRESULT res = m_iWhip2DC.Find(findX, findY, + FALSE, + ContourLabel, ContourLayer, TextLabel, TextLayer); + + if (TextLabel != "") + (*foundLabel) = TextLabel.AllocSysString(); + else if (ContourLabel != "") + (*foundLabel) = ContourLabel.AllocSysString(); + + double resX, resY; + res = m_iWhip2DC.DPtoDWG(findX, findY, &resX, &resY); + m_SLNKEvent->put_DwgX(resX); + m_SLNKEvent->put_DwgY(resY); + + m_SLNKEvent->put_ContourLabel(CComBSTR(ContourLabel)); + m_SLNKEvent->put_ContourLayer(CComBSTR(ContourLayer)); + m_SLNKEvent->put_TextLabel(CComBSTR(TextLabel)); + m_SLNKEvent->put_TextLayer(CComBSTR(TextLayer)); + + putDWGInfo(); // Generieke info naar het event + + DeleteDC(myDC); + ReleaseDC( NULL, pDC ); //Do not forget! + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::SetDimensions(LONG sizeX, LONG sizeY, // PNG image size + LONG offsetX, LONG offsetY, // Panning + DOUBLE dScale, // Zooming, 1.0 default + LONG lRotation) // Rotation, 0 default, multiple of 90 +{ + if (sizeX*dScale <=0 || + sizeY*dScale <=0 || + sizeX*dScale >=LONG_MAX+0.5 || + sizeY*dScale >=LONG_MAX+0.5) + return myAtlReportError (GetObjectCLSID(), "\nCWhip2PNG::SetDimensions invalid zoom"); + + m_sizeX = sizeX; + m_sizeY = sizeY; + m_offsetX = offsetX; + m_offsetY = offsetY; + m_dScale = dScale; + m_lRotation = lRotation; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::GetAsMap(BSTR* AsMap) +{ + myDoTRACE("\nCWhip2PNG::GetAsMAP()"); + CmyTimer timer("CWhip2PNG::GetAsMap"); + + HDC pDC = ::GetDC(0); + HDC myDC = CreateCompatibleDC(pDC); + + // Er hoeft geen bitmap naar myDC omdat we toch niet painten + // Let wel: daardoor kunnen we niet optimaliseren met RectVisible? + InitDC(myDC); + //ReleaseDC(pDC); + + CString result, dummy; + HRESULT res = m_iWhip2DC.Find(0, 0, + TRUE, /*AsMap*/ + result, dummy, dummy, dummy); + + // Als we dan toch door de tekening zijn gegaan is dit wel handig om te hebben + putDWGInfo(); // Generieke info naar het event + + (*AsMap) = result.AllocSysString(); + + DeleteDC(myDC); + ReleaseDC( NULL, pDC ); //Do not forget! + + return S_OK; +} + +// Testfunctie om RegExp's te testen +STDMETHODIMP CWhip2PNG::get_AtlRegExp(BSTR RegExp, BSTR TestExp, BSTR* pVal) +{ + CAtlRegExp<> reLayers; // Welke layers moeten aan + REParseError status = reLayers.Parse( CString(RegExp), false ); + if (REPARSE_ERROR_OK != status) + { + myTRACE("\nSorry, kan reguliere expressie layersOn niet parsen"); + // Unexpected error. + return S_FALSE; + } + + CAtlREMatchContext<> mcUrl; + //CAtlREMatchContext<> mcUrl2; + + BOOL b1 = reLayers.Match(CString(TestExp), &mcUrl); +// b &= (mcUrl.m_uNumGroups > 0); + CString res; + res.Format("Testing: %ls for %ls: %d", RegExp, TestExp, b1); + CComBSTR bstrString(res); + return bstrString.CopyTo(pVal); + + return S_OK; +} + +// Stream een CImage als PNG (bPNG) of als GIF (!bPNG) +HRESULT CWhip2PNG::StreamPNG(CxImage &img, VARIANT *ImageData, BOOL bPNG) +{ + SAFEARRAY *psaData; BYTE *pData; + SAFEARRAYBOUND rgsabound[1]; + + long size=0; + BYTE* pBuffer=0; + { + { + CmyTimer timer("CWhip2PNG::StreamPNG/de PNG encoden"); + if (!img.Encode(pBuffer,size, bPNG?CXIMAGE_FORMAT_PNG:CXIMAGE_FORMAT_GIF)) + return myAtlReportError (GetObjectCLSID(), "\nStreamPNG encode failed: %s", img.GetLastError()); + } + + // TODO: Echt netjes zou zijn om hier een IStream op te leveren? + // create safe array and copy image data + rgsabound[0].lLbound = 0; rgsabound[0].cElements = size; + psaData = SafeArrayCreate(VT_UI1, 1, rgsabound); + SafeArrayAccessData(psaData, (void **)&pData); + memcpy(pData,pBuffer,size); + SafeArrayUnaccessData(psaData); + img.FreeMemory (pBuffer); + // put data in variant + ImageData->vt = (VT_ARRAY | VT_UI1); + ImageData->parray = psaData; + } + myDoTRACE("\nCWhip2PNG::StreamPNG done, sending %d bytes", size); + + return S_OK; + +} + +// Draggable symbolen +STDMETHODIMP CWhip2PNG::GetAsTransGIF(VARIANT *ImageData) +{ + return CWhip2PNG::GetAsXXX(ImageData, FALSE); +} + +STDMETHODIMP CWhip2PNG::GetAsPNG(VARIANT *ImageData) +{ + return CWhip2PNG::GetAsXXX(ImageData, TRUE); +} + +STDMETHODIMP CWhip2PNG::GetAsXXX(VARIANT *ImageData, BOOL bPNG) +{ + try + { + myDoTRACE("\nCWhip2PNG::GetAsPNG()"); + + CxImage img; + BOOL res = CreateCxImage(&img); + if (!res) + { + CString err; err.Format("Could not CreateCxImage: %s", img.GetLastError()); + throw err; + } + + if (!bPNG) + { // Transparante GIF. + RGBQUAD back = {GetBValue(m_paperColor), // RGBQUAD is BGR!! + GetGValue(m_paperColor), + GetRValue(m_paperColor),0}; + if (m_forceGray) + { + img.GrayScale(); + BYTE gray = RGB2GRAY(GetRValue(m_paperColor), + GetGValue(m_paperColor), + GetBValue(m_paperColor)); + back.rgbBlue = back.rgbGreen = back.rgbRed = gray; + } + else + { + } + // GIF is 8 bit. + img.DecreaseBpp(8, FALSE); + img.SetTransIndex(img.GetNearestIndex(back)); + // GIF kent geen Alpha, IE6 geen PNG transparantie + //img.AlphaCreate(); + //img.AlphaSet(192); + } + return StreamPNG(img, ImageData, bPNG); + } + catch (DWFException& ex) + { + CString err; + err.Format("%ls\n%ls\n%s\n%ls(%d)",ex.type(),ex.message(),ex.function(),ex.file(),ex.line()); + return myAtlReportError (GetObjectCLSID(), "\nCWhip2PNG::GetAsPNG('%s')\n%s", m_WhipPath, err); + } + catch (CString& err) + { + return myAtlReportError (GetObjectCLSID(), "\nCWhip2PNG::GetAsPNG('%s')\n%s", m_WhipPath, err); + } +} + +STDMETHODIMP CWhip2PNG::SetLayers(BSTR RegExp) +{ + m_RegExp = RegExp; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::get_SLNKEvent(ISLNKEvent** pVal) +{ + return m_SLNKEvent->QueryInterface(IID_ISLNKEvent, (void**)pVal); +} + +void CWhip2PNG::InitDC(HDC &myDC) +{ + SetViewportOrgEx(myDC, m_offsetX, m_offsetY, NULL); + CEPlotSectionImpl *epli = NULL; + if (m_iEPlotSection) // Via stream? + m_iEPlotSection->get_EPlotSectionImpl((BYTE **)&epli); + m_iWhip2DC.Load(myDC, epli, + m_WhipPath, m_RegExp, + myRound(m_sizeX*m_dScale), myRound(m_sizeY*m_dScale), + VARIANT_TRUE /*center*/, m_Maximize, m_dwgScale); + + // Als m_dwgScale was gespecificeerd moeten we wel een goede bitmapgrootte kiezen + if (m_dwgScale > 0.0) + { + CSize newsize = m_iWhip2DC.get_Size(); + m_sizeX = newsize.cx; // Veronderstel m_dScale = 1.0 + m_sizeY = newsize.cy; + } +} +STDMETHODIMP CWhip2PNG::get_paperColor(LONG* pVal) +{ + (*pVal) = m_paperColor; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::put_paperColor(LONG newVal) +{ + m_paperColor = newVal; + m_forcePaper = TRUE; + + return S_OK; +} + +// Zet een vertaal kleur (afhankelijk van papierkleur) +STDMETHODIMP CWhip2PNG::ReplaceColor(LONG paperColor, LONG oldColor, LONG newColor) +{ + m_iWhip2DC.ReplaceColor(paperColor, oldColor, newColor); + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::get_Maximize(VARIANT_BOOL* pVal) +{ + (*pVal) = m_Maximize; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::put_Maximize(VARIANT_BOOL newVal) +{ + m_Maximize = newVal; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::get_dwgScale(DOUBLE* pVal) +{ + (*pVal) = m_dwgScale; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::put_dwgScale(DOUBLE newVal) +{ + if (newVal <= 0.0) + return myAtlReportError (GetObjectCLSID(), "\nInvalid dwgScale"); + + m_dwgScale = newVal; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::get_forceBW(VARIANT_BOOL* pVal) +{ + (*pVal) = m_forceBW; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::put_forceBW(VARIANT_BOOL newVal) +{ + m_forceBW = newVal; + if (m_forceBW) + { + m_paperColor = 0xFFFFFF; // Op wit alvast + m_forcePaper = TRUE; + } + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::get_forceGray(VARIANT_BOOL* pVal) +{ + (*pVal) = m_forceGray; + + return S_OK; +} + +STDMETHODIMP CWhip2PNG::put_forceGray(VARIANT_BOOL newVal) +{ + m_forceGray = newVal; + + return S_OK; +} diff --git a/SlnkDWFCom/Whip2PNG.h b/SlnkDWFCom/Whip2PNG.h new file mode 100644 index 0000000..1e59dab --- /dev/null +++ b/SlnkDWFCom/Whip2PNG.h @@ -0,0 +1,121 @@ +// Whip2PNG.h : Declaration of the CWhip2PNG + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" +#include "SLNKEvent.h" + +// CWhip2PNG + +class ATL_NO_VTABLE CWhip2PNG : + public CComObjectRootEx, + public CComCoClass, + public IDispatchImpl +{ +public: + +DECLARE_REGISTRY_RESOURCEID(IDR_WHIP2PNG) + + +BEGIN_COM_MAP(CWhip2PNG) + COM_INTERFACE_ENTRY(IWhip2PNG) + COM_INTERFACE_ENTRY(IDispatch) +END_COM_MAP() + + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + CComObject *pSLNKEvent; // For when the user has clicked on the drawing + HRESULT hr = CComObject::CreateInstance(&pSLNKEvent); + if(FAILED(hr)) return hr; + + pSLNKEvent->AddRef(); + hr = pSLNKEvent->QueryInterface(IID_ISLNKEvent, (void **)&m_SLNKEvent); + pSLNKEvent->Release(); + if(FAILED(hr)) return hr; + +// CComObject< CWhip2DC >* pWhip2DC; +// hr = CComObject::CreateInstance(&pWhip2DC); +// if(FAILED(hr)) return hr; + +// pWhip2DC->AddRef(); +// hr = pWhip2DC->QueryInterface(&m_iWhip2DC); +// pWhip2DC->Release(); + + return hr; + } + + void FinalRelease() + { + } + +public: + + CWhip2PNG(); // Default constructor + + // Een van de volgende twee moet gebruikt worden om de file te laden + STDMETHOD(Load)(BSTR WhipPath); + STDMETHOD(LoadStream)(VARIANT EPlotStream); + + STDMETHOD(SetDimensions)(LONG sizeX, LONG sizeY, LONG offsetX, LONG offsetY, DOUBLE dScale, LONG lRotation); + STDMETHOD(SetLayers)(BSTR RegExp); + + STDMETHOD(SaveAsPNG)(BSTR PNGPath); + STDMETHOD(SaveAsWMF)(BSTR WMFPath); + + STDMETHOD(TextAsPNG)(BSTR Message, VARIANT *ImageData); + STDMETHOD(GetAsPNG)(VARIANT *ImageData); + STDMETHOD(GetAsTransGIF)(VARIANT *ImageData); + STDMETHOD(GetAsXXX)(VARIANT *ImageData, BOOL bPNG); + + STDMETHOD(Find)(LONG findX, LONG findY, BSTR* foundLabel); + STDMETHOD(GetAsMap)(BSTR* AsMap); + STDMETHOD(get_AtlRegExp)(BSTR RegExp, BSTR TestExp, BSTR* pVal); +private: + bool CreateCxImage(CxImage* img); + void InitDC(HDC &myDC); + + HRESULT StreamPNG(CxImage &img, VARIANT *ImageData, BOOL bPNG); + + CComQIPtr m_SLNKEvent; // For when the user has clicked on the drawing + // Will also hold minmax drawing XY? + + //CComQIPtr m_iWhip2DC; + CWhip2DCImpl m_iWhip2DC; + + // Een van de volgende twee zal gezet zijn + CComQIPtr m_iEPlotSection; + CString m_WhipPath; + + void putDWGInfo(); + + LONG m_sizeX, m_sizeY; + LONG m_offsetX, m_offsetY; + double m_dScale; + LONG m_lRotation; + COLORREF m_paperColor; BOOL m_forcePaper; + BOOL m_forceBW; + BOOL m_forceGray; + BOOL m_Maximize; + double m_dwgScale; + + CString m_RegExp; +public: + STDMETHOD(get_SLNKEvent)(ISLNKEvent** pVal); + STDMETHOD(get_paperColor)(LONG* pVal); + STDMETHOD(put_paperColor)(LONG newVal); + STDMETHOD(ReplaceColor)(LONG paperColor, LONG oldColor, LONG newColor); + STDMETHOD(get_Maximize)(VARIANT_BOOL* pVal); + STDMETHOD(put_Maximize)(VARIANT_BOOL newVal); + STDMETHOD(get_dwgScale)(DOUBLE* pVal); + STDMETHOD(put_dwgScale)(DOUBLE newVal); + STDMETHOD(get_forceBW)(VARIANT_BOOL* pVal); + STDMETHOD(put_forceBW)(VARIANT_BOOL newVal); + STDMETHOD(get_forceGray)(VARIANT_BOOL* pVal); + STDMETHOD(put_forceGray)(VARIANT_BOOL newVal); +}; + +OBJECT_ENTRY_AUTO(__uuidof(Whip2PNG), CWhip2PNG) diff --git a/SlnkDWFCom/Whip2PNG.rgs b/SlnkDWFCom/Whip2PNG.rgs new file mode 100644 index 0000000..1a83470 --- /dev/null +++ b/SlnkDWFCom/Whip2PNG.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.Whip2PNG.1 = s 'Whip2PNG Class' + { + CLSID = s '{783AC7F0-E6E1-4CE1-A38B-FA047D44DC1C}' + } + SLNKDWF.Whip2PNG = s 'Whip2PNG Class' + { + CLSID = s '{783AC7F0-E6E1-4CE1-A38B-FA047D44DC1C}' + CurVer = s 'SLNKDWF.Whip2PNG.1' + } + NoRemove CLSID + { + ForceRemove {783AC7F0-E6E1-4CE1-A38B-FA047D44DC1C} = s 'Whip2PNG Class' + { + ProgID = s 'SLNKDWF.Whip2PNG.1' + VersionIndependentProgID = s 'SLNKDWF.Whip2PNG' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/WhipFile.cpp b/SlnkDWFCom/WhipFile.cpp new file mode 100644 index 0000000..3b3ca2f --- /dev/null +++ b/SlnkDWFCom/WhipFile.cpp @@ -0,0 +1,1065 @@ +// WhipFile.cpp : Implementation of CWhipFile + +#include "stdafx.h" +#include "myEPlotSection.h" +#include "WhipFile.h" +#include "SLNKContour.h" + +#include "Dwfcore/Mime.h" + +// +// WHIPFILE.CPP +// +// This file defines class CWhipFile +// which is mostly concerned with detecting closed contours +// and merging a Contour file with a planfile. <<= jun 2007: al lang obsolete +// + +// CWhipFile + +WT_Logical_Point star[] = { WT_Logical_Point(-1000, 0), + WT_Logical_Point( -200, 200), + WT_Logical_Point( 0, 1000), + WT_Logical_Point( 200, 200), + WT_Logical_Point( 1000, 0), + WT_Logical_Point( 200, -200), + WT_Logical_Point( 0,-1000), + WT_Logical_Point( -200, -200), + WT_Logical_Point(-1000, 0) + }; + +WT_Logical_Point octa[] = { WT_Logical_Point( 1000, 414), + WT_Logical_Point( 414, 1000), + WT_Logical_Point( -414, 1000), + WT_Logical_Point(-1000, 414), + WT_Logical_Point(-1000, -414), + WT_Logical_Point( -414,-1000), + WT_Logical_Point( 414,-1000), + WT_Logical_Point( 1000, -414), + WT_Logical_Point( 1000, 414) + }; + +CWhipFile::CWhipFile() +{ + m_FontName.set("Arial"); + m_FontHeight = 400.0; + m_FontHeightSymbols = 200.0; + + // Predefine fixed symbols + CSLNKSymbolDefinition * symb = new CSLNKSymbolDefinition(sizeof(star)/sizeof(star[0]), star); + m_State.m_SLNKSymbolDefinitions.SetAt("*STAR", symb); + + symb = new CSLNKSymbolDefinition(sizeof(octa)/sizeof(octa[0]), octa); + m_State.m_SLNKSymbolDefinitions.SetAt("*OCTAGON", symb); +} + +int xxxx; +STDMETHODIMP CWhipFile::InterfaceSupportsErrorInfo(REFIID riid) +{ + static const IID* arr[] = + { + &IID_IWhipFile + }; + + for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) + { + if (InlineIsEqualGUID(*arr[i],riid)) + return S_OK; + } + return S_FALSE; +} + +// Open de contour file +STDMETHODIMP CWhipFile::Load(BSTR WhipPath) +{ + myDoTRACE("\nCWhipFile::Open('%ls')", WhipPath); + + m_W2DFile.set_filename(WhipPath); + + return ProcessContouren(); +} + + +// Set xc = CreateObject("SLNKDWF.DWFFile") +// xc.Open(dwfFile) +// Set y = CreateObject("SLNKDWF.WhipFile") +// y.LoadStream xc.EplotSections.Item(0) +STDMETHODIMP CWhipFile::LoadStream(VARIANT EPlotStream) +{ + myDoTRACE("\nCCWhipFile::LoadStream()"); + + if (EPlotStream.vt!=VT_ERROR) + { + VARIANT *var2 = &EPlotStream; + if (var2->vt==(VT_VARIANT|VT_BYREF)) // ByRef + var2 = (VARIANT *)var2->pvarVal; + + if (var2->vt==VT_DISPATCH) + { + CComQIPtr EPlotSection; + EPlotSection = var2->pdispVal; + if (!EPlotSection) + return E_INVALIDARG; + else + { + m_iEPlotSection = EPlotSection; + CEPlotSectionImpl *epli; + m_iEPlotSection->get_EPlotSectionImpl((BYTE **)&epli); + m_W2DFile.set_eplotsection(epli); + } + } + else + return E_INVALIDARG; + } + + return ProcessContouren(); +} + +HRESULT CWhipFile::ProcessContouren() +{ + m_W2DFile.set_file_mode(WT_File::File_Read); + + // Alle callback functies zijn static. Die kunnen de variabele + // m_State niet benaderen. Daarom maar via set_user_data + m_W2DFile.heuristics().set_user_data((void *)&m_State); + + if (m_W2DFile.open() == WT_Result::Success) + { xxxx=0; + CmyTimer xx("Contouren opzoeken"); + m_State.contLayerActive = true; + m_State.labelLayerActive = true; // Kan bij de eerste laag anders blijken te zijn + + read_for_contours(); // Zoek eerst alle contouren en labels + processLabels(); // En verwerk ze daarna + myDoTRACE("\nFound %d polylines, %d contours and %d labels.", xxxx, m_State.m_SLNKContouren.GetCount(), m_State.m_SLNKLabels.GetCount()); + + m_W2DFile.close(); // closing Input file. + } + else + { + return myAtlReportError (GetObjectCLSID(), "ERROR CWhipFile:: Unable to open file/stream:"); + } + return S_OK; +} + +STDMETHODIMP CWhipFile::SetLayers(BSTR reContouren, BSTR reLabels) +{ + myTRACE("\nParsing met contouren %ls", reContouren); + myTRACE("\nParsing met labels %ls", (LPCTSTR)reLabels); + if (!m_State.SetLayers(reContouren, reLabels)) + return myAtlReportError (GetObjectCLSID(), "ERROR: Unable to parse Whipfile regLayers"); + + return S_OK; +} + +// Lagen die over moeten blijven. De rest wordt er uit gestript. +STDMETHODIMP CWhipFile::SetFilterLayers(BSTR reLayers) +{ + myTRACE("\nFilter met lagen %ls", reLayers); + if (!m_State.SetFilterLayers(reLayers)) + return myAtlReportError (GetObjectCLSID(), "ERROR: Unable to parse Whipfile SetFilterLayers"); + + return S_OK; +} + +void CWhipFile::read_for_contours() +{ + WT_Result result; + + m_W2DFile.set_text_action(my_process_text); + m_W2DFile.set_polyline_action(my_process_polyline); + + // AutoCAD does not generate polygon's for closed polylines + // It only does for filled SOLID hatching + //m_W2DFile.set_polygon_action(my_process_polygon); + //m_W2DFile.set_polytriangle_action(my_process_polytriangle); + m_W2DFile.set_layer_action(my_process_layer); + // Do the actual reading. + do { + result = m_W2DFile.process_next_object(); + } while (result == WT_Result::Success); + + // Nu zijn ze wel een keer bekend, we hebben ze later weer nodig + m_State.m_contunits=m_W2DFile.rendition().drawing_info().units(); + m_view=m_W2DFile.rendition().rendering_options().view(); + + // We gaan er later nog een keer door voor de plattegrond. Geen processing dan + m_W2DFile.set_text_action(WT_Text::default_process); + m_W2DFile.set_polyline_action(WT_Polyline::default_process); +} + +// Result: Area in original drawing coordinates +// Veronderstel dat het 5e punt gelijk is aan het eerste (daarom aan einde delen door 2?) +double PolygonArea(WT_Point_Set * ps, WT_Units units) +{ + int i,j; + double area = 0; + + for (i=0;icount();i++) { + j = (i + 1) % ps->count(); + WT_Point3D dwfPtA = units.transform(ps->points()[i]); + WT_Point3D dwfPtB = units.transform(ps->points()[j]); + + area += dwfPtA.m_x * dwfPtB.m_y; + area -= dwfPtA.m_y * dwfPtB.m_x; + } + + area /= 2; + return(area < 0 ? -area : area); +} + +// Iterate all labels and determine in which contour they fall +void CWhipFile::processLabels() +{ + for (size_t lbl=0; lblm_DWGArea/1e6); + if (contour->m_contLabel.length()==0) + { + if (prevContour != NULL) + { + myTRACE(" Hmm, we hadden al eerder succes"); + if (prevContour->m_DWGArea > contour->m_DWGArea) + { + myTRACE(" en we hebben een kleinere. Reset prevContour"); + prevContour->m_contLabel = ""; + prevContour = contour; + } + else // Nieuwe contour is niet beter + { + contour = prevContour; + } + } + else + prevContour = contour; + prevContour->m_contLabel = text.string(); + prevContour->m_Key = text.string().ascii(); + #ifdef SHAKE_FOR_TEST + if (1||prevContour->m_Label.equals("x706")) + { + srand( (unsigned)time( NULL ) ); + int i; + for (i=0;icount();i++) { + WT_Logical_Point *pt = &(prevContour->points()[i]); + int diff = (int)(400); // 0.1% afwijking + double dx = ((double)rand() / RAND_MAX - 0.5); + double dy = ((double)rand() / RAND_MAX - 0.5); + pt->m_x += diff * dx; + pt->m_y += diff * dy; + } + + } + #endif + prevContour->m_ptLabel = text.position(); + } + else + { + myTRACE("\nLabel %s with area %8.2fm2", text.string().ascii(), contour->m_DWGArea/1e6); + if (!strcmp(text.string().ascii(), contour->m_contLabel.ascii())) + myTRACE(" komt dubbel voor (maar wel dezelfde contour)!"); + else + myTRACE(" was al bezet door %s", contour->m_contLabel.ascii()); + } + } + } + } + return; +} + +WT_Result CWhipFile::my_process_layer (WT_Layer & layer, WT_File & file) +{ + file.rendition().layer() = layer; + if (layer.layer_name().length()>0) // Anders zittie alleen maar in de weg + { // Dat doet de default_process 'fout' + file.layer_list().add_layer(layer); + } + + WT_Integer32 layer_num = layer.layer_num(); + WT_Layer *ll = file.layer_list().find_layer_from_index(layer_num); + if (ll&& ll->layer_name().ascii()) + { + CWhipFileState *m_State = (CWhipFileState *)file.heuristics().user_data(); + m_State->labelLayerActive = m_State->labelMatch(ll->layer_name().ascii()); + m_State->contLayerActive = m_State->contMatch(ll->layer_name().ascii()); + } + + return WT_Result::Success; +} + +// This is what AutoCAD seems to create for a normal closed polyline +// but also for the rendition of the character '0' +WT_Result CWhipFile::my_process_polyline(WT_Polyline & polyline, WT_File & file) +{ + CWhipFileState *m_State = (CWhipFileState *)file.heuristics().user_data(); + if (!m_State->contLayerActive) + return WT_Result::Success; // Wrong layer + + bool frstIsLast = (polyline.points()[0].m_x == polyline.points()[polyline.count()-1].m_x && + polyline.points()[0].m_y == polyline.points()[polyline.count()-1].m_y); + // (Vigor) DWF's uit ARKEY hebben de onhebbelijke eigenschap dat de contour begint + // met een aanhaallijntje. Dat ondersteunen we dan toch maar. + bool scndIsLast = false; + if (g_SLNKOptions.m_SkipContLeader && polyline.count()>1) + { + scndIsLast = (polyline.points()[1].m_x == polyline.points()[polyline.count()-1].m_x && + polyline.points()[1].m_y == polyline.points()[polyline.count()-1].m_y); + } + if (!frstIsLast && !scndIsLast) + return WT_Result::Success; // Not closed. Who cares + +xxxx++; + + WT_Units units=file.rendition().drawing_info().units(); + + // WD_True as we are going to mess + CSLNKContourImpl *myContour; + if (scndIsLast) // eerste lijntje droppen + myContour = new CSLNKContourImpl(polyline.count()-1,polyline.points()+1, WD_True, m_State); + else + myContour = new CSLNKContourImpl(polyline.count(),polyline.points(), WD_True, m_State); + + // A major problem: Sometimes AutoCAD's DWFOUT merges two adjacent polylines + // into one WT_Polyline. We hate that so we start splitting them again here + // Note this also happens on rendering of some texts. We don't care about + // that but cannot detect the difference, so split them as well. + // TODO: Als een afgesplitste contour uiteindelijk binnen de start contour + // valt dan hebben we te maken met een eiland dat door een tekenaar + // gemaakt is. Dan moeten we niet splitsen. Zucht.. + + for (int i=1; icount()-2; i++) // -2: Laat normale eindpunt ongemoeid + { + if ((myContour->points()[i]).m_x == (myContour->points()[0]).m_x && + myContour->points()[i].m_y == myContour->points()[0].m_y + ) + { // Van 0..i is al een loop. Trek die er alvast uit + myTRACE("\nSplit case %d-%d",i,myContour->count()); + // Create a copy of the looping section + // Sample: i=6, j=2, diff=4 pt + CSLNKContourImpl *myContour2 = new CSLNKContourImpl(i, myContour->points(), WD_True, m_State); + myContour2->m_DWGArea = PolygonArea(myContour2, units); + m_State->m_SLNKContouren.Add(myContour2); + + // Create a copy of the end section + CSLNKContourImpl *myContour3 = new CSLNKContourImpl(myContour->count()-i, myContour->points()+i, WD_True, m_State); + // Delete the old one (seem all together a little overkill) + delete myContour; + myContour = myContour3; + i=0; // vanaf daar verder kijken + } + } + + // Bij akzo 4310 kwam (Alleen AutoCAD 2004) het volgende geval voor. + // Dat onderkennen we door te testen met het oude algoritme en een twee-punts overlap + // 0,8--->1 + // | | + // | v + // 3,7<--2,6 + // | ^ + // v | + // 4----->5 + + for (int i=1; icount()-1; i++) + { + for (int j=0; jpoints()[i] == myContour->points()[j]) + { + myTRACE("\nSplitsen?"); + if (myContour->points()[i+1] == myContour->points()[j+1]) + { + myTRACE(" YES"); + // Van j..i is een loop. Trek die er uit + // myTRACE("\nSplit case %d-%d",i,myContour->count()); + // Create a copy of the looping section + // Sample: i=6, j=2, diff=4 pt + CSLNKContourImpl *myContour2 = new CSLNKContourImpl(i-j+1, myContour->points()+j, WD_True, m_State); + myContour2->m_DWGArea = PolygonArea(myContour2, units); + m_State->m_SLNKContouren.Add(myContour2); + + // Close the hole in myContour + for (int k=j+1; k+i-jcount(); k++) + myContour->points()[k]=myContour->points()[k+i-j]; + + // Create a copy of the start section + CSLNKContourImpl *myContour3 = new CSLNKContourImpl(myContour->count()-(i-j), myContour->points(), WD_True, m_State); + // Delete the old one (seem all together a little overkill) + delete myContour; + myContour = myContour3; + i=j; // vanaf daar verder kijken + } + } + } + + // Last (or only) section + myContour->m_DWGArea = PolygonArea(myContour, units); + myTRACE("\nFound contour with area %8.2fm2", myContour->m_DWGArea/1e6); + if (myContour->m_DWGArea >= g_SLNKOptions.m_MinContSize) + m_State->m_SLNKContouren.Add(myContour);// Doet uiteindelijk wel een delete op myContour + else + { + myTRACE(" te klein bevonden"); + delete myContour; + } + + return WT_Result::Success; +} + +// Note: For SHX-fonts AutoCAD 2002+ creates an invisible (Text) object +// which will get used here +WT_Result CWhipFile::my_process_text (WT_Text & text, WT_File & file) +{ + CWhipFileState *m_State = (CWhipFileState *)file.heuristics().user_data(); + if (!m_State->labelLayerActive) + return WT_Result::Success; // Wrong layer + + m_State->m_SLNKLabels.Add(text); + return WT_Result::Success; +} + +// 'Herschrijf' de plan DWF naar de output +// Doe eerst de 'header' van de DWF (viewport en zo) en zodra +// we de eerste drawable tegenkomen doen we de contouren tussendoor +// zodat die (als ze ingekleurd worden) altijd onderaan liggen +HRESULT CWhipFile::SerializePlan(WT_File & my_plan_file, myWT_File & my_file, double scale) +{ + WT_Result result; + BOOL firstDrawable = true; + + BOOL CurrentLayerOn = TRUE; // Skip contourlagen + my_plan_file.set_layer_action(my_process_layer); // Override default processing + // Do the actual reading. + + while ((result = my_plan_file.process_next_object()) == WT_Result::Success) + { + switch(my_plan_file.current_object()->object_type()) + { + case WT_Object::Origin_ID: + break; + case WT_Object::Drawable: + if (firstDrawable) + GenerateContouren(my_plan_file, my_file, scale, true); // Alle 'solid' kleuren + firstDrawable = false; +#ifdef _DEBUG + if (my_plan_file.current_object()->object_id() == WT_Object::Origin_ID + && !my_file.heuristics().allow_binary_data() + ) + { // I do not understand why but it will assert otherwise + break; + } +#endif + if (CurrentLayerOn) + my_plan_file.current_object()->serialize(my_file); + break; + case WT_Object::Attribute: + { + const WT_Attribute *obj = (WT_Attribute *)my_plan_file.current_object(); + if (obj->object_id() == WT_Object::Layer_ID) + { // Sla de oorspronkelijke contour lagen over + // En ook de lagen die we niet willen + CurrentLayerOn = TRUE; + WT_Layer *layer = (WT_Layer *)obj; + WT_Integer32 layer_num = layer->layer_num(); + if (layer_num==0) + { // ARKEY heeft lagen met nummer 0. Dat mag niet volgens de + // Whip-spec en gaat ook mis (alleen) bij binaire DWF's + if (my_file.heuristics().allow_binary_data()) + { + myDoTRACE("\nSkipping layer with invalid number 0"); + break; + } + } + WT_Layer *ll = my_plan_file.layer_list().find_layer_from_index(layer_num); + if (ll&& + ll->layer_name().ascii()&& + (m_State.labelMatch(ll->layer_name().ascii()) || + m_State.contMatch(ll->layer_name().ascii()) || + !m_State.layerMatch(ll->layer_name().ascii())) + ) + CurrentLayerOn = FALSE; // Layer object hoeft ook niet meer geserialized + else + layer->serialize(my_file); + } + else + { +#ifdef _DEBUG + CString s(my_plan_file.file_stats()->descriptions()); + // myTRACE("Attribute '%s'\n", s); +#endif + // Hoewel een Attibute gaat hij toch niet via desired_rendition + // Omdat we weten dat we net uit uit een DWF komen kunnen we best + // wel rechtstreeks serializen + // Let wel: desired_rendition is dan niet meer te vertrouwen. Zie @@@ + obj->serialize(my_file); + } + } + break; + default: +#ifdef _DEBUG + CString s(my_plan_file.file_stats()->descriptions()); + //myTRACE("Skipping '%s'\n", s); +#endif + break; + } + } +// if (result == WT_Result::End_Of_DWF_Opcode_Found) +// dwfresult = DwfResult::Success; + +// TODO: desired_rendition klopt nu niet meer met de daadwerkelijke rendition? + + return S_OK; +} + +// Extra saveas wrapper om met __try een eventuele Win32 exception ook op te vangen +STDMETHODIMP CWhipFile::SaveAs(BSTR WhipPath) +{ + myTRACE("\nAbout to save into %ls with plan", (LPCTSTR)WhipPath); + + __try { + return SaveAs2(WhipPath); + } + __except(EXCEPTION_EXECUTE_HANDLER) + { + DWORD exCode = GetExceptionCode(); + myDoTRACE("\nUnhandled Win32 exception 0x%x in CWhipFile::SaveAs", exCode); + char err[128]; + sprintf(err, "\nUnhandled Win32 exception 0x%x", exCode); + + return myAtlReportError (GetObjectCLSID(), "\nCWhipFile::SaveAs('%ls')\n%s", (LPCSTR)WhipPath, err); + } +} + +STDMETHODIMP CWhipFile::SaveAs2(BSTR WhipPath) +{ + try { + myWT_File my_file; + my_file.set_filename(WhipPath); + return Generate(my_file); + } + catch (WT_Result::Enum e) + { + CString err; + err.Format("\nInternal error WT_Result::Enum %d",e); + return myAtlReportError (GetObjectCLSID(), "\nCWhipFile::SaveAs('%ls')\n%s", (LPCSTR)WhipPath, err); + } + catch (CString &err) + { + return myAtlReportError (GetObjectCLSID(), err); + } +} + +// Altijd hoogte 1000, echte fontheight gaf overflow bij SDU +class tempFontDC +{ +public: + tempFontDC(WT_String m_FontName) + { + HDC tempDC = CreateDC("DISPLAY",NULL,NULL,NULL); + m_DC = CreateCompatibleDC ( tempDC ); + DeleteDC(tempDC); + + LOGFONT lf; + memset(&lf, 0, sizeof(LOGFONT)); // clear out structure. + strncpy(lf.lfFaceName, m_FontName.ascii(), LF_FACESIZE); + lf.lfHeight = -FONT_SIZER; + fnt = CreateFontIndirect(&lf); + HGDIOBJ oldfont = SelectObject(m_DC, fnt); + } + + ~tempFontDC() + { + // Opruimen + DeleteObject(fnt); + DeleteDC(m_DC); + } + inline operator const HDC() + { return m_DC; } +private: + HDC m_DC; + HFONT fnt; +}; + +bool CWhipFile::GenerateSymbols(myWT_File &my_file) +{ + double scale = m_State.m_contunits.application_to_dwf_transform()(0,0); + // TODO: Echt uniek layernum (en URL num) bepalen + my_file.desired_rendition().layer() = WT_Layer(my_file, 1000, "SLNK Symbols"); + + for (size_t i=0; im_symbolName == "" || !m_State.m_SLNKSymbolDefinitions.Lookup(symbol->m_symbolName)) + symbol->serialize(my_file, m_State.m_contunits, NULL, m_State.m_hintScale); + else + { +#ifdef _DEBUG + WT_Comments cmt; + CString s; s.Format("About to insert symbol %s", symbol->m_symbolName); + cmt.set(s); + cmt.serialize(my_file); +#endif + symbol->serialize(my_file, m_State.m_contunits, m_State.m_SLNKSymbolDefinitions[symbol->m_symbolName], m_State.m_hintScale); + } + } + return true; +} + +bool CWhipFile::GenerateSymbolLabels(myWT_File &my_file) +{ + double scale = m_State.m_contunits.application_to_dwf_transform()(0,0); + // Zet een DC op om bij 'Center' de afmetingen van de tekst te kunnen bepalen + int fontheight= myRound(m_FontHeightSymbols * scale); + tempFontDC myDC(m_FontName); + + WT_Font myfont; + myfont.font_name() = m_FontName; + myfont.height() = fontheight; + my_file.desired_rendition().font() = my_file.rendition().font() = myfont; + myfont.serialize(my_file); // Vertrouw niets. Expliciete serialize. Zie @@@ + + WT_Color clr(255,255,255,0); //Teksten wit + my_file.desired_rendition().color() = my_file.rendition().color() = clr; + clr.serialize(my_file); // Vertrouw niets. Expliciete serialize. Zie @@@ + + // TODO: Echt uniek layernum (en URL num) bepalen + my_file.desired_rendition().layer() = WT_Layer(my_file, 1001, "SLNK Symbol Labels"); + for (size_t i=0; im_dwgX, symbol->m_dwgY)); + symbol->m_SLNKContour.m_ptLabel = center; + symbol->m_SLNKContour.SerializeLabel(my_file, CSLNKContourImpl::LABEL_OUTSIDEBOTTOM, fontheight, myDC); + } + return true; +} + +// Schrijf alle uitgerekende contouren naar het DWF bestand +// Deze functie wordt twee keer aangeroepen +// Heel vroeg (voor de plattegrond) worden alle contouren met een solid kleur +// wegeschreven. Die komen dan helemaal onderop. Ze zouden anders afdekken +// In de tweede slag komen alle transparante contouren. Die komen na de +// plattegrond zodat de plattegrond doorschijnt. +bool CWhipFile::GenerateContouren(WT_File &my_planfile, myWT_File &my_file, + double scale, BOOL solidOnly) +{ + // Zorg dat we zelf neutraal blijven + WT_Layer keepLayer = my_planfile.rendition().layer(); + WT_Color keepColor = my_planfile.rendition().color(); + + // Vertrouw de huidige rendition niet! + WT_Color().serialize(my_file); + + //Store the current object node hoewel die echt null zal zijn.... + WT_Object_Node current_node = my_file.desired_rendition().object_node(); + + // TODO: Echt uniek layernum (en URL num) bepalen + my_file.desired_rendition().layer() = WT_Layer(my_file, 1002, "SLNK Contours"); + + for (size_t i=0; iserialize(my_file, solidOnly); + } + my_file.desired_rendition().object_node() = current_node; + + my_file.desired_rendition().line_weight() = 0; // Voor als er later bijvoorbeeld nog symbolen komen + + my_file.desired_rendition().layer() = my_file.rendition().layer() = keepLayer; + if (keepLayer.layer_num()) keepLayer.serialize(my_file); // Zeker terugzetten + my_file.desired_rendition().color() = my_file.rendition().color() = keepColor; + keepColor.serialize(my_file); // Zeker terugzetten + return true; +} + +bool CWhipFile::GenerateLabels(WT_File &my_planfile, myWT_File &my_file, double scale) +{ + // Zorg dat we zelf neutraal blijven + WT_Layer keepLayer = my_planfile.rendition().layer(); + WT_Color keepColor = my_planfile.rendition().color(); + + // TODO: Echt uniek layernum (en URL num) bepalen + my_file.desired_rendition().layer() = WT_Layer(my_file, 1003, "SLNK Labels"); + + // Zet een DC op om bij 'Center' de afmetingen van de tekst te kunnen bepalen + int fontheight= myRound(m_FontHeight * scale); + tempFontDC myDC(m_FontName); + + WT_Font myfont; + myfont.font_name() = m_FontName; + myfont.height() = fontheight; + my_file.desired_rendition().font() = my_file.rendition().font() = myfont; + myfont.serialize(my_file); // Vertrouw niets. Expliciete serialize. Zie @@@ + + // En nu nog een keer alle teksten + for (size_t i=0; im_contLabel.length()!=0 && contour->m_ExtraLabel != "") + { // We have got a proper label/contour + // Alle teksten tekenen + contour->SerializeLabel(my_file, m_LabelPos, fontheight, myDC); + } + } + + my_file.desired_rendition().layer() = my_file.rendition().layer() = keepLayer; + if (keepLayer.layer_num()) keepLayer.serialize(my_file); // Zeker terugzetten + my_file.desired_rendition().color() = my_file.rendition().color() = keepColor; + keepColor.serialize(my_file); // Zeker terugzetten + + return true; +} + +// We hebben de contouren bepaald. Genereer daarvoor nu nieuwe DWF-primitieven +// In het bijzonder kennen we er een kleurtje aan toe en plaatsen wel de labels (opnieuw) +STDMETHODIMP CWhipFile::Generate(myWT_File &my_file) +{ + // Bepaal de te gebruiken hoogte in Logical Points + + double scale = m_State.m_contunits.application_to_dwf_transform()(0,0); + myDoTRACE("\nSchaal: %.2f", scale); + + WT_Result result; + + my_file.set_file_mode(WT_File::File_Write); +#ifdef _DEBUG + my_file.heuristics().set_allow_binary_data(WD_False); +#endif + // Zal niet zo snel meer gebeuren maar we willen het zeker niet + my_file.heuristics().set_allow_drawable_merging(WD_False); + // Let op: De viewer kan 60-file niet zo maar lezen, dat moet naar packed-DWF + // Later: viewer 6.5 kan gewoon een W2D file tonen + // Let op: bij versie 55 worden Node's niet weggeschreven + // my_file.heuristics().set_target_version(55); + if (my_file.open() != WT_Result::Success) + { + return myAtlReportError (GetObjectCLSID(), "ERROR: Unable to open file for writing: %s", my_file.filename().ascii()); + ATLASSERT(false); + } + + // Symbolen worden mogelijk geplaatst net buiten onze coordinatenruimte (met name X) + // Dat gaf clipping problemen. + // Daarom verplaatsen we alles in onze coordinatenruimte naar links/onder (0,0) + WT_Logical_Point lshift(-(max(0,this->m_view.view().m_min.m_x)), + -(max(0,this->m_view.view().m_min.m_y))); // Iets minder clipping van INT_MAX + // Contouren hebben we ondertussen al wel/ + // Nu nog een keer door de DWF om de rest te kopieren naar de output + m_W2DFile.set_file_mode(WT_File::File_Read); + my_file.heuristics().set_apply_transform(WD_False); + myTRACE("\nAbout to open plan"); + if (m_W2DFile.open() == WT_Result::Success) + { +#ifdef _DEBUG + WT_Comments cmt; + cmt.set("About to insert planfile"); + cmt.serialize(my_file); +#endif + // TODO: Dit moet uit de originele PlanDWF z'n Manifest/Paper komen + + int keep=my_file.heuristics().target_version(); + // Even background ondersteunen + my_file.heuristics().set_target_version(55); + WT_Background bg(WT_Color(0,0,0)); + bg.serialize(my_file); + my_file.heuristics().set_target_version(keep); + + my_file.heuristics().set_transform(WT_Transform (lshift, 1.0, 1.0, 0)); + my_file.heuristics().set_apply_transform(true); + + { + CmyTimer tm("Serializing plan"); + SerializePlan(m_W2DFile, my_file, scale); // Heeft eventueel een GenerateContouren in zich! + } +#ifdef _DEBUG + cmt.set("Plan is serialized"); + cmt.serialize(my_file); +#endif + myTRACE("\nPlan is serialized"); + m_W2DFile.close(); + } + else + { + myTRACE("\nKon plan niet openen"); + return myAtlReportError (GetObjectCLSID(), "ERROR: Unable to open plan file"); + } + + myTRACE("\nAbout to generate Contouren"); + // Twee loops. Eerst alle contouren (en vlakvullingen), daarna pas + // de teksten. Zodoende zijn de teksten altijd leesbaar + GenerateContouren(m_W2DFile, my_file, scale, false); // Alle transparante kleuren + //merging geeft vreemd effect op de contouren die we om symbolen tekenen in _DEBUG mode + // dan worden die contouren niet meer meegeschaalt? TODO: Uitzoeken + //my_file.heuristics().set_allow_drawable_merging(WD_True); // Voor symbolen kan het (na verschalen) wel schelen + GenerateSymbols(my_file); // Ook alle contouren van symbolen + GenerateSymbolLabels(my_file); + GenerateLabels(m_W2DFile, my_file, scale); + + myTRACE("\nAbout to close"); + //Restore the saved object node. + my_file.desired_rendition().fill() = WD_False; + my_file.close(); + + myTRACE("\nDone saving"); + return S_OK; +} + +// mei 2007: DEPRECATED +// Lege Identlabel zet alle labels op de extralabel+default +STDMETHODIMP CWhipFile::SetLabel(BSTR IdentLabel, BSTR ExtraLabel) +{ + try { + for (size_t i=0; im_contLabel.length()>0) + { + if (contour->m_contLabel.equals(IdentLabel) || SysStringLen(IdentLabel) == 0) + { + contour->m_ExtraLabel = ExtraLabel; + } + + if (SysStringLen(IdentLabel) == 0) + contour->m_ExtraLabel += contour->m_contLabel.ascii(); + } + } + return S_OK; + } + catch (WT_Result::Enum e) + { + CString err; + err.Format("\nInternal error WT_Result::Enum %d",e); + return myAtlReportError (GetObjectCLSID(), "\nCWhipFile::SetLabel('%ls')\n%s", (LPCSTR)IdentLabel, err); + } +} + +// mei 2007: DEPRECATED +// Lege Identlabel zet alle ruimtes op dezelfde kleur +STDMETHODIMP CWhipFile::SetColor(BSTR IdentLabel, ULONG rgb, BYTE Alpha /*=0*/) +{ + try { + for (size_t i=0; im_contLabel.length()>0 && + (SysStringLen(IdentLabel) == 0 || contour->m_contLabel.equals(IdentLabel))) + { + int b=rgb%256; + int g=(rgb>>8)%256; + int r=(rgb>>16)%256; + contour->m_Color.set(r, g, b, Alpha); + } + } + return S_OK; + } + catch (WT_Result::Enum e) + { + CString err; + err.Format("\nInternal error WT_Result::Enum %d",e); + return myAtlReportError (GetObjectCLSID(), "\nCWhipFile::SetColor('%ls')\n%s", (LPCSTR)IdentLabel, err); + } + +} + +STDMETHODIMP CWhipFile::SetLabelFont(BSTR FontName, DOUBLE FontHeight, DOUBLE FontHeightSymbols) +{ + m_FontName.set(FontName); + m_FontHeight = FontHeight; + m_FontHeightSymbols = (FontHeightSymbols>0)?FontHeightSymbols:FontHeight; + + return S_OK; +} + +STDMETHODIMP CWhipFile::SetLabelPosition(BYTE LabelPos) +{ + switch (LabelPos) + { + case 1: m_LabelPos = CSLNKContourImpl::LABEL_DEFAULT; break; + case 2: m_LabelPos = CSLNKContourImpl::LABEL_CENTROID; break; + case 3: m_LabelPos = CSLNKContourImpl::LABEL_TOPLEFT; break; + default: m_LabelPos = CSLNKContourImpl::LABEL_DEFAULT; + } + + return S_OK; +} + +STDMETHODIMP CWhipFile::get_ContoursXML(BSTR* pVal) +{ + DWFCore::DWFBufferOutputStream XMLProps(1024); + + DWFUUID _oUUID; + DWFXMLSerializer XML(_oUUID); + XML.attach(XMLProps); + XML.startElement( L"Contours", L"SLNKDWF" ); + for (size_t i=0; iserializeXML(XML, 0); + } + XML.endElement(); + XML.detach(); + + CComBSTR bstrString((int)XMLProps.bytes(), (LPCSTR)XMLProps.buffer()); + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CWhipFile::get_AddSymbol(DOUBLE dwgX, DOUBLE dwgY, BSTR symbolName, IUnknown** pVal) +{ + CString name(symbolName); + + myTRACE("\nAdding symbol %s at %.2f,%.2f", name, dwgX, dwgY); + + CSLNKSymbolImpl *mySymbol = new CSLNKSymbolImpl(dwgX, dwgY, &m_State); + m_State.m_SLNKSymbols.Add(mySymbol); + + // Als resultaat leveren we een COM object op waar je eventueel de rest van + // de properties op kunt zetten + CComObject *theSymbol; + HRESULT hr = CComObject::CreateInstance(&theSymbol); + if(FAILED(hr)) return hr; + + theSymbol->AddRef(); + hr = theSymbol->QueryInterface(IID_ISLNKSymbol, (void **)pVal); + theSymbol->SetParent(this); // Zodat scope blijft + theSymbol->Release(); + if(FAILED(hr)) return hr; + theSymbol->SetImpl(mySymbol); // Heel belangrijk: zet de implementatie waar we een interface op bieden + + if (!m_State.m_SLNKSymbolDefinitions.Lookup(name)) + name = "*STAR"; // Die vinden we altijd ja + ATLASSERT(m_State.m_SLNKSymbolDefinitions.Lookup(name)); + + mySymbol->m_symbolName = name; + mySymbol->m_SLNKContour.set(m_State.m_SLNKSymbolDefinitions[name]->m_BoundingContour.count(), + m_State.m_SLNKSymbolDefinitions[name]->m_BoundingContour.points(), true); // TODO: Is copy wel nodig?==>Ja, we gaan ze later transformeren! + if (name[0] == '*') + { + mySymbol->m_SLNKContour.m_Color = WT_Color(255,0,0,255); + mySymbol->m_SLNKContour.m_outlineAlpha = 255; // Anders wordtie helemaal niet getekend? + } + return S_OK; +} + +STDMETHODIMP CWhipFile::DefineSymbol(BSTR symbolName, VARIANT EPlotStream) +{ + myTRACE("\nDefining symbol %ls", symbolName); + if (EPlotStream.vt!=VT_ERROR) + { + VARIANT *var2 = &EPlotStream; + if (var2->vt==(VT_VARIANT|VT_BYREF)) // ByRef + var2 = (VARIANT *)var2->pvarVal; + + if (var2->vt==VT_DISPATCH) + { + CComQIPtr EPlotSection; + EPlotSection = var2->pdispVal; + if (!EPlotSection) + return E_INVALIDARG; + else + { + CSLNKSymbolDefinition * symb = new CSLNKSymbolDefinition(EPlotSection); + + CString name(symbolName); + m_State.m_SLNKSymbolDefinitions.SetAt(name, symb); + } + } + else + return E_INVALIDARG; + } + + return S_OK; +} + +STDMETHODIMP CWhipFile::DefineBitmapSymbol(BSTR symbolName, BSTR symbolPath, double height) +{ + myTRACE("\nDefining bitmap symbol %ls", symbolName); + CSLNKSymbolDefinition * symb = new CSLNKSymbolDefinition(CString(symbolPath), height); + CString name(symbolName); + m_State.m_SLNKSymbolDefinitions.SetAt(name, symb); + //return E_INVALIDARG; + + return S_OK; +} + +// Merk op: als iemand twee keer dezelfde contour opvraagt maken we twee onafhankelijke +// SLNKContour objecten aan die beide naar dezelfde CSLNKContourImpl wijzen +// Het maakt verder weinig uit en is wel gemakkelijker (toch?) +STDMETHODIMP CWhipFile::get_Contour(BSTR IdentLabel, IUnknown** pVal) +{ + try { + for (size_t i=0; im_contLabel.length()>0 && contour->m_contLabel.equals(IdentLabel)) + { + CComObject *theContour; + HRESULT hr = CComObject::CreateInstance(&theContour); + if(FAILED(hr)) return hr; + + theContour->AddRef(); + hr = theContour->QueryInterface(IID_ISLNKContour, (void **)pVal); + theContour->SetParent(this); + theContour->Release(); + if(FAILED(hr)) return hr; + theContour->SetImpl(contour); // Heel belangrijk: zet de implementatie waar we een interface op bieden + + return S_OK; // Wel gevonden + } + } + return S_OK; // Niet gevonden. Automatisch NULL? + } + catch (WT_Result::Enum e) + { + CString err; + err.Format("\nInternal error WT_Result::Enum %d",e); + return myAtlReportError (GetObjectCLSID(), "\nCWhipFile::get_Contour('%ls')\n%s", (LPCSTR)IdentLabel, err); + } + + return S_OK; +} + +STDMETHODIMP CWhipFile::get_hintScale(DOUBLE* pVal) +{ + (*pVal) = m_State.m_hintScale; + + return S_OK; +} + +STDMETHODIMP CWhipFile::put_hintScale(DOUBLE newVal) +{ + m_State.m_hintScale = newVal; + myTRACE("\nhintScale set to %.6f", newVal); + + return S_OK; +} + +STDMETHODIMP CWhipFile::get_FindInContour(DOUBLE dwgX, DOUBLE dwgY, BSTR* pVal) +{ + CString result; + WT_Point3D insertion(dwgX, dwgY); + WT_Logical_Point LPInsertion = m_State.m_contunits.transform(WT_Point3D(dwgX, dwgY)); + + for (size_t i=0; im_contLabel.length()>0) + if (CSLNKContourImpl::PointInPolygon(LPInsertion, *contour)) + { + result = contour->m_contLabel; + (*pVal) = result.AllocSysString(); + } + } + return S_OK; +} \ No newline at end of file diff --git a/SlnkDWFCom/WhipFile.h b/SlnkDWFCom/WhipFile.h new file mode 100644 index 0000000..8931c06 --- /dev/null +++ b/SlnkDWFCom/WhipFile.h @@ -0,0 +1,193 @@ +// WhipFile.h : Declaration of the CWhipFile + +#pragma once +#include "resource.h" // main symbols +#include "whiptk\whip_toolkit.h" +#include "myWT_File.h" + +using namespace DWFCore; +using namespace DWFToolkit; + +#include "SLNKContourImpl.h" +#include "SLNKSymbol.h" + +#include "SLNKDWF.h" + +class CWhipFileState +{ +public: + CWhipFileState() + { + m_reContouren.Parse(".*", FALSE); + m_reLabels.Parse(".*", FALSE); + m_reLayers.Parse(".*", FALSE); + m_hintScale = -1.0; + }; + BOOL SetLayers(BSTR reContouren, BSTR reLabels) + { + REParseError status = m_reContouren.Parse( CString(reContouren), false ); + if (REPARSE_ERROR_OK != status) + { + myTRACE("\nSorry, kan reguliere expressie contouren niet parsen"); + // Unexpected error. + return FALSE; + } + status = m_reLabels.Parse( CString(reLabels), false ); + if (REPARSE_ERROR_OK != status) + { + myTRACE("\nSorry, kan reguliere expressie labelsB niet parsen"); + // Unexpected error. + return FALSE; + } + return TRUE; + } + BOOL SetFilterLayers(BSTR reLayers) + { + REParseError status = m_reLayers.Parse( CString(reLayers), false ); + if (REPARSE_ERROR_OK != status) + { + myTRACE("\nSorry, kan reguliere expressie filterlayers niet parsen"); + // Unexpected error. + return FALSE; + } + return TRUE; + } + ~CWhipFileState() + { + for (size_t i=0; i mcUrl; + return m_reContouren.Match(str, &mcUrl); + } + // Is dit een contourlabel laag + BOOL labelMatch(const char* str) + { + CAtlREMatchContext<> mcUrl; + return m_reLabels.Match(str, &mcUrl); + } + // Is dit een 'gewone' laag die in het resultaat moet verschijnen? + BOOL layerMatch(const char* str) + { + CAtlREMatchContext<> mcUrl; + return m_reLayers.Match(str, &mcUrl); + } + CAtlArray m_SLNKContouren; + CAtlArray m_SLNKSymbols; + CAtlMap m_SLNKSymbolDefinitions; + CAtlArray m_SLNKLabels; + + WT_Units m_contunits; + BOOL contLayerActive; + BOOL labelLayerActive; + double m_hintScale; // Kunnen we gebruiken om symbolen te 'geeken' + +private: + CAtlRegExp<> m_reContouren; + CAtlRegExp<> m_reLabels; + CAtlRegExp<> m_reLayers; // Die met SaveAs moeten blijven +}; + +// CWhipFile +class ATL_NO_VTABLE CWhipFile : + public CComObjectRootEx, + public CComCoClass, + public ISupportErrorInfo, + public IDispatchImpl +{ +public: + CWhipFile(); + +DECLARE_REGISTRY_RESOURCEID(IDR_WHIPFILE) + + +BEGIN_COM_MAP(CWhipFile) + COM_INTERFACE_ENTRY(IWhipFile) + COM_INTERFACE_ENTRY(IDispatch) + COM_INTERFACE_ENTRY(ISupportErrorInfo) +END_COM_MAP() + +// ISupportsErrorInfo + STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + return S_OK; + } + + void FinalRelease() + { + } + +public: + + STDMETHOD(Load)(BSTR WhipPath); + STDMETHOD(LoadStream)(VARIANT EPlotStream); + STDMETHOD(SetLayers)(BSTR reContouren, BSTR reLabels); + STDMETHOD(SaveAs)(BSTR WhipPath); + STDMETHOD(SaveAs2)(BSTR WhipPath); + STDMETHOD(SetLabel)(BSTR IdentLabel, BSTR ExtraLabel); + STDMETHOD(SetColor)(BSTR IdentLabel, ULONG rgb, BYTE Alpha); + STDMETHOD(SetLabelFont)(BSTR FontName, DOUBLE FontHeight, DOUBLE FontHeightSymbols); + STDMETHOD(SetLabelPosition)(BYTE LabelPos); + STDMETHOD(get_ContoursXML)(BSTR* pVal); + STDMETHOD(get_AddSymbol)(DOUBLE dwgX, DOUBLE dwgY, BSTR symbolName, IUnknown** pVal); + STDMETHOD(DefineSymbol)(BSTR symbolName, VARIANT EPlotStream); + STDMETHOD(DefineBitmapSymbol)(BSTR symbolName, BSTR symbolPath, DOUBLE height); + STDMETHOD(get_Contour)(BSTR IdentLabel, IUnknown** pVal); + STDMETHOD(SetFilterLayers)(BSTR reLayers); + STDMETHOD(get_FindInContour)(DOUBLE dwgX, DOUBLE dwgY, BSTR* pVal); + +private: + CWhipFileState m_State; + + WT_String m_FontName; + double m_FontHeight, m_FontHeightSymbols; + CSLNKContourImpl::LABELPOS m_LabelPos; + + CComQIPtr m_iEPlotSection; // Om scope levend te houden + myWT_File m_W2DFile; + WT_View m_view; // Initial view + HRESULT ProcessContouren(); + HRESULT SerializePlan(WT_File & my_plan_file, myWT_File & my_file, double scale); + + bool GenerateSymbols(myWT_File &my_file); + bool GenerateSymbolLabels(myWT_File &my_file); + + bool GenerateContouren(WT_File &my_planfile, myWT_File &my_file, + double scale, BOOL solidOnly); + bool GenerateLabels(WT_File &my_planfile, myWT_File &my_file, double scale); + + STDMETHOD(Generate)(myWT_File &my_file); + void read_for_contours(); + void processLabels(); + static WT_Result my_process_layer (WT_Layer & layer, WT_File & file); + //static WT_Result my_process_polygon(WT_Polygon & polygon, WT_File & file); + static WT_Result my_process_polyline(WT_Polyline & polyline, WT_File & file); + static WT_Result my_process_polytriangle(WT_Polytriangle & polytriangle, WT_File & file); + static WT_Result my_process_text (WT_Text & text, WT_File & file); +public: + STDMETHOD(get_hintScale)(DOUBLE* pVal); + STDMETHOD(put_hintScale)(DOUBLE newVal); +}; + +OBJECT_ENTRY_AUTO(__uuidof(WhipFile), CWhipFile) diff --git a/SlnkDWFCom/WhipFile.rgs b/SlnkDWFCom/WhipFile.rgs new file mode 100644 index 0000000..1bdd2a1 --- /dev/null +++ b/SlnkDWFCom/WhipFile.rgs @@ -0,0 +1,27 @@ +HKCR +{ + SLNKDWF.WhipFile.1 = s 'WhipFile Class' + { + CLSID = s '{C2632BD5-3157-45A6-8FFC-57063FF2B169}' + } + SLNKDWF.WhipFile = s 'WhipFile Class' + { + CLSID = s '{C2632BD5-3157-45A6-8FFC-57063FF2B169}' + CurVer = s 'SLNKDWF.WhipFile.1' + } + NoRemove CLSID + { + ForceRemove {C2632BD5-3157-45A6-8FFC-57063FF2B169} = s 'WhipFile Class' + { + ProgID = s 'SLNKDWF.WhipFile.1' + VersionIndependentProgID = s 'SLNKDWF.WhipFile' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + val AppID = s '%APPID%' + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/comobjectembed.h b/SlnkDWFCom/comobjectembed.h new file mode 100644 index 0000000..cb5f8a9 --- /dev/null +++ b/SlnkDWFCom/comobjectembed.h @@ -0,0 +1,50 @@ +#ifndef __COMOBJECTEMBED_H_ +#define __COMOBJECTEMBED_H_ + + +template //Base must be derived from CComObjectRoot +class CComObjectEmbed : public Base +{ +public: + typedef Base _BaseClass; + + CComObjectEmbed() {m_pOuterUnknown = NULL;} + CComObjectEmbed(void* pv) {m_pOuterUnknown = (IUnknown*)pv;} + void SetOuterUnknown(IUnknown *punkContainer) {m_pOuterUnknown = punkContainer;} + +#ifdef xx_ATL_DEBUG_INTERFACES + ~CComObjectEmbed() + { + _Module.DeleteNonAddRefThunk(_GetRawUnknown()); + _Module.DeleteNonAddRefThunk(m_pOuterUnknown); + } +#endif + + STDMETHOD_(ULONG, AddRef)() {return OuterAddRef();} + STDMETHOD_(ULONG, Release)() {return OuterRelease();} + STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject) + { + return _InternalQueryInterface(iid, ppvObject); + } + template + HRESULT STDMETHODCALLTYPE QueryInterface(Q** pp) + { + return QueryInterface(__uuidof(Q), (void**)pp); + } + + //GetControllingUnknown may be virtual if the Base class has declared + //DECLARE_GET_CONTROLLING_UNKNOWN() + IUnknown* GetControllingUnknown() + { +#ifdef xx_ATL_DEBUG_INTERFACES + IUnknown* p; + _Module.AddNonAddRefThunk(m_pOuterUnknown, _T("CComObjectEmbed"), &p); + return p; +#else + return m_pOuterUnknown; +#endif + } +}; + + +#endif /* !__COMOBJECTEMBED_H_ */ diff --git a/SlnkDWFCom/eplotsections.cpp b/SlnkDWFCom/eplotsections.cpp new file mode 100644 index 0000000..7359ec4 --- /dev/null +++ b/SlnkDWFCom/eplotsections.cpp @@ -0,0 +1,88 @@ +// EPlotSections.cpp : Implementation of CEPlotSections + +#include "stdafx.h" +#include "EPlotSections.h" + + +// CEPlotSections + +STDMETHODIMP CEPlotSections::InterfaceSupportsErrorInfo(REFIID riid) +{ + static const IID* arr[] = + { + &IID_IEPlotSections + }; + + for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) + { + if (InlineIsEqualGUID(*arr[i],riid)) + return S_OK; + } + return S_FALSE; +} + +// Omdat de tellingen gekoppeld zijn weten we zeker dat de refcount van +// onze eigen objecten ook 0 zal zijn en is het dus veilig ze weg te gooien (toch...?) +void CEPlotSections::FinalRelease() +{ + return; + for (int i=0; i<(LONG)m_EPlotSections.GetCount(); i++) + { + CComObjectEmbed *mySection; + mySection = &m_EPlotSections.GetAt(i); + mySection->FinalRelease(); + // Gebeurt in de destructor van AtlArray! delete (&m_EPlotSections.GetAt(i)); + } +} + +void CEPlotSections::InitImpl(CEPlotSectionsImpl *epl) +{ + m_pSectionsImpl = epl; +} + +STDMETHODIMP CEPlotSections::get_Parent(IDWFFile **ppParent) +{ + return m_pParent->QueryInterface(IID_IDWFFile, (void**)ppParent); +} + +void CEPlotSections::SetParent(IDWFFile *pParent) +{ + m_pParent = pParent; +} + +// Actually process the EPlotSections and add them to our collection +BOOL CEPlotSections::ProcessManifest(DWFManifest& rManifest, CString sourceDescription) +{ + ATLASSERT(false); + return TRUE; +} + +STDMETHODIMP CEPlotSections::get_Count(LONG* pVal) +{ + (*pVal) = (LONG)m_pSectionsImpl->get_Count(); + return S_OK; +} + +STDMETHODIMP CEPlotSections::get_Item(LONG i, IDispatch** pVal) +{ + if (i<0 || i>=(LONG)m_pSectionsImpl->get_Count()) + return E_INVALIDARG; + + if (m_EPlotSections.GetCount() == 0) + { // Tijd om de myEplotSectionImpl's te wrappen met onze myEplotSection's + for (int j=0; jget_Count(); j++) + { + CComObjectEmbed *mySection = new CComObjectEmbed; //= new tMyEplot; + mySection->SetParent(this); + CEPlotSectionImpl *ps; + ps = m_pSectionsImpl->get_Item(j); + mySection->InitImpl(ps); + mySection->SetOuterUnknown(GetControllingUnknown()); + mySection->FinalConstruct(); + m_EPlotSections.Add(*mySection); + } + } + ATLASSERT(i<(LONG)m_EPlotSections.GetCount()); + + return (m_EPlotSections.GetAt(i).QueryInterface(pVal)); +} diff --git a/SlnkDWFCom/myEPlotSection.cpp b/SlnkDWFCom/myEPlotSection.cpp new file mode 100644 index 0000000..51d4048 --- /dev/null +++ b/SlnkDWFCom/myEPlotSection.cpp @@ -0,0 +1,121 @@ +// EPlotSection.cpp : Implementation of CEPlotSection + +#include "stdafx.h" +#include "myEPlotSection.h" + +// CEPlotSection + +STDMETHODIMP CEPlotSection::InterfaceSupportsErrorInfo(REFIID riid) +{ + static const IID* arr[] = + { + &IID_IEPlotSection + }; + + for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) + { + if (InlineIsEqualGUID(*arr[i],riid)) + return S_OK; + } + return S_FALSE; +} + +void CEPlotSection::InitImpl(CEPlotSectionImpl *epl) +{ + m_pSectionImpl = epl; +} + +void CEPlotSection::FinalRelease() +{ +} + +STDMETHODIMP CEPlotSection::get_Parent(IEPlotSections **ppParent) +{ + return m_pParent->QueryInterface(IID_IEPlotSections, (void**)ppParent); +} + +void CEPlotSection::SetParent(IEPlotSections *pParent) +{ + m_pParent = pParent; +} + +STDMETHODIMP CEPlotSection::get_Name(BSTR* pVal) +{ + CComBSTR bstrString(m_pSectionImpl->get_Name()); + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CEPlotSection::get_Title(BSTR* pVal) +{ + CComBSTR bstrString(m_pSectionImpl->get_Title()); + return bstrString.CopyTo(pVal); +} + +STDMETHODIMP CEPlotSection::get_PaperColor(ULONG* pVal) +{ + (*pVal) = m_pSectionImpl->get_PaperColor(); + return S_OK; +} + +// Always inches +STDMETHODIMP CEPlotSection::get_PaperClipWidth(DOUBLE* pVal) +{ + (*pVal) = m_pSectionImpl->get_PaperClipWidth(); + return S_OK; +} + +STDMETHODIMP CEPlotSection::Open(BOOL bForWrite) +{ + try + { + m_pSectionImpl->Open( bForWrite); + return S_OK; + } + catch (CString &err) + { + return myAtlReportError (GetObjectCLSID(), err); + } +} + +HRESULT CEPlotSection::Read( void *pv, ULONG cb, ULONG *pcbRead) +{ + return m_pSectionImpl->Read( pv, cb, pcbRead); +}; + +HRESULT CEPlotSection::Write( const void *pv, ULONG cb, ULONG *pcbWritten) +{ + return m_pSectionImpl->Write( pv, cb, pcbWritten) ; +}; + +STDMETHODIMP CEPlotSection::Close(void) +{ + return m_pSectionImpl->Close(); +} + +STDMETHODIMP CEPlotSection::get_SourceDescription(BSTR* pVal) +{ + CString s; + HRESULT res = m_pSectionImpl->get_SourceDescription(s); + (*pVal) = s.AllocSysString(); + return res; +} + +STDMETHODIMP CEPlotSection::get_PropertiesXML(BSTR* pVal) +{ + CString s; + HRESULT res = m_pSectionImpl->get_PropertiesXML(s); + (*pVal) = s.AllocSysString(); + return res; +} + +STDMETHODIMP CEPlotSection::get_EPlotSectionImpl(/* CEPlotSectionImpl ** */ BYTE ** pVal) +{ + (*pVal) = (BYTE *)m_pSectionImpl; + return S_OK; +} + +STDMETHODIMP CEPlotSection::put_EPlotSectionImpl(/* CEPlotSectionImpl * */ BYTE * newVal) +{ + return E_FAIL; + return S_OK; +} diff --git a/SlnkDWFCom/myEPlotSection.h b/SlnkDWFCom/myEPlotSection.h new file mode 100644 index 0000000..ddab093 --- /dev/null +++ b/SlnkDWFCom/myEPlotSection.h @@ -0,0 +1,78 @@ +// EPlotSection.h : Declaration of the CEPlotSection + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" + +#include "myEPlotSectionImpl.h" +#include "Whiptk/whip_toolkit.h" + +// CEPlotSection + +class ATL_NO_VTABLE CEPlotSection : + public CComObjectRootEx, + public CComCoClass, + public ISupportErrorInfo, + public IDispatchImpl +// public CEPlotSectionImpl +{ +public: + CEPlotSection() + { + } + + //REMOVED DECLARE_REGISTRY_RESOURCEID(IDR_EPLOTSECTION) + + BEGIN_COM_MAP(CEPlotSection) + COM_INTERFACE_ENTRY(IEPlotSection) + COM_INTERFACE_ENTRY(IDispatch) + COM_INTERFACE_ENTRY(ISupportErrorInfo) + END_COM_MAP() + + // ISupportsErrorInfo + STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + return S_OK; + } + + void FinalRelease(); + +protected: + IEPlotSections *m_pParent; // Non-addreffed! + +private: + CEPlotSectionImpl *m_pSectionImpl; + +public: + void SetParent(IEPlotSections *pParent); + + STDMETHODIMP get_Parent(IEPlotSections **ppParent); + STDMETHOD(get_Name)(BSTR* pVal); + STDMETHOD(get_Title)(BSTR* pVal); + + void InitImpl(CEPlotSectionImpl *epl); + +// IWhipSequentialStream Methods +public: + STDMETHOD(Open)(BOOL bForWrite); + STDMETHOD(Read) ( void *pv, ULONG cb, ULONG *pcbRead); + STDMETHOD(Write)( const void *pv, ULONG cb,ULONG *pcbWritten); + STDMETHOD(Close)(void); + STDMETHOD(get_PaperColor)(ULONG* pVal); + STDMETHOD(get_SourceDescription)(BSTR* pVal); +#if DESIRED_CODE(WHIP_OUTPUT) + STDMETHOD(get_PropertiesXML)(BSTR* pVal); +#endif + STDMETHOD(get_PaperClipWidth)(DOUBLE* pVal); +public: + STDMETHOD(get_EPlotSectionImpl)(/* CEPlotSectionImpl ** */ BYTE ** pVal); +public: + STDMETHOD(put_EPlotSectionImpl)(/* CEPlotSectionImpl * */ BYTE * newVal); +}; + +//REMOVED OBJECT_ENTRY_AUTO(__uuidof(EPlotSection), CEPlotSection) diff --git a/SlnkDWFCom/resource.h b/SlnkDWFCom/resource.h new file mode 100644 index 0000000..4964ec1 --- /dev/null +++ b/SlnkDWFCom/resource.h @@ -0,0 +1,38 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by SLNKdwf.rc +// +#define IDS_PROJNAME 100 +#define IDR_SLNKDWF 101 +#define IDR_DWFFILE 102 +#define IDR_WHIPFILE 103 +#define IDR_WHIP2PNG 104 +#define IDR_ABOUT 105 +#define IDR_SLNKEPLOTSECTION 106 +#define IDR_EPLOTSECTION 107 +#define IDR_EPLOTSECTIONS 108 +#define IDR_WHIPSEQUENTIALSTREAM 109 +#define IDR_TEST 110 +#define IDR_TEST2 111 +#define IDR_SLNKEVENT 112 +#define IDR_ASPOBJECT 113 +#define IDR_WHIP2DC 114 +#define IDR_DC2PNG 115 +#define IDB_MYCONTROL 116 +#define IDR_MYCONTROL 117 +#define IDR_BOUNDINGBOX 118 +#define IDR_DWGPOINT 119 +#define IDR_SLNKCONTOUR 120 +#define IDR_SLNKSYMBOL 126 +#define IDR_OPTIONS 127 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 201 +#define _APS_NEXT_COMMAND_VALUE 32768 +#define _APS_NEXT_CONTROL_VALUE 201 +#define _APS_NEXT_SYMED_VALUE 128 +#endif +#endif diff --git a/SlnkDWFCom/slnkcont.bin b/SlnkDWFCom/slnkcont.bin new file mode 100644 index 0000000..9063bce --- /dev/null +++ b/SlnkDWFCom/slnkcont.bin @@ -0,0 +1,26 @@ +HKCR +{ + SLNKDWFCom.SLNKContour.1 = s 'SLNKContour Class' + { + CLSID = s '{476C0F28-5860-485D-BEBD-D03F68E1C930}' + } + SLNKDWFCom.SLNKContour = s 'SLNKContour Class' + { + CLSID = s '{476C0F28-5860-485D-BEBD-D03F68E1C930}' + CurVer = s 'SLNKDWFCom.SLNKContour.1' + } + NoRemove CLSID + { + ForceRemove {476C0F28-5860-485D-BEBD-D03F68E1C930} = s 'SLNKContour Class' + { + ProgID = s 'SLNKDWFCom.SLNKContour.1' + VersionIndependentProgID = s 'SLNKDWFCom.SLNKContour' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + 'TypeLib' = s '{B6FCDE6E-141C-4601-B3AC-4DF4D5F25DF8}' + } + } +} diff --git a/SlnkDWFCom/slnksymbol.h b/SlnkDWFCom/slnksymbol.h new file mode 100644 index 0000000..65ab515 --- /dev/null +++ b/SlnkDWFCom/slnksymbol.h @@ -0,0 +1,74 @@ +// SLNKSymbol.h : Declaration of the CSLNKSymbol + +#pragma once +#include "resource.h" // main symbols + +#include "SLNKDWF.h" +#include "SLNKSymbolDefImpl.h" +#include "SLNKSymbolImpl.h" + +#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) +#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." +#endif + + + +// CSLNKSymbol + +class ATL_NO_VTABLE CSLNKSymbol : + public CComObjectRootEx, + public CComCoClass, + public IDispatchImpl +{ +public: + CSLNKSymbol() + { + } + +//REMOVED DECLARE_REGISTRY_RESOURCEID(IDR_SLNKSYMBOL) + + +BEGIN_COM_MAP(CSLNKSymbol) + COM_INTERFACE_ENTRY(ISLNKSymbol) + COM_INTERFACE_ENTRY(IDispatch) +END_COM_MAP() + +// ISupportsErrorInfo + STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + return S_OK; + } + + void FinalRelease() + { + } + + // Deze SLNKSymbol wijst naar een CSLNKSymbolImpl in een WhipFile object. We moeten voorkomen + // dat deze te snel uit de scope wegvalt. Dat doen we mbv SetParent + // Omgekeerd is geen probleem: de WhipFile verwijst niet(!) naar de CSLNKSymbol en heeft er dus + // geen last van dat die wegvalt (van zijn SLNKSymbolImpl objecten is hij gewoon eigenaar) + + void SetParent(IWhipFile *pParent) + { + HRESULT hr = pParent->QueryInterface(IID_IWhipFile, (void **)&m_parent_iWhipFile); + }; + void SetImpl(CSLNKSymbolImpl * pSLNKSymbol); + +private: + CSLNKSymbolImpl * m_SLNKSymbol; + CComQIPtr m_parent_iWhipFile; // Om scope levend te houden + +public: + + STDMETHOD(get_Scale)(DOUBLE* pVal); + STDMETHOD(put_Scale)(DOUBLE newVal); + STDMETHOD(get_Rotation)(LONG* pVal); + STDMETHOD(put_Rotation)(LONG newVal); + STDMETHOD(get_Contour)(IUnknown** pVal); +}; + +//REMOVED OBJECT_ENTRY_AUTO(__uuidof(SLNKSymbol), CSLNKSymbol) diff --git a/SlnkDWFCom/stdafx.cpp b/SlnkDWFCom/stdafx.cpp new file mode 100644 index 0000000..67ecdda --- /dev/null +++ b/SlnkDWFCom/stdafx.cpp @@ -0,0 +1,5 @@ +// stdafx.cpp : source file that includes just the standard includes +// SLNKDWF.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" diff --git a/SlnkDWFCom/stdafx.h b/SlnkDWFCom/stdafx.h new file mode 100644 index 0000000..6800469 --- /dev/null +++ b/SlnkDWFCom/stdafx.h @@ -0,0 +1,77 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, +// but are changed infrequently + +#pragma once + +#ifndef STRICT +#define STRICT +#endif + +// Modify the following defines if you have to target a platform prior to the ones specified below. +// Refer to MSDN for the latest info on corresponding values for different platforms. +#ifndef WINVER // Allow use of features specific to Windows XP or later. +#define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows. +#endif + +#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. +#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. +#endif + +#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. +#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. +#endif + +#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later. +#define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE. +#endif + +#define _ATL_APARTMENT_THREADED +#define _ATL_NO_AUTOMATIC_NAMESPACE + +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit + +// turns off ATL's hiding of some common and often safely ignored warning messages +#define _ATL_ALL_WARNINGS + +#ifdef _DEBUG +//#define _ATL_DEBUG_INTERFACES +#endif + +#include "resource.h" +#include +#include + +using namespace ATL; + +// [JGL] added manually +#include +#include "atlstr.h" +#include "atlrx.h" +#include "../SLNKDwfImpl/jglutil.h" + +#include "Options.h" + +#include "SLNKDWFStaticRW.h" + +#include "dwfcore/File.h" +#include "dwfcore/String.h" + +#include "dwf/package/Constants.h" +#include "dwf/package/Manifest.h" +#include "dwf/package/EPlotSection.h" +#include "dwf/package/reader/PackageReader.h" +//#include "dwf/package/writer/PackageWriter.h" +#include "dwf/package/xml.h" +#include "dwf/package/reader/DuplicateAttributeFilter.h" + +using namespace DWFCore; +using namespace DWFToolkit; +//using namespace DWFManifest; +//using namespace DWFXmlObjects; +//using namespace DWFEPlot; +//using DWF::DwfResult; + +#ifdef _DEBUG +#include "MemLeakDetect.h" +#endif \ No newline at end of file diff --git a/SlnkDWFCom/unloadIIS.bat b/SlnkDWFCom/unloadIIS.bat new file mode 100644 index 0000000..d37a33d --- /dev/null +++ b/SlnkDWFCom/unloadIIS.bat @@ -0,0 +1,4 @@ +C:\Inetpub\AdminScripts\adsutil.vbs APPUNLOAD W3SVC/1/Root/SLNKDWF +C:\Inetpub\AdminScripts\adsutil.vbs APPUNLOAD W3SVC/1/Root/Vigor +C:\Inetpub\AdminScripts\adsutil.vbs APPUNLOAD W3SVC/1/Root/FacilitorWork +C:\Inetpub\AdminScripts\adsutil.vbs START_SERVER W3SVC/1 diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/.gitignore b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.cpp b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.cpp new file mode 100644 index 0000000..a4e844c --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.cpp @@ -0,0 +1,13 @@ +// CxImageCrtDll.cpp : Defines the entry point for the CxImageCrtDll application. +// + +#include "stdcrt.h" + +BOOL APIENTRY DllMain( HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + return TRUE; +} + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.dsp b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.dsp new file mode 100644 index 0000000..bda9795 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.dsp @@ -0,0 +1,346 @@ +# Microsoft Developer Studio Project File - Name="CxImageCrtDll" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=CxImageCrtDll - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "CxImageCrtDll.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "CxImageCrtDll.mak" CFG="CxImageCrtDll - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "CxImageCrtDll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "CxImageCrtDll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "CxImageCrtDll - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRCxImageCrtDll" /D "CxImageCrtDll_EXPORTS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "../../zlib" /I "../../jasper/include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "JAS_WIN_MSVC_BUILD" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# 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 /nologo /machine:I386 /CxImageCrtDll +# ADD LINK32 kernel32.lib user32.lib gdi32.lib /nologo /dll /machine:I386 /out:"../../bin/cximagecrt.dll" +# SUBTRACT LINK32 /pdb:none + +!ELSEIF "$(CFG)" == "CxImageCrtDll - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRCxImageCrtDll" /D "CxImageCrtDll_EXPORTS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "../../zlib" /I "../../jasper/include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "JAS_WIN_MSVC_BUILD" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# 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 /nologo /debug /machine:I386 /pdbtype:sept /CxImageCrtDll +# ADD LINK32 kernel32.lib user32.lib gdi32.lib /nologo /dll /debug /machine:I386 /out:"../../bin/cximagecrtd.dll" /pdbtype:sept +# SUBTRACT LINK32 /pdb:none + +!ENDIF + +# Begin Target + +# Name "CxImageCrtDll - Win32 Release" +# Name "CxImageCrtDll - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\CxImageCrtDll.cpp +# End Source File +# Begin Source File + +SOURCE=.\CxImageCrtDll.rc +# End Source File +# Begin Source File + +SOURCE=..\tif_xfile.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximabmp.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximadsp.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximaenc.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximaexif.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximage.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximagif.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximahist.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximaico.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximainfo.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximaint.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximaj2k.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximajas.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximajbg.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximajpg.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximalpha.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximalyr.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximamng.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximapal.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximapcx.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximapng.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximasel.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximatga.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximath.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximatif.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximatran.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximawbmp.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximawmf.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\ximawnd.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\xmemfile.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\StdAfx.h +# End Source File +# Begin Source File + +SOURCE=..\xfile.h +# End Source File +# Begin Source File + +SOURCE=..\ximabmp.h +# End Source File +# Begin Source File + +SOURCE=..\ximadefs.h +# End Source File +# Begin Source File + +SOURCE=..\xImage.h +# End Source File +# Begin Source File + +SOURCE=..\ximagif.h +# End Source File +# Begin Source File + +SOURCE=..\ximaico.h +# End Source File +# Begin Source File + +SOURCE=..\ximaiter.h +# End Source File +# Begin Source File + +SOURCE=..\ximaj2k.h +# End Source File +# Begin Source File + +SOURCE=..\ximajas.h +# End Source File +# Begin Source File + +SOURCE=..\ximajbg.h +# End Source File +# Begin Source File + +SOURCE=..\ximajpg.h +# End Source File +# Begin Source File + +SOURCE=..\ximamng.h +# End Source File +# Begin Source File + +SOURCE=..\ximapcx.h +# End Source File +# Begin Source File + +SOURCE=..\ximapng.h +# End Source File +# Begin Source File + +SOURCE=..\ximatga.h +# End Source File +# Begin Source File + +SOURCE=..\ximath.h +# End Source File +# Begin Source File + +SOURCE=..\ximatif.h +# End Source File +# Begin Source File + +SOURCE=..\ximawbmp.h +# End Source File +# Begin Source File + +SOURCE=..\ximawmf.h +# End Source File +# Begin Source File + +SOURCE=..\xiofile.h +# End Source File +# Begin Source File + +SOURCE=..\xmemfile.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.rc b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.rc new file mode 100644 index 0000000..7f8902b --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.rc @@ -0,0 +1,123 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resrc1.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "resource.h" +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Neutral resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) +#ifdef _WIN32 +LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL +#pragma code_page(1252) +#endif //_WIN32 + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 5,9,9,3 + PRODUCTVERSION 5,9,9,3 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "000004b0" + BEGIN + VALUE "Comments", "CxImage 5.99c CRT DLL\0" + VALUE "CompanyName", "Pizzolato Davide - www.xdp.it\0" + VALUE "FileDescription", "cximage\0" + VALUE "FileVersion", "5, 9, 9, c\0" + VALUE "InternalName", "cximage\0" + VALUE "LegalCopyright", "Copyright © 2001 - 2004\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "cximagecrt.dll\0" + VALUE "PrivateBuild", "\0" + VALUE "ProductName", "cximage\0" + VALUE "ProductVersion", "5, 9, 9, c\0" + VALUE "SpecialBuild", "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0, 1200 + END +END + +#endif // !_MAC + +#endif // Neutral resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Italian (Italy) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ITA) +#ifdef _WIN32 +LANGUAGE LANG_ITALIAN, SUBLANG_ITALIAN +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resrc1.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""resource.h""\r\n" + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // Italian (Italy) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.vcproj b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.vcproj new file mode 100644 index 0000000..00a320f --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.vcproj @@ -0,0 +1,1017 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..f57b253 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageCrtDll.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageDll.dsw b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageDll.dsw new file mode 100644 index 0000000..afdd4ba --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageDll.dsw @@ -0,0 +1,152 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "CxImageCrtDll"=.\CxImageCrtDll.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name j2000 + End Project Dependency + Begin Project Dependency + Project_Dep_Name jbig + End Project Dependency + Begin Project Dependency + Project_Dep_Name jpeg + End Project Dependency + Begin Project Dependency + Project_Dep_Name png + End Project Dependency + Begin Project Dependency + Project_Dep_Name tiff + End Project Dependency + Begin Project Dependency + Project_Dep_Name zlib + End Project Dependency + Begin Project Dependency + Project_Dep_Name j2k + End Project Dependency +}}} + +############################################################################### + +Project: "CxImageMfcDll"=.\cximagemfcdll.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name j2k + End Project Dependency + Begin Project Dependency + Project_Dep_Name jbig + End Project Dependency + Begin Project Dependency + Project_Dep_Name jpeg + End Project Dependency + Begin Project Dependency + Project_Dep_Name png + End Project Dependency + Begin Project Dependency + Project_Dep_Name tiff + End Project Dependency + Begin Project Dependency + Project_Dep_Name zlib + End Project Dependency +}}} + +############################################################################### + +Project: "j2k"=..\..\j2k\j2k.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "jbig"=..\..\jbig\jbig.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "jpeg"=..\..\jpeg\Jpeg.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "png"=..\..\png\png.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "tiff"=..\..\tiff\Tiff.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "zlib"=..\..\zlib\zlib.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.clw b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.clw new file mode 100644 index 0000000..349133d --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.clw @@ -0,0 +1,16 @@ +; CLW file contains information for the MFC ClassWizard + +[General Info] +Version=1 +ClassCount=1 +Class1=CcximagemfcdllApp +LastClass=CcximagemfcdllApp +NewFileInclude2=#include "cximagemfcdll.h" +ResourceCount=0 +NewFileInclude1=#include "stdafx.h" + +[CLS:CcximagemfcdllApp] +Type=0 +HeaderFile=cximagemfcdll.h +ImplementationFile=cximagemfcdll.cpp +Filter=N diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.cpp b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.cpp new file mode 100644 index 0000000..ff4e12e --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.cpp @@ -0,0 +1,62 @@ +// cximagemfcdll.cpp : Defines the initialization routines for the DLL. +// + +#include "stdafx.h" +#include "cximagemfcdll.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +// +// Note! +// +// If this DLL is dynamically linked against the MFC +// DLLs, any functions exported from this DLL which +// call into MFC must have the AFX_MANAGE_STATE macro +// added at the very beginning of the function. +// +// For example: +// +// extern "C" BOOL PASCAL EXPORT ExportedFunction() +// { +// AFX_MANAGE_STATE(AfxGetStaticModuleState()); +// // normal function body here +// } +// +// It is very important that this macro appear in each +// function, prior to any calls into MFC. This means that +// it must appear as the first statement within the +// function, even before any object variable declarations +// as their constructors may generate calls into the MFC +// DLL. +// +// Please see MFC Technical Notes 33 and 58 for additional +// details. +// + +///////////////////////////////////////////////////////////////////////////// +// CcximagemfcdllApp + +BEGIN_MESSAGE_MAP(CcximagemfcdllApp, CWinApp) + //{{AFX_MSG_MAP(CcximagemfcdllApp) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CcximagemfcdllApp construction + +CcximagemfcdllApp::CcximagemfcdllApp() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + +///////////////////////////////////////////////////////////////////////////// +// The one and only CcximagemfcdllApp object + +CcximagemfcdllApp theApp; diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.h b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.h new file mode 100644 index 0000000..43d62cf --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.h @@ -0,0 +1,45 @@ +// cximagemfcdll.h : main header file for the cximagemfcdll DLL +// + +#if !defined(AFX_cximagemfcdll_H__E98F71A6_B361_11D6_BB83_CAEE2E1CB77B__INCLUDED_) +#define AFX_cximagemfcdll_H__E98F71A6_B361_11D6_BB83_CAEE2E1CB77B__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +///////////////////////////////////////////////////////////////////////////// +// CcximagemfcdllApp +// See cximagemfcdll.cpp for the implementation of this class +// + +class CcximagemfcdllApp : public CWinApp +{ +public: + CcximagemfcdllApp(); + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CcximagemfcdllApp) + //}}AFX_VIRTUAL + + //{{AFX_MSG(CcximagemfcdllApp) + // NOTE - the ClassWizard will add and remove member functions here. + // DO NOT EDIT what you see in these blocks of generated code ! + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_cximagemfcdll_H__E98F71A6_B361_11D6_BB83_CAEE2E1CB77B__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.rc b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.rc new file mode 100644 index 0000000..79f8064 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/CxImageMfcDll.rc @@ -0,0 +1,123 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resrc1.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "resource.h" +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Neutral resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) +#ifdef _WIN32 +LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL +#pragma code_page(1252) +#endif //_WIN32 + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 5,9,9,3 + PRODUCTVERSION 5,9,9,3 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "000004b0" + BEGIN + VALUE "Comments", "CxImage 5.99c MFC DLL\0" + VALUE "CompanyName", "Pizzolato Davide - www.xdp.it\0" + VALUE "FileDescription", "cximage\0" + VALUE "FileVersion", "5, 9, 9, c\0" + VALUE "InternalName", "cximage\0" + VALUE "LegalCopyright", "Copyright © 2001 - 2004\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "cximage.dll\0" + VALUE "PrivateBuild", "\0" + VALUE "ProductName", "cximage\0" + VALUE "ProductVersion", "5, 9, 9, c\0" + VALUE "SpecialBuild", "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0, 1200 + END +END + +#endif // !_MAC + +#endif // Neutral resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Italian (Italy) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ITA) +#ifdef _WIN32 +LANGUAGE LANG_ITALIAN, SUBLANG_ITALIAN +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resrc1.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""resource.h""\r\n" + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // Italian (Italy) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdAfx.cpp b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdAfx.cpp new file mode 100644 index 0000000..a5e4a08 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdAfx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// cximagemfcdll.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdAfx.h b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdAfx.h new file mode 100644 index 0000000..c8b1b0c --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdAfx.h @@ -0,0 +1,42 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__E98F71A8_B361_11D6_BB83_CAEE2E1CB77B__INCLUDED_) +#define AFX_STDAFX_H__E98F71A8_B361_11D6_BB83_CAEE2E1CB77B__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include // MFC core and standard components +#include // MFC extensions + +#ifndef _AFX_NO_OLE_SUPPORT +#include // MFC OLE classes +#include // MFC OLE dialog classes +#include // MFC Automation classes +#endif // _AFX_NO_OLE_SUPPORT + + +#ifndef _AFX_NO_DB_SUPPORT +#include // MFC ODBC database classes +#endif // _AFX_NO_DB_SUPPORT + +#ifndef _AFX_NO_DAO_SUPPORT +#include // MFC DAO database classes +#endif // _AFX_NO_DAO_SUPPORT + +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__E98F71A8_B361_11D6_BB83_CAEE2E1CB77B__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdCrt.h b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdCrt.h new file mode 100644 index 0000000..60e3632 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/StdCrt.h @@ -0,0 +1,24 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__F30A8A60_284F_4DF6_9431_6283105686F6__INCLUDED_) +#define AFX_STDAFX_H__F30A8A60_284F_4DF6_9431_6283105686F6__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + + +// Insert your headers here +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + +#include + +// TODO: reference additional headers your program requires here + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__F30A8A60_284F_4DF6_9431_6283105686F6__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.dsp b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.dsp new file mode 100644 index 0000000..80cbd3c --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.dsp @@ -0,0 +1,330 @@ +# Microsoft Developer Studio Project File - Name="CxImageMfcDll" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=CxImageMfcDll - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "cximagemfcdll.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "cximagemfcdll.mak" CFG="CxImageMfcDll - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "CxImageMfcDll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "CxImageMfcDll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "CxImageMfcDll - Win32 Release" + +# PROP BASE Use_MFC 6 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 6 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_WINDLL" /D "_AFXDLL" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "../../zlib" /I "../../jasper/include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_WINDLL" /D "_AFXDLL" /D "_MBCS" /D "_USRDLL" /D "JAS_WIN_MSVC_BUILD" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x410 /d "NDEBUG" /d "_AFXDLL" +# ADD RSC /l 0x410 /d "NDEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 /nologo /subsystem:windows /dll /machine:I386 +# ADD LINK32 /nologo /subsystem:windows /dll /machine:I386 /out:"../../bin/cximage.dll" + +!ELSEIF "$(CFG)" == "CxImageMfcDll - Win32 Debug" + +# PROP BASE Use_MFC 6 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 6 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_WINDLL" /D "_AFXDLL" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "../../zlib" /I "../../jasper/include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_WINDLL" /D "_AFXDLL" /D "_MBCS" /D "_USRDLL" /D "JAS_WIN_MSVC_BUILD" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x410 /d "_DEBUG" /d "_AFXDLL" +# ADD RSC /l 0x410 /d "_DEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 /nologo /subsystem:windows /dll /debug /machine:I386 /out:"../../bin/cximaged.dll" /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "CxImageMfcDll - Win32 Release" +# Name "CxImageMfcDll - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\cximagemfcdll.cpp +# End Source File +# Begin Source File + +SOURCE=.\cximagemfcdll.rc +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.cpp +# ADD CPP /Yc"stdafx.h" +# End Source File +# Begin Source File + +SOURCE=..\tif_xfile.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximabmp.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximadsp.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximaenc.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximaexif.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximage.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximagif.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximahist.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximaico.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximainfo.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximaint.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximaj2k.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximajas.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximajbg.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximajpg.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximalpha.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximalyr.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximamng.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximapal.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximapcx.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximapng.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximasel.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximatga.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximath.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximatif.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximatran.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximawbmp.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximawmf.cpp +# End Source File +# Begin Source File + +SOURCE=..\ximawnd.cpp +# End Source File +# Begin Source File + +SOURCE=..\xmemfile.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\cximagemfcdll.h +# End Source File +# Begin Source File + +SOURCE=.\Resource.h +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.h +# End Source File +# Begin Source File + +SOURCE=..\xfile.h +# End Source File +# Begin Source File + +SOURCE=..\ximabmp.h +# End Source File +# Begin Source File + +SOURCE=..\ximadefs.h +# End Source File +# Begin Source File + +SOURCE=..\ximage.h +# End Source File +# Begin Source File + +SOURCE=..\ximagif.h +# End Source File +# Begin Source File + +SOURCE=..\ximaico.h +# End Source File +# Begin Source File + +SOURCE=..\ximaiter.h +# End Source File +# Begin Source File + +SOURCE=..\ximaj2k.h +# End Source File +# Begin Source File + +SOURCE=..\ximajas.h +# End Source File +# Begin Source File + +SOURCE=..\ximajpg.h +# End Source File +# Begin Source File + +SOURCE=..\ximamng.h +# End Source File +# Begin Source File + +SOURCE=..\ximapcx.h +# End Source File +# Begin Source File + +SOURCE=..\ximapng.h +# End Source File +# Begin Source File + +SOURCE=..\ximatga.h +# End Source File +# Begin Source File + +SOURCE=..\ximath.h +# End Source File +# Begin Source File + +SOURCE=..\ximatif.h +# End Source File +# Begin Source File + +SOURCE=..\ximawbmp.h +# End Source File +# Begin Source File + +SOURCE=..\ximawmf.h +# End Source File +# Begin Source File + +SOURCE=..\xiofile.h +# End Source File +# Begin Source File + +SOURCE=..\xmemfile.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.vcproj b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.vcproj new file mode 100644 index 0000000..58099be --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.vcproj @@ -0,0 +1,1050 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..f57b253 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/cximagemfcdll.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/resource.h b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/resource.h new file mode 100644 index 0000000..cc1626b --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/resource.h @@ -0,0 +1,15 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by CxImageMFCdll.rc +// + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 6000 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 6000 +#define _APS_NEXT_SYMED_VALUE 6000 +#endif +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/resrc1.h b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/resrc1.h new file mode 100644 index 0000000..39ff26e --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/CxImageDLL/resrc1.h @@ -0,0 +1,15 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by CxImageCrtDll.rc +// + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 6000 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 6000 +#define _APS_NEXT_SYMED_VALUE 6000 +#endif +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/_ximacfg.h b/SlnkDWFImpl/CxImage/CxImage/_ximacfg.h new file mode 100644 index 0000000..20168d9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/_ximacfg.h @@ -0,0 +1,52 @@ +#if !defined(__ximaCFG_h) +#define __ximaCFG_h + +///////////////////////////////////////////////////////////////////////////// +// CxImage supported features +#define CXIMAGE_SUPPORT_ALPHA 1 +#define CXIMAGE_SUPPORT_SELECTION 1 +#define CXIMAGE_SUPPORT_TRANSFORMATION 1 +#define CXIMAGE_SUPPORT_DSP 1 +#define CXIMAGE_SUPPORT_LAYERS 1 +#define CXIMAGE_SUPPORT_INTERPOLATION 1 + +#define CXIMAGE_SUPPORT_DECODE 1 +#define CXIMAGE_SUPPORT_ENCODE 1 // +#define CXIMAGE_SUPPORT_WINDOWS 1 +#define CXIMAGE_SUPPORT_WINCE 0 // + +///////////////////////////////////////////////////////////////////////////// +// CxImage supported formats +#define CXIMAGE_SUPPORT_BMP 1 +#define CXIMAGE_SUPPORT_GIF 1 +#define CXIMAGE_SUPPORT_JPG 1 +#define CXIMAGE_SUPPORT_PNG 1 +#define CXIMAGE_SUPPORT_MNG 0 +#define CXIMAGE_SUPPORT_ICO 1 +#define CXIMAGE_SUPPORT_TIF 1 +#define CXIMAGE_SUPPORT_TGA 1 +#define CXIMAGE_SUPPORT_PCX 1 +#define CXIMAGE_SUPPORT_WBMP 1 +#define CXIMAGE_SUPPORT_WMF 1 +#define CXIMAGE_SUPPORT_J2K 0 // Beta, use JP2 +#define CXIMAGE_SUPPORT_JBG 0 // GPL'd see ../jbig/copying.txt & ../jbig/patents.htm + +#define CXIMAGE_SUPPORT_JP2 1 +#define CXIMAGE_SUPPORT_JPC 1 +#define CXIMAGE_SUPPORT_PGX 1 +#define CXIMAGE_SUPPORT_PNM 1 +#define CXIMAGE_SUPPORT_RAS 1 + + +///////////////////////////////////////////////////////////////////////////// +#define CXIMAGE_MAX_MEMORY 256000000 + +#define CXIMAGE_ERR_NOFILE "null file handler" +#define CXIMAGE_ERR_NOIMAGE "null image!!!" + +///////////////////////////////////////////////////////////////////////////// +//color to grey mapping +//#define RGB2GRAY(r,g,b) (((b)*114 + (g)*587 + (r)*299)/1000) +#define RGB2GRAY(r,g,b) (((b)*117 + (g)*601 + (r)*306) >> 10) + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/cximage.dsp b/SlnkDWFImpl/CxImage/CxImage/cximage.dsp new file mode 100644 index 0000000..7908b85 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/cximage.dsp @@ -0,0 +1,302 @@ +# Microsoft Developer Studio Project File - Name="CxImage" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=CxImage - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "cximage.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "cximage.mak" CFG="CxImage - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "CxImage - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "CxImage - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "CxImage - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\jpeg" /I "..\png" /I "..\zlib" /I "..\mng" /I "..\tiff" /I "..\j2k" /I "..\jasper\include" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D "_AFXDLL" /D "JAS_WIN_MSVC_BUILD" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x410 /d "NDEBUG" +# ADD RSC /l 0x410 /d "NDEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "CxImage - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\jpeg" /I "..\png" /I "..\zlib" /I "..\mng" /I "..\tiff" /I "..\j2k" /I "..\jasper\include" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D "_AFXDLL" /D "JAS_WIN_MSVC_BUILD" /FD /GZ /c +# SUBTRACT CPP /Fr /YX +# ADD BASE RSC /l 0x410 /d "_DEBUG" +# ADD RSC /l 0x410 /d "_DEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "CxImage - Win32 Release" +# Name "CxImage - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\tif_xfile.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximabmp.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximadsp.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximaenc.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximaexif.cpp +# End Source File +# Begin Source File + +SOURCE=.\xImage.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximagif.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximahist.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximaico.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximainfo.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximaint.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximaj2k.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximajas.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximajbg.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximajpg.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximalpha.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximalyr.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximamng.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximapal.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximapcx.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximapng.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximasel.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximatga.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximath.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximatif.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximatran.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximawbmp.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximawmf.cpp +# End Source File +# Begin Source File + +SOURCE=.\ximawnd.cpp +# End Source File +# Begin Source File + +SOURCE=.\xmemfile.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\xfile.h +# End Source File +# Begin Source File + +SOURCE=.\ximabmp.h +# End Source File +# Begin Source File + +SOURCE=.\ximacfg.h +# End Source File +# Begin Source File + +SOURCE=.\ximadef.h +# End Source File +# Begin Source File + +SOURCE=.\ximage.h +# End Source File +# Begin Source File + +SOURCE=.\ximagif.h +# End Source File +# Begin Source File + +SOURCE=.\ximaico.h +# End Source File +# Begin Source File + +SOURCE=.\ximaiter.h +# End Source File +# Begin Source File + +SOURCE=.\ximaj2k.h +# End Source File +# Begin Source File + +SOURCE=.\ximajas.h +# End Source File +# Begin Source File + +SOURCE=.\ximajbg.h +# End Source File +# Begin Source File + +SOURCE=.\ximajpg.h +# End Source File +# Begin Source File + +SOURCE=.\ximamng.h +# End Source File +# Begin Source File + +SOURCE=.\ximapcx.h +# End Source File +# Begin Source File + +SOURCE=.\ximapng.h +# End Source File +# Begin Source File + +SOURCE=.\ximatga.h +# End Source File +# Begin Source File + +SOURCE=.\ximath.h +# End Source File +# Begin Source File + +SOURCE=.\ximatif.h +# End Source File +# Begin Source File + +SOURCE=.\ximawbmp.h +# End Source File +# Begin Source File + +SOURCE=.\ximawmf.h +# End Source File +# Begin Source File + +SOURCE=.\xiofile.h +# End Source File +# Begin Source File + +SOURCE=.\xmemfile.h +# End Source File +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/CxImage/cximage.dsw b/SlnkDWFImpl/CxImage/CxImage/cximage.dsw new file mode 100644 index 0000000..d855b5f --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/cximage.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "CxImage"=.\CxImage.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/CxImage/cximage.sln b/SlnkDWFImpl/CxImage/CxImage/cximage.sln new file mode 100644 index 0000000..13614ee --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/cximage.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 7.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CxImage", "CxImage.vcproj", "{E6F8F128-84D9-48D6-81D6-C427EAFE738D}" +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + ConfigName.0 = Debug + ConfigName.1 = Release + EndGlobalSection + GlobalSection(ProjectDependencies) = postSolution + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {E6F8F128-84D9-48D6-81D6-C427EAFE738D}.Debug.ActiveCfg = Debug|Win32 + {E6F8F128-84D9-48D6-81D6-C427EAFE738D}.Debug.Build.0 = Debug|Win32 + {E6F8F128-84D9-48D6-81D6-C427EAFE738D}.Release.ActiveCfg = Release|Win32 + {E6F8F128-84D9-48D6-81D6-C427EAFE738D}.Release.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/SlnkDWFImpl/CxImage/CxImage/cximage.vcproj b/SlnkDWFImpl/CxImage/CxImage/cximage.vcproj new file mode 100644 index 0000000..6ea85b7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/cximage.vcproj @@ -0,0 +1,932 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/CxImage/cximage.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/CxImage/cximage.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..2bdefdc --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/cximage.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/CxImage/cximage2003.vcproj b/SlnkDWFImpl/CxImage/CxImage/cximage2003.vcproj new file mode 100644 index 0000000..e8d81c3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/cximage2003.vcproj @@ -0,0 +1,272 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/CxImage/license.txt b/SlnkDWFImpl/CxImage/CxImage/license.txt new file mode 100644 index 0000000..b5db06b --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/license.txt @@ -0,0 +1,48 @@ +This copy of the CxImage notices is provided for your convenience. In case of +any discrepancy between this copy and the notices in the file ximage.h that is +included in the CxImage distribution, the latter shall prevail. + +If you modify CxImage you may insert additional notices immediately following +this sentence. + +-------------------------------------------------------------------------------- + +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: + +CxImage version 5.99c 17/Oct/2004 + +CxImage : Copyright (C) 2001 - 2004, Davide Pizzolato + +Original CImage and CImageIterator implementation are: +Copyright (C) 1995, Alejandro Aguilar Sierra (asierra(at)servidor(dot)unam(dot)mx) + +Covered code is provided under this license on an "as is" basis, without warranty +of any kind, either expressed or implied, including, without limitation, warranties +that the covered code is free of defects, merchantable, fit for a particular purpose +or non-infringing. The entire risk as to the quality and performance of the covered +code is with you. Should any covered code prove defective in any respect, you (not +the initial developer or any other contributor) assume the cost of any necessary +servicing, repair or correction. This disclaimer of warranty constitutes an essential +part of this license. No use of any covered code is authorized hereunder except under +this disclaimer. + +Permission is hereby granted to use, copy, modify, and distribute this +source code, or portions hereof, for any purpose, including commercial applications, +freely and without fee, 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. + +-------------------------------------------------------------------------------- + +Other information: about CxImage, and the latest version, can be found at the +CxImage home page: http://www.xdp.it + +-------------------------------------------------------------------------------- diff --git a/SlnkDWFImpl/CxImage/CxImage/tif_xfile.cpp b/SlnkDWFImpl/CxImage/CxImage/tif_xfile.cpp new file mode 100644 index 0000000..6f72475 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/tif_xfile.cpp @@ -0,0 +1,208 @@ +/* + * TIFF file IO, using CxFile. + */ + +#ifdef WIN32 + #include +#endif +#include + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_TIF + +#include "../tiff/tiffiop.h" + +#include "xfile.h" + +static tsize_t +_tiffReadProcEx(thandle_t fd, tdata_t buf, tsize_t size) +{ + return ((CxFile*)fd)->Read(buf, 1, size); +} + +static tsize_t +_tiffWriteProcEx(thandle_t fd, tdata_t buf, tsize_t size) +{ + return ((CxFile*)fd)->Write(buf, 1, size); +} + +static toff_t +_tiffSeekProcEx(thandle_t fd, toff_t off, int whence) +{ + if ( off == 0xFFFFFFFF ) + return 0xFFFFFFFF; + if (!((CxFile*)fd)->Seek(off, whence)) + return 0xFFFFFFFF; + if (whence == SEEK_SET) + return off; + + return (toff_t)((CxFile*)fd)->Tell(); +} + +// Return nonzero if error +static int +_tiffCloseProcEx(thandle_t fd) +{ +// return !((CxFile*)fd)->Close(); // "//" needed for memory files + return 0; +} + +#include + +static toff_t +_tiffSizeProcEx(thandle_t fd) +{ + return ((CxFile*)fd)->Size(); +} + +static int +_tiffMapProcEx(thandle_t fd, tdata_t* pbase, toff_t* psize) +{ + return (0); +} + +static void +_tiffUnmapProcEx(thandle_t fd, tdata_t base, toff_t size) +{ +} + +// Open a TIFF file descriptor for read/writing. +/* +TIFF* +TIFFOpen(const char* name, const char* mode) +{ + static const char module[] = "TIFFOpen"; + FILE* stream = fopen(name, mode); + if (stream == NULL) + { + TIFFError(module, "%s: Cannot open", name); + return NULL; + } + return (TIFFFdOpen((int)stream, name, mode)); +} +*/ + +TIFF* +_TIFFFdOpen(int fd, const char* name, const char* mode) +{ + TIFF* tif; + + tif = TIFFClientOpen(name, mode, + (thandle_t) fd, + _tiffReadProcEx, _tiffWriteProcEx, _tiffSeekProcEx, _tiffCloseProcEx, + _tiffSizeProcEx, _tiffMapProcEx, _tiffUnmapProcEx); + if (tif) + tif->tif_fd = fd; + return (tif); +} + +extern "C" TIFF* _TIFFOpenEx(CxFile* stream, const char* mode) +{ + return (_TIFFFdOpen((int)stream, "TIFF IMAGE", mode)); +} + +#ifdef __GNUC__ +extern char* malloc(); +extern char* realloc(); +#else +#include +#endif + +tdata_t +_TIFFmalloc(tsize_t s) +{ + return (malloc((size_t) s)); +} + +void +_TIFFfree(tdata_t p) +{ + free(p); +} + +tdata_t +_TIFFrealloc(tdata_t p, tsize_t s) +{ + return (realloc(p, (size_t) s)); +} + +void +_TIFFmemset(tdata_t p, int v, tsize_t c) +{ + memset(p, v, (size_t) c); +} + +void +_TIFFmemcpy(tdata_t d, const tdata_t s, tsize_t c) +{ + memcpy(d, s, (size_t) c); +} + +int +_TIFFmemcmp(const tdata_t p1, const tdata_t p2, tsize_t c) +{ + return (memcmp(p1, p2, (size_t) c)); +} + +static void +Win32WarningHandler(const char* module, const char* fmt, va_list ap) +{ +#ifdef _DEBUG +#if (!defined(_CONSOLE) && defined(WIN32)) + LPTSTR szTitle; + LPTSTR szTmp; + LPCTSTR szTitleText = "%s Warning"; + LPCTSTR szDefaultModule = "TIFFLIB"; + szTmp = (module == NULL) ? (LPTSTR)szDefaultModule : (LPTSTR)module; + if ((szTitle = (LPTSTR)LocalAlloc(LMEM_FIXED, (lstrlen(szTmp) + + lstrlen(szTitleText) + lstrlen(fmt) + 128)*sizeof(TCHAR))) == NULL) + return; + wsprintf(szTitle, szTitleText, szTmp); + szTmp = szTitle + (lstrlen(szTitle)+2)*sizeof(TCHAR); + wvsprintf(szTmp, fmt, ap); + MessageBox(GetFocus(), szTmp, szTitle, MB_OK | MB_ICONINFORMATION); + LocalFree(szTitle); + return; +#else + if (module != NULL) + fprintf(stderr, "%s: ", module); + fprintf(stderr, "Warning, "); + vfprintf(stderr, fmt, ap); + fprintf(stderr, ".\n"); +#endif +#endif +} +TIFFErrorHandler _TIFFwarningHandler = Win32WarningHandler; + +static void +Win32ErrorHandler(const char* module, const char* fmt, va_list ap) +{ +#ifdef _DEBUG +#if (!defined(_CONSOLE) && defined(WIN32)) + LPTSTR szTitle; + LPTSTR szTmp; + LPCTSTR szTitleText = "%s Error"; + LPCTSTR szDefaultModule = "TIFFLIB"; + szTmp = (module == NULL) ? (LPTSTR)szDefaultModule : (LPTSTR)module; + if ((szTitle = (LPTSTR)LocalAlloc(LMEM_FIXED, (lstrlen(szTmp) + + lstrlen(szTitleText) + lstrlen(fmt) + 128)*sizeof(TCHAR))) == NULL) + return; + wsprintf(szTitle, szTitleText, szTmp); + szTmp = szTitle + (lstrlen(szTitle)+2)*sizeof(TCHAR); + wvsprintf(szTmp, fmt, ap); + MessageBox(GetFocus(), szTmp, szTitle, MB_OK | MB_ICONEXCLAMATION); + LocalFree(szTitle); + return; +#else + if (module != NULL) + fprintf(stderr, "%s: ", module); + vfprintf(stderr, fmt, ap); + fprintf(stderr, ".\n"); +#endif +#endif +} +TIFFErrorHandler _TIFFerrorHandler = Win32ErrorHandler; + +#endif + diff --git a/SlnkDWFImpl/CxImage/CxImage/xfile.h b/SlnkDWFImpl/CxImage/CxImage/xfile.h new file mode 100644 index 0000000..268c9aa --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/xfile.h @@ -0,0 +1,76 @@ +/* + * File: xfile.h + * Purpose: General Purpose File Class + */ +/* + -------------------------------------------------------------------------------- + + COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: + + CxFile (c) 11/May/2002 Davide Pizzolato - www.xdp.it + CxFile version 2.00 23/Aug/2002 + + Special thanks to Chris Shearer Cooper for new features, enhancements and bugfixes + + Covered code is provided under this license on an "as is" basis, without warranty + of any kind, either expressed or implied, including, without limitation, warranties + that the covered code is free of defects, merchantable, fit for a particular purpose + or non-infringing. The entire risk as to the quality and performance of the covered + code is with you. Should any covered code prove defective in any respect, you (not + the initial developer or any other contributor) assume the cost of any necessary + servicing, repair or correction. This disclaimer of warranty constitutes an essential + part of this license. No use of any covered code is authorized hereunder except under + this disclaimer. + + Permission is hereby granted to use, copy, modify, and distribute this + source code, or portions hereof, for any purpose, including commercial applications, + freely and without fee, 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. + -------------------------------------------------------------------------------- + */ +#if !defined(__xfile_h) +#define __xfile_h + +#ifdef WIN32 + #include +#endif + +#include +#include + +#include "ximadef.h" + +class DLL_EXP CxFile +{ +public: + CxFile(void) { }; + virtual ~CxFile() { }; + + virtual bool Close() = 0; + virtual size_t Read(void *buffer, size_t size, size_t count) = 0; + virtual size_t Write(const void *buffer, size_t size, size_t count) = 0; + virtual bool Seek(long offset, int origin) = 0; + virtual long Tell() = 0; + virtual long Size() = 0; + virtual bool Flush() = 0; + virtual bool Eof() = 0; + virtual long Error() = 0; + virtual bool PutC(unsigned char c) + { + // Default implementation + size_t nWrote = Write(&c, 1, 1); + return (bool)(nWrote == 1); + } + virtual long GetC() = 0; +}; + +#endif //__xfile_h diff --git a/SlnkDWFImpl/CxImage/CxImage/ximabmp.cpp b/SlnkDWFImpl/CxImage/CxImage/ximabmp.cpp new file mode 100644 index 0000000..80ac102 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximabmp.cpp @@ -0,0 +1,361 @@ +/* + * File: ximabmp.cpp + * Purpose: Platform Independent BMP Image Class Loader and Writer + * 07/Aug/2001 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximabmp.h" + +#if CXIMAGE_SUPPORT_BMP + +#include "ximaiter.h" + +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImageBMP::Encode(CxFile * hFile) +{ + + if (EncodeSafeCheck(hFile)) return false; + + BITMAPFILEHEADER hdr; + + hdr.bfType = 0x4d42; // 'BM' WINDOWS_BITMAP_SIGNATURE + hdr.bfSize = GetSize() + 14 /*sizeof(BITMAPFILEHEADER)*/; + hdr.bfReserved1 = hdr.bfReserved2 = 0; + hdr.bfOffBits = 14 /*sizeof(BITMAPFILEHEADER)*/ + head.biSize + GetPaletteSize(); + + //copy attributes + memcpy(pDib,&head,sizeof(BITMAPINFOHEADER)); + // Write the file header + hFile->Write(&hdr,min(14,sizeof(BITMAPFILEHEADER)),1); + // Write the DIB header and the pixels + hFile->Write(pDib,GetSize(),1); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_DECODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImageBMP::Decode(CxFile * hFile) +{ + if (hFile == NULL) return false; + + BITMAPFILEHEADER bf; + DWORD off = hFile->Tell(); // + try { + if (hFile->Read(&bf,min(14,sizeof(bf)),1)==0) throw "Not a BMP"; + if (bf.bfType != BFT_BITMAP) { //do we have a RC HEADER? + bf.bfOffBits = 0L; + hFile->Seek(off,SEEK_SET); + } + + BITMAPINFOHEADER bmpHeader; + if (!DibReadBitmapInfo(hFile,&bmpHeader)) throw "Error reading BMP info"; + DWORD dwCompression=bmpHeader.biCompression; + DWORD dwBitCount=bmpHeader.biBitCount; //preserve for BI_BITFIELDS compression + bool bIsOldBmp = bmpHeader.biSize == sizeof(BITMAPCOREHEADER); + + bool bTopDownDib = bmpHeader.biHeight<0; // check if it's a top-down bitmap + if (bTopDownDib) bmpHeader.biHeight=-bmpHeader.biHeight; + + if (info.nEscape == -1) { + // Return output dimensions only + head.biWidth = bmpHeader.biWidth; + head.biHeight = bmpHeader.biHeight; + throw "output dimensions returned"; + } + + if (!Create(bmpHeader.biWidth,bmpHeader.biHeight,bmpHeader.biBitCount,CXIMAGE_FORMAT_BMP)) + throw "Can't allocate memory"; + + head.biXPelsPerMeter = bmpHeader.biXPelsPerMeter; + head.biYPelsPerMeter = bmpHeader.biYPelsPerMeter; + info.xDPI = (long) floor(bmpHeader.biXPelsPerMeter * 254.0 / 10000.0 + 0.5); + info.yDPI = (long) floor(bmpHeader.biYPelsPerMeter * 254.0 / 10000.0 + 0.5); + + if (info.nEscape) throw "Cancelled"; // - cancel decoding + + RGBQUAD *pRgb = GetPalette(); + if (pRgb){ + if (bIsOldBmp){ + // convert a old color table (3 byte entries) to a new + // color table (4 byte entries) + hFile->Read((void*)pRgb,DibNumColors(&bmpHeader) * sizeof(RGBTRIPLE),1); + for (int i=DibNumColors(&head)-1; i>=0; i--){ + pRgb[i].rgbRed = ((RGBTRIPLE *)pRgb)[i].rgbtRed; + pRgb[i].rgbBlue = ((RGBTRIPLE *)pRgb)[i].rgbtBlue; + pRgb[i].rgbGreen = ((RGBTRIPLE *)pRgb)[i].rgbtGreen; + pRgb[i].rgbReserved = (BYTE)0; + } + } else { + hFile->Read((void*)pRgb,DibNumColors(&bmpHeader) * sizeof(RGBQUAD),1); + //force rgbReserved=0, to avoid problems with some WinXp bitmaps + for (unsigned int i=0; i - cancel decoding + + switch (dwBitCount) { + case 32 : + if (bf.bfOffBits != 0L) hFile->Seek(off + bf.bfOffBits,SEEK_SET); + if (dwCompression == BI_BITFIELDS || dwCompression == BI_RGB){ + long imagesize=4*head.biHeight*head.biWidth; + BYTE* buff32=(BYTE*)malloc(imagesize); + if (buff32){ + hFile->Read(buff32, imagesize,1); // read in the pixels + Bitfield2RGB(buff32,0,0,0,32); + free(buff32); + } else throw "can't allocate memory"; + } else throw "unknown compression"; + break; + case 24 : + if (bf.bfOffBits != 0L) hFile->Seek(off + bf.bfOffBits,SEEK_SET); + if (dwCompression == BI_RGB){ + hFile->Read(info.pImage, head.biSizeImage,1); // read in the pixels + } else throw "unknown compression"; + break; + case 16 : + { + DWORD bfmask[3]; + if (dwCompression == BI_BITFIELDS) + { + hFile->Read(bfmask, 12, 1); + } else { + bfmask[0]=0x7C00; bfmask[1]=0x3E0; bfmask[2]=0x1F; //RGB555 + } + // bf.bfOffBits required after the bitfield mask + if (bf.bfOffBits != 0L) hFile->Seek(off + bf.bfOffBits,SEEK_SET); + // read in the pixels + hFile->Read(info.pImage, head.biHeight*((head.biWidth+1)/2)*4,1); + // transform into RGB + Bitfield2RGB(info.pImage,(WORD)bfmask[0],(WORD)bfmask[1],(WORD)bfmask[2],16); + break; + } + case 8 : + case 4 : + case 1 : + if (bf.bfOffBits != 0L) hFile->Seek(off + bf.bfOffBits,SEEK_SET); + switch (dwCompression) { + case BI_RGB : + hFile->Read(info.pImage, head.biSizeImage,1); // read in the pixels + break; + case BI_RLE4 : + { + BYTE status_byte = 0; + BYTE second_byte = 0; + int scanline = 0; + int bits = 0; + BOOL low_nibble = FALSE; + CImageIterator iter(this); + + for (BOOL bContinue = TRUE; bContinue;) { + hFile->Read(&status_byte, sizeof(BYTE), 1); + switch (status_byte) { + case RLE_COMMAND : + hFile->Read(&status_byte, sizeof(BYTE), 1); + switch (status_byte) { + case RLE_ENDOFLINE : + bits = 0; + scanline++; + low_nibble = FALSE; + break; + case RLE_ENDOFBITMAP : + bContinue=FALSE; + break; + case RLE_DELTA : + { + // read the delta values + BYTE delta_x; + BYTE delta_y; + hFile->Read(&delta_x, sizeof(BYTE), 1); + hFile->Read(&delta_y, sizeof(BYTE), 1); + // apply them + bits += delta_x / 2; + scanline += delta_y; + break; + } + default : + hFile->Read(&second_byte, sizeof(BYTE), 1); + BYTE *sline = iter.GetRow(scanline); + for (int i = 0; i < status_byte; i++) { + if (low_nibble) { + if ((DWORD)(sline+bits) < (DWORD)(info.pImage+head.biSizeImage)){ + *(sline + bits) |= (second_byte & 0x0F); + } + if (i != status_byte - 1) + hFile->Read(&second_byte, sizeof(BYTE), 1); + bits++; + } else { + if ((DWORD)(sline+bits) < (DWORD)(info.pImage+head.biSizeImage)){ + *(sline + bits) = (BYTE)(second_byte & 0xF0); + } + } + low_nibble = !low_nibble; + } + if ((((status_byte+1) >> 1) & 1 )== 1) + hFile->Read(&second_byte, sizeof(BYTE), 1); + break; + }; + break; + default : + { + BYTE *sline = iter.GetRow(scanline); + hFile->Read(&second_byte, sizeof(BYTE), 1); + for (unsigned i = 0; i < status_byte; i++) { + if (low_nibble) { + if ((DWORD)(sline+bits) < (DWORD)(info.pImage+head.biSizeImage)){ + *(sline + bits) |= (second_byte & 0x0F); + } + bits++; + } else { + if ((DWORD)(sline+bits) < (DWORD)(info.pImage+head.biSizeImage)){ + *(sline + bits) = (BYTE)(second_byte & 0xF0); + } + } + low_nibble = !low_nibble; + } + } + break; + }; + } + break; + } + case BI_RLE8 : + { + BYTE status_byte = 0; + BYTE second_byte = 0; + int scanline = 0; + int bits = 0; + CImageIterator iter(this); + + for (BOOL bContinue = TRUE; bContinue; ) { + hFile->Read(&status_byte, sizeof(BYTE), 1); + switch (status_byte) { + case RLE_COMMAND : + hFile->Read(&status_byte, sizeof(BYTE), 1); + switch (status_byte) { + case RLE_ENDOFLINE : + bits = 0; + scanline++; + break; + case RLE_ENDOFBITMAP : + bContinue=FALSE; + break; + case RLE_DELTA : + { + // read the delta values + BYTE delta_x; + BYTE delta_y; + hFile->Read(&delta_x, sizeof(BYTE), 1); + hFile->Read(&delta_y, sizeof(BYTE), 1); + // apply them + bits += delta_x; + scanline += delta_y; + break; + } + default : + hFile->Read((void *)(iter.GetRow(scanline) + bits), sizeof(BYTE) * status_byte, 1); + // align run length to even number of bytes + if ((status_byte & 1) == 1) + hFile->Read(&second_byte, sizeof(BYTE), 1); + bits += status_byte; + break; + }; + break; + default : + BYTE *sline = iter.GetRow(scanline); + hFile->Read(&second_byte, sizeof(BYTE), 1); + for (unsigned i = 0; i < status_byte; i++) { + if ((DWORD)bits + + } catch (char *message) { + strncpy(info.szLastError,message,255); + if (info.nEscape==-1) return true; + return false; + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/* ReadDibBitmapInfo() + * + * Will read a file in DIB format and return a global HANDLE to its + * BITMAPINFO. This function will work with both "old" and "new" + * bitmap formats, but will always return a "new" BITMAPINFO. + */ +bool CxImageBMP::DibReadBitmapInfo(CxFile* fh, BITMAPINFOHEADER *pdib) +{ + if ((fh==NULL)||(pdib==NULL)) return false; + + if (fh->Read(pdib,sizeof(BITMAPINFOHEADER),1)==0) return false; + + BITMAPCOREHEADER bc; + + switch (pdib->biSize) // what type of bitmap info is this? + { + case sizeof(BITMAPINFOHEADER): + break; + + case 64: //sizeof(OS2_BMP_HEADER): + fh->Seek((long)(64 - sizeof(BITMAPINFOHEADER)),SEEK_CUR); + break; + + case sizeof(BITMAPCOREHEADER): + bc = *(BITMAPCOREHEADER*)pdib; + pdib->biSize = bc.bcSize; + pdib->biWidth = (DWORD)bc.bcWidth; + pdib->biHeight = (DWORD)bc.bcHeight; + pdib->biPlanes = bc.bcPlanes; + pdib->biBitCount = bc.bcBitCount; + pdib->biCompression = BI_RGB; + pdib->biSizeImage = 0; + pdib->biXPelsPerMeter = 0; + pdib->biYPelsPerMeter = 0; + pdib->biClrUsed = 0; + pdib->biClrImportant = 0; + + fh->Seek((long)(sizeof(BITMAPCOREHEADER)-sizeof(BITMAPINFOHEADER)), SEEK_CUR); + + break; + default: + //give a last chance + if (pdib->biSize>(sizeof(BITMAPINFOHEADER))&& + (pdib->biSizeImage==(unsigned long)(pdib->biHeight*((((pdib->biBitCount*pdib->biWidth)+31)/32)*4)))&& + (pdib->biPlanes==1)&&(pdib->biCompression==BI_RGB)&&(pdib->biClrUsed==0)) + { + fh->Seek((long)(pdib->biSize - sizeof(BITMAPINFOHEADER)),SEEK_CUR); + break; + } + return false; + } + + FixBitmapInfo(pdib); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_DECODE +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_BMP +//////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/CxImage/ximabmp.h b/SlnkDWFImpl/CxImage/CxImage/ximabmp.h new file mode 100644 index 0000000..3b794d9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximabmp.h @@ -0,0 +1,79 @@ +/* + * File: ximabmp.h + * Purpose: BMP Image Class Loader and Writer + */ +/* ========================================================== + * CxImageBMP (c) 07/Aug/2001 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * Special thanks to Troels Knakkergaard for new features, enhancements and bugfixes + * + * original CImageBMP and CImageIterator implementation are: + * Copyright: (c) 1995, Alejandro Aguilar Sierra + * + * ========================================================== + */ + +#if !defined(__ximaBMP_h) +#define __ximaBMP_h + +#include "ximage.h" + +const int RLE_COMMAND = 0; +const int RLE_ENDOFLINE = 0; +const int RLE_ENDOFBITMAP = 1; +const int RLE_DELTA = 2; + +#if !defined(BI_RLE8) + #define BI_RLE8 1L +#endif +#if !defined(BI_RLE4) + #define BI_RLE4 2L +#endif + +#if CXIMAGE_SUPPORT_BMP + +class CxImageBMP: public CxImage +{ +public: + CxImageBMP(): CxImage(CXIMAGE_FORMAT_BMP) {}; + + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE + +protected: + bool DibReadBitmapInfo(CxFile* fh, BITMAPINFOHEADER *pdib); +}; + +#define BFT_ICON 0x4349 /* 'IC' */ +#define BFT_BITMAP 0x4d42 /* 'BM' */ +#define BFT_CURSOR 0x5450 /* 'PT' */ + +#ifndef WIDTHBYTES +#define WIDTHBYTES(i) ((unsigned)((i+31)&(~31))/8) /* ULONG aligned ! */ +#endif + +#endif + +#define DibWidthBytesN(lpbi, n) (UINT)WIDTHBYTES((UINT)(lpbi)->biWidth * (UINT)(n)) +#define DibWidthBytes(lpbi) DibWidthBytesN(lpbi, (lpbi)->biBitCount) + +#define DibSizeImage(lpbi) ((lpbi)->biSizeImage == 0 \ + ? ((DWORD)(UINT)DibWidthBytes(lpbi) * (DWORD)(UINT)(lpbi)->biHeight) \ + : (lpbi)->biSizeImage) + +#define DibNumColors(lpbi) ((lpbi)->biClrUsed == 0 && (lpbi)->biBitCount <= 8 \ + ? (int)(1 << (int)(lpbi)->biBitCount) \ + : (int)(lpbi)->biClrUsed) + +#define FixBitmapInfo(lpbi) if ((lpbi)->biSizeImage == 0) \ + (lpbi)->biSizeImage = DibSizeImage(lpbi); \ + if ((lpbi)->biClrUsed == 0) \ + (lpbi)->biClrUsed = DibNumColors(lpbi); \ + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximacfg.h b/SlnkDWFImpl/CxImage/CxImage/ximacfg.h new file mode 100644 index 0000000..17dd221 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximacfg.h @@ -0,0 +1,52 @@ +#if !defined(__ximaCFG_h) +#define __ximaCFG_h + +///////////////////////////////////////////////////////////////////////////// +// CxImage supported features +#define CXIMAGE_SUPPORT_ALPHA 1 +#define CXIMAGE_SUPPORT_SELECTION 0 +#define CXIMAGE_SUPPORT_TRANSFORMATION 1 +#define CXIMAGE_SUPPORT_DSP 0 +#define CXIMAGE_SUPPORT_LAYERS 0 +#define CXIMAGE_SUPPORT_INTERPOLATION 0 + +#define CXIMAGE_SUPPORT_DECODE 1 +#define CXIMAGE_SUPPORT_ENCODE 1 // +#define CXIMAGE_SUPPORT_WINDOWS 1 +#define CXIMAGE_SUPPORT_WINCE 0 // + +///////////////////////////////////////////////////////////////////////////// +// CxImage supported formats +#define CXIMAGE_SUPPORT_BMP 0 +#define CXIMAGE_SUPPORT_GIF 1 +#define CXIMAGE_SUPPORT_JPG 1 +#define CXIMAGE_SUPPORT_PNG 1 +#define CXIMAGE_SUPPORT_MNG 0 +#define CXIMAGE_SUPPORT_ICO 0 +#define CXIMAGE_SUPPORT_TIF 1 +#define CXIMAGE_SUPPORT_TGA 0 +#define CXIMAGE_SUPPORT_PCX 0 +#define CXIMAGE_SUPPORT_WBMP 0 +#define CXIMAGE_SUPPORT_WMF 0 +#define CXIMAGE_SUPPORT_J2K 0 // Beta, use JP2 +#define CXIMAGE_SUPPORT_JBG 0 // GPL'd see ../jbig/copying.txt & ../jbig/patents.htm + +#define CXIMAGE_SUPPORT_JP2 0 +#define CXIMAGE_SUPPORT_JPC 0 +#define CXIMAGE_SUPPORT_PGX 0 +#define CXIMAGE_SUPPORT_PNM 0 +#define CXIMAGE_SUPPORT_RAS 0 + + +///////////////////////////////////////////////////////////////////////////// +#define CXIMAGE_MAX_MEMORY 256000000 + +#define CXIMAGE_ERR_NOFILE "null file handler" +#define CXIMAGE_ERR_NOIMAGE "null image!!!" + +///////////////////////////////////////////////////////////////////////////// +//color to grey mapping +//#define RGB2GRAY(r,g,b) (((b)*114 + (g)*587 + (r)*299)/1000) +#define RGB2GRAY(r,g,b) (((b)*117 + (g)*601 + (r)*306) >> 10) + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximadef.h b/SlnkDWFImpl/CxImage/CxImage/ximadef.h new file mode 100644 index 0000000..54c4c94 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximadef.h @@ -0,0 +1,197 @@ +#if !defined(__ximadefs_h) +#define __ximadefs_h + +#include "ximacfg.h" + +#if defined(_AFXDLL)||defined(_USRDLL) + #define DLL_EXP __declspec(dllexport) +#elif defined(_MSC_VER)&&(_MSC_VER<1200) + #define DLL_EXP __declspec(dllimport) +#else + #define DLL_EXP +#endif + +#if CXIMAGE_SUPPORT_JP2 || CXIMAGE_SUPPORT_JPC || CXIMAGE_SUPPORT_PGX || CXIMAGE_SUPPORT_PNM || CXIMAGE_SUPPORT_RAS + #define CXIMAGE_SUPPORT_JASPER 1 +#else + #define CXIMAGE_SUPPORT_JASPER 0 +#endif + +#if CXIMAGE_SUPPORT_DSP +#undef CXIMAGE_SUPPORT_TRANSFORMATION + #define CXIMAGE_SUPPORT_TRANSFORMATION 1 +#endif + +#if CXIMAGE_SUPPORT_TRANSFORMATION || CXIMAGE_SUPPORT_TIF || CXIMAGE_SUPPORT_TGA || CXIMAGE_SUPPORT_BMP || CXIMAGE_SUPPORT_WINDOWS + #define CXIMAGE_SUPPORT_BASICTRANSFORMATIONS 1 +#endif + +#if CXIMAGE_SUPPORT_DSP || CXIMAGE_SUPPORT_TRANSFORMATION +#undef CXIMAGE_SUPPORT_INTERPOLATION + #define CXIMAGE_SUPPORT_INTERPOLATION 1 +#endif + +#if CXIMAGE_SUPPORT_WINCE + #undef CXIMAGE_SUPPORT_WMF + #define CXIMAGE_SUPPORT_WMF 0 + #undef CXIMAGE_SUPPORT_WINDOWS + #define CXIMAGE_SUPPORT_WINDOWS 0 +#endif + +#ifndef WIN32 + #undef CXIMAGE_SUPPORT_WINDOWS + #define CXIMAGE_SUPPORT_WINDOWS 0 +#endif + +#ifndef min +#define min(a,b) (((a)<(b))?(a):(b)) +#endif +#ifndef max +#define max(a,b) (((a)>(b))?(a):(b)) +#endif + +#ifndef PI + #define PI 3.141592653589793f +#endif + + +#ifdef WIN32 +#include +#include +#endif + +#include +#include + + +#ifdef __BORLANDC__ + +#ifndef _COMPLEX_DEFINED + +typedef struct tagcomplex { + double x,y; +} _complex; + +#endif + +#define _cabs(c) sqrt(c.x*c.x+c.y*c.y) + +#endif + + +#ifndef WIN32 + +#include +#include +#include + +typedef unsigned char BYTE; +typedef unsigned short WORD; +typedef unsigned long DWORD; +typedef unsigned int UINT; + +typedef DWORD COLORREF; +typedef unsigned int HANDLE; +typedef void* HRGN; + +#ifndef BOOL +#define BOOL bool +#endif + +#ifndef TRUE +#define TRUE true +#endif + +#ifndef FALSE +#define FALSE false +#endif + +#ifndef TCHAR +#define TCHAR char +#define _T +#endif + +typedef struct tagRECT +{ + long left; + long top; + long right; + long bottom; +} RECT; + +typedef struct tagPOINT +{ + long x; + long y; +} POINT; + +typedef struct tagRGBQUAD { + BYTE rgbBlue; + BYTE rgbGreen; + BYTE rgbRed; + BYTE rgbReserved; +} RGBQUAD; + +#pragma pack(1) + +typedef struct tagBITMAPINFOHEADER{ + DWORD biSize; + long biWidth; + long biHeight; + WORD biPlanes; + WORD biBitCount; + DWORD biCompression; + DWORD biSizeImage; + long biXPelsPerMeter; + long biYPelsPerMeter; + DWORD biClrUsed; + DWORD biClrImportant; +} BITMAPINFOHEADER; + +typedef struct tagBITMAPFILEHEADER { + WORD bfType; + DWORD bfSize; + WORD bfReserved1; + WORD bfReserved2; + DWORD bfOffBits; +} BITMAPFILEHEADER; + +typedef struct tagBITMAPCOREHEADER { + DWORD bcSize; + WORD bcWidth; + WORD bcHeight; + WORD bcPlanes; + WORD bcBitCount; +} BITMAPCOREHEADER; + +typedef struct tagRGBTRIPLE { + BYTE rgbtBlue; + BYTE rgbtGreen; + BYTE rgbtRed; +} RGBTRIPLE; + +#pragma pack() + +#define BI_RGB 0L +#define BI_RLE8 1L +#define BI_RLE4 2L +#define BI_BITFIELDS 3L + +#define GetRValue(rgb) ((BYTE)(rgb)) +#define GetGValue(rgb) ((BYTE)(((WORD)(rgb)) >> 8)) +#define GetBValue(rgb) ((BYTE)((rgb)>>16)) +#define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) + +#ifndef _COMPLEX_DEFINED + +typedef struct tagcomplex { + double x,y; +} _complex; + +#endif + +#define _cabs(c) sqrt(c.x*c.x+c.y*c.y) + +#endif + +#endif //__ximadefs diff --git a/SlnkDWFImpl/CxImage/CxImage/ximadsp.cpp b/SlnkDWFImpl/CxImage/CxImage/ximadsp.cpp new file mode 100644 index 0000000..11bca60 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximadsp.cpp @@ -0,0 +1,2370 @@ +// xImaDsp.cpp : DSP functions +/* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +#include "ximaiter.h" + +#if CXIMAGE_SUPPORT_DSP + +//////////////////////////////////////////////////////////////////////////////// +/** + * Converts the image to B&W. + * The Mean() function can be used for calculating the optimal threshold. + * \param level: the lightness threshold. + * \return true if everything is ok + */ +bool CxImage::Threshold(BYTE level) +{ + if (!pDib) return false; + if (head.biBitCount == 1) return true; + + GrayScale(); + + CxImage tmp(head.biWidth,head.biHeight,1); + if (!tmp.IsValid()) return false; + + for (long y=0;ylevel) + tmp.SetPixelIndex(x,y,1); + else + tmp.SetPixelIndex(x,y,0); + } + } + tmp.SetPaletteColor(0,0,0,0); + tmp.SetPaletteColor(1,255,255,255); + Transfer(tmp); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Extract RGB channels from the image. Each channel is an 8 bit grayscale image. + * \param r,g,b: pointers to CxImage objects, to store the splited channels + * \return true if everything is ok + */ +bool CxImage::SplitRGB(CxImage* r,CxImage* g,CxImage* b) +{ + if (!pDib) return false; + if (r==NULL && g==NULL && b==NULL) return false; + + CxImage tmpr(head.biWidth,head.biHeight,8); + CxImage tmpg(head.biWidth,head.biHeight,8); + CxImage tmpb(head.biWidth,head.biHeight,8); + + RGBQUAD color; + for(long y=0; yTransfer(tmpr); + if (g) g->Transfer(tmpg); + if (b) b->Transfer(tmpb); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Extract CMYK channels from the image. Each channel is an 8 bit grayscale image. + * \param c,m,y,k: pointers to CxImage objects, to store the splited channels + * \return true if everything is ok + */ +bool CxImage::SplitCMYK(CxImage* c,CxImage* m,CxImage* y,CxImage* k) +{ + if (!pDib) return false; + if (c==NULL && m==NULL && y==NULL && k==NULL) return false; + + CxImage tmpc(head.biWidth,head.biHeight,8); + CxImage tmpm(head.biWidth,head.biHeight,8); + CxImage tmpy(head.biWidth,head.biHeight,8); + CxImage tmpk(head.biWidth,head.biHeight,8); + + RGBQUAD color; + for(long yy=0; yyTransfer(tmpc); + if (m) m->Transfer(tmpm); + if (y) y->Transfer(tmpy); + if (k) k->Transfer(tmpk); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Extract YUV channels from the image. Each channel is an 8 bit grayscale image. + * \param y,u,v: pointers to CxImage objects, to store the splited channels + * \return true if everything is ok + */ +bool CxImage::SplitYUV(CxImage* y,CxImage* u,CxImage* v) +{ + if (!pDib) return false; + if (y==NULL && u==NULL && v==NULL) return false; + + CxImage tmpy(head.biWidth,head.biHeight,8); + CxImage tmpu(head.biWidth,head.biHeight,8); + CxImage tmpv(head.biWidth,head.biHeight,8); + + RGBQUAD color; + for(long yy=0; yyTransfer(tmpy); + if (u) u->Transfer(tmpu); + if (v) v->Transfer(tmpv); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Extract YIQ channels from the image. Each channel is an 8 bit grayscale image. + * \param y,i,q: pointers to CxImage objects, to store the splited channels + * \return true if everything is ok + */ +bool CxImage::SplitYIQ(CxImage* y,CxImage* i,CxImage* q) +{ + if (!pDib) return false; + if (y==NULL && i==NULL && q==NULL) return false; + + CxImage tmpy(head.biWidth,head.biHeight,8); + CxImage tmpi(head.biWidth,head.biHeight,8); + CxImage tmpq(head.biWidth,head.biHeight,8); + + RGBQUAD color; + for(long yy=0; yyTransfer(tmpy); + if (i) i->Transfer(tmpi); + if (q) q->Transfer(tmpq); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Extract XYZ channels from the image. Each channel is an 8 bit grayscale image. + * \param x,y,z: pointers to CxImage objects, to store the splited channels + * \return true if everything is ok + */ +bool CxImage::SplitXYZ(CxImage* x,CxImage* y,CxImage* z) +{ + if (!pDib) return false; + if (x==NULL && y==NULL && z==NULL) return false; + + CxImage tmpx(head.biWidth,head.biHeight,8); + CxImage tmpy(head.biWidth,head.biHeight,8); + CxImage tmpz(head.biWidth,head.biHeight,8); + + RGBQUAD color; + for(long yy=0; yyTransfer(tmpx); + if (y) y->Transfer(tmpy); + if (z) z->Transfer(tmpz); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Extract HSL channels from the image. Each channel is an 8 bit grayscale image. + * \param h,s,l: pointers to CxImage objects, to store the splited channels + * \return true if everything is ok + */ +bool CxImage::SplitHSL(CxImage* h,CxImage* s,CxImage* l) +{ + if (!pDib) return false; + if (h==NULL && s==NULL && l==NULL) return false; + + CxImage tmph(head.biWidth,head.biHeight,8); + CxImage tmps(head.biWidth,head.biHeight,8); + CxImage tmpl(head.biWidth,head.biHeight,8); + + RGBQUAD color; + for(long y=0; yTransfer(tmph); + if (s) s->Transfer(tmps); + if (l) l->Transfer(tmpl); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#define HSLMAX 255 /* H,L, and S vary over 0-HSLMAX */ +#define RGBMAX 255 /* R,G, and B vary over 0-RGBMAX */ + /* HSLMAX BEST IF DIVISIBLE BY 6 */ + /* RGBMAX, HSLMAX must each fit in a BYTE. */ +/* Hue is undefined if Saturation is 0 (grey-scale) */ +/* This value determines where the Hue scrollbar is */ +/* initially set for achromatic colors */ +#define HSLUNDEFINED (HSLMAX*2/3) +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::RGBtoHSL(RGBQUAD lRGBColor) +{ + BYTE R,G,B; /* input RGB values */ + BYTE H,L,S; /* output HSL values */ + BYTE cMax,cMin; /* max and min RGB values */ + WORD Rdelta,Gdelta,Bdelta; /* intermediate value: % of spread from max*/ + + R = lRGBColor.rgbRed; /* get R, G, and B out of DWORD */ + G = lRGBColor.rgbGreen; + B = lRGBColor.rgbBlue; + + cMax = max( max(R,G), B); /* calculate lightness */ + cMin = min( min(R,G), B); + L = (BYTE)((((cMax+cMin)*HSLMAX)+RGBMAX)/(2*RGBMAX)); + + if (cMax==cMin){ /* r=g=b --> achromatic case */ + S = 0; /* saturation */ + H = HSLUNDEFINED; /* hue */ + } else { /* chromatic case */ + if (L <= (HSLMAX/2)) /* saturation */ + S = (BYTE)((((cMax-cMin)*HSLMAX)+((cMax+cMin)/2))/(cMax+cMin)); + else + S = (BYTE)((((cMax-cMin)*HSLMAX)+((2*RGBMAX-cMax-cMin)/2))/(2*RGBMAX-cMax-cMin)); + /* hue */ + Rdelta = (WORD)((((cMax-R)*(HSLMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); + Gdelta = (WORD)((((cMax-G)*(HSLMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); + Bdelta = (WORD)((((cMax-B)*(HSLMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); + + if (R == cMax) + H = (BYTE)(Bdelta - Gdelta); + else if (G == cMax) + H = (BYTE)((HSLMAX/3) + Rdelta - Bdelta); + else /* B == cMax */ + H = (BYTE)(((2*HSLMAX)/3) + Gdelta - Rdelta); + +// if (H < 0) H += HSLMAX; //always false + if (H > HSLMAX) H -= HSLMAX; + } + RGBQUAD hsl={L,S,H,0}; + return hsl; +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::HueToRGB(float n1,float n2, float hue) +{ + // fixed implementation for HSL2RGB routine + float rValue; + + if (hue > 360) + hue = hue - 360; + else if (hue < 0) + hue = hue + 360; + + if (hue < 60) + rValue = n1 + (n2-n1)*hue/60.0f; + else if (hue < 180) + rValue = n2; + else if (hue < 240) + rValue = n1+(n2-n1)*(240-hue)/60; + else + rValue = n1; + + return rValue; +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::HSLtoRGB(COLORREF cHSLColor) +{ + return HSLtoRGB(RGBtoRGBQUAD(cHSLColor)); +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::HSLtoRGB(RGBQUAD lHSLColor) +{ + // fixed implementation for HSL2RGB routine + float h,s,l; + float m1,m2; + BYTE r,g,b; + + h = (float)lHSLColor.rgbRed * 360.0f/255.0f; + s = (float)lHSLColor.rgbGreen/255.0f; + l = (float)lHSLColor.rgbBlue/255.0f; + + if (l <= 0.5) m2 = l * (1+s); + else m2 = l + s - l*s; + + m1 = 2 * l - m2; + + if (s == 0) { + r=g=b=(BYTE)(l*255.0f); + } else { + r = (BYTE)(HueToRGB(m1,m2,h+120) * 255.0f); + g = (BYTE)(HueToRGB(m1,m2,h) * 255.0f); + b = (BYTE)(HueToRGB(m1,m2,h-120) * 255.0f); + } + + RGBQUAD rgb = {b,g,r,0}; + return rgb; +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::YUVtoRGB(RGBQUAD lYUVColor) +{ + int U,V,R,G,B; + float Y = lYUVColor.rgbRed; + U = lYUVColor.rgbGreen - 128; + V = lYUVColor.rgbBlue - 128; + +// R = (int)(1.164 * Y + 2.018 * U); +// G = (int)(1.164 * Y - 0.813 * V - 0.391 * U); +// B = (int)(1.164 * Y + 1.596 * V); + R = (int)( Y + 1.403f * V); + G = (int)( Y - 0.344f * U - 0.714f * V); + B = (int)( Y + 1.770f * U); + + R= min(255,max(0,R)); + G= min(255,max(0,G)); + B= min(255,max(0,B)); + RGBQUAD rgb={(BYTE)B,(BYTE)G,(BYTE)R,0}; + return rgb; +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::RGBtoYUV(RGBQUAD lRGBColor) +{ + int Y,U,V,R,G,B; + R = lRGBColor.rgbRed; + G = lRGBColor.rgbGreen; + B = lRGBColor.rgbBlue; + +// Y = (int)( 0.257 * R + 0.504 * G + 0.098 * B); +// U = (int)( 0.439 * R - 0.368 * G - 0.071 * B + 128); +// V = (int)(-0.148 * R - 0.291 * G + 0.439 * B + 128); + Y = (int)(0.299f * R + 0.587f * G + 0.114f * B); + U = (int)((B-Y) * 0.565f + 128); + V = (int)((R-Y) * 0.713f + 128); + + Y= min(255,max(0,Y)); + U= min(255,max(0,U)); + V= min(255,max(0,V)); + RGBQUAD yuv={(BYTE)V,(BYTE)U,(BYTE)Y,0}; + return yuv; +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::YIQtoRGB(RGBQUAD lYIQColor) +{ + int I,Q,R,G,B; + float Y = lYIQColor.rgbRed; + I = lYIQColor.rgbGreen - 128; + Q = lYIQColor.rgbBlue - 128; + + R = (int)( Y + 0.956f * I + 0.621f * Q); + G = (int)( Y - 0.273f * I - 0.647f * Q); + B = (int)( Y - 1.104f * I + 1.701f * Q); + + R= min(255,max(0,R)); + G= min(255,max(0,G)); + B= min(255,max(0,B)); + RGBQUAD rgb={(BYTE)B,(BYTE)G,(BYTE)R,0}; + return rgb; +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::RGBtoYIQ(RGBQUAD lRGBColor) +{ + int Y,I,Q,R,G,B; + R = lRGBColor.rgbRed; + G = lRGBColor.rgbGreen; + B = lRGBColor.rgbBlue; + + Y = (int)( 0.2992f * R + 0.5868f * G + 0.1140f * B); + I = (int)( 0.5960f * R - 0.2742f * G - 0.3219f * B + 128); + Q = (int)( 0.2109f * R - 0.5229f * G + 0.3120f * B + 128); + + Y= min(255,max(0,Y)); + I= min(255,max(0,I)); + Q= min(255,max(0,Q)); + RGBQUAD yiq={(BYTE)Q,(BYTE)I,(BYTE)Y,0}; + return yiq; +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::XYZtoRGB(RGBQUAD lXYZColor) +{ + int X,Y,Z,R,G,B; + X = lXYZColor.rgbRed; + Y = lXYZColor.rgbGreen; + Z = lXYZColor.rgbBlue; + double k=1.088751; + + R = (int)( 3.240479f * X - 1.537150f * Y - 0.498535f * Z * k); + G = (int)( -0.969256f * X + 1.875992f * Y + 0.041556f * Z * k); + B = (int)( 0.055648f * X - 0.204043f * Y + 1.057311f * Z * k); + + R= min(255,max(0,R)); + G= min(255,max(0,G)); + B= min(255,max(0,B)); + RGBQUAD rgb={(BYTE)B,(BYTE)G,(BYTE)R,0}; + return rgb; +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::RGBtoXYZ(RGBQUAD lRGBColor) +{ + int X,Y,Z,R,G,B; + R = lRGBColor.rgbRed; + G = lRGBColor.rgbGreen; + B = lRGBColor.rgbBlue; + + X = (int)( 0.412453f * R + 0.357580f * G + 0.180423f * B); + Y = (int)( 0.212671f * R + 0.715160f * G + 0.072169f * B); + Z = (int)((0.019334f * R + 0.119193f * G + 0.950227f * B)*0.918483657f); + + //X= min(255,max(0,X)); + //Y= min(255,max(0,Y)); + //Z= min(255,max(0,Z)); + RGBQUAD xyz={(BYTE)Z,(BYTE)Y,(BYTE)X,0}; + return xyz; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Generates a "rainbow" palette with saturated colors + * \param correction: 1 generates a single hue spectrum. 0.75 is nice for scientific applications. + */ +void CxImage::HuePalette(float correction) +{ + if (head.biClrUsed==0) return; + + for(DWORD j=0; j 1.0f) blend = 1.0f; + int a0 = (int)(256*blend); + int a1 = 256 - a0; + + bool bFullBlend = false; + if (blend > 0.999f) bFullBlend = true; + + RGBQUAD color,hsl; + if (head.biClrUsed==0){ + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + + for(long y=ymin; y>8); + color.rgbBlue = (BYTE)((hsl.rgbBlue * a0 + color.rgbBlue * a1)>>8); + color.rgbGreen = (BYTE)((hsl.rgbGreen * a0 + color.rgbGreen * a1)>>8); + SetPixelColor(x,y,color); + } + } + } + } + } else { + for(DWORD j=0; j + for (int i=0;i<256;i++) { + cTable[i] = (BYTE)max(0,min(255,(int)((i-128)*c + brightness))); + } + + return Lut(cTable); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \return mean lightness of the image. Useful with Threshold() and Light() + */ +float CxImage::Mean() +{ + if (!pDib) return 0; + + CxImage tmp(*this,true); + if (!tmp.IsValid()) return false; + + tmp.GrayScale(); + float sum=0; + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + if (xmin==xmax || ymin==ymax) return (float)0.0; + + BYTE *iSrc=tmp.info.pImage; + iSrc += tmp.info.dwEffWidth*ymin; // necessary for selections + + for(long y=ymin; y + for(long x=xmin; x 0 && (y+kmax-1) < head.biHeight && x-k2 > 0 && (x+kmax-1) < head.biWidth) + { + b=0; + iCount = 0; + iY2 = ((y-k2)*info.dwEffWidth); + for(long j=-k2;j r) r=c.rgbRed; + if (c.rgbGreen > g) g=c.rgbGreen; + if (c.rgbBlue > b) b=c.rgbBlue; + } + } + c.rgbRed = r; + c.rgbGreen = g; + c.rgbBlue = b; + tmp.SetPixelColor(x,y,c); + } + } + } + Transfer(tmp); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Enhance the variations between adjacent pixels. + * Similar results can be achieved using Filter(), + * but the algorithms are different both in Edge() and in Contour(). + * \param Ksize: size of the kernel. + * \return true if everything is ok + */ +bool CxImage::Edge(long Ksize) +{ + if (!pDib) return false; + + long k2 = Ksize/2; + long kmax= Ksize-k2; + BYTE r,g,b,rr,gg,bb; + RGBQUAD c; + + CxImage tmp(*this,pSelection!=0,true,true); + if (!tmp.IsValid()) return false; + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + + for(long y=ymin; y r) r=c.rgbRed; + if (c.rgbGreen > g) g=c.rgbGreen; + if (c.rgbBlue > b) b=c.rgbBlue; + + if (c.rgbRed < rr) rr=c.rgbRed; + if (c.rgbGreen < gg) gg=c.rgbGreen; + if (c.rgbBlue < bb) bb=c.rgbBlue; + } + } + c.rgbRed = 255-abs(r-rr); + c.rgbGreen = 255-abs(g-gg); + c.rgbBlue = 255-abs(b-bb); + tmp.SetPixelColor(x,y,c); + } + } + } + Transfer(tmp); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Blends two images + * \param imgsrc2: image to be mixed with this + * \param op: blending method; see ImageOpType + * \param lXOffset, lYOffset: image displacement + * \param bMixAlpha: if true and imgsrc2 has a valid alpha layer, it will be mixed in the destination image. + * \return true if everything is ok + * + * thanks to Mwolski + */ +// +void CxImage::Mix(CxImage & imgsrc2, ImageOpType op, long lXOffset, long lYOffset, bool bMixAlpha) +{ + long lWide = min(GetWidth(),imgsrc2.GetWidth()-lXOffset); + long lHeight = min(GetHeight(),imgsrc2.GetHeight()-lYOffset); + + bool bEditAlpha = imgsrc2.AlphaIsValid() & bMixAlpha; + + if (bEditAlpha && AlphaIsValid()==false){ + AlphaCreate(); + } + + RGBQUAD rgbBackgrnd = GetTransColor(); + RGBQUAD rgb1, rgb2, rgbDest; + + for(long lY=0;lY>8); + } else { + a=255; + } + + if (a==0){ //transparent + rgbDest = rgb1; + } else if (a==255){ //opaque + rgbDest = rgb2; + } else { //blend + a1 = (BYTE)~a; + rgbDest.rgbBlue = (BYTE)((rgb1.rgbBlue*a1+rgb2.rgbBlue*a)>>8); + rgbDest.rgbGreen = (BYTE)((rgb1.rgbGreen*a1+rgb2.rgbGreen*a)>>8); + rgbDest.rgbRed = (BYTE)((rgb1.rgbRed*a1+rgb2.rgbRed*a)>>8); + } + + if (bEditAlpha) rgbDest.rgbReserved = (BYTE)(((1+rgb1.rgbReserved)*a)>>8); + } + break; + case OpSrcBlend: + if(memcmp(&rgb1,&rgbBackgrnd,sizeof(RGBQUAD))==0) + rgbDest = rgb2; + else + { + long lBDiff = abs(rgb1.rgbBlue - rgbBackgrnd.rgbBlue); + long lGDiff = abs(rgb1.rgbGreen - rgbBackgrnd.rgbGreen); + long lRDiff = abs(rgb1.rgbRed - rgbBackgrnd.rgbRed); + + double lAverage = (lBDiff+lGDiff+lRDiff)/3; + double lThresh = 16; + double dLarge = lAverage/lThresh; + double dSmall = (lThresh-lAverage)/lThresh; + double dSmallAmt = dSmall*((double)rgb2.rgbBlue); + + if( lAverage < lThresh+1){ + rgbDest.rgbBlue = (BYTE)max(0,min(255,(int)(dLarge*((double)rgb1.rgbBlue) + + dSmallAmt))); + rgbDest.rgbGreen = (BYTE)max(0,min(255,(int)(dLarge*((double)rgb1.rgbGreen) + + dSmallAmt))); + rgbDest.rgbRed = (BYTE)max(0,min(255,(int)(dLarge*((double)rgb1.rgbRed) + + dSmallAmt))); + } + else + rgbDest = rgb1; + } + break; + default: + return; + } + SetPixelColor(lX,lY,rgbDest,bEditAlpha); + } + } + } +} +//////////////////////////////////////////////////////////////////////////////// +// thanks to Kenneth Ballard +void CxImage::MixFrom(CxImage & imagesrc2, long lXOffset, long lYOffset) +{ + RGBQUAD rgbBackgrnd = imagesrc2.GetTransColor(); + RGBQUAD rgb1; + + long width = imagesrc2.GetWidth(); + long height = imagesrc2.GetHeight(); + + int x, y; + + for(x = 0; x < width; x++) + { + for(y = 0; y < height; y++) + { + rgb1 = imagesrc2.GetPixelColor(x, y); + if(memcmp(&rgb1, &rgbBackgrnd, sizeof(RGBQUAD)) != 0) + SetPixelColor(x + lXOffset, y + lYOffset, rgb1); + } + } +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Adjusts separately the red, green, and blue values in the image. + * \param r, g, b: can be from -255 to +255. + * \return true if everything is ok + */ +bool CxImage::ShiftRGB(long r, long g, long b) +{ + if (!pDib) return false; + RGBQUAD color; + if (head.biClrUsed==0){ + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + + for(long y=ymin; y + for (int i=0;i<256;i++) { + cTable[i] = (BYTE)max(0,min(255,(int)( pow((double)i, dinvgamma) / dMax))); + } + + return Lut(cTable); +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_WINCE == 0 +/** + * Adjusts the intensity of each pixel to the median intensity of its surrounding pixels. + * \param Ksize: size of the kernel. + * \return true if everything is ok + */ +bool CxImage::Median(long Ksize) +{ + if (!pDib) return false; + + long k2 = Ksize/2; + long kmax= Ksize-k2; + long i,j,k; + + RGBQUAD* kernel = (RGBQUAD*)malloc(Ksize*Ksize*sizeof(RGBQUAD)); + + CxImage tmp(*this,pSelection!=0,true,true); + if (!tmp.IsValid()) return false; + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + + for(long y=ymin; y + for(long x=xmin; xGetWidth(); + h=srcReal->GetHeight(); + } else { + w=srcImag->GetWidth(); + h=srcImag->GetHeight(); + } + + bool bXpow2 = IsPowerof2(w); + bool bYpow2 = IsPowerof2(h); + //if bForceFFT, width AND height must be powers of 2 + if (bForceFFT && !(bXpow2 && bYpow2)) { + long i; + + i=0; + while((1< copy the image + if (srcReal && dstReal) tmpReal->Copy(*srcReal,true,false,false); + if (srcImag && dstImag) tmpImag->Copy(*srcImag,true,false,false); + + // dst&&src are empty -> create new one, else turn to GrayScale + if (srcReal==0 && dstReal==0){ + tmpReal = new CxImage(w,h,8); + tmpReal->Clear(0); + tmpReal->SetGrayPalette(); + } else { + if (!tmpReal->IsGrayScale()) tmpReal->GrayScale(); + } + if (srcImag==0 && dstImag==0){ + tmpImag = new CxImage(w,h,8); + tmpImag->Clear(0); + tmpImag->SetGrayPalette(); + } else { + if (!tmpImag->IsGrayScale()) tmpImag->GrayScale(); + } + + if (!(tmpReal->IsValid() && tmpImag->IsValid())){ + if (srcReal==0 && dstReal==0) delete tmpReal; + if (srcImag==0 && dstImag==0) delete tmpImag; + return false; + } + + //resample for FFT, if necessary + tmpReal->Resample(w,h,0); + tmpImag->Resample(w,h,0); + + //ok, here we have 2 (w x h), grayscale images ready for a FFT + + double* real; + double* imag; + long j,k,m; + + _complex **grid; + //double mean = tmpReal->Mean(); + /* Allocate memory for the grid */ + grid = (_complex **)malloc(w * sizeof(_complex)); + for (k=0;kGetPixelIndex(k,j)-128; + grid[k][j].y = tmpImag->GetPixelIndex(k,j)-128; + } + } + + //DFT buffers + double *real2,*imag2; + real2 = (double*)malloc(max(w,h) * sizeof(double)); + imag2 = (double*)malloc(max(w,h) * sizeof(double)); + + /* Transform the rows */ + real = (double *)malloc(w * sizeof(double)); + imag = (double *)malloc(w * sizeof(double)); + + m=0; + while((1<SetPixelIndex(k,j,(BYTE)max(0,min(255,(nn*(3+log(_cabs(grid[k][j]))))))); + if (grid[k][j].x==0){ + tmpImag->SetPixelIndex(k,j,(BYTE)max(0,min(255,(128+(atan(grid[k][j].y/0.0000000001)*nn))))); + } else { + tmpImag->SetPixelIndex(k,j,(BYTE)max(0,min(255,(128+(atan(grid[k][j].y/grid[k][j].x)*nn))))); + } + } else { + tmpReal->SetPixelIndex(k,j,(BYTE)max(0,min(255,(128 + grid[k][j].x*nn)))); + tmpImag->SetPixelIndex(k,j,(BYTE)max(0,min(255,(128 + grid[k][j].y*nn)))); + } + } + } + + for (k=0;k> 1; + j = 0; + for (i=0;i>= 1; + } + j += k; + } + + /* Compute the FFT */ + c1 = -1.0; + c2 = 0.0; + l2 = 1; + for (l=0;lGetWidth(); + long h = r->GetHeight(); + + Create(w,h,24); + + g->Resample(w,h); + b->Resample(w,h); + + if (a) { + a->Resample(w,h); +#if CXIMAGE_SUPPORT_ALPHA + AlphaCreate(); +#endif //CXIMAGE_SUPPORT_ALPHA + } + + RGBQUAD c; + for (long y=0;y + for (long x=0;xGetPixelIndex(x,y); + c.rgbGreen=g->GetPixelIndex(x,y); + c.rgbBlue=b->GetPixelIndex(x,y); + switch (colorspace){ + case 1: + SetPixelColor(x,y,HSLtoRGB(c)); + break; + case 2: + SetPixelColor(x,y,YUVtoRGB(c)); + break; + case 3: + SetPixelColor(x,y,YIQtoRGB(c)); + break; + case 4: + SetPixelColor(x,y,XYZtoRGB(c)); + break; + default: + SetPixelColor(x,y,c); + } +#if CXIMAGE_SUPPORT_ALPHA + if (a) AlphaSet(x,y,a->GetPixelIndex(x,y)); +#endif //CXIMAGE_SUPPORT_ALPHA + } + } + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Smart blurring to remove small defects, dithering or artifacts. + * \param radius: normally between 0.01 and 0.5 + * \param niterations: should be trimmed with radius, to avoid blurring should be (radius*niterations)<1 + * \param colorspace: 0 = RGB, 1 = HSL, 2 = YUV, 3 = YIQ, 4 = XYZ + * \return true if everything is ok + */ +bool CxImage::Repair(float radius, long niterations, long colorspace) +{ + if (!IsValid()) return false; + + long w = GetWidth(); + long h = GetHeight(); + + CxImage r,g,b; + + r.Create(w,h,8); + g.Create(w,h,8); + b.Create(w,h,8); + + switch (colorspace){ + case 1: + SplitHSL(&r,&g,&b); + break; + case 2: + SplitYUV(&r,&g,&b); + break; + case 3: + SplitYIQ(&r,&g,&b); + break; + case 4: + SplitXYZ(&r,&g,&b); + break; + default: + SplitRGB(&r,&g,&b); + } + + for (int i=0; iGetWidth()-1; + long h = ch->GetHeight()-1; + + double correction,ix,iy,ixx,ixy,iyy,den,num; + int x,y,xy0,xp1,xm1,yp1,ym1; + for(x=1; xGetPixelIndex(x,y); + xm1 = ch->GetPixelIndex(x-1,y); + xp1 = ch->GetPixelIndex(x+1,y); + ym1 = ch->GetPixelIndex(x,y-1); + yp1 = ch->GetPixelIndex(x,y+1); + + ix= (xp1-xm1)/2.0; + iy= (yp1-ym1)/2.0; + ixx= xp1 - 2.0 * xy0 + xm1; + iyy= yp1 - 2.0 * xy0 + ym1; + ixy=(ch->GetPixelIndex(x+1,y+1)+ch->GetPixelIndex(x-1,y-1)- + ch->GetPixelIndex(x-1,y+1)-ch->GetPixelIndex(x+1,y-1))/4.0; + + num= (1.0+iy*iy)*ixx - ix*iy*ixy + (1.0+ix*ix)*iyy; + den= 1.0+ix*ix+iy*iy; + correction = num/den; + + tmp.SetPixelIndex(x,y,(BYTE)min(255,max(0,(xy0 + radius * correction)))); + } + } + + for (x=0;x<=w;x++){ + tmp.SetPixelIndex(x,0,ch->GetPixelIndex(x,0)); + tmp.SetPixelIndex(x,h,ch->GetPixelIndex(x,h)); + } + for (y=0;y<=h;y++){ + tmp.SetPixelIndex(0,y,ch->GetPixelIndex(0,y)); + tmp.SetPixelIndex(w,y,ch->GetPixelIndex(w,y)); + } + ch->Transfer(tmp); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Enhance the variations between adjacent pixels. + * Similar results can be achieved using Filter(), + * but the algorithms are different both in Edge() and in Contour(). + * \return true if everything is ok + */ +bool CxImage::Contour() +{ + if (!pDib) return false; + + long Ksize = 3; + long k2 = Ksize/2; + long kmax= Ksize-k2; + long i,j,k; + BYTE maxr,maxg,maxb; + RGBQUAD pix1,pix2; + + CxImage tmp(*this,pSelection!=0,true,true); + if (!tmp.IsValid()) return false; + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + + for(long y=ymin; ymaxb) maxb = pix2.rgbBlue; + if ((pix2.rgbGreen-pix1.rgbGreen)>maxg) maxg = pix2.rgbGreen; + if ((pix2.rgbRed-pix1.rgbRed)>maxr) maxr = pix2.rgbRed; + } + } + pix1.rgbBlue=(BYTE)(255-maxb); + pix1.rgbGreen=(BYTE)(255-maxg); + pix1.rgbRed=(BYTE)(255-maxr); + tmp.SetPixelColor(x,y,pix1); + } + } + } + Transfer(tmp); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Adds a random offset to each pixel in the image + * \param radius: maximum pixel displacement + * \return true if everything is ok + */ +bool CxImage::Jitter(long radius) +{ + if (!pDib) return false; + + long nx,ny; + + CxImage tmp(*this,pSelection!=0,true,true); + if (!tmp.IsValid()) return false; + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + + for(long y=ymin; y y) + { + for (row = 0; row < y ; row++) + { + scale=0; + /* find the scale factor */ + for (j = 0; j < y ; j++) + { + /* if the index is in bounds, add it to the scale counter */ + if ((j + cmatrix_length/2 - row >= 0) && + (j + cmatrix_length/2 - row < cmatrix_length)) + scale += cmatrix[j + cmatrix_length/2 - row]; + } + for (i = 0; i= row - cmatrix_length/2) && + (j <= row + cmatrix_length/2)) + sum += cur_col[j*bytes + i] * cmatrix[j]; + } + dest_col[row*bytes + i] = (BYTE)(0.5f + sum / scale); + } + } + } + else + { + /* for the edge condition, we only use available info and scale to one */ + for (row = 0; row < cmatrix_middle; row++) + { + /* find scale factor */ + scale=0; + for (j = cmatrix_middle - row; j0; j--) + { + sum += *(ctable_p + *cur_col_p1); + cur_col_p1 += bytes; + ctable_p += 256; + } + cur_col_p++; + *(dest_col_p++) = (BYTE)(0.5f + sum); + } + } + + /* for the edge condition , we only use available info, and scale to one */ + for (; row < y; row++) + { + /* find scale factor */ + scale=0; + for (j = 0; j< y-row + cmatrix_middle; j++) + scale += cmatrix[j]; + for (i = 0; i 255) dest_row[u*3+v] = 255; + else dest_row[u*3+v] = value; + } + } + } + + Transfer(tmp); + + return TRUE; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Apply a look up table to the image. + * \param pLut: BYTE[256] look up table + * \return true if everything is ok + */ +bool CxImage::Lut(BYTE* pLut) +{ + if (!pDib || !pLut) return false; + RGBQUAD color; + + double dbScaler; + if (head.biClrUsed==0){ + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + // faster loop for full image + BYTE *iSrc=info.pImage; + for(unsigned long i=0; i < head.biSizeImage ; i++){ + *iSrc++ = pLut[*iSrc]; + } + return true; + } + + dbScaler = 100.0/ymax; + + for(long y=ymin; y + for(long x=xmin; x + if (!pDib) return false; + FloodFill2(x,y,GetPixelColor(x,y),FillColor); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImage::FloodFill2(int x, int y, RGBQUAD old_color, RGBQUAD new_color) +{ + // Fill in the actual pixels. + // Function steps recursively until it finds borders (color that is not old_color) + if (!IsInside(x,y)) return; + + RGBQUAD r = GetPixelColor(x,y); + COLORREF cr = RGB(r.rgbRed,r.rgbGreen,r.rgbBlue); + + if(cr == RGB(old_color.rgbRed,old_color.rgbGreen,old_color.rgbBlue) + && cr != RGB(new_color.rgbRed,new_color.rgbGreen,new_color.rgbBlue) ) { + + // the above if statement, after && is there to prevent + // stack overflows. The program will continue to find + // colors if you flood-fill an entire region (entire picture) + + SetPixelColor(x,y,new_color); + + FloodFill2((x+1),y,old_color,new_color); + FloodFill2((x-1),y,old_color,new_color); + FloodFill2(x,(y+1),old_color,new_color); + FloodFill2(x,(y-1),old_color,new_color); + } +}*/ +/////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_DSP diff --git a/SlnkDWFImpl/CxImage/CxImage/ximaenc.cpp b/SlnkDWFImpl/CxImage/CxImage/ximaenc.cpp new file mode 100644 index 0000000..277ee85 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximaenc.cpp @@ -0,0 +1,920 @@ +// xImaCodec.cpp : Encode Decode functions +/* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_JPG +#include "ximajpg.h" +#endif + +#if CXIMAGE_SUPPORT_GIF +#include "ximagif.h" +#endif + +#if CXIMAGE_SUPPORT_PNG +#include "ximapng.h" +#endif + +#if CXIMAGE_SUPPORT_MNG +#include "ximamng.h" +#endif + +#if CXIMAGE_SUPPORT_BMP +#include "ximabmp.h" +#endif + +#if CXIMAGE_SUPPORT_ICO +#include "ximaico.h" +#endif + +#if CXIMAGE_SUPPORT_TIF +#include "ximatif.h" +#endif + +#if CXIMAGE_SUPPORT_TGA +#include "ximatga.h" +#endif + +#if CXIMAGE_SUPPORT_PCX +#include "ximapcx.h" +#endif + +#if CXIMAGE_SUPPORT_WBMP +#include "ximawbmp.h" +#endif + +#if CXIMAGE_SUPPORT_WMF +#include "ximawmf.h" // - WMF/EMF support +#endif + +#if CXIMAGE_SUPPORT_J2K +#include "ximaj2k.h" +#endif + +#if CXIMAGE_SUPPORT_JBG +#include "ximajbg.h" +#endif + +#if CXIMAGE_SUPPORT_JASPER +#include "ximajas.h" +#endif + +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::EncodeSafeCheck(CxFile *hFile) +{ + if (hFile==NULL) { + strcpy(info.szLastError,CXIMAGE_ERR_NOFILE); + return true; + } + + if (pDib==NULL){ + strcpy(info.szLastError,CXIMAGE_ERR_NOIMAGE); + return true; + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +//#ifdef WIN32 +//bool CxImage::Save(LPCWSTR filename, DWORD imagetype) +//{ +// FILE* hFile; //file handle to write the image +// if ((hFile=_wfopen(filename,L"wb"))==NULL) return false; +// bool bOK = Encode(hFile,imagetype); +// fclose(hFile); +// return bOK; +//} +//#endif //WIN32 +//////////////////////////////////////////////////////////////////////////////// +// For UNICODE support: char -> TCHAR +/** + * Saves to disk the image in a specific format. + * \param filename: file name + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + * \return true if everything is ok + */ +bool CxImage::Save(const TCHAR * filename, DWORD imagetype) +{ + FILE* hFile; //file handle to write the image + +#ifdef WIN32 + if ((hFile=_tfopen(filename,_T("wb")))==NULL) return false; // For UNICODE support +#else + if ((hFile=fopen(filename,"wb"))==NULL) return false; +#endif + + bool bOK = Encode(hFile,imagetype); + fclose(hFile); + return bOK; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Saves to disk the image in a specific format. + * \param hFile: file handle, open and enabled for writing. + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + * \return true if everything is ok + */ +bool CxImage::Encode(FILE *hFile, DWORD imagetype) +{ + CxIOFile file(hFile); + return Encode(&file,imagetype); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Saves to memory buffer the image in a specific format. + * \param buffer: output memory buffer pointer. Must be NULL, + * the function allocates and fill the memory, + * the application must free the buffer, see also FreeMemory(). + * \param size: output memory buffer size. + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + * \return true if everything is ok + */ +bool CxImage::Encode(BYTE * &buffer, long &size, DWORD imagetype) +{ + if (buffer!=NULL){ + strcpy(info.szLastError,"the buffer must be empty"); + return false; + } + CxMemFile file; + file.Open(); + if(Encode(&file,imagetype)){ + buffer=file.GetBuffer(); + size=file.Size(); + return true; + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Saves to disk the image in a specific format. + * \param hFile: file handle (implemented using CxMemFile or CxIOFile), + * open and enabled for writing. + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + * \return true if everything is ok + * \sa ENUM_CXIMAGE_FORMATS + */ +bool CxImage::Encode(CxFile *hFile, DWORD imagetype) +{ + +#if CXIMAGE_SUPPORT_BMP + + if (imagetype==CXIMAGE_FORMAT_BMP){ + CxImageBMP newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_ICO + if (imagetype==CXIMAGE_FORMAT_ICO){ + CxImageICO newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_TIF + if (imagetype==CXIMAGE_FORMAT_TIF){ + CxImageTIF newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_JPG + if (imagetype==CXIMAGE_FORMAT_JPG){ + CxImageJPG newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_GIF + if (imagetype==CXIMAGE_FORMAT_GIF){ + CxImageGIF newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_PNG + if (imagetype==CXIMAGE_FORMAT_PNG){ + CxImagePNG newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_MNG + if (imagetype==CXIMAGE_FORMAT_MNG){ + CxImageMNG newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_TGA + if (imagetype==CXIMAGE_FORMAT_TGA){ + CxImageTGA newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_PCX + if (imagetype==CXIMAGE_FORMAT_PCX){ + CxImagePCX newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_WBMP + if (imagetype==CXIMAGE_FORMAT_WBMP){ + CxImageWBMP newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS // - WMF/EMF support + if (imagetype==CXIMAGE_FORMAT_WMF){ + CxImageWMF newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_J2K + if (imagetype==CXIMAGE_FORMAT_J2K){ + CxImageJ2K newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_JBG + if (imagetype==CXIMAGE_FORMAT_JBG){ + CxImageJBG newima; + newima.Ghost(this); + if (newima.Encode(hFile)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_JASPER + if ( + #if CXIMAGE_SUPPORT_JP2 + imagetype==CXIMAGE_FORMAT_JP2 || + #endif + #if CXIMAGE_SUPPORT_JPC + imagetype==CXIMAGE_FORMAT_JPC || + #endif + #if CXIMAGE_SUPPORT_PGX + imagetype==CXIMAGE_FORMAT_PGX || + #endif + #if CXIMAGE_SUPPORT_PNM + imagetype==CXIMAGE_FORMAT_PNM || + #endif + #if CXIMAGE_SUPPORT_RAS + imagetype==CXIMAGE_FORMAT_RAS || + #endif + false ){ + CxImageJAS newima; + newima.Ghost(this); + if (newima.Encode(hFile,imagetype)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif + + strcpy(info.szLastError,"Encode: Unknown format"); + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Saves to disk or memory pagecount images, referenced by an array of CxImage pointers. + * \param hFile: file handle. + * \param pImages: array of CxImage pointers. + * \param pagecount: number of images. + * \param imagetype: can be CXIMAGE_FORMAT_TIF or CXIMAGE_FORMAT_GIF. + * \return true if everything is ok + */ +bool CxImage::Encode(FILE * hFile, CxImage ** pImages, int pagecount, DWORD imagetype) +{ + CxIOFile file(hFile); + return Encode(&file, pImages, pagecount,imagetype); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Saves to disk or memory pagecount images, referenced by an array of CxImage pointers. + * \param hFile: file handle (implemented using CxMemFile or CxIOFile). + * \param pImages: array of CxImage pointers. + * \param pagecount: number of images. + * \param imagetype: can be CXIMAGE_FORMAT_TIF or CXIMAGE_FORMAT_GIF. + * \return true if everything is ok + */ +bool CxImage::Encode(CxFile * hFile, CxImage ** pImages, int pagecount, DWORD imagetype) +{ +#if CXIMAGE_SUPPORT_TIF + if (imagetype==CXIMAGE_FORMAT_TIF){ + CxImageTIF newima; + newima.Ghost(this); + if (newima.Encode(hFile,pImages,pagecount)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_GIF + if (imagetype==CXIMAGE_FORMAT_GIF){ + CxImageGIF newima; + newima.Ghost(this); + if (newima.Encode(hFile,pImages,pagecount)){ + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif + strcpy(info.szLastError,"Multipage Encode, Unsupported operation for this format"); + return false; +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * exports the image into a RGBA buffer, Useful for OpenGL applications. + * \param buffer: output memory buffer pointer. Must be NULL, + * the function allocates and fill the memory, + * the application must free the buffer, see also FreeMemory(). + * \param size: output memory buffer size. + * \return true if everything is ok + */ +bool CxImage::Encode2RGBA(BYTE * &buffer, long &size) +{ + if (buffer!=NULL){ + strcpy(info.szLastError,"the buffer must be empty"); + return false; + } + CxMemFile file; + file.Open(); + if(Encode2RGBA(&file)){ + buffer=file.GetBuffer(); + size=file.Size(); + return true; + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * exports the image into a RGBA buffer, Useful for OpenGL applications. + * \param hFile: file handle (implemented using CxMemFile or CxIOFile). + * \return true if everything is ok + */ +bool CxImage::Encode2RGBA(CxFile *hFile) +{ + if (EncodeSafeCheck(hFile)) return false; + + for (DWORD y = 0; yPutC(color.rgbRed); + hFile->PutC(color.rgbGreen); + hFile->PutC(color.rgbBlue); + hFile->PutC(color.rgbReserved); + } + } + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_DECODE +//////////////////////////////////////////////////////////////////////////////// +// For UNICODE support: char -> TCHAR +/** + * Reads from disk the image in a specific format. + * - If decoding fails using the specified image format, + * the function will try the automatic file format recognition. + * + * \param filename: file name + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + * \return true if everything is ok + */ +bool CxImage::Load(const TCHAR * filename, DWORD imagetype) +//bool CxImage::Load(const char * filename, DWORD imagetype) +{ + /*FILE* hFile; //file handle to read the image + if ((hFile=fopen(filename,"rb"))==NULL) return false; + bool bOK = Decode(hFile,imagetype); + fclose(hFile);*/ + + /* automatic file type recognition */ + bool bOK = false; + if ( imagetype > 0 && imagetype < CMAX_IMAGE_FORMATS ){ + FILE* hFile; //file handle to read the image + +#ifdef WIN32 + if ((hFile=_tfopen(filename,_T("rb")))==NULL) return false; // For UNICODE support +#else + if ((hFile=fopen(filename,"rb"))==NULL) return false; +#endif + + bOK = Decode(hFile,imagetype); + fclose(hFile); + if (bOK) return bOK; + } + + char szError[256]; + strcpy(szError,info.szLastError); //save the first error + + // if failed, try automatic recognition of the file... + FILE* hFile; + +#ifdef WIN32 + if ((hFile=_tfopen(filename,_T("rb")))==NULL) return false; // For UNICODE support +#else + if ((hFile=fopen(filename,"rb"))==NULL) return false; +#endif + + bOK = Decode(hFile,CXIMAGE_FORMAT_UNKNOWN); + fclose(hFile); + + if (!bOK && imagetype > 0) strcpy(info.szLastError,szError); //restore the first error + + return bOK; +} +//////////////////////////////////////////////////////////////////////////////// +#ifdef WIN32 +//bool CxImage::Load(LPCWSTR filename, DWORD imagetype) +//{ +// /*FILE* hFile; //file handle to read the image +// if ((hFile=_wfopen(filename, L"rb"))==NULL) return false; +// bool bOK = Decode(hFile,imagetype); +// fclose(hFile);*/ +// +// /* automatic file type recognition */ +// bool bOK = false; +// if ( imagetype > 0 && imagetype < CMAX_IMAGE_FORMATS ){ +// FILE* hFile; //file handle to read the image +// if ((hFile=_wfopen(filename,L"rb"))==NULL) return false; +// bOK = Decode(hFile,imagetype); +// fclose(hFile); +// if (bOK) return bOK; +// } +// +// char szError[256]; +// strcpy(szError,info.szLastError); //save the first error +// +// // if failed, try automatic recognition of the file... +// FILE* hFile; //file handle to read the image +// if ((hFile=_wfopen(filename,L"rb"))==NULL) return false; +// bOK = Decode(hFile,CXIMAGE_FORMAT_UNKNOWN); +// fclose(hFile); +// +// if (!bOK && imagetype > 0) strcpy(info.szLastError,szError); //restore the first error +// +// return bOK; +//} +//////////////////////////////////////////////////////////////////////////////// +/** + * Loads an image from the application resources. + * \param hRes: the resource handle returned by FindResource(). + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS. + * \param hModule: NULL for internal resource, or external application/DLL hinstance returned by LoadLibray. + * \return true if everything is ok + */ +bool CxImage::LoadResource(HRSRC hRes, DWORD imagetype, HMODULE hModule) +{ + DWORD rsize=SizeofResource(hModule,hRes); + HGLOBAL hMem=::LoadResource(hModule,hRes); + if (hMem){ + char* lpVoid=(char*)LockResource(hMem); + if (lpVoid){ + // FILE* fTmp=tmpfile(); doesn't work with network + /*char tmpPath[MAX_PATH] = {0}; + char tmpFile[MAX_PATH] = {0}; + GetTempPath(MAX_PATH,tmpPath); + GetTempFileName(tmpPath,"IMG",0,tmpFile); + FILE* fTmp=fopen(tmpFile,"w+b"); + if (fTmp){ + fwrite(lpVoid,rsize,1,fTmp); + fseek(fTmp,0,SEEK_SET); + bool bOK = Decode(fTmp,imagetype); + fclose(fTmp); + DeleteFile(tmpFile); + return bOK; + }*/ + + CxMemFile fTmp((BYTE*)lpVoid,rsize); + return Decode(&fTmp,imagetype); + } + } else strcpy(info.szLastError,"Unable to load resource!"); + return false; +} +#endif //WIN32 +//////////////////////////////////////////////////////////////////////////////// +/** + * Constructor from file name, see Load() + * \param filename: file name + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + */ +// +// > filename: file name +// > imagetype: specify the image format (CXIMAGE_FORMAT_BMP,...) +// For UNICODE support: char -> TCHAR +CxImage::CxImage(const TCHAR * filename, DWORD imagetype) +//CxImage::CxImage(const char * filename, DWORD imagetype) +{ + Startup(imagetype); + Load(filename,imagetype); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Constructor from file handle, see Decode() + * \param stream: file handle, with read access. + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + */ +CxImage::CxImage(FILE * stream, DWORD imagetype) +{ + Startup(imagetype); + Decode(stream,imagetype); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Constructor from CxFile object, see Decode() + * \param stream: file handle (implemented using CxMemFile or CxIOFile), with read access. + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + */ +CxImage::CxImage(CxFile * stream, DWORD imagetype) +{ + Startup(imagetype); + Decode(stream,imagetype); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Constructor from memory buffer, see Decode() + * \param buffer: memory buffer + * \param size: size of buffer + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + */ +CxImage::CxImage(BYTE * buffer, DWORD size, DWORD imagetype) +{ + Startup(imagetype); + CxMemFile stream(buffer,size); + Decode(&stream,imagetype); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Loads an image from memory buffer + * \param buffer: memory buffer + * \param size: size of buffer + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + * \return true if everything is ok + */ +bool CxImage::Decode(BYTE * buffer, DWORD size, DWORD imagetype) +{ + CxMemFile file(buffer,size); + return Decode(&file,imagetype); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Loads an image from file handle. + * \param hFile: file handle, with read access. + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + * \return true if everything is ok + */ +bool CxImage::Decode(FILE *hFile, DWORD imagetype) +{ + CxIOFile file(hFile); + return Decode(&file,imagetype); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Loads an image from CxFile object + * \param hFile: file handle (implemented using CxMemFile or CxIOFile), with read access. + * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS + * \return true if everything is ok + * \sa ENUM_CXIMAGE_FORMATS + */ +bool CxImage::Decode(CxFile *hFile, DWORD imagetype) +{ + + if (imagetype==CXIMAGE_FORMAT_UNKNOWN){ + DWORD pos = hFile->Tell(); +#if CXIMAGE_SUPPORT_BMP + { CxImageBMP newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_JPG + { CxImageJPG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_ICO + { CxImageICO newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_GIF + { CxImageGIF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_PNG + { CxImagePNG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_TIF + { CxImageTIF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_MNG + { CxImageMNG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_TGA + { CxImageTGA newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_PCX + { CxImagePCX newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_WBMP + { CxImageWBMP newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS + { CxImageWMF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_J2K + { CxImageJ2K newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_JBG + { CxImageJBG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif +#if CXIMAGE_SUPPORT_JASPER + { CxImageJAS newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } +#endif + } + +#if CXIMAGE_SUPPORT_BMP + if (imagetype==CXIMAGE_FORMAT_BMP){ + CxImageBMP newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_JPG + if (imagetype==CXIMAGE_FORMAT_JPG){ + CxImageJPG newima; + newima.CopyInfo(*this); // + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_ICO + if (imagetype==CXIMAGE_FORMAT_ICO){ + CxImageICO newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + info.nNumFrames = newima.info.nNumFrames; + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_GIF + if (imagetype==CXIMAGE_FORMAT_GIF){ + CxImageGIF newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + info.nNumFrames = newima.info.nNumFrames; + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_PNG + if (imagetype==CXIMAGE_FORMAT_PNG){ + CxImagePNG newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_TIF + if (imagetype==CXIMAGE_FORMAT_TIF){ + CxImageTIF newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + info.nNumFrames = newima.info.nNumFrames; + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_MNG + if (imagetype==CXIMAGE_FORMAT_MNG){ + CxImageMNG newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + info.nNumFrames = newima.info.nNumFrames; + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_TGA + if (imagetype==CXIMAGE_FORMAT_TGA){ + CxImageTGA newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_PCX + if (imagetype==CXIMAGE_FORMAT_PCX){ + CxImagePCX newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_WBMP + if (imagetype==CXIMAGE_FORMAT_WBMP){ + CxImageWBMP newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS // vho - WMF support + if (imagetype == CXIMAGE_FORMAT_WMF){ + CxImageWMF newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_J2K + if (imagetype==CXIMAGE_FORMAT_J2K){ + CxImageJ2K newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_JBG + if (imagetype==CXIMAGE_FORMAT_JBG){ + CxImageJBG newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif +#if CXIMAGE_SUPPORT_JASPER + if ( + #if CXIMAGE_SUPPORT_JP2 + imagetype==CXIMAGE_FORMAT_JP2 || + #endif + #if CXIMAGE_SUPPORT_JPC + imagetype==CXIMAGE_FORMAT_JPC || + #endif + #if CXIMAGE_SUPPORT_PGX + imagetype==CXIMAGE_FORMAT_PGX || + #endif + #if CXIMAGE_SUPPORT_PNM + imagetype==CXIMAGE_FORMAT_PNM || + #endif + #if CXIMAGE_SUPPORT_RAS + imagetype==CXIMAGE_FORMAT_RAS || + #endif + false ){ + CxImageJAS newima; + newima.CopyInfo(*this); + if (newima.Decode(hFile,imagetype)){ + Transfer(newima); + return true; + } else { + strcpy(info.szLastError,newima.GetLastError()); + return false; + } + } +#endif + + strcpy(info.szLastError,"Decode: Unknown or wrong format"); + return false; +} +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_DECODE +//////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/CxImage/ximaexif.cpp b/SlnkDWFImpl/CxImage/CxImage/ximaexif.cpp new file mode 100644 index 0000000..480252c --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximaexif.cpp @@ -0,0 +1,873 @@ +/* + * File: ximaexif.cpp + * Purpose: EXIF reader + * 18/Aug/2002 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + * based on jhead-1.8 by Matthias Wandel + */ + +#include "ximajpg.h" + +#if CXIMAGEJPG_SUPPORT_EXIF + +//////////////////////////////////////////////////////////////////////////////// +CxImageJPG::CxExifInfo::CxExifInfo(EXIFINFO* info) +{ + if (info) { + m_exifinfo = info; + freeinfo = false; + } else { + m_exifinfo = new EXIFINFO; + memset(m_exifinfo,0,sizeof(EXIFINFO)); + freeinfo = true; + } + + m_szLastError[0]='\0'; + ExifImageWidth = MotorolaOrder = 0; + SectionsRead=0; + memset(&Sections, 0, MAX_SECTIONS * sizeof(Section_t)); +} +//////////////////////////////////////////////////////////////////////////////// +CxImageJPG::CxExifInfo::~CxExifInfo() +{ + for(int i=0;iGetC(); + + if (a != 0xff || hFile->GetC() != M_SOI){ + return FALSE; + } + + for(;;){ + int itemlen; + int marker = 0; + int ll,lh, got; + BYTE * Data; + + if (SectionsRead >= MAX_SECTIONS){ + strcpy(m_szLastError,"Too many sections in jpg file"); + return false; + } + + for (a=0;a<7;a++){ + marker = hFile->GetC(); + if (marker != 0xff) break; + + if (a >= 6){ + printf("too many padding bytes\n"); + return false; + } + } + + if (marker == 0xff){ + // 0xff is legal padding, but if we get that many, something's wrong. + strcpy(m_szLastError,"too many padding bytes!"); + return false; + } + + Sections[SectionsRead].Type = marker; + + // Read the length of the section. + lh = hFile->GetC(); + ll = hFile->GetC(); + + itemlen = (lh << 8) | ll; + + if (itemlen < 2){ + strcpy(m_szLastError,"invalid marker"); + return false; + } + + Sections[SectionsRead].Size = itemlen; + + Data = (BYTE *)malloc(itemlen); + if (Data == NULL){ + strcpy(m_szLastError,"Could not allocate memory"); + return false; + } + Sections[SectionsRead].Data = Data; + + // Store first two pre-read bytes. + Data[0] = (BYTE)lh; + Data[1] = (BYTE)ll; + + got = hFile->Read(Data+2, 1, itemlen-2); // Read the whole section. + if (got != itemlen-2){ + strcpy(m_szLastError,"Premature end of file?"); + return false; + } + SectionsRead += 1; + + switch(marker){ + + case M_SOS: // stop before hitting compressed data + // If reading entire image is requested, read the rest of the data. + if (nReadMode & EXIF_READ_IMAGE){ + int cp, ep, size; + // Determine how much file is left. + cp = hFile->Tell(); + hFile->Seek(0, SEEK_END); + ep = hFile->Tell(); + hFile->Seek(cp, SEEK_SET); + + size = ep-cp; + Data = (BYTE *)malloc(size); + if (Data == NULL){ + strcpy(m_szLastError,"could not allocate data for entire image"); + return false; + } + + got = hFile->Read(Data, 1, size); + if (got != size){ + strcpy(m_szLastError,"could not read the rest of the image"); + return false; + } + + Sections[SectionsRead].Data = Data; + Sections[SectionsRead].Size = size; + Sections[SectionsRead].Type = PSEUDO_IMAGE_MARKER; + SectionsRead ++; + } + return true; + + case M_EOI: // in case it's a tables-only JPEG stream + printf("No image in jpeg!\n"); + return FALSE; + + case M_COM: // Comment section + if (HaveCom || ((nReadMode & EXIF_READ_EXIF) == 0)){ + // Discard this section. + free(Sections[--SectionsRead].Data); + Sections[SectionsRead].Data=0; + }else{ + process_COM(Data, itemlen); + HaveCom = TRUE; + } + break; + + case M_JFIF: + // Regular jpegs always have this tag, exif images have the exif + // marker instead, althogh ACDsee will write images with both markers. + // this program will re-create this marker on absence of exif marker. + // hence no need to keep the copy from the file. + free(Sections[--SectionsRead].Data); + Sections[SectionsRead].Data=0; + break; + + case M_EXIF: + // Seen files from some 'U-lead' software with Vivitar scanner + // that uses marker 31 for non exif stuff. Thus make sure + // it says 'Exif' in the section before treating it as exif. + if ((nReadMode & EXIF_READ_EXIF) && memcmp(Data+2, "Exif", 4) == 0){ + m_exifinfo->IsExif = process_EXIF((BYTE *)Data+2, itemlen); + }else{ + // Discard this section. + free(Sections[--SectionsRead].Data); + Sections[SectionsRead].Data=0; + } + break; + + case M_SOF0: + case M_SOF1: + case M_SOF2: + case M_SOF3: + case M_SOF5: + case M_SOF6: + case M_SOF7: + case M_SOF9: + case M_SOF10: + case M_SOF11: + case M_SOF13: + case M_SOF14: + case M_SOF15: + process_SOFn(Data, marker); + break; + default: + // Skip any other sections. + //if (ShowTags) printf("Jpeg section marker 0x%02x size %d\n",marker, itemlen); + break; + } + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/*-------------------------------------------------------------------------- + Process a EXIF marker + Describes all the drivel that most digital cameras include... +--------------------------------------------------------------------------*/ +bool CxImageJPG::CxExifInfo::process_EXIF(unsigned char * CharBuf, unsigned int length) +{ + m_exifinfo->FlashUsed = 0; + /* If it's from a digicam, and it used flash, it says so. */ + m_exifinfo->Comments[0] = '\0'; /* Initial value - null string */ + + ExifImageWidth = 0; + + { /* Check the EXIF header component */ + static const unsigned char ExifHeader[] = "Exif\0\0"; + if (memcmp(CharBuf+0, ExifHeader,6)){ + strcpy(m_szLastError,"Incorrect Exif header"); + return false; + } + } + + if (memcmp(CharBuf+6,"II",2) == 0){ + MotorolaOrder = 0; + }else{ + if (memcmp(CharBuf+6,"MM",2) == 0){ + MotorolaOrder = 1; + }else{ + strcpy(m_szLastError,"Invalid Exif alignment marker."); + return false; + } + } + + /* Check the next two values for correctness. */ + if (Get16u(CharBuf+8) != 0x2a){ + strcpy(m_szLastError,"Invalid Exif start (1)"); + return false; + } + + int FirstOffset = Get32u(CharBuf+10); + /* + if (FirstOffset < 8 || FirstOffset > 16){ + // I used to ensure this was set to 8 (website I used indicated its 8) + // but PENTAX Optio 230 has it set differently, and uses it as offset. (Sept 11 2002) + strcpy(m_szLastError,"Suspicious offset of first IFD value"); + return false; + }*/ + + unsigned char * LastExifRefd = CharBuf; + + /* First directory starts 16 bytes in. Offsets start at 8 bytes in. */ + if (!ProcessExifDir(CharBuf+14, CharBuf+6, length-6, m_exifinfo, &LastExifRefd)) + return false; + + /* give a chance for a second directory */ + if (FirstOffset > 8) { + if (!ProcessExifDir(CharBuf+14+FirstOffset-8, CharBuf+6, length-6, m_exifinfo, &LastExifRefd)) + return false; + } + + /* This is how far the interesting (non thumbnail) part of the exif went. */ + // int ExifSettingsLength = LastExifRefd - CharBuf; + + /* Compute the CCD width, in milimeters. */ + if (m_exifinfo->FocalplaneXRes != 0){ + m_exifinfo->CCDWidth = (float)(ExifImageWidth * m_exifinfo->FocalplaneUnits / m_exifinfo->FocalplaneXRes); + } + + return true; +} +//-------------------------------------------------------------------------- +// Get 16 bits motorola order (always) for jpeg header stuff. +//-------------------------------------------------------------------------- +int CxImageJPG::CxExifInfo::Get16m(void * Short) +{ + return (((unsigned char *)Short)[0] << 8) | ((unsigned char *)Short)[1]; +} +//////////////////////////////////////////////////////////////////////////////// +/*-------------------------------------------------------------------------- + Convert a 16 bit unsigned value from file's native byte order +--------------------------------------------------------------------------*/ +int CxImageJPG::CxExifInfo::Get16u(void * Short) +{ + if (MotorolaOrder){ + return (((unsigned char *)Short)[0] << 8) | ((unsigned char *)Short)[1]; + }else{ + return (((unsigned char *)Short)[1] << 8) | ((unsigned char *)Short)[0]; + } +} +//////////////////////////////////////////////////////////////////////////////// +/*-------------------------------------------------------------------------- + Convert a 32 bit signed value from file's native byte order +--------------------------------------------------------------------------*/ +long CxImageJPG::CxExifInfo::Get32s(void * Long) +{ + if (MotorolaOrder){ + return ((( char *)Long)[0] << 24) | (((unsigned char *)Long)[1] << 16) + | (((unsigned char *)Long)[2] << 8 ) | (((unsigned char *)Long)[3] << 0 ); + }else{ + return ((( char *)Long)[3] << 24) | (((unsigned char *)Long)[2] << 16) + | (((unsigned char *)Long)[1] << 8 ) | (((unsigned char *)Long)[0] << 0 ); + } +} +//////////////////////////////////////////////////////////////////////////////// +/*-------------------------------------------------------------------------- + Convert a 32 bit unsigned value from file's native byte order +--------------------------------------------------------------------------*/ +unsigned long CxImageJPG::CxExifInfo::Get32u(void * Long) +{ + return (unsigned long)Get32s(Long) & 0xffffffff; +} +//////////////////////////////////////////////////////////////////////////////// + +/* Describes format descriptor */ +static const int BytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8}; +#define NUM_FORMATS 12 + +#define FMT_BYTE 1 +#define FMT_STRING 2 +#define FMT_USHORT 3 +#define FMT_ULONG 4 +#define FMT_URATIONAL 5 +#define FMT_SBYTE 6 +#define FMT_UNDEFINED 7 +#define FMT_SSHORT 8 +#define FMT_SLONG 9 +#define FMT_SRATIONAL 10 +#define FMT_SINGLE 11 +#define FMT_DOUBLE 12 + +/* Describes tag values */ + +#define TAG_EXIF_VERSION 0x9000 +#define TAG_EXIF_OFFSET 0x8769 +#define TAG_INTEROP_OFFSET 0xa005 + +#define TAG_MAKE 0x010F +#define TAG_MODEL 0x0110 + +#define TAG_ORIENTATION 0x0112 +#define TAG_XRESOLUTION 0x011A +#define TAG_YRESOLUTION 0x011B +#define TAG_RESOLUTIONUNIT 0x0128 + +#define TAG_EXPOSURETIME 0x829A +#define TAG_FNUMBER 0x829D + +#define TAG_SHUTTERSPEED 0x9201 +#define TAG_APERTURE 0x9202 +#define TAG_BRIGHTNESS 0x9203 +#define TAG_MAXAPERTURE 0x9205 +#define TAG_FOCALLENGTH 0x920A + +#define TAG_DATETIME_ORIGINAL 0x9003 +#define TAG_USERCOMMENT 0x9286 + +#define TAG_SUBJECT_DISTANCE 0x9206 +#define TAG_FLASH 0x9209 + +#define TAG_FOCALPLANEXRES 0xa20E +#define TAG_FOCALPLANEYRES 0xa20F +#define TAG_FOCALPLANEUNITS 0xa210 +#define TAG_EXIF_IMAGEWIDTH 0xA002 +#define TAG_EXIF_IMAGELENGTH 0xA003 + +/* the following is added 05-jan-2001 vcs */ +#define TAG_EXPOSURE_BIAS 0x9204 +#define TAG_WHITEBALANCE 0x9208 +#define TAG_METERING_MODE 0x9207 +#define TAG_EXPOSURE_PROGRAM 0x8822 +#define TAG_ISO_EQUIVALENT 0x8827 +#define TAG_COMPRESSION_LEVEL 0x9102 + +#define TAG_THUMBNAIL_OFFSET 0x0201 +#define TAG_THUMBNAIL_LENGTH 0x0202 + + +/*-------------------------------------------------------------------------- + Process one of the nested EXIF directories. +--------------------------------------------------------------------------*/ +bool CxImageJPG::CxExifInfo::ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength, + EXIFINFO * const m_exifinfo, unsigned char ** const LastExifRefdP ) +{ + int de; + int a; + int NumDirEntries; + unsigned ThumbnailOffset = 0; + unsigned ThumbnailSize = 0; + + NumDirEntries = Get16u(DirStart); + + if ((DirStart+2+NumDirEntries*12) > (OffsetBase+ExifLength)){ + strcpy(m_szLastError,"Illegally sized directory"); + return false; + } + + for (de=0;de= NUM_FORMATS) { + /* (-1) catches illegal zero case as unsigned underflows to positive large */ + strcpy(m_szLastError,"Illegal format code in EXIF dir"); + return false; + } + + ByteCount = Components * BytesPerFormat[Format]; + + if (ByteCount > 4){ + unsigned OffsetVal; + OffsetVal = Get32u(DirEntry+8); + /* If its bigger than 4 bytes, the dir entry contains an offset.*/ + if (OffsetVal+ByteCount > ExifLength){ + /* Bogus pointer offset and / or bytecount value */ + strcpy(m_szLastError,"Illegal pointer offset value in EXIF."); + return false; + } + ValuePtr = OffsetBase+OffsetVal; + }else{ + /* 4 bytes or less and value is in the dir entry itself */ + ValuePtr = DirEntry+8; + } + + if (*LastExifRefdP < ValuePtr+ByteCount){ + /* Keep track of last byte in the exif header that was + actually referenced. That way, we know where the + discardable thumbnail data begins. + */ + *LastExifRefdP = ValuePtr+ByteCount; + } + + /* Extract useful components of tag */ + switch(Tag){ + + case TAG_MAKE: + strncpy(m_exifinfo->CameraMake, (char*)ValuePtr, 31); + break; + + case TAG_MODEL: + strncpy(m_exifinfo->CameraModel, (char*)ValuePtr, 39); + break; + + case TAG_EXIF_VERSION: + strncpy(m_exifinfo->Version,(char*)ValuePtr, 4); + break; + + case TAG_DATETIME_ORIGINAL: + strncpy(m_exifinfo->DateTime, (char*)ValuePtr, 19); + break; + + case TAG_USERCOMMENT: + // Olympus has this padded with trailing spaces. Remove these first. + for (a=ByteCount;;){ + a--; + if (((char*)ValuePtr)[a] == ' '){ + ((char*)ValuePtr)[a] = '\0'; + }else{ + break; + } + if (a == 0) break; + } + + /* Copy the comment */ + if (memcmp(ValuePtr, "ASCII",5) == 0){ + for (a=5;a<10;a++){ + char c; + c = ((char*)ValuePtr)[a]; + if (c != '\0' && c != ' '){ + strncpy(m_exifinfo->Comments, (char*)ValuePtr+a, 199); + break; + } + } + + }else{ + strncpy(m_exifinfo->Comments, (char*)ValuePtr, 199); + } + break; + + case TAG_FNUMBER: + /* Simplest way of expressing aperture, so I trust it the most. + (overwrite previously computd value if there is one) + */ + m_exifinfo->ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_APERTURE: + case TAG_MAXAPERTURE: + /* More relevant info always comes earlier, so only + use this field if we don't have appropriate aperture + information yet. + */ + if (m_exifinfo->ApertureFNumber == 0){ + m_exifinfo->ApertureFNumber = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2.0f)*0.5); + } + break; + + case TAG_BRIGHTNESS: + m_exifinfo->Brightness = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_FOCALLENGTH: + /* Nice digital cameras actually save the focal length + as a function of how farthey are zoomed in. + */ + + m_exifinfo->FocalLength = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_SUBJECT_DISTANCE: + /* Inidcates the distacne the autofocus camera is focused to. + Tends to be less accurate as distance increases. + */ + m_exifinfo->Distance = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_EXPOSURETIME: + /* Simplest way of expressing exposure time, so I + trust it most. (overwrite previously computd value + if there is one) + */ + m_exifinfo->ExposureTime = + (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_SHUTTERSPEED: + /* More complicated way of expressing exposure time, + so only use this value if we don't already have it + from somewhere else. + */ + if (m_exifinfo->ExposureTime == 0){ + m_exifinfo->ExposureTime = (float) + (1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2.0f))); + } + break; + + case TAG_FLASH: + if ((int)ConvertAnyFormat(ValuePtr, Format) & 7){ + m_exifinfo->FlashUsed = 1; + }else{ + m_exifinfo->FlashUsed = 0; + } + break; + + case TAG_ORIENTATION: + m_exifinfo->Orientation = (int)ConvertAnyFormat(ValuePtr, Format); + if (m_exifinfo->Orientation < 1 || m_exifinfo->Orientation > 8){ + strcpy(m_szLastError,"Undefined rotation value"); + m_exifinfo->Orientation = 0; + } + break; + + case TAG_EXIF_IMAGELENGTH: + case TAG_EXIF_IMAGEWIDTH: + /* Use largest of height and width to deal with images + that have been rotated to portrait format. + */ + a = (int)ConvertAnyFormat(ValuePtr, Format); + if (ExifImageWidth < a) ExifImageWidth = a; + break; + + case TAG_FOCALPLANEXRES: + m_exifinfo->FocalplaneXRes = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_FOCALPLANEYRES: + m_exifinfo->FocalplaneYRes = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_RESOLUTIONUNIT: + switch((int)ConvertAnyFormat(ValuePtr, Format)){ + case 1: m_exifinfo->ResolutionUnit = 1.0f; break; /* 1 inch */ + case 2: m_exifinfo->ResolutionUnit = 1.0f; break; + case 3: m_exifinfo->ResolutionUnit = 0.3937007874f; break; /* 1 centimeter*/ + case 4: m_exifinfo->ResolutionUnit = 0.03937007874f; break; /* 1 millimeter*/ + case 5: m_exifinfo->ResolutionUnit = 0.00003937007874f; /* 1 micrometer*/ + } + break; + + case TAG_FOCALPLANEUNITS: + switch((int)ConvertAnyFormat(ValuePtr, Format)){ + case 1: m_exifinfo->FocalplaneUnits = 1.0f; break; /* 1 inch */ + case 2: m_exifinfo->FocalplaneUnits = 1.0f; break; + case 3: m_exifinfo->FocalplaneUnits = 0.3937007874f; break; /* 1 centimeter*/ + case 4: m_exifinfo->FocalplaneUnits = 0.03937007874f; break; /* 1 millimeter*/ + case 5: m_exifinfo->FocalplaneUnits = 0.00003937007874f; /* 1 micrometer*/ + } + break; + + // Remaining cases contributed by: Volker C. Schoech + + case TAG_EXPOSURE_BIAS: + m_exifinfo->ExposureBias = (float) ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_WHITEBALANCE: + m_exifinfo->Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_METERING_MODE: + m_exifinfo->MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_EXPOSURE_PROGRAM: + m_exifinfo->ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_ISO_EQUIVALENT: + m_exifinfo->ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format); + if ( m_exifinfo->ISOequivalent < 50 ) m_exifinfo->ISOequivalent *= 200; + break; + + case TAG_COMPRESSION_LEVEL: + m_exifinfo->CompressionLevel = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_XRESOLUTION: + m_exifinfo->Xresolution = (float)ConvertAnyFormat(ValuePtr, Format); + break; + case TAG_YRESOLUTION: + m_exifinfo->Yresolution = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_THUMBNAIL_OFFSET: + ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_THUMBNAIL_LENGTH: + ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format); + break; + + } + + if (Tag == TAG_EXIF_OFFSET || Tag == TAG_INTEROP_OFFSET){ + unsigned char * SubdirStart; + unsigned Offset = Get32u(ValuePtr); + if (Offset>8){ + SubdirStart = OffsetBase + Offset; + if (SubdirStart < OffsetBase || + SubdirStart > OffsetBase+ExifLength){ + strcpy(m_szLastError,"Illegal subdirectory link"); + return false; + } + ProcessExifDir(SubdirStart, OffsetBase, ExifLength, m_exifinfo, LastExifRefdP); + } + continue; + } + } + + + { + /* In addition to linking to subdirectories via exif tags, + there's also a potential link to another directory at the end + of each directory. This has got to be the result of a + committee! + */ + unsigned char * SubdirStart; + unsigned Offset; + Offset = Get16u(DirStart+2+12*NumDirEntries); + if (Offset){ + SubdirStart = OffsetBase + Offset; + if (SubdirStart < OffsetBase + || SubdirStart > OffsetBase+ExifLength){ + strcpy(m_szLastError,"Illegal subdirectory link"); + return false; + } + ProcessExifDir(SubdirStart, OffsetBase, ExifLength, m_exifinfo, LastExifRefdP); + } + } + + + if (ThumbnailSize && ThumbnailOffset){ + if (ThumbnailSize + ThumbnailOffset <= ExifLength){ + /* The thumbnail pointer appears to be valid. Store it. */ + m_exifinfo->ThumbnailPointer = OffsetBase + ThumbnailOffset; + m_exifinfo->ThumbnailSize = ThumbnailSize; + } + } + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/*-------------------------------------------------------------------------- + Evaluate number, be it int, rational, or float from directory. +--------------------------------------------------------------------------*/ +double CxImageJPG::CxExifInfo::ConvertAnyFormat(void * ValuePtr, int Format) +{ + double Value; + Value = 0; + + switch(Format){ + case FMT_SBYTE: Value = *(signed char *)ValuePtr; break; + case FMT_BYTE: Value = *(unsigned char *)ValuePtr; break; + + case FMT_USHORT: Value = Get16u(ValuePtr); break; + case FMT_ULONG: Value = Get32u(ValuePtr); break; + + case FMT_URATIONAL: + case FMT_SRATIONAL: + { + int Num,Den; + Num = Get32s(ValuePtr); + Den = Get32s(4+(char *)ValuePtr); + if (Den == 0){ + Value = 0; + }else{ + Value = (double)Num/Den; + } + break; + } + + case FMT_SSHORT: Value = (signed short)Get16u(ValuePtr); break; + case FMT_SLONG: Value = Get32s(ValuePtr); break; + + /* Not sure if this is correct (never seen float used in Exif format) + */ + case FMT_SINGLE: Value = (double)*(float *)ValuePtr; break; + case FMT_DOUBLE: Value = *(double *)ValuePtr; break; + } + return Value; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageJPG::CxExifInfo::process_COM (const BYTE * Data, int length) +{ + int ch; + char Comment[MAX_COMMENT+1]; + int nch; + int a; + + nch = 0; + + if (length > MAX_COMMENT) length = MAX_COMMENT; // Truncate if it won't fit in our structure. + + for (a=2;aComments,Comment); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageJPG::CxExifInfo::process_SOFn (const BYTE * Data, int marker) +{ + int data_precision, num_components; + + data_precision = Data[2]; + m_exifinfo->Height = Get16m((void*)(Data+3)); + m_exifinfo->Width = Get16m((void*)(Data+5)); + num_components = Data[7]; + + if (num_components == 3){ + m_exifinfo->IsColor = 1; + }else{ + m_exifinfo->IsColor = 0; + } + + m_exifinfo->Process = marker; + + //if (ShowTags) printf("JPEG image is %uw * %uh, %d color components, %d bits per sample\n", + // ImageInfo.Width, ImageInfo.Height, num_components, data_precision); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * this will work only on a CxImageJPG object, if the image originally has valid EXIF data + \verbatim + CxImageJPG jpg; + CxIOFile in,out; + in.Open("D:\\exif_in.jpg","rb"); + out.Open("D:\\exif_out.jpg","w+b"); + jpg.Decode(&in); + if (jpg.IsValid()){ + jpg.RotateLeft(); + jpg.Encode(&out); + } + \endverbatim +*/ +bool CxImageJPG::CxExifInfo::EncodeExif(CxFile * hFile) +{ + int a; + + if (FindSection(M_SOS)==NULL){ + strcpy(m_szLastError,"Can't write exif : didn't read all"); + return false; + } + + // Initial static jpeg marker. + hFile->PutC(0xff); + hFile->PutC(0xd8); + + if (Sections[0].Type != M_EXIF && Sections[0].Type != M_JFIF){ + // The image must start with an exif or jfif marker. If we threw those away, create one. + static BYTE JfifHead[18] = { + 0xff, M_JFIF, + 0x00, 0x10, 'J' , 'F' , 'I' , 'F' , 0x00, 0x01, + 0x01, 0x01, 0x01, 0x2C, 0x01, 0x2C, 0x00, 0x00 + }; + hFile->Write(JfifHead, 18, 1); + } + + // Write all the misc sections + for (a=0;aPutC(0xff); + hFile->PutC(Sections[a].Type); + hFile->Write(Sections[a].Data, Sections[a].Size, 1); + } + + // Write the remaining image data. + hFile->Write(Sections[a].Data, Sections[a].Size, 1); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageJPG::CxExifInfo::DiscardAllButExif() +{ + Section_t ExifKeeper; + Section_t CommentKeeper; + int a; + + memset(&ExifKeeper, 0, sizeof(ExifKeeper)); + memset(&CommentKeeper, 0, sizeof(ExifKeeper)); + + for (a=0;a Use it before Create() + */ +void CxImage::CopyInfo(const CxImage &src) +{ + if (pDib==NULL) memcpy(&info,&src.info,sizeof(CXIMAGEINFO)); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \sa Copy + */ +CxImage& CxImage::operator = (const CxImage& isrc) +{ + if (this != &isrc) Copy(isrc); + return *this; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Initializes or rebuilds the image. + * \param dwWidth: width + * \param dwHeight: height + * \param wBpp: bit per pixel, can be 1, 4, 8, 24 + * \param imagetype: (optional) set the image format, see ENUM_CXIMAGE_FORMATS + * \return pointer to the internal pDib object; NULL if an error occurs. + */ +void* CxImage::Create(DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype) +{ + // destroy the existing image (if any) + if (!Destroy()) + return NULL; + + // prevent further actions if width or height are not vaild + if ((dwWidth == 0) || (dwHeight == 0)){ + strcpy(info.szLastError,"CxImage::Create : width and height must be greater than zero"); + return NULL; + } + + // Make sure bits per pixel is valid + if (wBpp <= 1) wBpp = 1; + else if (wBpp <= 4) wBpp = 4; + else if (wBpp <= 8) wBpp = 8; + else wBpp = 24; + + // limit memory requirements (and also a check for bad parameters) + if (((dwWidth*dwHeight*wBpp)>>8) > CXIMAGE_MAX_MEMORY){ + strcpy(info.szLastError,"CXIMAGE_MAX_MEMORY exceeded"); + return NULL; + } + + // set the correct bpp value + switch (wBpp){ + case 1: + head.biClrUsed = 2; break; + case 4: + head.biClrUsed = 16; break; + case 8: + head.biClrUsed = 256; break; + default: + head.biClrUsed = 0; + } + + //set the common image informations + info.dwEffWidth = ((((wBpp * dwWidth) + 31) / 32) * 4); + info.dwType = imagetype; + + // initialize BITMAPINFOHEADER + head.biSize = sizeof(BITMAPINFOHEADER); // + head.biWidth = dwWidth; // fill in width from parameter + head.biHeight = dwHeight; // fill in height from parameter + head.biPlanes = 1; // must be 1 + head.biBitCount = (WORD)wBpp; // from parameter + head.biCompression = BI_RGB; + head.biSizeImage = info.dwEffWidth * dwHeight; +// head.biXPelsPerMeter = 0; See SetXDPI +// head.biYPelsPerMeter = 0; See SetYDPI + head.biClrImportant = 0; + + pDib = malloc(GetSize()); // alloc memory block to store our bitmap + if (!pDib){ + strcpy(info.szLastError,"CxImage::Create can't allocate memory"); + return NULL; + } + + //clear the palette + RGBQUAD* pal=GetPalette(); + if (pal) memset(pal,0,GetPaletteSize()); + //Destroy the existing selection +#if CXIMAGE_SUPPORT_SELECTION + if (pSelection) SelectionDelete(); +#endif //CXIMAGE_SUPPORT_SELECTION + //Destroy the existing alpha channel +#if CXIMAGE_SUPPORT_ALPHA + if (pAlpha) AlphaDelete(); +#endif //CXIMAGE_SUPPORT_ALPHA + + // use our bitmap info structure to fill in first part of + // our DIB with the BITMAPINFOHEADER + BITMAPINFOHEADER* lpbi; + lpbi = (BITMAPINFOHEADER*)(pDib); + *lpbi = head; + + info.pImage=GetBits(); + + return pDib; //return handle to the DIB +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \return pointer to the image pixels. USE CAREFULLY + */ +BYTE* CxImage::GetBits(DWORD row) +{ + if (pDib){ + if (row) { + if (row<(DWORD)head.biHeight){ + return ((BYTE*)pDib + *(DWORD*)pDib + GetPaletteSize() + (info.dwEffWidth * row)); + } else { + return NULL; + } + } else { + return ((BYTE*)pDib + *(DWORD*)pDib + GetPaletteSize()); + } + } + return NULL; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \return the size in bytes of the internal pDib object + */ +long CxImage::GetSize() +{ + return head.biSize + head.biSizeImage + GetPaletteSize(); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Checks if the coordinates are inside the image + * \return true if x and y are both inside the image + */ +bool CxImage::IsInside(long x, long y) +{ + return (0<=y && y 0) bval = 255; + } + if (GetBpp() == 4){ + bval = (BYTE)(17*(0x0F & bval)); + } + + memset(info.pImage,bval,head.biSizeImage); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Transfers the image from an existing source image. The source becomes empty. + * \return true if everything is ok + */ +bool CxImage::Transfer(CxImage &from) +{ + if (!Destroy()) + return false; + + memcpy(&head,&from.head,sizeof(BITMAPINFOHEADER)); + memcpy(&info,&from.info,sizeof(CXIMAGEINFO)); + + pDib = from.pDib; + pSelection = from.pSelection; + pAlpha = from.pAlpha; + pLayers = from.pLayers; + + memset(&from.head,0,sizeof(BITMAPINFOHEADER)); + memset(&from.info,0,sizeof(CXIMAGEINFO)); + from.pDib = from.pSelection = from.pAlpha = NULL; + from.pLayers = NULL; + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * (this) points to the same pDib owned by (*from), the image remains in (*from) + * but (this) has the access to the pixels. Use carefully !!! + */ +void CxImage::Ghost(CxImage *from) +{ + if (from){ + memcpy(&head,&from->head,sizeof(BITMAPINFOHEADER)); + memcpy(&info,&from->info,sizeof(CXIMAGEINFO)); + pDib = from->pDib; + pSelection = from->pSelection; + pAlpha = from->pAlpha; + pLayers = from->pLayers; + info.pGhost=from; + } +} +//////////////////////////////////////////////////////////////////////////////// +/** + * turns a 16 or 32 bit bitfield image into a RGB image + */ +void CxImage::Bitfield2RGB(BYTE *src, WORD redmask, WORD greenmask, WORD bluemask, BYTE bpp) +{ + switch (bpp){ + case 16: + { + DWORD ns[3]={0,0,0}; + // compute the number of shift for each mask + for (int i=0;i<16;i++){ + if ((redmask>>i)&0x01) ns[0]++; + if ((greenmask>>i)&0x01) ns[1]++; + if ((bluemask>>i)&0x01) ns[2]++; + } + ns[1]+=ns[0]; ns[2]+=ns[1]; ns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8; + // dword aligned width for 16 bit image + long effwidth2=(((head.biWidth + 1) / 2) * 4); + WORD w; + long y2,y3,x2,x3; + BYTE *p=info.pImage; + // scan the buffer in reverse direction to avoid reallocations + for (long y=head.biHeight-1; y>=0; y--){ + y2=effwidth2*y; + y3=info.dwEffWidth*y; + for (long x=head.biWidth-1; x>=0; x--){ + x2 = 2*x+y2; + x3 = 3*x+y3; + w = (WORD)(src[x2]+256*src[1+x2]); + p[ x3]=(BYTE)((w & bluemask)<>ns[1]); + p[2+x3]=(BYTE)((w & redmask)>>ns[2]); + } + } + break; + } + case 32: + { + // dword aligned width for 32 bit image + long effwidth4 = head.biWidth * 4; + long y4,y3,x4,x3; + BYTE *p=info.pImage; + // scan the buffer in reverse direction to avoid reallocations + for (long y=head.biHeight-1; y>=0; y--){ + y4=effwidth4*y; + y3=info.dwEffWidth*y; + for (long x=head.biWidth-1; x>=0; x--){ + x4 = 4*x+y4; + x3 = 3*x+y3; + p[ x3]=src[ x4]; + p[1+x3]=src[1+x4]; + p[2+x3]=src[2+x4]; + } + } + } + + } + return; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Creates an image from a generic buffer + * \param pArray: source memory buffer + * \param dwWidth: image width + * \param dwHeight: image height + * \param dwBitsperpixel: can be 1,4,8,24,32 + * \param dwBytesperline: line alignment, in bytes, for a single row stored in pArray + * \param bFlipImage: tune this parameter if the image is upsidedown + * \return true if everything is ok + */ +bool CxImage::CreateFromArray(BYTE* pArray,DWORD dwWidth,DWORD dwHeight,DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage) +{ + if (pArray==NULL) return false; + if (!((dwBitsperpixel==1)||(dwBitsperpixel==4)||(dwBitsperpixel==8)|| + (dwBitsperpixel==24)||(dwBitsperpixel==32))) return false; + + if (!Create(dwWidth,dwHeight,dwBitsperpixel)) return false; + + if (dwBitsperpixel<24) SetGrayPalette(); + +#if CXIMAGE_SUPPORT_ALPHA + if (dwBitsperpixel==32) AlphaCreate(); +#endif //CXIMAGE_SUPPORT_ALPHA + + BYTE *dst,*src; + + for (DWORD y = 0; yrgbRed,c1->rgbGreen,c1->rgbBlue); + int g2 = (int)RGB2GRAY(c2->rgbRed,c2->rgbGreen,c2->rgbBlue); + + return (g1-g2); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * simply calls "if (memblock) free(memblock);". + * Useful when calling Encode for a memory buffer, + * from a DLL compiled with different memory management options. + * CxImage::FreeMemory will use the same memory environment used by Encode. + */ +void CxImage::FreeMemory(void* memblock) +{ + if (memblock) + free(memblock); +} +//////////////////////////////////////////////////////////////////////////////// +//EOF diff --git a/SlnkDWFImpl/CxImage/CxImage/ximage.h b/SlnkDWFImpl/CxImage/CxImage/ximage.h new file mode 100644 index 0000000..0ebadcf --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximage.h @@ -0,0 +1,648 @@ +/* + * File: ximage.h + * Purpose: General Purpose Image Class + */ +/* + -------------------------------------------------------------------------------- + + COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: + + CxImage version 5.99c 17/Oct/2004 + + CxImage : Copyright (C) 2001 - 2004, Davide Pizzolato + + Original CImage and CImageIterator implementation are: + Copyright (C) 1995, Alejandro Aguilar Sierra (asierra(at)servidor(dot)unam(dot)mx) + + Covered code is provided under this license on an "as is" basis, without warranty + of any kind, either expressed or implied, including, without limitation, warranties + that the covered code is free of defects, merchantable, fit for a particular purpose + or non-infringing. The entire risk as to the quality and performance of the covered + code is with you. Should any covered code prove defective in any respect, you (not + the initial developer or any other contributor) assume the cost of any necessary + servicing, repair or correction. This disclaimer of warranty constitutes an essential + part of this license. No use of any covered code is authorized hereunder except under + this disclaimer. + + Permission is hereby granted to use, copy, modify, and distribute this + source code, or portions hereof, for any purpose, including commercial applications, + freely and without fee, 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. + + -------------------------------------------------------------------------------- + + Other information: about CxImage, and the latest version, can be found at the + CxImage home page: http://www.xdp.it + + -------------------------------------------------------------------------------- + */ +#if !defined(__CXIMAGE_H) +#define __CXIMAGE_H + +#if _MSC_VER > 1000 +#pragma once +#endif + +///////////////////////////////////////////////////////////////////////////// +#include "xfile.h" +#include "xiofile.h" +#include "xmemfile.h" +#include "ximadef.h" // adjust some #define + +/* see "ximacfg.h" for CxImage configuration options */ + +///////////////////////////////////////////////////////////////////////////// +// CxImage formats enumerator +enum ENUM_CXIMAGE_FORMATS{ +CXIMAGE_FORMAT_UNKNOWN, +#if CXIMAGE_SUPPORT_BMP +CXIMAGE_FORMAT_BMP, +#endif +#if CXIMAGE_SUPPORT_GIF +CXIMAGE_FORMAT_GIF, +#endif +#if CXIMAGE_SUPPORT_JPG +CXIMAGE_FORMAT_JPG, +#endif +#if CXIMAGE_SUPPORT_PNG +CXIMAGE_FORMAT_PNG, +#endif +#if CXIMAGE_SUPPORT_MNG +CXIMAGE_FORMAT_MNG, +#endif +#if CXIMAGE_SUPPORT_ICO +CXIMAGE_FORMAT_ICO, +#endif +#if CXIMAGE_SUPPORT_TIF +CXIMAGE_FORMAT_TIF, +#endif +#if CXIMAGE_SUPPORT_TGA +CXIMAGE_FORMAT_TGA, +#endif +#if CXIMAGE_SUPPORT_PCX +CXIMAGE_FORMAT_PCX, +#endif +#if CXIMAGE_SUPPORT_WBMP +CXIMAGE_FORMAT_WBMP, +#endif +#if CXIMAGE_SUPPORT_WMF +CXIMAGE_FORMAT_WMF, +#endif +#if CXIMAGE_SUPPORT_J2K +CXIMAGE_FORMAT_J2K, +#endif +#if CXIMAGE_SUPPORT_JBG +CXIMAGE_FORMAT_JBG, +#endif +#if CXIMAGE_SUPPORT_JP2 +CXIMAGE_FORMAT_JP2, +#endif +#if CXIMAGE_SUPPORT_JPC +CXIMAGE_FORMAT_JPC, +#endif +#if CXIMAGE_SUPPORT_PGX +CXIMAGE_FORMAT_PGX, +#endif +#if CXIMAGE_SUPPORT_PNM +CXIMAGE_FORMAT_PNM, +#endif +#if CXIMAGE_SUPPORT_RAS +CXIMAGE_FORMAT_RAS, +#endif +CMAX_IMAGE_FORMATS +}; + +///////////////////////////////////////////////////////////////////////////// +// CxImage class +///////////////////////////////////////////////////////////////////////////// +class DLL_EXP CxImage +{ +//extensible information collector +typedef struct tagCxImageInfo { + DWORD dwEffWidth; ///< DWORD aligned scan line width + BYTE* pImage; ///< THE IMAGE BITS + CxImage* pGhost; ///< if this is a ghost, pGhost points to the body + CxImage* pParent; ///< if this is a layer, pParent points to the body + DWORD dwType; ///< original image format + char szLastError[256]; ///< debugging + long nProgress; ///< monitor + long nEscape; ///< escape + long nBkgndIndex; ///< used for GIF, PNG, MNG + RGBQUAD nBkgndColor; ///< used for RGB transparency + BYTE nQuality; ///< used for JPEG + BYTE nJpegScale; ///< used for JPEG [ignacio] + long nFrame; ///< used for TIF, GIF, MNG : actual frame + long nNumFrames; ///< used for TIF, GIF, MNG : total number of frames + DWORD dwFrameDelay; ///< used for GIF, MNG + long xDPI; ///< horizontal resolution + long yDPI; ///< vertical resolution + RECT rSelectionBox; ///< bounding rectangle + BYTE nAlphaMax; ///< max opacity (fade) + bool bAlphaPaletteEnabled; ///< true if alpha values in the palette are enabled. + bool bEnabled; ///< enables the painting functions + long xOffset; + long yOffset; + DWORD dwCodecOpt[CMAX_IMAGE_FORMATS]; ///< for GIF, TIF : 0=def.1=unc,2=fax3,3=fax4,4=pack,5=jpg + RGBQUAD last_c; ///< for GetNearestIndex optimization + BYTE last_c_index; + bool last_c_isvalid; + long nNumLayers; + DWORD dwFlags; ///< 0x??00000 = reserved, 0x00??0000 = blend mode, 0x0000???? = layer id - user flags + +} CXIMAGEINFO; + +public: + //public structures +struct rgb_color { BYTE r,g,b; }; + +#if CXIMAGE_SUPPORT_WINDOWS +// text placement data +// members must be initialized with the InitTextInfo(&this) function. +typedef struct tagCxTextInfo +{ + TCHAR text[4096]; ///< text (char -> TCHAR for UNICODE [Cesar M]) + LOGFONT lfont; ///< font and codepage data + COLORREF fcolor; ///< foreground color + long align; ///< DT_CENTER, DT_RIGHT, DT_LEFT aligment for multiline text + BYTE opaque; ///< text has background or hasn't. Default is true. + ///< data for background (ignored if .opaque==FALSE) + COLORREF bcolor; ///< background color + float b_opacity; ///< opacity value for background between 0.0-1.0 Default is 0. (opaque) + BYTE b_outline; ///< outline width for background (zero: no outline) + BYTE b_round; ///< rounding radius for background rectangle. % of the height, between 0-50. Default is 10. + ///< (backgr. always has a frame: width = 3 pixel + 10% of height by default.) +} CXTEXTINFO; +#endif + +public: +/** \addtogroup Constructors */ //@{ + CxImage(DWORD imagetype = 0); + CxImage(DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype = 0); + CxImage(const CxImage &src, bool copypixels = true, bool copyselection = true, bool copyalpha = true); + CxImage(const TCHAR * filename, DWORD imagetype); // For UNICODE support: char -> TCHAR + CxImage(FILE * stream, DWORD imagetype); + CxImage(CxFile * stream, DWORD imagetype); + CxImage(BYTE * buffer, DWORD size, DWORD imagetype); + virtual ~CxImage() { Destroy(); }; + CxImage& operator = (const CxImage&); +//@} + +/** \addtogroup Initialization */ //@{ + void* Create(DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype = 0); + bool Destroy(); + void Clear(BYTE bval=0); + void Copy(const CxImage &src, bool copypixels = true, bool copyselection = true, bool copyalpha = true); + bool Transfer(CxImage &from); + bool CreateFromArray(BYTE* pArray,DWORD dwWidth,DWORD dwHeight,DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage); + bool CreateFromMatrix(BYTE** ppMatrix,DWORD dwWidth,DWORD dwHeight,DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage); + void FreeMemory(void* memblock); +//@} + +/** \addtogroup Attributes */ //@{ + long GetSize(); + BYTE* GetBits(DWORD row = 0); + BYTE GetColorType(); + void* GetDIB() const; + DWORD GetHeight() const; + DWORD GetWidth() const; + DWORD GetEffWidth() const; + DWORD GetNumColors() const; + WORD GetBpp() const; + DWORD GetType() const; + const char* GetLastError(); + const TCHAR* GetVersion(); + const float GetVersionNumber(); + + DWORD GetFrameDelay() const; + void SetFrameDelay(DWORD d); + + void GetOffset(long *x,long *y); + void SetOffset(long x,long y); + + BYTE GetJpegQuality() const; + void SetJpegQuality(BYTE q); + + BYTE GetJpegScale() const; + void SetJpegScale(BYTE q); + + long GetXDPI() const; + long GetYDPI() const; + void SetXDPI(long dpi); + void SetYDPI(long dpi); + + DWORD GetClrImportant() const; + void SetClrImportant(DWORD ncolors = 0); + + long GetProgress() const; + long GetEscape() const; + void SetProgress(long p); + void SetEscape(long i); + + long GetTransIndex() const; + RGBQUAD GetTransColor(); + void SetTransIndex(long idx); + void SetTransColor(RGBQUAD rgb); + bool IsTransparent() const; + + DWORD GetCodecOption(DWORD imagetype = 0); + bool SetCodecOption(DWORD opt, DWORD imagetype = 0); + + DWORD GetFlags() const; + void SetFlags(DWORD flags, bool bLockReservedFlags = true); + + //void* GetUserData() const {return info.pUserData;} + //void SetUserData(void* pUserData) {info.pUserData = pUserData;} +//@} + +/** \addtogroup Palette + * These functions have no effects on RGB images and in this case the returned value is always 0. + * @{ */ + bool IsGrayScale(); + bool IsIndexed() const; + bool IsSamePalette(CxImage &img, bool bCheckAlpha = true); + DWORD GetPaletteSize(); + RGBQUAD* GetPalette() const; + RGBQUAD GetPaletteColor(BYTE idx); + bool GetPaletteColor(BYTE i, BYTE* r, BYTE* g, BYTE* b); + BYTE GetNearestIndex(RGBQUAD c); + void BlendPalette(COLORREF cr,long perc); + void SetGrayPalette(); + void SetPalette(DWORD n, BYTE *r, BYTE *g, BYTE *b); + void SetPalette(RGBQUAD* pPal,DWORD nColors=256); + void SetPalette(rgb_color *rgb,DWORD nColors=256); + void SetPaletteColor(BYTE idx, BYTE r, BYTE g, BYTE b, BYTE alpha=0); + void SetPaletteColor(BYTE idx, RGBQUAD c); + void SetPaletteColor(BYTE idx, COLORREF cr); + void SwapIndex(BYTE idx1, BYTE idx2); + void SetStdPalette(); +//@} + +/** \addtogroup Pixel */ //@{ + bool IsInside(long x, long y); + bool IsTransparent(long x,long y); + RGBQUAD GetPixelColor(long x,long y, bool bGetAlpha = true); + BYTE GetPixelIndex(long x,long y); + BYTE GetPixelGray(long x, long y); + void SetPixelColor(long x,long y,RGBQUAD c, bool bSetAlpha = false); + void SetPixelColor(long x,long y,COLORREF cr); + void SetPixelIndex(long x,long y,BYTE i); + void DrawLine(int StartX, int EndX, int StartY, int EndY, RGBQUAD color, bool bSetAlpha=false); + void DrawLine(int StartX, int EndX, int StartY, int EndY, COLORREF cr); + void BlendPixelColor(long x,long y,RGBQUAD c, float blend, bool bSetAlpha = false); +//@} + +protected: +/** \addtogroup Protected */ //@{ + BYTE BlindGetPixelIndex(const long x,const long y); + RGBQUAD BlindGetPixelColor(const long x,const long y); + void *BlindGetPixelPointer(const long x,const long y); +//@} + +public: + +#if CXIMAGE_SUPPORT_INTERPOLATION +/** \addtogroup Interpolation */ //@{ + //overflow methods: + enum OverflowMethod { + OM_COLOR=1, + OM_BACKGROUND=2, + OM_TRANSPARENT=3, + OM_WRAP=4, + OM_REPEAT=5, + OM_MIRROR=6 + }; + void OverflowCoordinates(float &x, float &y, OverflowMethod const ofMethod); + void OverflowCoordinates(long &x, long &y, OverflowMethod const ofMethod); + RGBQUAD GetPixelColorWithOverflow(long x, long y, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD* const rplColor=0); + //interpolation methods: + enum InterpolationMethod { + IM_NEAREST_NEIGHBOUR=1, + IM_BILINEAR =2, + IM_BSPLINE =3, + IM_BICUBIC =4, + IM_BICUBIC2 =5, + IM_LANCZOS =6, + IM_BOX =7, + IM_HERMITE =8, + IM_HAMMING =9, + IM_SINC =10, + IM_BLACKMAN =11, + IM_BESSEL =12, + IM_GAUSSIAN =13, + IM_QUADRATIC =14, + IM_MITCHELL =15, + IM_CATROM =16 + }; + RGBQUAD GetPixelColorInterpolated(float x,float y, InterpolationMethod const inMethod=IM_BILINEAR, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD* const rplColor=0); + RGBQUAD GetAreaColorInterpolated(float const xc, float const yc, float const w, float const h, InterpolationMethod const inMethod, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD* const rplColor=0); +//@} + +protected: +/** \addtogroup Protected */ //@{ + void AddAveragingCont(RGBQUAD const &color, float const surf, float &rr, float &gg, float &bb, float &aa); +//@} + +/** \addtogroup Kernels */ //@{ +public: + static float KernelBSpline(const float x); + static float KernelLinear(const float t); + static float KernelCubic(const float t); + static float KernelGeneralizedCubic(const float t, const float a=-1); + static float KernelLanczosSinc(const float t, const float r = 3); + static float KernelBox(const float x); + static float KernelHermite(const float x); + static float KernelHamming(const float x); + static float KernelSinc(const float x); + static float KernelBlackman(const float x); + static float KernelBessel_J1(const float x); + static float KernelBessel_P1(const float x); + static float KernelBessel_Q1(const float x); + static float KernelBessel_Order1(float x); + static float KernelBessel(const float x); + static float KernelGaussian(const float x); + static float KernelQuadratic(const float x); + static float KernelMitchell(const float x); + static float KernelCatrom(const float x); +//@} +#endif //CXIMAGE_SUPPORT_INTERPOLATION + +/** \addtogroup Painting */ //@{ +#if CXIMAGE_SUPPORT_WINCE + long Blt(HDC pDC, long x=0, long y=0); +#endif +#if CXIMAGE_SUPPORT_WINDOWS + HBITMAP MakeBitmap(HDC hdc = NULL); + HANDLE CopyToHandle(); + bool CreateFromHANDLE(HANDLE hMem); //Windows objects (clipboard) + bool CreateFromHBITMAP(HBITMAP hbmp, HPALETTE hpal=0); //Windows resource + bool CreateFromHICON(HICON hico); + long Draw(HDC hdc, long x=0, long y=0, long cx = -1, long cy = -1, RECT* pClipRect = 0, bool bSmooth = false); + long Draw(HDC hdc, const RECT& rect, RECT* pClipRect=NULL, bool bSmooth = false); + long Stretch(HDC hdc, long xoffset, long yoffset, long xsize, long ysize, DWORD dwRop = SRCCOPY); + long Stretch(HDC hdc, const RECT& rect, DWORD dwRop = SRCCOPY); + long Tile(HDC hdc, RECT *rc); + long Draw2(HDC hdc, long x=0, long y=0, long cx = -1, long cy = -1); + long Draw2(HDC hdc, const RECT& rect); + //long DrawString(HDC hdc, long x, long y, const char* text, RGBQUAD color, const char* font, long lSize=0, long lWeight=400, BYTE bItalic=0, BYTE bUnderline=0, bool bSetAlpha=false); + long DrawString(HDC hdc, long x, long y, const TCHAR* text, RGBQUAD color, const TCHAR* font, long lSize=0, long lWeight=400, BYTE bItalic=0, BYTE bUnderline=0, bool bSetAlpha=false); + // extensions + long DrawStringEx(HDC hdc, long x, long y, CXTEXTINFO *pTextType, bool bSetAlpha=false ); + void InitTextInfo( CXTEXTINFO *txt ); +#endif //CXIMAGE_SUPPORT_WINDOWS +//@} + + // file operations +#if CXIMAGE_SUPPORT_DECODE +/** \addtogroup Decode */ //@{ +#ifdef WIN32 + //bool Load(LPCWSTR filename, DWORD imagetype=0); + bool LoadResource(HRSRC hRes, DWORD imagetype, HMODULE hModule=NULL); +#endif + // For UNICODE support: char -> TCHAR + bool Load(const TCHAR* filename, DWORD imagetype=0); + //bool Load(const char * filename, DWORD imagetype=0); + bool Decode(FILE * hFile, DWORD imagetype); + bool Decode(CxFile * hFile, DWORD imagetype); + bool Decode(BYTE * buffer, DWORD size, DWORD imagetype); +//@} +#endif //CXIMAGE_SUPPORT_DECODE + +#if CXIMAGE_SUPPORT_ENCODE +protected: +/** \addtogroup Protected */ //@{ + bool EncodeSafeCheck(CxFile *hFile); +//@} + +public: +/** \addtogroup Encode */ //@{ +#ifdef WIN32 + //bool Save(LPCWSTR filename, DWORD imagetype=0); +#endif + // For UNICODE support: char -> TCHAR + bool Save(const TCHAR* filename, DWORD imagetype); + //bool Save(const char * filename, DWORD imagetype=0); + bool Encode(FILE * hFile, DWORD imagetype); + bool Encode(CxFile * hFile, DWORD imagetype); + bool Encode(CxFile * hFile, CxImage ** pImages, int pagecount, DWORD imagetype); + bool Encode(FILE *hFile, CxImage ** pImages, int pagecount, DWORD imagetype); + bool Encode(BYTE * &buffer, long &size, DWORD imagetype); + + bool Encode2RGBA(CxFile *hFile); + bool Encode2RGBA(BYTE * &buffer, long &size); +//@} +#endif //CXIMAGE_SUPPORT_ENCODE + +/** \addtogroup Attributes */ //@{ + //misc. + bool IsValid() const; + bool IsEnabled() const; + void Enable(bool enable=true); + + // frame operations + long GetNumFrames() const; + long GetFrame() const; + void SetFrame(long nFrame); +//@} + +#if CXIMAGE_SUPPORT_BASICTRANSFORMATIONS +/** \addtogroup BasicTransformations */ //@{ + bool GrayScale(); + bool Flip(); + bool Mirror(); + bool Negative(); + bool RotateLeft(CxImage* iDst = NULL); + bool RotateRight(CxImage* iDst = NULL); +//@} +#endif //CXIMAGE_SUPPORT_BASICTRANSFORMATIONS + +#if CXIMAGE_SUPPORT_TRANSFORMATION +/** \addtogroup Transformations */ //@{ + // image operations + bool Rotate(float angle, CxImage* iDst = NULL); + bool Rotate2(float angle, CxImage *iDst = NULL, InterpolationMethod inMethod=IM_BILINEAR, + OverflowMethod ofMethod=OM_BACKGROUND, RGBQUAD *replColor=0, + bool const optimizeRightAngles=true, bool const bKeepOriginalSize=false); + bool Rotate180(CxImage* iDst = NULL); + bool Resample(long newx, long newy, int mode = 1, CxImage* iDst = NULL); + bool Resample2(long newx, long newy, InterpolationMethod const inMethod=IM_BICUBIC2, + OverflowMethod const ofMethod=OM_REPEAT, CxImage* const iDst = NULL, + bool const disableAveraging=false); + bool DecreaseBpp(DWORD nbit, bool errordiffusion, RGBQUAD* ppal = 0, DWORD clrimportant = 0); + bool IncreaseBpp(DWORD nbit); + bool Dither(long method = 0); + bool Crop(long left, long top, long right, long bottom, CxImage* iDst = NULL); + bool Crop(const RECT& rect, CxImage* iDst = NULL); + bool CropRotatedRectangle( long topx, long topy, long width, long height, float angle, CxImage* iDst = NULL); + bool Skew(float xgain, float ygain, long xpivot=0, long ypivot=0, bool bEnableInterpolation = false); + bool Expand(long left, long top, long right, long bottom, RGBQUAD canvascolor, CxImage* iDst = 0); + bool Expand(long newx, long newy, RGBQUAD canvascolor, CxImage* iDst = 0); + bool Thumbnail(long newx, long newy, RGBQUAD canvascolor, CxImage* iDst = 0); + bool CircleTransform(int type,long rmax=0,float Koeff=1.0f); + bool RedEyeRemove(); + bool QIShrink(long newx, long newy, CxImage* const iDst = NULL); +//@} +#endif //CXIMAGE_SUPPORT_TRANSFORMATION + +#if CXIMAGE_SUPPORT_DSP +/** \addtogroup DSP */ //@{ + bool Contour(); + bool HistogramStretch(long method = 0); + bool HistogramEqualize(); + bool HistogramNormalize(); + bool HistogramRoot(); + bool HistogramLog(); + long Histogram(long* red, long* green = 0, long* blue = 0, long* gray = 0, long colorspace = 0); + bool Jitter(long radius=2); + bool Repair(float radius = 0.25f, long niterations = 1, long colorspace = 0); + bool Combine(CxImage* r,CxImage* g,CxImage* b,CxImage* a, long colorspace = 0); + bool FFT2(CxImage* srcReal, CxImage* srcImag, CxImage* dstReal, CxImage* dstImag, long direction = 1, bool bForceFFT = true, bool bMagnitude = true); + bool Noise(long level); + bool Median(long Ksize=3); + bool Gamma(float gamma); + bool ShiftRGB(long r, long g, long b); + bool Threshold(BYTE level); + bool Colorize(BYTE hue, BYTE sat, float blend = 1.0f); + bool Light(long brightness, long contrast = 0); + float Mean(); + bool Filter(long* kernel, long Ksize, long Kfactor, long Koffset); + bool Erode(long Ksize=2); + bool Dilate(long Ksize=2); + bool Edge(long Ksize=2); + void HuePalette(float correction=1); + enum ImageOpType { OpAdd, OpAnd, OpXor, OpOr, OpMask, OpSrcCopy, OpDstCopy, OpSub, OpSrcBlend, OpScreen }; + void Mix(CxImage & imgsrc2, ImageOpType op, long lXOffset = 0, long lYOffset = 0, bool bMixAlpha = false); + void MixFrom(CxImage & imagesrc2, long lXOffset, long lYOffset); + bool UnsharpMask(float radius = 5.0, float amount = 0.5, int threshold = 0); + bool Lut(BYTE* pLut); + bool Lut(BYTE* pLutR, BYTE* pLutG, BYTE* pLutB, BYTE* pLutA = 0); +//@} + +protected: +/** \addtogroup Protected */ //@{ + bool IsPowerof2(long x); + bool FFT(int dir,int m,double *x,double *y); + bool DFT(int dir,long m,double *x1,double *y1,double *x2,double *y2); + bool RepairChannel(CxImage *ch, float radius); + // + int gen_convolve_matrix (float radius, float **cmatrix_p); + float* gen_lookup_table (float *cmatrix, int cmatrix_length); + void blur_line (float *ctable, float *cmatrix, int cmatrix_length, BYTE* cur_col, BYTE* dest_col, int y, long bytes); +//@} + +public: +/** \addtogroup ColorSpace */ //@{ + bool SplitRGB(CxImage* r,CxImage* g,CxImage* b); + bool SplitYUV(CxImage* y,CxImage* u,CxImage* v); + bool SplitHSL(CxImage* h,CxImage* s,CxImage* l); + bool SplitYIQ(CxImage* y,CxImage* i,CxImage* q); + bool SplitXYZ(CxImage* x,CxImage* y,CxImage* z); + bool SplitCMYK(CxImage* c,CxImage* m,CxImage* y,CxImage* k); + static RGBQUAD HSLtoRGB(COLORREF cHSLColor); + static RGBQUAD RGBtoHSL(RGBQUAD lRGBColor); + static RGBQUAD HSLtoRGB(RGBQUAD lHSLColor); + static RGBQUAD YUVtoRGB(RGBQUAD lYUVColor); + static RGBQUAD RGBtoYUV(RGBQUAD lRGBColor); + static RGBQUAD YIQtoRGB(RGBQUAD lYIQColor); + static RGBQUAD RGBtoYIQ(RGBQUAD lRGBColor); + static RGBQUAD XYZtoRGB(RGBQUAD lXYZColor); + static RGBQUAD RGBtoXYZ(RGBQUAD lRGBColor); +#endif //CXIMAGE_SUPPORT_DSP + static RGBQUAD RGBtoRGBQUAD(COLORREF cr); + static COLORREF RGBQUADtoRGB (RGBQUAD c); +//@} + +#if CXIMAGE_SUPPORT_SELECTION +/** \addtogroup Selection */ //@{ + bool SelectionClear(); + bool SelectionCreate(); + bool SelectionDelete(); + bool SelectionInvert(); + bool SelectionAddRect(RECT r); + bool SelectionAddEllipse(RECT r); + bool SelectionAddPolygon(POINT *points, long npoints); + bool SelectionAddColor(RGBQUAD c); + bool SelectionAddPixel(int x, int y); + bool SelectionCopy(CxImage &from); + bool SelectionIsInside(long x, long y); + bool SelectionIsValid(); + void SelectionGetBox(RECT& r); + bool SelectionToHRGN(HRGN& region); + bool SelectionSplit(CxImage *dest); +//@} +#endif //CXIMAGE_SUPPORT_SELECTION + +#if CXIMAGE_SUPPORT_ALPHA +/** \addtogroup Alpha */ //@{ + void AlphaClear(); + void AlphaCreate(); + void AlphaDelete(); + void AlphaInvert(); + bool AlphaMirror(); + bool AlphaFlip(); + bool AlphaCopy(CxImage &from); + bool AlphaSplit(CxImage *dest); + void AlphaStrip(); + void AlphaSet(BYTE level); + bool AlphaSet(CxImage &from); + void AlphaSet(const long x,const long y,const BYTE level); + BYTE AlphaGet(const long x,const long y); + BYTE AlphaGetMax() const; + void AlphaSetMax(BYTE nAlphaMax); + bool AlphaIsValid(); + BYTE* AlphaGetPointer(const long x = 0,const long y = 0); + + void AlphaPaletteClear(); + void AlphaPaletteEnable(bool enable=true); + bool AlphaPaletteIsEnabled(); + bool AlphaPaletteIsValid(); + bool AlphaPaletteSplit(CxImage *dest); +//@} + +protected: +/** \addtogroup Protected */ //@{ + BYTE BlindAlphaGet(const long x,const long y); +//@} +#endif //CXIMAGE_SUPPORT_ALPHA + +public: +#if CXIMAGE_SUPPORT_LAYERS +/** \addtogroup Layers */ //@{ + bool LayerCreate(long position = -1); + bool LayerDelete(long position = -1); + void LayerDeleteAll(); + CxImage* GetLayer(long position); + CxImage* GetParent() const; + long GetNumLayers() const; +//@} +#endif //CXIMAGE_SUPPORT_LAYERS + +protected: +/** \addtogroup Protected */ //@{ + void Startup(DWORD imagetype = 0); + void CopyInfo(const CxImage &src); + void Ghost(CxImage *src); + void RGBtoBGR(BYTE *buffer, int length); + static float HueToRGB(float n1,float n2, float hue); + void Bitfield2RGB(BYTE *src, WORD redmask, WORD greenmask, WORD bluemask, BYTE bpp); + static int CompareColors(const void *elem1, const void *elem2); + + void* pDib; //contains the header, the palette, the pixels + BITMAPINFOHEADER head; //standard header + CXIMAGEINFO info; //extended information + BYTE* pSelection; //selected region + BYTE* pAlpha; //alpha channel + CxImage** pLayers; //generic layers +//@} +}; + +//////////////////////////////////////////////////////////////////////////// +#endif // !defined(__CXIMAGE_H) diff --git a/SlnkDWFImpl/CxImage/CxImage/ximagif.cpp b/SlnkDWFImpl/CxImage/CxImage/ximagif.cpp new file mode 100644 index 0000000..bd2f32c --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximagif.cpp @@ -0,0 +1,1564 @@ +/* + * File: ximagif.cpp + * Purpose: Platform Independent GIF Image Class Loader and Writer + * 07/Aug/2001 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximagif.h" + +#if CXIMAGE_SUPPORT_GIF + +#include "ximaiter.h" + +#if CXIMAGE_SUPPORT_WINCE + #define assert(s) +#else + #include +#endif + +//////////////////////////////////////////////////////////////////////////////// +bool CxImageGIF::Decode(CxFile *fp) +{ + /* AD - for transparency */ + struct_dscgif dscgif; + struct_image image; + struct_TabCol TabCol; + + if (fp == NULL) return false; + + fp->Read(&dscgif,/*sizeof(dscgif)*/13,1); + //if (strncmp(dscgif.header,"GIF8",3)!=0) { + if (strncmp(dscgif.header,"GIF8",4)!=0) return FALSE; + + if (info.nEscape == -1) { + // Return output dimensions only + head.biWidth = dscgif.scrwidth; + head.biHeight = dscgif.scrheight; + return true; + } + + /* AD - for interlace */ + TabCol.sogct = (short)(1 << ((dscgif.pflds & 0x07)+1)); + TabCol.colres = (short)(((dscgif.pflds & 0x70) >> 3) + 1); + + // assume that the image is a truecolor-gif if + // 1) no global color map found + // 2) (image.w, image.h) of the 1st image != (dscgif.scrwidth, dscgif.scrheight) + long bTrueColor=0; + CxImage* imaRGB=NULL; + + // Global colour map? + if (dscgif.pflds & 0x80) + fp->Read(TabCol.paleta,sizeof(struct rgb_color)*TabCol.sogct,1); + else + bTrueColor++; //first chance for a truecolor gif + + long first_transparent_index; + + int iImage = 0; + info.nNumFrames=get_num_frames(fp,&TabCol,&dscgif); + + if ((info.nFrame<0)||(info.nFrame>=info.nNumFrames)) return false; + + //it cannot be a true color GIF with only one frame + if (info.nNumFrames == 1) + bTrueColor=0; + + char ch; + bool bPreviousWasNull = true; + int prevdispmeth = 0; + + for (BOOL bContinue = TRUE; bContinue; ) + { + if (fp->Read(&ch, sizeof(ch), 1) != 1) {break;} + + if (info.nEscape > 0) return false; // - cancel decoding + if (bPreviousWasNull || ch==0) + { + switch (ch) + { + case '!': // extension + { + bContinue = DecodeExtension(fp); + break; + } + case ',': // image + { + assert(sizeof(image) == 9); + fp->Read(&image,sizeof(image),1); + //avoid byte order problems with Solaris + BYTE *byteData = (BYTE *) & image; + image.l = byteData[0]+byteData[1]*256; + image.t = byteData[2]+byteData[3]*256; + image.w = byteData[4]+byteData[5]*256; + image.h = byteData[6]+byteData[7]*256; + + if (((image.l + image.w) > dscgif.scrwidth)||((image.t + image.h) > dscgif.scrheight)) + break; + + // check if it could be a truecolor gif + if ((iImage==0) && (image.w != dscgif.scrwidth) && (image.h != dscgif.scrheight)) + bTrueColor++; + + // Local colour map? + if (image.pf & 0x80) { + TabCol.sogct = (short)(1 << ((image.pf & 0x07) +1)); + assert(3 == sizeof(struct rgb_color)); + fp->Read(TabCol.paleta,sizeof(struct rgb_color)*TabCol.sogct,1); + //log << "Local colour map" << endl; + } + + int bpp; // select the correct bit per pixel value + if (TabCol.sogct <= 2) bpp = 1; + else if (TabCol.sogct <= 16) bpp = 4; + else bpp = 8; + + CxImageGIF backimage; + backimage.CopyInfo(*this); + if (iImage==0){ + //first frame: build image background + backimage.Create(dscgif.scrwidth, dscgif.scrheight, bpp, CXIMAGE_FORMAT_GIF); + first_transparent_index = info.nBkgndIndex; + backimage.Clear((BYTE)gifgce.transpcolindex); + } else { + //generic frame: handle disposal method from previous one + /*Values : 0 - No disposal specified. The decoder is + not required to take any action. + 1 - Do not dispose. The graphic is to be left + in place. + 2 - Restore to background color. The area used by the + graphic must be restored to the background color. + 3 - Restore to previous. The decoder is required to + restore the area overwritten by the graphic with + what was there prior to rendering the graphic. + */ + backimage.Copy(*this); + if (prevdispmeth==2){ + backimage.Clear((BYTE)first_transparent_index); + } + } + + //active frame + Create(image.w, image.h, bpp, CXIMAGE_FORMAT_GIF); + + if ((image.pf & 0x80) || (dscgif.pflds & 0x80)) { + unsigned char r[256], g[256], b[256]; + int i, has_white = 0; + + for (i=0; i < TabCol.sogct; i++) { + r[i] = TabCol.paleta[i].r; + g[i] = TabCol.paleta[i].g; + b[i] = TabCol.paleta[i].b; + + if (RGB(r[i],g[i],b[i]) == 0xFFFFFF) has_white = 1; + } + + // Force transparency colour white... + //if (0) if (info.nBkgndIndex != -1) + // r[info.nBkgndIndex] = g[info.nBkgndIndex] = b[info.nBkgndIndex] = 255; + // Fill in with white // AD + if (info.nBkgndIndex != -1) { + while (i < 256) { + has_white = 1; + r[i] = g[i] = b[i] = 255; + i++; + } + } + + // Force last colour to white... // AD + //if ((info.nBkgndIndex != -1) && !has_white) { + // r[255] = g[255] = b[255] = 255; + //} + + SetPalette((info.nBkgndIndex != -1 ? 256 : TabCol.sogct), r, g, b); + } + + CImageIterator* iter = new CImageIterator(this); + iter->Upset(); + int badcode=0; + ibf = GIFBUFTAM+1; + + interlaced = image.pf & 0x40; + iheight = image.h; + istep = 8; + iypos = 0; + ipass = 0; + + long pos_start = fp->Tell(); + //if (interlaced) log << "Interlaced" << endl; + decoder(fp, iter, image.w, badcode); + delete iter; + + if (info.nEscape) return false; // - cancel decoding + + if (bTrueColor<2 ){ //standard GIF: mix frame with background + backimage.GifMix(*this,image); + backimage.SetTransIndex(first_transparent_index); + backimage.SetPalette(GetPalette()); + Transfer(backimage); + } else { //it's a truecolor gif! + //force full image decoding + info.nFrame=info.nNumFrames-1; + //build the RGB image + if (imaRGB==NULL) imaRGB = new CxImage(dscgif.scrwidth,dscgif.scrheight,24,CXIMAGE_FORMAT_GIF); + //copy the partial image into the full RGB image + for(long y=0;ySetPixelColor(x+image.l,dscgif.scrheight-1-image.t-y,GetPixelColor(x,image.h-y-1)); + } + } + } + + prevdispmeth = gifgce.dispmeth; + + //restore the correct position in the file for the next image + if (badcode){ + seek_next_image(fp,pos_start); + } else { + fp->Seek(-(ibfmax - ibf - 1), SEEK_CUR); + } + + if (info.nFrame==iImage) bContinue=false; else iImage++; + + break; + } + case ';': //terminator + bContinue=false; + break; + default: + bPreviousWasNull = (ch==0); + break; + } + } + } + + if (bTrueColor>=2 && imaRGB){ + if (gifgce.transpcolflag){ + imaRGB->SetTransColor(GetPaletteColor((BYTE)info.nBkgndIndex)); + imaRGB->SetTransIndex(0); + } + Transfer(*imaRGB); + } + delete imaRGB; + + return true; + +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImageGIF::DecodeExtension(CxFile *fp) +{ + bool bContinue; + unsigned char count; + unsigned char fc; + + bContinue = (1 == fp->Read(&fc, sizeof(fc), 1)); + if (bContinue) { + /* AD - for transparency */ + if (fc == 0xF9) { + bContinue = (1 == fp->Read(&count, sizeof(count), 1)); + if (bContinue) { + assert(sizeof(gifgce) == 4); + bContinue = (count == fp->Read(&gifgce, 1, sizeof(gifgce))); + if (bContinue) { + if (gifgce.transpcolflag) info.nBkgndIndex = gifgce.transpcolindex; + info.dwFrameDelay = gifgce.delaytime; + m_dispmeth = gifgce.dispmeth; + } } } + + if (fc == 0xFE) { // Comment block + bContinue = (1 == fp->Read(&count, sizeof(count), 1)); + if (bContinue) { + bContinue = (1 == fp->Read(m_comment, count, 1)); + m_comment[count]='\0'; + } } + + if (fc == 0xFF) { // Application Extension block + bContinue = (1 == fp->Read(&count, sizeof(count), 1)); + if (bContinue) { + bContinue = (count==11); + if (bContinue){ + char AppID[11]; + bContinue = (1 == fp->Read(AppID, count, 1)); + if (bContinue) { + bContinue = (1 == fp->Read(&count, sizeof(count), 1)); + if (bContinue) { + BYTE* dati = (BYTE*)malloc(count); + bContinue = (dati!=NULL); + if (bContinue){ + bContinue = (1 == fp->Read(dati, count, 1)); + if (count>2){ + m_loops = dati[1]+256*dati[2]; + } + } + free(dati); + } } } } } + + while (bContinue && fp->Read(&count, sizeof(count), 1) && count) { + //log << "Skipping " << count << " bytes" << endl; + fp->Seek(count, SEEK_CUR); + } + } + return bContinue; + +} + + +// - This external (machine specific) function is expected to return +// either the next BYTE from the GIF file, or a negative error number. +int CxImageGIF::get_byte(CxFile* file) +{ + if (ibf>=GIFBUFTAM){ + // FW 06/02/98 >>> + ibfmax = file->Read( buf , 1 , GIFBUFTAM) ; + if( ibfmax < GIFBUFTAM ) buf[ ibfmax ] = 255 ; + // FW 06/02/98 <<< + ibf = 0; + } + if (ibf>=ibfmax) return -1; // avoid overflows + return buf[ibf++]; +} +//////////////////////////////////////////////////////////////////////////////// +/* - This function takes a full line of pixels (one BYTE per pixel) and + * displays them (or does whatever your program wants with them...). It + * should return zero, or negative if an error or some other event occurs + * which would require aborting the decode process... Note that the length + * passed will almost always be equal to the line length passed to the + * decoder function, with the sole exception occurring when an ending code + * occurs in an odd place in the GIF file... In any case, linelen will be + * equal to the number of pixels passed... +*/ +int CxImageGIF::out_line(CImageIterator* iter, unsigned char *pixels, int linelen) +{ + // for 1 & 4 bpp images, the pixels are compressed + if (head.biBitCount < 8){ + for(long x=0;x> 3); + if (head.biBitCount==4){ + pos = (BYTE)(4*(1-x%2)); + *iDst &= ~(0x0F<SetY(iheight-iypos-1); + iter->SetRow(pixels, linelen); + + if ((iypos += istep) >= iheight) { + do { + if (ipass++ > 0) istep /= 2; + iypos = istep / 2; + } + while (iypos > iheight); + } + return 0; + } else { + if (iter->ItOK()) { + iter->SetRow(pixels, linelen); + (void)iter->PrevRow(); + return 0; + } else { + // puts("chafeo"); + return -1; + } + } +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +// SaveFile - writes GIF87a gif file +// Randy Spann 6/15/97 +// R.Spann@ConnRiver.net +bool CxImageGIF::Encode(CxFile * fp) +{ + if (EncodeSafeCheck(fp)) return false; + + if(head.biBitCount > 8) { + //strcpy(info.szLastError,"GIF Images must be 8 bit or less"); + //return FALSE; + return EncodeRGB(fp); + } + + EncodeHeader(fp); + + EncodeExtension(fp); + + EncodeComment(fp); + + EncodeBody(fp); + + fp->PutC(';'); // Write the GIF file terminator + + return true; // done! +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImageGIF::Encode(CxFile * fp, CxImage ** pImages, int pagecount, bool bLocalColorMap) +{ + try{ + if (fp==NULL) throw "invalid file pointer"; + if (pImages==NULL || pagecount==0 || pImages[0]==NULL) throw "multipage GIF, no images!"; + + CxImageGIF ghost; + + //write the first image + ghost.Ghost(pImages[0]); + ghost.EncodeHeader(fp); + + if (m_loops!=1){ + ghost.SetLoops(max(0,m_loops-1)); + ghost.EncodeLoopExtension(fp); + } + + ghost.SetDisposalMethod(GetDisposalMethod()); + ghost.EncodeExtension(fp); + + EncodeComment(fp); + + ghost.EncodeBody(fp); + + for (int i=2; i<=pagecount; i++){ + if (pImages[i-1]==NULL) throw "Bad image pointer"; + ghost.Ghost(pImages[i-1]); + + ghost.SetDisposalMethod(GetDisposalMethod()); + ghost.EncodeExtension(fp); + + ghost.EncodeBody(fp,bLocalColorMap); + } + + fp->PutC(';'); // Write the GIF file terminator + + } catch (char *message) { + strncpy(info.szLastError,message,255); + return false; + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::EncodeHeader(CxFile *fp) +{ + fp->Write("GIF89a",1,6); //GIF Header + + Putword(head.biWidth,fp); //Logical screen descriptor + Putword(head.biHeight,fp); + + BYTE Flags; + if (head.biClrUsed==0){ + Flags=0x11; + } else { + Flags = 0x80; + Flags |=(head.biBitCount - 1) << 5; + Flags |=(head.biBitCount - 1); + } + + fp->PutC(Flags); //GIF "packed fields" + fp->PutC(0); //GIF "BackGround" + fp->PutC(0); //GIF "pixel aspect ratio" + + if (head.biClrUsed!=0){ + RGBQUAD* pPal = GetPalette(); + for(DWORD i=0; iPutC(pPal[i].rgbRed); + fp->PutC(pPal[i].rgbGreen); + fp->PutC(pPal[i].rgbBlue); + } + } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::EncodeExtension(CxFile *fp) +{ + // TRK BEGIN : transparency + fp->PutC('!'); + fp->PutC(TRANSPARENCY_CODE); + + gifgce.transpcolflag = (info.nBkgndIndex != -1) ? 1 : 0; + gifgce.userinputflag = 0; + gifgce.dispmeth = m_dispmeth; + gifgce.res = 0; + gifgce.delaytime = (WORD)info.dwFrameDelay; + gifgce.transpcolindex = (BYTE)info.nBkgndIndex; + fp->PutC(sizeof(gifgce)); + fp->Write(&gifgce, sizeof(gifgce), 1); + fp->PutC(0); + // TRK END +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::EncodeLoopExtension(CxFile *fp) +{ + fp->PutC('!'); //byte 1 : 33 (hex 0x21) GIF Extension code + fp->PutC(255); //byte 2 : 255 (hex 0xFF) Application Extension Label + fp->PutC(11); //byte 3 : 11 (hex (0x0B) Length of Application Block (eleven bytes of data to follow) + fp->Write("NETSCAPE2.0",11,1); + fp->PutC(3); //byte 15 : 3 (hex 0x03) Length of Data Sub-Block (three bytes of data to follow) + fp->PutC(1); //byte 16 : 1 (hex 0x01) + Putword(m_loops,fp); //bytes 17 to 18 : 0 to 65535, an unsigned integer in lo-hi byte format. + //This indicate the number of iterations the loop should be executed. + fp->PutC(0); //bytes 19 : 0 (hex 0x00) a Data Sub-block Terminator. +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::EncodeBody(CxFile *fp, bool bLocalColorMap) +{ + curx = 0; + cury = head.biHeight - 1; //because we read the image bottom to top + CountDown = (long)head.biWidth * (long)head.biHeight; + + fp->PutC(','); + + Putword(info.xOffset,fp); + Putword(info.yOffset,fp); + Putword(head.biWidth,fp); + Putword(head.biHeight,fp); + + BYTE Flags=0x00; //non-interlaced (0x40 = interlaced) (0x80 = LocalColorMap) + if (bLocalColorMap) { Flags|=0x80; Flags|=head.biBitCount-1; } + fp->PutC(Flags); + + if (bLocalColorMap){ + Flags|=0x87; + RGBQUAD* pPal = GetPalette(); + for(DWORD i=0; iPutC(pPal[i].rgbRed); + fp->PutC(pPal[i].rgbGreen); + fp->PutC(pPal[i].rgbBlue); + } + } + + int InitCodeSize = head.biBitCount <=1 ? 2 : head.biBitCount; + // Write out the initial code size + fp->PutC((BYTE)InitCodeSize); + + // Go and actually compress the data + switch (GetCodecOption(CXIMAGE_FORMAT_GIF)) + { + case 1: //uncompressed + compressNONE(InitCodeSize+1, fp); + break; + case 2: //RLE + compressRLE(InitCodeSize+1, fp); + break; + default: //LZW + compressLZW(InitCodeSize+1, fp); + } + + // Write out a Zero-length packet (to end the series) + fp->PutC(0); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::EncodeComment(CxFile *fp) +{ + unsigned long n = (unsigned long) strlen(m_comment); + if (n>255) n=255; + if (n) { + fp->PutC('!'); //extension code: + fp->PutC(254); //comment extension + fp->PutC((BYTE)n); //size of comment + fp->Write(m_comment,n,1); + fp->PutC(0); //block terminator + } +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImageGIF::EncodeRGB(CxFile *fp) +{ + EncodeHeader(fp); + +// EncodeLoopExtension(fp); + + EncodeComment(fp); + + unsigned long w,h; + w=h=0; + const long cellw = 17; + const long cellh = 15; + CxImageGIF tmp; + for (long y=0;yPutC(';'); // Write the GIF file terminator + + return true; // done! +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +// Return the next pixel from the image +// fix for 1 & 4 bpp images +int CxImageGIF::GifNextPixel( ) +{ + if( CountDown == 0 ) return EOF; + --CountDown; + int r = GetPixelIndex(curx,cury); + // Bump the current X position + ++curx; + if( curx == head.biWidth ){ + curx = 0; + cury--; //bottom to top + } + return r; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::Putword(int w, CxFile *fp ) +{ + fp->PutC((BYTE)(w & 0xff)); + fp->PutC((BYTE)((w / 256) & 0xff)); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::compressNONE( int init_bits, CxFile* outfile) +{ + register long c; + register long ent; + + // g_init_bits - initial number of bits + // g_outfile - pointer to output file + g_init_bits = init_bits; + g_outfile = outfile; + + // Set up the necessary values + cur_accum = cur_bits = clear_flg = 0; + maxcode = (short)MAXCODE(n_bits = g_init_bits); + code_int maxmaxcode = (code_int)1 << MAXBITSCODES; + + ClearCode = (1 << (init_bits - 1)); + EOFCode = ClearCode + 1; + free_ent = (short)(ClearCode + 2); + + a_count=0; + ent = GifNextPixel( ); + + output( (code_int)ClearCode ); + + while ( ent != EOF ) { + c = GifNextPixel(); + + output ( (code_int) ent ); + ent = c; + if ( free_ent < maxmaxcode ) { + free_ent++; + } else { + free_ent=(short)(ClearCode+2); + clear_flg=1; + output((code_int)ClearCode); + } + } + // Put out the final code. + output( (code_int) EOFCode ); +} +//////////////////////////////////////////////////////////////////////////////// + +/*************************************************************************** + * + * GIFCOMPR.C - LZW GIF Image compression routines + * + ***************************************************************************/ + +void CxImageGIF::compressLZW( int init_bits, CxFile* outfile) +{ + register long fcode; + register long c; + register long ent; + register long hshift; + register long disp; + register long i; + + // g_init_bits - initial number of bits + // g_outfile - pointer to output file + g_init_bits = init_bits; + g_outfile = outfile; + + // Set up the necessary values + cur_accum = cur_bits = clear_flg = 0; + maxcode = (short)MAXCODE(n_bits = g_init_bits); + code_int maxmaxcode = (code_int)1 << MAXBITSCODES; + + ClearCode = (1 << (init_bits - 1)); + EOFCode = ClearCode + 1; + free_ent = (short)(ClearCode + 2); + + a_count=0; + ent = GifNextPixel( ); + + hshift = 0; + for ( fcode = (long) HSIZE; fcode < 65536L; fcode *= 2L ) ++hshift; + hshift = 8 - hshift; /* set hash code range bound */ + cl_hash((long)HSIZE); /* clear hash table */ + output( (code_int)ClearCode ); + + while ( (c = GifNextPixel( )) != EOF ) { + + fcode = (long) (((long) c << MAXBITSCODES) + ent); + i = (((code_int)c << hshift) ^ ent); /* xor hashing */ + + if ( HashTabOf (i) == fcode ) { + ent = CodeTabOf (i); + continue; + } else if ( (long)HashTabOf (i) < 0 ) /* empty slot */ + goto nomatch; + disp = HSIZE - i; /* secondary hash (after G. Knott) */ + if ( i == 0 ) disp = 1; +probe: + if ( (i -= disp) < 0 ) i += HSIZE; + if ( HashTabOf (i) == fcode ) { ent = CodeTabOf (i); continue; } + if ( (long)HashTabOf (i) > 0 ) goto probe; +nomatch: + output ( (code_int) ent ); + ent = c; + if ( free_ent < maxmaxcode ) { + CodeTabOf (i) = free_ent++; /* code -> hashtable */ + HashTabOf (i) = fcode; + } else { + cl_hash((long)HSIZE); + free_ent=(short)(ClearCode+2); + clear_flg=1; + output((code_int)ClearCode); + } + } + // Put out the final code. + output( (code_int)ent ); + output( (code_int) EOFCode ); +} +//////////////////////////////////////////////////////////////////////////////// + +static const unsigned long code_mask[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, + 0x001F, 0x003F, 0x007F, 0x00FF, + 0x01FF, 0x03FF, 0x07FF, 0x0FFF, + 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::output( code_int code) +{ + cur_accum &= code_mask[ cur_bits ]; + + if( cur_bits > 0 ) + cur_accum |= ((long)code << cur_bits); + else + cur_accum = code; + + cur_bits += n_bits; + + while( cur_bits >= 8 ) { + char_out( (unsigned int)(cur_accum & 0xff) ); + cur_accum >>= 8; + cur_bits -= 8; + } + + /* + * If the next entry is going to be too big for the code size, + * then increase it, if possible. + */ + + if ( free_ent > maxcode || clear_flg ) { + if( clear_flg ) { + maxcode = (short)MAXCODE(n_bits = g_init_bits); + clear_flg = 0; + } else { + ++n_bits; + if ( n_bits == MAXBITSCODES ) + maxcode = (code_int)1 << MAXBITSCODES; /* should NEVER generate this code */ + else + maxcode = (short)MAXCODE(n_bits); + } + } + + if( code == EOFCode ) { + // At EOF, write the rest of the buffer. + while( cur_bits > 0 ) { + char_out( (unsigned int)(cur_accum & 0xff) ); + cur_accum >>= 8; + cur_bits -= 8; + } + + flush_char(); + g_outfile->Flush(); + + if(g_outfile->Error()) strcpy(info.szLastError,"Write Error in GIF file"); + } +} +//////////////////////////////////////////////////////////////////////////////// + +void CxImageGIF::cl_hash(register long hsize) + +{ + register long *htab_p = htab+hsize; + + register long i; + register long m1 = -1L; + + i = hsize - 16; + + do { + *(htab_p-16)=m1; + *(htab_p-15)=m1; + *(htab_p-14)=m1; + *(htab_p-13)=m1; + *(htab_p-12)=m1; + *(htab_p-11)=m1; + *(htab_p-10)=m1; + *(htab_p-9)=m1; + *(htab_p-8)=m1; + *(htab_p-7)=m1; + *(htab_p-6)=m1; + *(htab_p-5)=m1; + *(htab_p-4)=m1; + *(htab_p-3)=m1; + *(htab_p-2)=m1; + *(htab_p-1)=m1; + + htab_p-=16; + } while ((i-=16) >=0); + + for (i+=16;i>0;--i) + *--htab_p=m1; +} + +/******************************************************************************* +* GIF specific +*******************************************************************************/ + +void CxImageGIF::char_out(int c) +{ + accum[a_count++]=(char)c; + if (a_count >=254) + flush_char(); +} + +void CxImageGIF::flush_char() +{ + if (a_count > 0) { + g_outfile->PutC((BYTE)a_count); + g_outfile->Write(accum,1,a_count); + a_count=0; + } +} + +/******************************************************************************* +* GIF decoder +*******************************************************************************/ +/* DECODE.C - An LZW decoder for GIF + * Copyright (C) 1987, by Steven A. Bennett + * Copyright (C) 1994, C++ version by Alejandro Aguilar Sierra +* + * Permission is given by the author to freely redistribute and include + * this code in any program as long as this credit is given where due. + * + * In accordance with the above, I want to credit Steve Wilhite who wrote + * the code which this is heavily inspired by... + * + * GIF and 'Graphics Interchange Format' are trademarks (tm) of + * Compuserve, Incorporated, an H&R Block Company. + * + * Release Notes: This file contains a decoder routine for GIF images + * which is similar, structurally, to the original routine by Steve Wilhite. + * It is, however, somewhat noticably faster in most cases. + * + */ + +//////////////////////////////////////////////////////////////////////////////// + +short CxImageGIF::init_exp(short size) +{ + curr_size = (short)(size + 1); + top_slot = (short)(1 << curr_size); + clear = (short)(1 << size); + ending = (short)(clear + 1); + slot = newcodes = (short)(ending + 1); + navail_bytes = nbits_left = 0; + + memset(stack,0,MAX_CODES + 1); + memset(prefix,0,MAX_CODES + 1); + memset(suffix,0,MAX_CODES + 1); + return(0); +} +//////////////////////////////////////////////////////////////////////////////// + +/* get_next_code() + * - gets the next code from the GIF file. Returns the code, or else + * a negative number in case of file errors... + */ +short CxImageGIF::get_next_code(CxFile* file) +{ + short i, x; + DWORD ret; + + if (nbits_left == 0) { + if (navail_bytes <= 0) { + /* Out of bytes in current block, so read next block */ + pbytes = byte_buff; + if ((navail_bytes = (short)get_byte(file)) < 0) + return(navail_bytes); + else if (navail_bytes) { + for (i = 0; i < navail_bytes; ++i) { + if ((x = (short)get_byte(file)) < 0) return(x); + byte_buff[i] = (BYTE)x; + } + } + } + b1 = *pbytes++; + nbits_left = 8; + --navail_bytes; + } + + if (navail_bytes<0) return ending; // prevent deadlocks (thanks to Mike Melnikov) + + ret = b1 >> (8 - nbits_left); + while (curr_size > nbits_left){ + if (navail_bytes <= 0){ + /* Out of bytes in current block, so read next block*/ + pbytes = byte_buff; + if ((navail_bytes = (short)get_byte(file)) < 0) + return(navail_bytes); + else if (navail_bytes){ + for (i = 0; i < navail_bytes; ++i){ + if ((x = (short)get_byte(file)) < 0) return(x); + byte_buff[i] = (BYTE)x; + } + } + } + b1 = *pbytes++; + ret |= b1 << nbits_left; + nbits_left += 8; + --navail_bytes; + } + nbits_left = (short)(nbits_left-curr_size); + ret &= code_mask[curr_size]; + return((short)(ret)); +} +//////////////////////////////////////////////////////////////////////////////// + +/* short decoder(linewidth) + * short linewidth; * Pixels per line of image * + * + * - This function decodes an LZW image, according to the method used + * in the GIF spec. Every *linewidth* "characters" (ie. pixels) decoded + * will generate a call to out_line(), which is a user specific function + * to display a line of pixels. The function gets it's codes from + * get_next_code() which is responsible for reading blocks of data and + * seperating them into the proper size codes. Finally, get_byte() is + * the global routine to read the next BYTE from the GIF file. + * + * It is generally a good idea to have linewidth correspond to the actual + * width of a line (as specified in the Image header) to make your own + * code a bit simpler, but it isn't absolutely necessary. + * + * Returns: 0 if successful, else negative. (See ERRS.H) + * + */ +/* bad_code_count is incremented each time an out of range code is read. + * When this value is non-zero after a decode, your GIF file is probably + * corrupt in some way... + */ +short CxImageGIF::decoder(CxFile* file, CImageIterator* iter, short linewidth, int &bad_code_count) +{ + register BYTE *sp, *bufptr; + BYTE *buf; + register short code, fc, oc, bufcnt; + short c, size, ret; + + /* Initialize for decoding a new image... */ + bad_code_count = 0; + if ((size = (short)get_byte(file)) < 0) return(size); + if (size < 2 || 9 < size) return(BAD_CODE_SIZE); + // out_line = outline; + init_exp(size); + //printf("L %d %x\n",linewidth,size); + + /* Initialize in case they forgot to put in a clear code. + * (This shouldn't happen, but we'll try and decode it anyway...) + */ + oc = fc = 0; + + /* Allocate space for the decode buffer */ + if ((buf = new BYTE[linewidth + 1]) == NULL) return(OUT_OF_MEMORY); + + /* Set up the stack pointer and decode buffer pointer */ + sp = stack; + bufptr = buf; + bufcnt = linewidth; + + /* This is the main loop. For each code we get we pass through the + * linked list of prefix codes, pushing the corresponding "character" for + * each code onto the stack. When the list reaches a single "character" + * we push that on the stack too, and then start unstacking each + * character for output in the correct order. Special handling is + * included for the clear code, and the whole thing ends when we get + * an ending code. + */ + while ((c = get_next_code(file)) != ending) { + /* If we had a file error, return without completing the decode*/ + if (c < 0){ + delete[] buf; + return(0); + } + /* If the code is a clear code, reinitialize all necessary items.*/ + if (c == clear){ + curr_size = (short)(size + 1); + slot = newcodes; + top_slot = (short)(1 << curr_size); + + /* Continue reading codes until we get a non-clear code + * (Another unlikely, but possible case...) + */ + while ((c = get_next_code(file)) == clear); + + /* If we get an ending code immediately after a clear code + * (Yet another unlikely case), then break out of the loop. + */ + if (c == ending) break; + + /* Finally, if the code is beyond the range of already set codes, + * (This one had better NOT happen... I have no idea what will + * result from this, but I doubt it will look good...) then set it + * to color zero. + */ + if (c >= slot) c = 0; + oc = fc = c; + + /* And let us not forget to put the char into the buffer... And + * if, on the off chance, we were exactly one pixel from the end + * of the line, we have to send the buffer to the out_line() + * routine... + */ + *bufptr++ = (BYTE)c; + if (--bufcnt == 0) { + if ((ret = (short)out_line(iter, buf, linewidth)) < 0) { + delete[] buf; + return(ret); + } + bufptr = buf; + bufcnt = linewidth; + } + } else { + /* In this case, it's not a clear code or an ending code, so + * it must be a code code... So we can now decode the code into + * a stack of character codes. (Clear as mud, right?) + */ + code = c; + + /* Here we go again with one of those off chances... If, on the + * off chance, the code we got is beyond the range of those already + * set up (Another thing which had better NOT happen...) we trick + * the decoder into thinking it actually got the last code read. + * (Hmmn... I'm not sure why this works... But it does...) + */ + if (code >= slot) { + if (code > slot) ++bad_code_count; + code = oc; + *sp++ = (BYTE)fc; + } + + /* Here we scan back along the linked list of prefixes, pushing + * helpless characters (ie. suffixes) onto the stack as we do so. + */ + while (code >= newcodes) { + *sp++ = suffix[code]; + code = prefix[code]; + } + + /* Push the last character on the stack, and set up the new + * prefix and suffix, and if the required slot number is greater + * than that allowed by the current bit size, increase the bit + * size. (NOTE - If we are all full, we *don't* save the new + * suffix and prefix... I'm not certain if this is correct... + * it might be more proper to overwrite the last code... + */ + *sp++ = (BYTE)code; + if (slot < top_slot){ + suffix[slot] = (BYTE)(fc = (BYTE)code); + prefix[slot++] = oc; + oc = c; + } + if (slot >= top_slot){ + if (curr_size < 12) { + top_slot <<= 1; + ++curr_size; + } + } + + /* Now that we've pushed the decoded string (in reverse order) + * onto the stack, lets pop it off and put it into our decode + * buffer... And when the decode buffer is full, write another + * line... + */ + while (sp > stack) { + *bufptr++ = *(--sp); + if (--bufcnt == 0) { + if ((ret = (short)out_line(iter, buf, linewidth)) < 0) { + delete[] buf; + return(ret); + } + bufptr = buf; + bufcnt = linewidth; + } + } + } + } + ret = 0; + if (bufcnt != linewidth) + ret = (short)out_line(iter, buf, (linewidth - bufcnt)); + delete[] buf; + return(ret); +} +//////////////////////////////////////////////////////////////////////////////// +int CxImageGIF::get_num_frames(CxFile *fp,struct_TabCol* TabColSrc,struct_dscgif* dscgif) +{ + struct_image image; + + long pos=fp->Tell(); + int nframes=0; + + struct_TabCol TempTabCol; + memcpy(&TempTabCol,TabColSrc,sizeof(struct_TabCol)); + + char ch; + bool bPreviousWasNull = true; + + for (BOOL bContinue = TRUE; bContinue; ) + { + if (fp->Read(&ch, sizeof(ch), 1) != 1) {break;} + + if (bPreviousWasNull || ch==0) + { + switch (ch) + { + case '!': // extension + { + DecodeExtension(fp); + break; + } + case ',': // image + { + + assert(sizeof(image) == 9); + //log << "Image header" << endl; + fp->Read(&image,sizeof(image),1); + + //avoid byte order problems with Solaris + BYTE *byteData = (BYTE *) & image; + image.l = byteData[0]+byteData[1]*256; + image.t = byteData[2]+byteData[3]*256; + image.w = byteData[4]+byteData[5]*256; + image.h = byteData[6]+byteData[7]*256; + + if (((image.l + image.w) > dscgif->scrwidth)||((image.t + image.h) > dscgif->scrheight)) + break; + + nframes++; + + // Local colour map? + if (image.pf & 0x80) { + TempTabCol.sogct = (short)(1 << ((image.pf & 0x07) +1)); + assert(3 == sizeof(struct rgb_color)); + fp->Read(TempTabCol.paleta,sizeof(struct rgb_color)*TempTabCol.sogct,1); + //log << "Local colour map" << endl; + } + + int bpp; // select the correct bit per pixel value + if (TempTabCol.sogct <= 2) bpp = 1; + else if (TempTabCol.sogct <= 16) bpp = 4; + else bpp = 8; + + Create(image.w, image.h, bpp, CXIMAGE_FORMAT_GIF); + + CImageIterator* iter = new CImageIterator(this); + iter->Upset(); + int badcode=0; + ibf = GIFBUFTAM+1; + + interlaced = image.pf & 0x40; + iheight = image.h; + istep = 8; + iypos = 0; + ipass = 0; + + long pos_start = fp->Tell(); + + //if (interlaced) log << "Interlaced" << endl; + decoder(fp, iter, image.w, badcode); + delete iter; + + if (badcode){ + seek_next_image(fp,pos_start); + } else { + fp->Seek(-(ibfmax - ibf - 1), SEEK_CUR); + } + + break; + } + case ';': //terminator + bContinue=false; + break; + default: + bPreviousWasNull = (ch==0); + break; + } + } + } + + fp->Seek(pos,SEEK_SET); + return nframes; +} +//////////////////////////////////////////////////////////////////////////////// +long CxImageGIF::seek_next_image(CxFile* fp, long position) +{ + fp->Seek(position, SEEK_SET); + char ch1,ch2; + ch1=ch2=0; + while(fp->Read(&ch2,sizeof(char),1)>0){ + if (ch1 == 0 && ch2 == ','){ + fp->Seek(-1,SEEK_CUR); + return fp->Tell(); + } else { + ch1 = ch2; + } + } + return -1; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::SetDisposalMethod(int dm) +{ m_dispmeth=dm; } +//////////////////////////////////////////////////////////////////////////////// +long CxImageGIF::GetDisposalMethod() +{ return m_dispmeth; } +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::SetLoops(int loops) +{ m_loops=loops; } +//////////////////////////////////////////////////////////////////////////////// +long CxImageGIF::GetLoops() +{ return m_loops; } +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::SetComment(const char* sz_comment_in) +{ if (sz_comment_in) strncpy(m_comment,sz_comment_in,255); } +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::GetComment(char* sz_comment_out) +{ if (sz_comment_out) strncpy(sz_comment_out,m_comment,255); } +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::GifMix(CxImage & imgsrc2, struct_image & imgdesc) +{ + long ymin = max(0,(long)(GetHeight()-imgdesc.t - imgdesc.h)); + long ymax = GetHeight()-imgdesc.t; + long xmin = imgdesc.l; + long xmax = min(GetWidth(), (DWORD)(imgdesc.l + imgdesc.w)); + + long ibg2= imgsrc2.GetTransIndex(); + BYTE i2; + + for(long y = ymin; y < ymax; y++){ + for(long x = xmin; x < xmax; x++){ + i2 = imgsrc2.GetPixelIndex(x-xmin,y-ymin); + if(i2!=ibg2) SetPixelIndex(x,y,i2); + } + } +} +//////////////////////////////////////////////////////////////////////////////// +/*----------------------------------------------------------------------- + * + * miGIF Compression - mouse and ivo's GIF-compatible compression + * + * -run length encoding compression routines- + * + * Copyright (C) 1998 Hutchison Avenue Software Corporation + * http://www.hasc.com + * info@hasc.com + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose and without fee is hereby granted, provided + * that the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation. This software is provided "AS IS." The Hutchison Avenue + * Software Corporation disclaims all warranties, either express or implied, + * including but not limited to implied warranties of merchantability and + * fitness for a particular purpose, with respect to this code and accompanying + * documentation. + * + * The miGIF compression routines do not, strictly speaking, generate files + * conforming to the GIF spec, since the image data is not LZW-compressed + * (this is the point: in order to avoid transgression of the Unisys patent + * on the LZW algorithm.) However, miGIF generates data streams that any + * reasonably sane LZW decompresser will decompress to what we want. + * + * miGIF compression uses run length encoding. It compresses horizontal runs + * of pixels of the same color. This type of compression gives good results + * on images with many runs, for example images with lines, text and solid + * shapes on a solid-colored background. It gives little or no compression + * on images with few runs, for example digital or scanned photos. + * + * der Mouse + * mouse@rodents.montreal.qc.ca + * 7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B + * + * ivo@hasc.com + * + * The Graphics Interchange Format(c) is the Copyright property of + * CompuServe Incorporated. GIF(sm) is a Service Mark property of + * CompuServe Incorporated. + * + */ +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_clear(struct_RLE* rle) +{ + rle->out_bits = rle->out_bits_init; + rle->out_bump = rle->out_bump_init; + rle->out_clear = rle->out_clear_init; + rle->out_count = 0; + rle->rl_table_max = 0; + rle->just_cleared = 1; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_flush(struct_RLE* rle) +{ + if (rle->rl_count == 1){ + rle_output_plain(rle->rl_pixel,rle); + rle->rl_count = 0; + return; + } + if (rle->just_cleared){ + rle_flush_fromclear(rle->rl_count,rle); + } else if ((rle->rl_table_max < 2) || (rle->rl_table_pixel != rle->rl_pixel)) { + rle_flush_clearorrep(rle->rl_count,rle); + } else { + rle_flush_withtable(rle->rl_count,rle); + } + rle->rl_count = 0; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_output_plain(int c,struct_RLE* rle) +{ + rle->just_cleared = 0; + rle_output(c,rle); + rle->out_count++; + if (rle->out_count >= rle->out_bump){ + rle->out_bits ++; + rle->out_bump += 1 << (rle->out_bits - 1); + } + if (rle->out_count >= rle->out_clear){ + rle_output(rle->code_clear,rle); + rle_clear(rle); + } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_flush_fromclear(int count,struct_RLE* rle) +{ + int n; + + rle->out_clear = rle->max_ocodes; + rle->rl_table_pixel = rle->rl_pixel; + n = 1; + while (count > 0){ + if (n == 1){ + rle->rl_table_max = 1; + rle_output_plain(rle->rl_pixel,rle); + count --; + } else if (count >= n){ + rle->rl_table_max = n; + rle_output_plain(rle->rl_basecode+n-2,rle); + count -= n; + } else if (count == 1){ + rle->rl_table_max ++; + rle_output_plain(rle->rl_pixel,rle); + count = 0; + } else { + rle->rl_table_max ++; + rle_output_plain(rle->rl_basecode+count-2,rle); + count = 0; + } + if (rle->out_count == 0) n = 1; else n ++; + } + rle_reset_out_clear(rle); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_reset_out_clear(struct_RLE* rle) +{ + rle->out_clear = rle->out_clear_init; + if (rle->out_count >= rle->out_clear){ + rle_output(rle->code_clear,rle); + rle_clear(rle); + } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_flush_withtable(int count, struct_RLE* rle) +{ + int repmax; + int repleft; + int leftover; + + repmax = count / rle->rl_table_max; + leftover = count % rle->rl_table_max; + repleft = (leftover ? 1 : 0); + if (rle->out_count+repmax+repleft > rle->max_ocodes){ + repmax = rle->max_ocodes - rle->out_count; + leftover = count - (repmax * rle->rl_table_max); + repleft = 1 + rle_compute_triangle_count(leftover,rle->max_ocodes); + } + if (1+rle_compute_triangle_count(count,rle->max_ocodes) < (unsigned int)(repmax+repleft)){ + rle_output(rle->code_clear,rle); + rle_clear(rle); + rle_flush_fromclear(count,rle); + return; + } + rle->out_clear = rle->max_ocodes; + for (;repmax>0;repmax--) rle_output_plain(rle->rl_basecode+rle->rl_table_max-2,rle); + if (leftover){ + if (rle->just_cleared){ + rle_flush_fromclear(leftover,rle); + } else if (leftover == 1){ + rle_output_plain(rle->rl_pixel,rle); + } else { + rle_output_plain(rle->rl_basecode+leftover-2,rle); + } + } + rle_reset_out_clear(rle); +} +//////////////////////////////////////////////////////////////////////////////// +unsigned int CxImageGIF::rle_compute_triangle_count(unsigned int count, unsigned int nrepcodes) +{ + unsigned int perrep; + unsigned int cost; + + cost = 0; + perrep = (nrepcodes * (nrepcodes+1)) / 2; + while (count >= perrep){ + cost += nrepcodes; + count -= perrep; + } + if (count > 0){ + unsigned int n; + n = rle_isqrt(count); + while ((n*(n+1)) >= 2*count) n --; + while ((n*(n+1)) < 2*count) n ++; + cost += n; + } + return(cost); +} +//////////////////////////////////////////////////////////////////////////////// +unsigned int CxImageGIF::rle_isqrt(unsigned int x) +{ + unsigned int r; + unsigned int v; + + if (x < 2) return(x); + for (v=x,r=1;v;v>>=2,r<<=1) ; + while (1){ + v = ((x / r) + r) / 2; + if ((v == r) || (v == r+1)) return(r); + r = v; + } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_flush_clearorrep(int count, struct_RLE* rle) +{ + int withclr; + withclr = 1 + rle_compute_triangle_count(count,rle->max_ocodes); + if (withclr < count) { + rle_output(rle->code_clear,rle); + rle_clear(rle); + rle_flush_fromclear(count,rle); + } else { + for (;count>0;count--) rle_output_plain(rle->rl_pixel,rle); + } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_write_block(struct_RLE* rle) +{ + g_outfile->PutC((BYTE)rle->oblen); + g_outfile->Write(rle->oblock,1,rle->oblen); + rle->oblen = 0; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_block_out(unsigned char c, struct_RLE* rle) +{ + rle->oblock[rle->oblen++] = c; + if (rle->oblen >= 255) rle_write_block(rle); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_block_flush(struct_RLE* rle) +{ + if (rle->oblen > 0) rle_write_block(rle); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_output(int val, struct_RLE* rle) +{ + rle->obuf |= val << rle->obits; + rle->obits += rle->out_bits; + while (rle->obits >= 8){ + rle_block_out(rle->obuf&0xff,rle); + rle->obuf >>= 8; + rle->obits -= 8; + } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::rle_output_flush(struct_RLE* rle) +{ + if (rle->obits > 0) rle_block_out(rle->obuf,rle); + rle_block_flush(rle); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageGIF::compressRLE( int init_bits, CxFile* outfile) +{ + g_init_bits = init_bits; + g_outfile = outfile; + + struct_RLE rle; + rle.code_clear = 1 << (init_bits - 1); + rle.code_eof = rle.code_clear + 1; + rle.rl_basecode = rle.code_eof + 1; + rle.out_bump_init = (1 << (init_bits - 1)) - 1; + rle.out_clear_init = (init_bits <= 3) ? 9 : (rle.out_bump_init-1); + rle.out_bits_init = init_bits; + rle.max_ocodes = (1 << MAXBITSCODES) - ((1 << (rle.out_bits_init - 1)) + 3); + rle.rl_count = 0; + rle_clear(&rle); + rle.obuf = 0; + rle.obits = 0; + rle.oblen = 0; + + rle_output(rle.code_clear,&rle); + + int c; + while (1){ + c = GifNextPixel(); + if ((rle.rl_count > 0) && (c != rle.rl_pixel)) rle_flush(&rle); + if (c == EOF) break; + if (rle.rl_pixel == c){ + rle.rl_count++; + } else { + rle.rl_pixel = c; + rle.rl_count = 1; + } + } + rle_output(rle.code_eof,&rle); + rle_output_flush(&rle); +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_GIF diff --git a/SlnkDWFImpl/CxImage/CxImage/ximagif.h b/SlnkDWFImpl/CxImage/CxImage/ximagif.h new file mode 100644 index 0000000..c7b7af6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximagif.h @@ -0,0 +1,248 @@ +/* + * File: ximagif.h + * Purpose: GIF Image Class Loader and Writer + */ +/* ========================================================== + * CxImageGIF (c) 07/Aug/2001 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * Special thanks to Troels Knakkergaard for new features, enhancements and bugfixes + * + * original CImageGIF and CImageIterator implementation are: + * Copyright: (c) 1995, Alejandro Aguilar Sierra + * + * 6/15/97 Randy Spann: Added GIF87a writing support + * R.Spann@ConnRiver.net + * + * DECODE.C - An LZW decoder for GIF + * Copyright (C) 1987, by Steven A. Bennett + * Copyright (C) 1994, C++ version by Alejandro Aguilar Sierra + * + * In accordance with the above, I want to credit Steve Wilhite who wrote + * the code which this is heavily inspired by... + * + * GIF and 'Graphics Interchange Format' are trademarks (tm) of + * Compuserve, Incorporated, an H&R Block Company. + * + * Release Notes: This file contains a decoder routine for GIF images + * which is similar, structurally, to the original routine by Steve Wilhite. + * It is, however, somewhat noticably faster in most cases. + * + * ========================================================== + */ + +#if !defined(__ximaGIF_h) +#define __ximaGIF_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_GIF + +typedef short int code_int; + +/* Various error codes used by decoder */ +#define OUT_OF_MEMORY -10 +#define BAD_CODE_SIZE -20 +#define READ_ERROR -1 +#define WRITE_ERROR -2 +#define OPEN_ERROR -3 +#define CREATE_ERROR -4 +#define MAX_CODES 4095 +#define GIFBUFTAM 16383 +#define TRANSPARENCY_CODE 0xF9 + +//LZW GIF Image compression +#define MAXBITSCODES 12 +#define HSIZE 5003 /* 80% occupancy */ +#define MAXCODE(n_bits) (((code_int) 1 << (n_bits)) - 1) +#define HashTabOf(i) htab[i] +#define CodeTabOf(i) codetab[i] + + +class CImageIterator; +class DLL_EXP CxImageGIF: public CxImage +{ +#pragma pack(1) + +typedef struct tag_gifgce{ + BYTE transpcolflag:1; + BYTE userinputflag:1; + BYTE dispmeth:3; + BYTE res:3; + WORD delaytime; + BYTE transpcolindex; +} struct_gifgce; + +typedef struct tag_dscgif{ /* Logic Screen Descriptor */ + char header[6]; /* Firma and version */ + WORD scrwidth; + WORD scrheight; + char pflds; + char bcindx; + char pxasrat; +} struct_dscgif; + +typedef struct tag_image{ /* Image Descriptor */ + WORD l; + WORD t; + WORD w; + WORD h; + BYTE pf; +} struct_image; + +typedef struct tag_TabCol{ /* Tabla de colores */ + short colres; /* color resolution */ + short sogct; /* size of global color table */ + rgb_color paleta[256]; /* paleta */ +} struct_TabCol; + +typedef struct tag_RLE{ + int rl_pixel; + int rl_basecode; + int rl_count; + int rl_table_pixel; + int rl_table_max; + int just_cleared; + int out_bits; + int out_bits_init; + int out_count; + int out_bump; + int out_bump_init; + int out_clear; + int out_clear_init; + int max_ocodes; + int code_clear; + int code_eof; + unsigned int obuf; + int obits; + unsigned char oblock[256]; + int oblen; +} struct_RLE; +#pragma pack() + +public: + CxImageGIF(): CxImage(CXIMAGE_FORMAT_GIF) {m_loops=0; m_dispmeth=0; m_comment[0]='\0';} + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_GIF);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_GIF);} + + bool Decode(CxFile * fp); + bool Decode(FILE *fp) { CxIOFile file(fp); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * fp); + bool Encode(CxFile * fp, CxImage ** pImages, int pagecount, bool bLocalColorMap = false); + bool Encode(FILE *fp) { CxIOFile file(fp); return Encode(&file); } + bool Encode(FILE *fp, CxImage ** pImages, int pagecount, bool bLocalColorMap = false) + { CxIOFile file(fp); return Encode(&file, pImages, pagecount, bLocalColorMap); } +#endif // CXIMAGE_SUPPORT_ENCODE + + void SetLoops(int loops); + long GetLoops(); + void SetComment(const char* sz_comment_in); + void GetComment(char* sz_comment_out); + void SetDisposalMethod(int dm); + long GetDisposalMethod(); + +protected: + bool DecodeExtension(CxFile *fp); + void EncodeHeader(CxFile *fp); + void EncodeLoopExtension(CxFile *fp); + void EncodeExtension(CxFile *fp); + void EncodeBody(CxFile *fp, bool bLocalColorMap = false); + void EncodeComment(CxFile *fp); + bool EncodeRGB(CxFile *fp); + void GifMix(CxImage & imgsrc2, struct_image & imgdesc); + + struct_gifgce gifgce; + + int curx, cury; + long CountDown; + unsigned long cur_accum; + int cur_bits; + int interlaced, iypos, istep, iheight, ipass; + int ibf; + int ibfmax; + BYTE buf[GIFBUFTAM + 1]; +// Implementation + int GifNextPixel (); + void Putword (int w, CxFile* fp ); + void compressNONE (int init_bits, CxFile* outfile); + void compressLZW (int init_bits, CxFile* outfile); + void output (code_int code ); + void cl_hash (long hsize); + void char_out (int c); + void flush_char (); + short init_exp(short size); + short get_next_code(CxFile*); + short decoder(CxFile*, CImageIterator* iter, short linewidth, int &bad_code_count); + int get_byte(CxFile*); + int out_line(CImageIterator* iter, unsigned char *pixels, int linelen); + int get_num_frames(CxFile *f,struct_TabCol* TabColSrc,struct_dscgif* dscgif); + long seek_next_image(CxFile* fp, long position); + + short curr_size; /* The current code size */ + short clear; /* Value for a clear code */ + short ending; /* Value for a ending code */ + short newcodes; /* First available code */ + short top_slot; /* Highest code for current size */ + short slot; /* Last read code */ + + /* The following static variables are used + * for seperating out codes */ + short navail_bytes; /* # bytes left in block */ + short nbits_left; /* # bits left in current BYTE */ + BYTE b1; /* Current BYTE */ + BYTE byte_buff[257]; /* Current block */ + BYTE *pbytes; /* Pointer to next BYTE in block */ + /* The reason we have these seperated like this instead of using + * a structure like the original Wilhite code did, is because this + * stuff generally produces significantly faster code when compiled... + * This code is full of similar speedups... (For a good book on writing + * C for speed or for space optomisation, see Efficient C by Tom Plum, + * published by Plum-Hall Associates...) + */ + BYTE stack[MAX_CODES + 1]; /* Stack for storing pixels */ + BYTE suffix[MAX_CODES + 1]; /* Suffix table */ + WORD prefix[MAX_CODES + 1]; /* Prefix linked list */ + +//LZW GIF Image compression routines + long htab [HSIZE]; + unsigned short codetab [HSIZE]; + int n_bits; /* number of bits/code */ + code_int maxcode; /* maximum code, given n_bits */ + code_int free_ent; /* first unused entry */ + int clear_flg; + int g_init_bits; + CxFile* g_outfile; + int ClearCode; + int EOFCode; + + int a_count; + char accum[256]; + + char m_comment[256]; + int m_loops; + int m_dispmeth; + +//RLE compression routines + void compressRLE( int init_bits, CxFile* outfile); + void rle_clear(struct_RLE* rle); + void rle_flush(struct_RLE* rle); + void rle_flush_withtable(int count, struct_RLE* rle); + void rle_flush_clearorrep(int count, struct_RLE* rle); + void rle_flush_fromclear(int count,struct_RLE* rle); + void rle_output_plain(int c,struct_RLE* rle); + void rle_reset_out_clear(struct_RLE* rle); + unsigned int rle_compute_triangle_count(unsigned int count, unsigned int nrepcodes); + unsigned int rle_isqrt(unsigned int x); + void rle_write_block(struct_RLE* rle); + void rle_block_out(unsigned char c, struct_RLE* rle); + void rle_block_flush(struct_RLE* rle); + void rle_output(int val, struct_RLE* rle); + void rle_output_flush(struct_RLE* rle); +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximahist.cpp b/SlnkDWFImpl/CxImage/CxImage/ximahist.cpp new file mode 100644 index 0000000..2b2a2e8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximahist.cpp @@ -0,0 +1,649 @@ +// xImaHist.cpp : histogram functions +/* 28/01/2004 v1.00 - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_DSP + +//////////////////////////////////////////////////////////////////////////////// +long CxImage::Histogram(long* red, long* green, long* blue, long* gray, long colorspace) +{ + if (!pDib) return 0; + RGBQUAD color; + + if (red) memset(red,0,256*sizeof(long)); + if (green) memset(green,0,256*sizeof(long)); + if (blue) memset(blue,0,256*sizeof(long)); + if (gray) memset(gray,0,256*sizeof(long)); + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + + for(long y=ymin; yn) n=red[i]; + if (green && green[i]>n) n=green[i]; + if (blue && blue[i]>n) n=blue[i]; + if (gray && gray[i]>n) n=gray[i]; + } + + return n; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * HistogramStretch + * \param method: 0 = luminance (default), 1 = linked channels , 2 = independent channels. + * \return true if everything is ok + * \author [dave] and [nipper] + */ +bool CxImage::HistogramStretch(long method) +{ + if (!pDib) return false; + + if ((head.biBitCount==8) && IsGrayScale()){ + // get min/max info + BYTE minc = 255, maxc = 0; + BYTE gray; + long y; + + double dbScaler = 50.0/head.biHeight; + + for (y=0; y maxc) maxc = gray; + } + } + + if (minc == 0 && maxc == 255) return true; + + // calculate LUT + BYTE lut[256]; + BYTE range = maxc - minc; + if (range != 0){ + for (long x = minc; x <= maxc; x++){ + lut[x] = (BYTE)(255 * (x - minc) / range); + } + } else lut[minc] = minc; + + for (y=0; y + // get min/max info + BYTE minc = 255, maxc = 0; + RGBQUAD color; + long y; + + for (y=0; y maxc) maxc = color.rgbRed; + if (color.rgbBlue > maxc) maxc = color.rgbBlue; + if (color.rgbGreen > maxc) maxc = color.rgbGreen; + } + } + + if (minc == 0 && maxc == 255) + return true; + + // calculate LUT + BYTE lut[256]; + BYTE range = maxc - minc; + + if (range != 0){ + for (long x = minc; x <= maxc; x++){ + lut[x] = (BYTE)(255 * (x - minc) / range); + } + } else lut[minc] = minc; + + // normalize image + double dbScaler = 100.0/head.biHeight; + + for (y=0; y + // get min/max info + BYTE minR = 255, maxR = 0; + BYTE minG = 255, maxG = 0; + BYTE minB = 255, maxB = 0; + RGBQUAD color; + long y; + + for (y=0; y maxR) maxR = color.rgbRed; + if (color.rgbBlue > maxB) maxB = color.rgbBlue; + if (color.rgbGreen > maxG) maxG = color.rgbGreen; + } + } + + if (minR == 0 && maxR == 255 && minG == 0 && maxG == 255 && minB == 0 && maxB == 255) + return true; + + // calculate LUT + BYTE lutR[256]; + BYTE range = maxR - minR; + if (range != 0) { + for (long x = minR; x <= maxR; x++){ + lutR[x] = (BYTE)(255 * (x - minR) / range); + } + } else lutR[minR] = minR; + + BYTE lutG[256]; + range = maxG - minG; + if (range != 0) { + for (long x = minG; x <= maxG; x++){ + lutG[x] = (BYTE)(255 * (x - minG) / range); + } + } else lutG[minG] = minG; + + BYTE lutB[256]; + range = maxB - minB; + if (range != 0) { + for (long x = minB; x <= maxB; x++){ + lutB[x] = (BYTE)(255 * (x - minB) / range); + } + } else lutB[minB] = minB; + + // normalize image + double dbScaler = 100.0/head.biHeight; + + for (y=0; y + // S = ( R - C ) ( B - A / D - C ) + double alimit = 0.0; + double blimit = 255.0; + double lowerc = 255.0; + double upperd = 0.0; + double tmpGray; + + RGBQUAD color; + RGBQUAD yuvClr; + double stretcheds; + + if ( head.biClrUsed == 0 ){ + long x, y, xmin, xmax, ymin, ymax; + xmin = ymin = 0; + xmax = head.biWidth; + ymax = head.biHeight; + + for( y = ymin; y < ymax; y++ ){ + info.nProgress = (long)(50*y/ymax); + if (info.nEscape) break; + for( x = xmin; x < xmax; x++ ){ + color = GetPixelColor( x, y ); + tmpGray = RGB2GRAY(color.rgbRed, color.rgbGreen, color.rgbBlue); + if ( tmpGray < lowerc ) lowerc = tmpGray; + if ( tmpGray > upperd ) upperd = tmpGray; + } + } + if (upperd==lowerc) return false; + + for( y = ymin; y < ymax; y++ ){ + info.nProgress = (long)(50+50*y/ymax); + if (info.nEscape) break; + for( x = xmin; x < xmax; x++ ){ + + color = GetPixelColor( x, y ); + yuvClr = RGBtoYUV(color); + + // Stretch Luminance + tmpGray = (double)yuvClr.rgbRed; + stretcheds = (double)(tmpGray - lowerc) * ( (blimit - alimit) / (upperd - lowerc) ); // + alimit; + if ( stretcheds < 0.0 ) stretcheds = 0.0; + else if ( stretcheds > 255.0 ) stretcheds = 255.0; + yuvClr.rgbRed = (BYTE)stretcheds; + + color = YUVtoRGB(yuvClr); + SetPixelColor( x, y, color ); + } + } + } else { + DWORD j; + for( j = 0; j < head.biClrUsed; j++ ){ + color = GetPaletteColor( (BYTE)j ); + tmpGray = RGB2GRAY(color.rgbRed, color.rgbGreen, color.rgbBlue); + if ( tmpGray < lowerc ) lowerc = tmpGray; + if ( tmpGray > upperd ) upperd = tmpGray; + } + if (upperd==lowerc) return false; + + for( j = 0; j < head.biClrUsed; j++ ){ + + color = GetPaletteColor( (BYTE)j ); + yuvClr = RGBtoYUV( color ); + + // Stretch Luminance + tmpGray = (double)yuvClr.rgbRed; + stretcheds = (double)(tmpGray - lowerc) * ( (blimit - alimit) / (upperd - lowerc) ); // + alimit; + if ( stretcheds < 0.0 ) stretcheds = 0.0; + else if ( stretcheds > 255.0 ) stretcheds = 255.0; + yuvClr.rgbRed = (BYTE)stretcheds; + + color = YUVtoRGB(yuvClr); + SetPaletteColor( (BYTE)j, color ); + } + } + } + } + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +// HistogramEqualize function by : dave(at)posortho(dot)com +bool CxImage::HistogramEqualize() +{ + if (!pDib) return false; + + int histogram[256]; + int map[256]; + int equalize_map[256]; + int x, y, i, j; + RGBQUAD color; + RGBQUAD yuvClr; + unsigned int YVal, high, low; + + memset( &histogram, 0, sizeof(int) * 256 ); + memset( &map, 0, sizeof(int) * 256 ); + memset( &equalize_map, 0, sizeof(int) * 256 ); + + // form histogram + for(y=0; y < head.biHeight; y++){ + info.nProgress = (long)(50*y/head.biHeight); + if (info.nEscape) break; + for(x=0; x < head.biWidth; x++){ + color = GetPixelColor( x, y ); + YVal = (unsigned int)RGB2GRAY(color.rgbRed, color.rgbGreen, color.rgbBlue); + histogram[YVal]++; + } + } + + // integrate the histogram to get the equalization map. + j = 0; + for(i=0; i <= 255; i++){ + j += histogram[i]; + map[i] = j; + } + + // equalize + low = map[0]; + high = map[255]; + if (low == high) return false; + for( i = 0; i <= 255; i++ ){ + equalize_map[i] = (unsigned int)((((double)( map[i] - low ) ) * 255) / ( high - low ) ); + } + + // stretch the histogram + if(head.biClrUsed == 0){ // No Palette + for( y = 0; y < head.biHeight; y++ ){ + info.nProgress = (long)(50+50*y/head.biHeight); + if (info.nEscape) break; + for( x = 0; x < head.biWidth; x++ ){ + + color = GetPixelColor( x, y ); + yuvClr = RGBtoYUV(color); + + yuvClr.rgbRed = (BYTE)equalize_map[yuvClr.rgbRed]; + + color = YUVtoRGB(yuvClr); + SetPixelColor( x, y, color ); + } + } + } else { // Palette + for( i = 0; i < (int)head.biClrUsed; i++ ){ + + color = GetPaletteColor((BYTE)i); + yuvClr = RGBtoYUV(color); + + yuvClr.rgbRed = (BYTE)equalize_map[yuvClr.rgbRed]; + + color = YUVtoRGB(yuvClr); + SetPaletteColor( (BYTE)i, color ); + } + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +// HistogramNormalize function by : dave(at)posortho(dot)com +bool CxImage::HistogramNormalize() +{ + if (!pDib) return false; + + int histogram[256]; + int threshold_intensity, intense; + int x, y, i; + unsigned int normalize_map[256]; + unsigned int high, low, YVal; + + RGBQUAD color; + RGBQUAD yuvClr; + + memset( &histogram, 0, sizeof( int ) * 256 ); + memset( &normalize_map, 0, sizeof( unsigned int ) * 256 ); + + // form histogram + for(y=0; y < head.biHeight; y++){ + info.nProgress = (long)(50*y/head.biHeight); + if (info.nEscape) break; + for(x=0; x < head.biWidth; x++){ + color = GetPixelColor( x, y ); + YVal = (unsigned int)RGB2GRAY(color.rgbRed, color.rgbGreen, color.rgbBlue); + histogram[YVal]++; + } + } + + // find histogram boundaries by locating the 1 percent levels + threshold_intensity = ( head.biWidth * head.biHeight) / 100; + + intense = 0; + for( low = 0; low < 255; low++ ){ + intense += histogram[low]; + if( intense > threshold_intensity ) break; + } + + intense = 0; + for( high = 255; high != 0; high--){ + intense += histogram[ high ]; + if( intense > threshold_intensity ) break; + } + + if ( low == high ){ + // Unreasonable contrast; use zero threshold to determine boundaries. + threshold_intensity = 0; + intense = 0; + for( low = 0; low < 255; low++){ + intense += histogram[low]; + if( intense > threshold_intensity ) break; + } + intense = 0; + for( high = 255; high != 0; high-- ){ + intense += histogram [high ]; + if( intense > threshold_intensity ) break; + } + } + if( low == high ) return false; // zero span bound + + // Stretch the histogram to create the normalized image mapping. + for(i = 0; i <= 255; i++){ + if ( i < (int) low ){ + normalize_map[i] = 0; + } else { + if(i > (int) high) + normalize_map[i] = 255; + else + normalize_map[i] = ( 255 - 1) * ( i - low) / ( high - low ); + } + } + + // Normalize + if( head.biClrUsed == 0 ){ + for( y = 0; y < head.biHeight; y++ ){ + info.nProgress = (long)(50+50*y/head.biHeight); + if (info.nEscape) break; + for( x = 0; x < head.biWidth; x++ ){ + + color = GetPixelColor( x, y ); + yuvClr = RGBtoYUV( color ); + + yuvClr.rgbRed = (BYTE)normalize_map[yuvClr.rgbRed]; + + color = YUVtoRGB( yuvClr ); + SetPixelColor( x, y, color ); + } + } + } else { + for(i = 0; i < (int)head.biClrUsed; i++){ + + color = GetPaletteColor( (BYTE)i ); + yuvClr = RGBtoYUV( color ); + + yuvClr.rgbRed = (BYTE)normalize_map[yuvClr.rgbRed]; + + color = YUVtoRGB( yuvClr ); + SetPaletteColor( (BYTE)i, color ); + } + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +// HistogramLog function by : dave(at)posortho(dot)com +bool CxImage::HistogramLog() +{ + if (!pDib) return false; + + //q(i,j) = 255/log(1 + |high|) * log(1 + |p(i,j)|); + int x, y, i; + RGBQUAD color; + RGBQUAD yuvClr; + + unsigned int YVal, high = 1; + + // Find Highest Luminance Value in the Image + if( head.biClrUsed == 0 ){ // No Palette + for(y=0; y < head.biHeight; y++){ + info.nProgress = (long)(50*y/head.biHeight); + if (info.nEscape) break; + for(x=0; x < head.biWidth; x++){ + color = GetPixelColor( x, y ); + YVal = (unsigned int)RGB2GRAY(color.rgbRed, color.rgbGreen, color.rgbBlue); + if (YVal > high ) high = YVal; + } + } + } else { // Palette + for(i = 0; i < (int)head.biClrUsed; i++){ + color = GetPaletteColor((BYTE)i); + YVal = (unsigned int)RGB2GRAY(color.rgbRed, color.rgbGreen, color.rgbBlue); + if (YVal > high ) high = YVal; + } + } + + // Logarithm Operator + double k = 255.0 / ::log( 1.0 + (double)high ); + if( head.biClrUsed == 0 ){ + for( y = 0; y < head.biHeight; y++ ){ + info.nProgress = (long)(50+50*y/head.biHeight); + if (info.nEscape) break; + for( x = 0; x < head.biWidth; x++ ){ + + color = GetPixelColor( x, y ); + yuvClr = RGBtoYUV( color ); + + yuvClr.rgbRed = (BYTE)(k * ::log( 1.0 + (double)yuvClr.rgbRed ) ); + + color = YUVtoRGB( yuvClr ); + SetPixelColor( x, y, color ); + } + } + } else { + for(i = 0; i < (int)head.biClrUsed; i++){ + + color = GetPaletteColor( (BYTE)i ); + yuvClr = RGBtoYUV( color ); + + yuvClr.rgbRed = (BYTE)(k * ::log( 1.0 + (double)yuvClr.rgbRed ) ); + + color = YUVtoRGB( yuvClr ); + SetPaletteColor( (BYTE)i, color ); + } + } + + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +// HistogramRoot function by : dave(at)posortho(dot)com +bool CxImage::HistogramRoot() +{ + if (!pDib) return false; + //q(i,j) = sqrt(|p(i,j)|); + + int x, y, i; + RGBQUAD color; + RGBQUAD yuvClr; + double dtmp; + unsigned int YVal, high = 1; + + // Find Highest Luminance Value in the Image + if( head.biClrUsed == 0 ){ // No Palette + for(y=0; y < head.biHeight; y++){ + info.nProgress = (long)(50*y/head.biHeight); + if (info.nEscape) break; + for(x=0; x < head.biWidth; x++){ + color = GetPixelColor( x, y ); + YVal = (unsigned int)RGB2GRAY(color.rgbRed, color.rgbGreen, color.rgbBlue); + if (YVal > high ) high = YVal; + } + } + } else { // Palette + for(i = 0; i < (int)head.biClrUsed; i++){ + color = GetPaletteColor((BYTE)i); + YVal = (unsigned int)RGB2GRAY(color.rgbRed, color.rgbGreen, color.rgbBlue); + if (YVal > high ) high = YVal; + } + } + + // Root Operator + double k = 128.0 / ::log( 1.0 + (double)high ); + if( head.biClrUsed == 0 ){ + for( y = 0; y < head.biHeight; y++ ){ + info.nProgress = (long)(50+50*y/head.biHeight); + if (info.nEscape) break; + for( x = 0; x < head.biWidth; x++ ){ + + color = GetPixelColor( x, y ); + yuvClr = RGBtoYUV( color ); + + dtmp = k * ::sqrt( (double)yuvClr.rgbRed ); + if ( dtmp > 255.0 ) dtmp = 255.0; + if ( dtmp < 0 ) dtmp = 0; + yuvClr.rgbRed = (BYTE)dtmp; + + color = YUVtoRGB( yuvClr ); + SetPixelColor( x, y, color ); + } + } + } else { + for(i = 0; i < (int)head.biClrUsed; i++){ + + color = GetPaletteColor( (BYTE)i ); + yuvClr = RGBtoYUV( color ); + + dtmp = k * ::sqrt( (double)yuvClr.rgbRed ); + if ( dtmp > 255.0 ) dtmp = 255.0; + if ( dtmp < 0 ) dtmp = 0; + yuvClr.rgbRed = (BYTE)dtmp; + + color = YUVtoRGB( yuvClr ); + SetPaletteColor( (BYTE)i, color ); + } + } + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximaico.cpp b/SlnkDWFImpl/CxImage/CxImage/ximaico.cpp new file mode 100644 index 0000000..8650c39 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximaico.cpp @@ -0,0 +1,299 @@ +/* + * File: ximaico.cpp + * Purpose: Platform Independent ICON Image Class Loader and Writer (MS version) + * 07/Aug/2001 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximaico.h" + +#if CXIMAGE_SUPPORT_ICO + +//////////////////////////////////////////////////////////////////////////////// +bool CxImageICO::Decode(CxFile *hFile) +{ + if (hFile==NULL) return false; + + DWORD off = hFile->Tell(); // + int page=info.nFrame; //internal icon structure indexes + + // read the first part of the header + ICONHEADER icon_header; + hFile->Read(&icon_header,sizeof(ICONHEADER),1); + // check if it's an icon or a cursor + if ((icon_header.idReserved == 0) && ((icon_header.idType == 1)||(icon_header.idType == 2))) { + + info.nNumFrames = icon_header.idCount; + + // load the icon descriptions + ICONDIRENTRY *icon_list = (ICONDIRENTRY *)malloc(icon_header.idCount * sizeof(ICONDIRENTRY)); + int c; + for (c = 0; c < icon_header.idCount; c++) + hFile->Read(icon_list + c, sizeof(ICONDIRENTRY), 1); + + if ((page>=0)&&(page + BITMAPINFOHEADER bih; + hFile->Seek(off + icon_list[page].dwImageOffset, SEEK_SET); + hFile->Read(&bih,sizeof(BITMAPINFOHEADER),1); + c = bih.biBitCount; + + // allocate memory for one icon + Create(icon_list[page].bWidth,icon_list[page].bHeight, c, CXIMAGE_FORMAT_ICO); //image creation + + // read the palette + RGBQUAD pal[256]; + hFile->Read(pal,head.biClrUsed*sizeof(RGBQUAD), 1); + SetPalette(pal,head.biClrUsed); //palette assign + + //read the icon + if (c<=24){ + hFile->Read(info.pImage, head.biSizeImage, 1); + } else { // 32 bit icon + BYTE* dst = info.pImage; + BYTE* buf=(BYTE*)malloc(4*head.biHeight*head.biWidth); + BYTE* src = buf; + hFile->Read(buf, 4*head.biHeight*head.biWidth, 1); +#if CXIMAGE_SUPPORT_ALPHA + if (!AlphaIsValid()) AlphaCreate(); +#endif //CXIMAGE_SUPPORT_ALPHA + for (long y = 0; y < head.biHeight; y++) { + for(long x=0;xRead(mask, masksize, 1)){ + + bool bGoodMask=false; + for (int im=0;im>3)]>>(7-x%8))&0x01)){ + AlphaSet(x,y,0); + bNeedAlpha=true; + } + } + } + if (!bNeedAlpha) AlphaDelete(); +#endif //CXIMAGE_SUPPORT_ALPHA + + if (c==24){ //check if there is only one transparent color + RGBQUAD cc,ct; + long* pcc = (long*)&cc; + long* pct = (long*)&ct; + int nTransColors=0; + for (int y = 0; y < head.biHeight; y++){ + for (int x = 0; x < head.biWidth; x++){ + if (((mask[y*maskwdt+(x>>3)] >> (7-x%8)) & 0x01)){ + cc = GetPixelColor(x,y,false); + if (nTransColors==0){ + nTransColors++; + ct = cc; + } else { + if (*pct!=*pcc){ + nTransColors++; + } + } + } + } + } + if (nTransColors==1){ + SetTransColor(ct); + SetTransIndex(0); +#if CXIMAGE_SUPPORT_ALPHA + AlphaDelete(); //because we have a unique transparent color in the image +#endif //CXIMAGE_SUPPORT_ALPHA + } + } + + // - Transparency support w/o Alpha support + if (c <= 8){ // only for icons with less than 256 colors (XP icons need alpha). + + // find a color index, which is not used in the image + // it is almost sure to find one, bcs. nobody uses all possible colors for an icon + + BYTE colorsUsed[256]; + memset(colorsUsed, 0, sizeof(colorsUsed)); + + for (int y = 0; y < head.biHeight; y++){ + for (int x = 0; x < head.biWidth; x++){ + colorsUsed[GetPixelIndex(x,y)] = 1; + } + } + + int iTransIdx = -1; + for (int x = 0; x < (int)head.biClrUsed; x++){ + if (colorsUsed[x] == 0){ + iTransIdx = x; // this one is not in use. we may use it as transparent color + break; + } + } + + // Go thru image and set unused color as transparent index if needed + if (iTransIdx >= 0){ + bool bNeedTrans = false; + for (int y = 0; y < head.biHeight; y++){ + for (int x = 0; x < head.biWidth; x++){ + // AND mask (Each Byte represents 8 Pixels) + if (((mask[y*maskwdt+(x>>3)] >> (7-x%8)) & 0x01)){ + // AND mask is set (!=0). This is a transparent part + SetPixelIndex(x, y, iTransIdx); + bNeedTrans = true; + } + } + } + // set transparent index if needed + if (bNeedTrans) SetTransIndex(iTransIdx); +#if CXIMAGE_SUPPORT_ALPHA + AlphaDelete(); //because we have a transparent color in the palette +#endif //CXIMAGE_SUPPORT_ALPHA + } + } + } else { + SetTransIndex(0); //empty mask, set black as transparent color + Negative(); + } + } + free(mask); + + free(icon_list); + // icon has been loaded successfully! + return true; + } + free(icon_list); + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImageICO::Encode(CxFile * hFile) +{ + if (EncodeSafeCheck(hFile)) return false; + + //check format limits + if ((head.biWidth>255)||(head.biHeight>255)){ + strcpy(info.szLastError,"Can't save this image as icon"); + return false; + } + + //prepare the palette struct + RGBQUAD* pal=GetPalette(); + if (head.biBitCount<=8 && pal==NULL) return false; + + int maskwdt=((head.biWidth+31)/32)*4; //mask line width + int masksize=head.biHeight * maskwdt; //size of mask + int bitcount=head.biBitCount; + int imagesize=head.biSizeImage; +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid() && head.biClrUsed==0){ + bitcount=32; + imagesize=4*head.biHeight*head.biWidth; + } +#endif + + //fill the icon headers + ICONHEADER icon_header={0,1,1}; + ICONDIRENTRY icon_list={(BYTE)head.biWidth,(BYTE)head.biHeight,(BYTE)head.biClrUsed ,0,0,(WORD)bitcount, + sizeof(BITMAPINFOHEADER)+head.biClrUsed*sizeof(RGBQUAD)+ + imagesize+masksize, + sizeof(ICONHEADER)+sizeof(ICONDIRENTRY)}; + BITMAPINFOHEADER bi={sizeof(BITMAPINFOHEADER),head.biWidth,2*head.biHeight,1,(WORD)bitcount, + 0,imagesize,0,0,0,0}; + + hFile->Write(&icon_header,sizeof(ICONHEADER),1); //write the headers + hFile->Write(&icon_list,sizeof(ICONDIRENTRY),1); + hFile->Write(&bi,sizeof(BITMAPINFOHEADER),1); + if (pal) hFile->Write(pal,head.biClrUsed*sizeof(RGBQUAD),1); //write palette + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid() && head.biClrUsed==0){ + BYTE* src = info.pImage; + BYTE* buf=(BYTE*)malloc(imagesize); + BYTE* dst = buf; + for (long y = 0; y < head.biHeight; y++) { + for(long x=0;xWrite(buf,imagesize, 1); + free(buf); + } else { + hFile->Write(info.pImage,imagesize,1); //write image + } +#else + hFile->Write(info.pImage,imagesize,1); //write image +#endif + + //save transparency mask + BYTE* mask=(BYTE*)calloc(masksize,1); //create empty AND/XOR masks + if (!mask) return false; + + //prepare the variables to build the mask + BYTE* iDst; + int pos,i; + RGBQUAD c={0,0,0,0}; + RGBQUAD ct = GetTransColor(); + long* pc = (long*)&c; + long* pct= (long*)&ct; + bool bTransparent = info.nBkgndIndex != -1; +#if CXIMAGE_SUPPORT_ALPHA + bool bAlphaPaletteIsValid = AlphaPaletteIsValid(); + bool bAlphaIsValid = AlphaIsValid(); +#endif + //build the mask + for (int y = 0; y < head.biHeight; y++) { + for (int x = 0; x < head.biWidth; x++) { + i=0; +#if CXIMAGE_SUPPORT_ALPHA + if (bAlphaIsValid && AlphaGet(x,y)==0) i=1; + if (bAlphaPaletteIsValid && GetPixelColor(x,y).rgbReserved==0) i=1; +#endif + c=GetPixelColor(x,y,false); + if (bTransparent && *pc==*pct) i=1; + iDst = mask + y*maskwdt + (x>>3); + pos = 7-x%8; + *iDst &= ~(0x01<Write(mask,masksize,1); + free(mask); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ICO + diff --git a/SlnkDWFImpl/CxImage/CxImage/ximaico.h b/SlnkDWFImpl/CxImage/CxImage/ximaico.h new file mode 100644 index 0000000..5698d70 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximaico.h @@ -0,0 +1,52 @@ +/* + * File: ximaico.h + * Purpose: ICON Image Class Loader and Writer + */ +/* ========================================================== + * CxImageICO (c) 07/Aug/2001 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * ========================================================== + */ +#if !defined(__ximaICO_h) +#define __ximaICO_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_ICO + +class CxImageICO: public CxImage +{ +typedef struct tagIconDirectoryEntry { + BYTE bWidth; + BYTE bHeight; + BYTE bColorCount; + BYTE bReserved; + WORD wPlanes; + WORD wBitCount; + DWORD dwBytesInRes; + DWORD dwImageOffset; +} ICONDIRENTRY; + +typedef struct tagIconDir { + WORD idReserved; + WORD idType; + WORD idCount; +} ICONHEADER; + +public: + CxImageICO(): CxImage(CXIMAGE_FORMAT_ICO) {} + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_ICO);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_ICO);} + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximainfo.cpp b/SlnkDWFImpl/CxImage/CxImage/ximainfo.cpp new file mode 100644 index 0000000..76bf495 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximainfo.cpp @@ -0,0 +1,388 @@ +// ximainfo.cpp : main attributes +/* 03/10/2004 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +//////////////////////////////////////////////////////////////////////////////// +/** + * \return the color used for transparency, and/or for background color + */ +RGBQUAD CxImage::GetTransColor() +{ + if (head.biBitCount<24 && info.nBkgndIndex != -1) return GetPaletteColor((BYTE)info.nBkgndIndex); + return info.nBkgndColor; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Gets the index used for transparency. Returns -1 for no transparancy. + */ +long CxImage::GetTransIndex() const +{ + return info.nBkgndIndex; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Sets the index used for transparency with 1, 4 and 8 bpp images. Set to -1 to remove the effect. + */ +void CxImage::SetTransIndex(long idx) +{ + info.nBkgndIndex = idx; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Sets the color used for transparency with 24 bpp images. + * You must call SetTransIndex(0) to enable the effect, SetTransIndex(-1) to disable it. + */ +void CxImage::SetTransColor(RGBQUAD rgb) +{ + rgb.rgbReserved=0; + info.nBkgndColor = rgb; +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::IsTransparent() const +{ + return info.nBkgndIndex>=0; // +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Returns true if the image has 256 colors or less. + */ +bool CxImage::IsIndexed() const +{ + return head.biClrUsed!=0; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \return 1 = indexed, 2 = RGB, 4 = RGBA + */ +BYTE CxImage::GetColorType() +{ + BYTE b = (BYTE)((head.biBitCount>8) ? 2 /*COLORTYPE_COLOR*/ : 1 /*COLORTYPE_PALETTE*/); +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) b = 4 /*COLORTYPE_ALPHA*/; +#endif //CXIMAGE_SUPPORT_ALPHA + return b; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \return Resolution for TIFF, JPEG, PNG and BMP formats. + */ +long CxImage::GetXDPI() const +{ + return info.xDPI; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \return Resolution for TIFF, JPEG, PNG and BMP formats. + */ +long CxImage::GetYDPI() const +{ + return info.yDPI; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Set resolution for TIFF, JPEG, PNG and BMP formats. + */ +void CxImage::SetXDPI(long dpi) +{ + if (dpi<=0) dpi=96; + info.xDPI = dpi; + head.biXPelsPerMeter = (long) floor(dpi * 10000.0 / 254.0 + 0.5); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Set resolution for TIFF, JPEG, PNG and BMP formats. + */ +void CxImage::SetYDPI(long dpi) +{ + if (dpi<=0) dpi=96; + info.yDPI = dpi; + head.biYPelsPerMeter = (long) floor(dpi * 10000.0 / 254.0 + 0.5); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \sa SetFlags + */ +DWORD CxImage::GetFlags() const +{ + return info.dwFlags; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Image flags, for future use + * \param flags + * - 0x??00000 = reserved for 16 bit, CMYK, multilayer + * - 0x00??0000 = blend modes + * - 0x0000???? = layer id or user flags + * + * \param bLockReservedFlags protects the "reserved" and "blend modes" flags + */ +void CxImage::SetFlags(DWORD flags, bool bLockReservedFlags) +{ + if (bLockReservedFlags) info.dwFlags = flags & 0x0000ffff; + else info.dwFlags = flags; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \sa SetCodecOption + */ +DWORD CxImage::GetCodecOption(DWORD imagetype) +{ + if (imagetype=head.biWidth) x=head.biWidth-(x % head.biWidth + 1); + if (y<0) y=((-y) % head.biHeight); + else if (y>=head.biHeight) y=head.biHeight-(y % head.biHeight + 1); + break; + default: + return; + }//switch +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * See OverflowCoordinates for integer version + * \author ***bd*** 2.2004 + */ +void CxImage::OverflowCoordinates(float &x, float &y, OverflowMethod const ofMethod) +{ + if (x>=0 && x=0 && y=head.biWidth) x=head.biWidth-((float)fmod(x, (float) head.biWidth) + 1); + if (y<0) y=(float)fmod(-y, (float) head.biHeight); + else if (y>=head.biHeight) y=head.biHeight-((float)fmod(y, (float) head.biHeight) + 1); + break; + default: + return; + }//switch +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * Method return pixel color. Different methods are implemented for out of bounds pixels. + * If an image has alpha channel, alpha value is returned in .RGBReserved. + * + * \param x,y : pixel coordinates + * \param ofMethod : out-of-bounds method: + * - OF_WRAP - wrap over to pixels on other side of the image + * - OF_REPEAT - repeat last pixel on the edge + * - OF_COLOR - return input value of color + * - OF_BACKGROUND - return background color (if not set, return input color) + * - OF_TRANSPARENT - return transparent pixel + * + * \param rplColor : input color (returned for out-of-bound coordinates in OF_COLOR mode and if other mode is not applicable) + * + * \return color : color of pixel + * \author ***bd*** 2.2004 + */ +RGBQUAD CxImage::GetPixelColorWithOverflow(long x, long y, OverflowMethod const ofMethod, RGBQUAD* const rplColor) +{ + RGBQUAD color; //color to return + if ((!IsInside(x,y)) || pDib==NULL) { //is pixel within bouns?: + //pixel is out of bounds or no DIB + if (rplColor!=NULL) + color=*rplColor; + else { + color.rgbRed=color.rgbGreen=color.rgbBlue=255; color.rgbReserved=0; //default replacement colour: white transparent + }//if + if (pDib==NULL) return color; + //pixel is out of bounds: + switch (ofMethod) { + case OM_TRANSPARENT: +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) { + //alpha transparency is supported and image has alpha layer + color.rgbReserved=0; + } else { +#endif //CXIMAGE_SUPPORT_ALPHA + //no alpha transparency + if (GetTransIndex()>=0) { + color=GetTransColor(); //single color transparency enabled (return transparent color) + }//if +#if CXIMAGE_SUPPORT_ALPHA + }//if +#endif //CXIMAGE_SUPPORT_ALPHA + return color; + case OM_BACKGROUND: + //return background color (if it exists, otherwise input value) + if (info.nBkgndIndex != -1) { + if (head.biBitCount<24) color = GetPaletteColor((BYTE)info.nBkgndIndex); + else color = info.nBkgndColor; + }//if + return color; + case OM_REPEAT: + case OM_WRAP: + case OM_MIRROR: + OverflowCoordinates(x,y,ofMethod); + break; + default: + //simply return replacement color (OM_COLOR and others) + return color; + }//switch + }//if + //just return specified pixel (it's within bounds) + return BlindGetPixelColor(x,y); +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * This method reconstructs image according to chosen interpolation method and then returns pixel (x,y). + * (x,y) can lie between actual image pixels. If (x,y) lies outside of image, method returns value + * according to overflow method. + * This method is very useful for geometrical image transformations, where destination pixel + * can often assume color value lying between source pixels. + * + * \param (x,y) - coordinates of pixel to return + * GPCI method recreates "analogue" image back from digital data, so x and y + * are float values and color value of point (1.1,1) will generally not be same + * as (1,1). Center of first pixel is at (0,0) and center of pixel right to it is (1,0). + * (0.5,0) is half way between these two pixels. + * \param inMethod - interpolation (reconstruction) method (kernel) to use: + * - IM_NEAREST_NEIGHBOUR - returns colour of nearest lying pixel (causes stairy look of + * processed images) + * - IM_BILINEAR - interpolates colour from four neighbouring pixels (softens image a bit) + * - IM_BICUBIC - interpolates from 16 neighbouring pixels (can produce "halo" artifacts) + * - IM_BICUBIC2 - interpolates from 16 neighbouring pixels (perhaps a bit less halo artifacts + than IM_BICUBIC) + * - IM_BSPLINE - interpolates from 16 neighbouring pixels (softens image, washes colours) + * (As far as I know, image should be prefiltered for this method to give + * good results... some other time :) ) + * This method uses bicubic interpolation kernel from CXImage 5.99a and older + * versions. + * - IM_LANCZOS - interpolates from 12*12 pixels (slow, ringing artifacts) + * + * \param ofMethod - overflow method (see comments at GetPixelColorWithOverflow) + * \param rplColor - pointer to color used for out of borders pixels in OM_COLOR mode + * (and other modes if colour can't calculated in a specified way) + * + * \return interpolated color value (including interpolated alpha value, if image has alpha layer) + * + * \author ***bd*** 2.2004 + */ +RGBQUAD CxImage::GetPixelColorInterpolated( + float x,float y, + InterpolationMethod const inMethod, + OverflowMethod const ofMethod, + RGBQUAD* const rplColor) +{ + //calculate nearest pixel + int xi=(int)(x); if (x<0) xi--; //these replace (incredibly slow) floor (Visual c++ 2003, AMD Athlon) + int yi=(int)(y); if (y<0) yi--; + RGBQUAD color; //calculated colour + + switch (inMethod) { + case IM_NEAREST_NEIGHBOUR: + return GetPixelColorWithOverflow((long)(x+0.5f), (long)(y+0.5f), ofMethod, rplColor); + default: { + //bilinear interpolation + if (xi<-1 || xi>=head.biWidth || yi<-1 || yi>=head.biHeight) { //all 4 points are outside bounds?: + switch (ofMethod) { + case OM_COLOR: case OM_TRANSPARENT: case OM_BACKGROUND: + //we don't need to interpolate anything with all points outside in this case + return GetPixelColorWithOverflow(-999, -999, ofMethod, rplColor); + default: + //recalculate coordinates and use faster method later on + OverflowCoordinates(x,y,ofMethod); + xi=(int)(x); if (x<0) xi--; //x and/or y have changed ... recalculate xi and yi + yi=(int)(y); if (y<0) yi--; + }//switch + }//if + //get four neighbouring pixels + if ((xi+1)=0 && (yi+1)=0 && head.biClrUsed==0) { + //all pixels are inside RGB24 image... optimize reading (and use fixed point arithmetic) + WORD wt1=(WORD)((x-xi)*256.0f), wt2=(WORD)((y-yi)*256.0f); + WORD wd=wt1*wt2>>8; + WORD wb=wt1-wd; + WORD wc=wt2-wd; + WORD wa=256-wt1-wc; + WORD wrr,wgg,wbb; + BYTE *pxptr=(BYTE*)info.pImage+yi*info.dwEffWidth+xi*3; + wbb=wa*(*pxptr++); wgg=wa*(*pxptr++); wrr=wa*(*pxptr++); + wbb+=wb*(*pxptr++); wgg+=wb*(*pxptr++); wrr+=wb*(*pxptr); + pxptr+=(info.dwEffWidth-5); //move to next row + wbb+=wc*(*pxptr++); wgg+=wc*(*pxptr++); wrr+=wc*(*pxptr++); + wbb+=wd*(*pxptr++); wgg+=wd*(*pxptr++); wrr+=wd*(*pxptr); + color.rgbRed=(BYTE) (wrr>>8); color.rgbGreen=(BYTE) (wgg>>8); color.rgbBlue=(BYTE) (wbb>>8); +#if CXIMAGE_SUPPORT_ALPHA + if (pAlpha) { + WORD waa; + //image has alpha layer... we have to do the same for alpha data + pxptr=AlphaGetPointer(xi,yi); //pointer to first byte + waa=wa*(*pxptr++); waa+=wb*(*pxptr); //first two pixels + pxptr+=(head.biWidth-1); //move to next row + waa+=wc*(*pxptr++); waa+=wd*(*pxptr); //and second row pixels + color.rgbReserved=(BYTE) (waa>>8); + } else +#endif + { //Alpha not supported or no alpha at all + color.rgbReserved = 0; + } + return color; + } else { + //default (slower) way to get pixels (not RGB24 or some pixels out of borders) + float t1=x-xi, t2=y-yi; + float d=t1*t2; + float b=t1-d; + float c=t2-d; + float a=1-t1-c; + RGBQUAD rgb11,rgb21,rgb12,rgb22; + rgb11=GetPixelColorWithOverflow(xi, yi, ofMethod, rplColor); + rgb21=GetPixelColorWithOverflow(xi+1, yi, ofMethod, rplColor); + rgb12=GetPixelColorWithOverflow(xi, yi+1, ofMethod, rplColor); + rgb22=GetPixelColorWithOverflow(xi+1, yi+1, ofMethod, rplColor); + //calculate linear interpolation + color.rgbRed=(BYTE) (a*rgb11.rgbRed+b*rgb21.rgbRed+c*rgb12.rgbRed+d*rgb22.rgbRed); + color.rgbGreen=(BYTE) (a*rgb11.rgbGreen+b*rgb21.rgbGreen+c*rgb12.rgbGreen+d*rgb22.rgbGreen); + color.rgbBlue=(BYTE) (a*rgb11.rgbBlue+b*rgb21.rgbBlue+c*rgb12.rgbBlue+d*rgb22.rgbBlue); +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) + color.rgbReserved=(BYTE) (a*rgb11.rgbReserved+b*rgb21.rgbReserved+c*rgb12.rgbReserved+d*rgb22.rgbReserved); + else +#endif + { //Alpha not supported or no alpha at all + color.rgbReserved = 0; + } + return color; + }//if + }//default + case IM_BICUBIC: + case IM_BICUBIC2: + case IM_BSPLINE: + case IM_BOX: + case IM_HERMITE: + case IM_HAMMING: + case IM_SINC: + case IM_BLACKMAN: + case IM_BESSEL: + case IM_GAUSSIAN: + case IM_QUADRATIC: + case IM_MITCHELL: + case IM_CATROM: + //bicubic interpolation(s) + if (((xi+2)<0) || ((xi-1)>=head.biWidth) || ((yi+2)<0) || ((yi-1)>=head.biHeight)) { //all points are outside bounds?: + switch (ofMethod) { + case OM_COLOR: case OM_TRANSPARENT: case OM_BACKGROUND: + //we don't need to interpolate anything with all points outside in this case + return GetPixelColorWithOverflow(-999, -999, ofMethod, rplColor); + break; + default: + //recalculate coordinates and use faster method later on + OverflowCoordinates(x,y,ofMethod); + xi=(int)(x); if (x<0) xi--; //x and/or y have changed ... recalculate xi and yi + yi=(int)(y); if (y<0) yi--; + }//switch + }//if + + //some variables needed from here on + int xii,yii; //x any y integer indexes for loops + float kernel, kernelyc; //kernel cache + float kernelx[12], kernely[4]; //precalculated kernel values + float rr,gg,bb,aa; //accumulated color values + //calculate multiplication factors for all pixels + int i; + switch (inMethod) { + case IM_BICUBIC: + for (i=0; i<4; i++) { + kernelx[i]=KernelCubic((float)(xi+i-1-x)); + kernely[i]=KernelCubic((float)(yi+i-1-y)); + }//for i + break; + case IM_BICUBIC2: + for (i=0; i<4; i++) { + kernelx[i]=KernelGeneralizedCubic((float)(xi+i-1-x), -0.5); + kernely[i]=KernelGeneralizedCubic((float)(yi+i-1-y), -0.5); + }//for i + break; + case IM_BSPLINE: + for (i=0; i<4; i++) { + kernelx[i]=KernelBSpline((float)(xi+i-1-x)); + kernely[i]=KernelBSpline((float)(yi+i-1-y)); + }//for i + break; + case IM_BOX: + for (i=0; i<4; i++) { + kernelx[i]=KernelBox((float)(xi+i-1-x)); + kernely[i]=KernelBox((float)(yi+i-1-y)); + }//for i + break; + case IM_HERMITE: + for (i=0; i<4; i++) { + kernelx[i]=KernelHermite((float)(xi+i-1-x)); + kernely[i]=KernelHermite((float)(yi+i-1-y)); + }//for i + break; + case IM_HAMMING: + for (i=0; i<4; i++) { + kernelx[i]=KernelHamming((float)(xi+i-1-x)); + kernely[i]=KernelHamming((float)(yi+i-1-y)); + }//for i + break; + case IM_SINC: + for (i=0; i<4; i++) { + kernelx[i]=KernelSinc((float)(xi+i-1-x)); + kernely[i]=KernelSinc((float)(yi+i-1-y)); + }//for i + break; + case IM_BLACKMAN: + for (i=0; i<4; i++) { + kernelx[i]=KernelBlackman((float)(xi+i-1-x)); + kernely[i]=KernelBlackman((float)(yi+i-1-y)); + }//for i + break; + case IM_BESSEL: + for (i=0; i<4; i++) { + kernelx[i]=KernelBessel((float)(xi+i-1-x)); + kernely[i]=KernelBessel((float)(yi+i-1-y)); + }//for i + break; + case IM_GAUSSIAN: + for (i=0; i<4; i++) { + kernelx[i]=KernelGaussian((float)(xi+i-1-x)); + kernely[i]=KernelGaussian((float)(yi+i-1-y)); + }//for i + break; + case IM_QUADRATIC: + for (i=0; i<4; i++) { + kernelx[i]=KernelQuadratic((float)(xi+i-1-x)); + kernely[i]=KernelQuadratic((float)(yi+i-1-y)); + }//for i + break; + case IM_MITCHELL: + for (i=0; i<4; i++) { + kernelx[i]=KernelMitchell((float)(xi+i-1-x)); + kernely[i]=KernelMitchell((float)(yi+i-1-y)); + }//for i + break; + case IM_CATROM: + for (i=0; i<4; i++) { + kernelx[i]=KernelCatrom((float)(xi+i-1-x)); + kernely[i]=KernelCatrom((float)(yi+i-1-y)); + }//for i + break; + }//switch + rr=gg=bb=aa=0; + if (((xi+2)=1 && ((yi+2)=1) && !IsIndexed()) { + //optimized interpolation (faster pixel reads) for RGB24 images with all pixels inside bounds + BYTE *pxptr, *pxptra; + for (yii=yi-1; yii255) rr=255; if (rr<0) rr=0; color.rgbRed=(BYTE) rr; + if (gg>255) gg=255; if (gg<0) gg=0; color.rgbGreen=(BYTE) gg; + if (bb>255) bb=255; if (bb<0) bb=0; color.rgbBlue=(BYTE) bb; +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) { + if (aa>255) aa=255; if (aa<0) aa=0; color.rgbReserved=(BYTE) aa; + } else +#endif + { //Alpha not supported or no alpha at all + color.rgbReserved = 0; + } + return color; + case IM_LANCZOS: + //lanczos window (16*16) sinc interpolation + if (((xi+6)<0) || ((xi-5)>=head.biWidth) || ((yi+6)<0) || ((yi-5)>=head.biHeight)) { + //all points are outside bounds + switch (ofMethod) { + case OM_COLOR: case OM_TRANSPARENT: case OM_BACKGROUND: + //we don't need to interpolate anything with all points outside in this case + return GetPixelColorWithOverflow(-999, -999, ofMethod, rplColor); + break; + default: + //recalculate coordinates and use faster method later on + OverflowCoordinates(x,y,ofMethod); + xi=(int)(x); if (x<0) xi--; //x and/or y have changed ... recalculate xi and yi + yi=(int)(y); if (y<0) yi--; + }//switch + }//if + + for (xii=xi-5; xii=0) && ((yi+6)=0) && !IsIndexed()) { + //optimized interpolation (faster pixel reads) for RGB24 images with all pixels inside bounds + BYTE *pxptr, *pxptra; + for (yii=yi-5; yii255) rr=255; if (rr<0) rr=0; color.rgbRed=(BYTE) rr; + if (gg>255) gg=255; if (gg<0) gg=0; color.rgbGreen=(BYTE) gg; + if (bb>255) bb=255; if (bb<0) bb=0; color.rgbBlue=(BYTE) bb; +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) { + if (aa>255) aa=255; if (aa<0) aa=0; color.rgbReserved=(BYTE) aa; + } else +#endif + { //Alpha not supported or no alpha at all + color.rgbReserved = 0; + } + return color; + }//switch +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Helper function for GetAreaColorInterpolated. + * Adds 'surf' portion of image pixel with color 'color' to (rr,gg,bb,aa). + */ +void CxImage::AddAveragingCont(RGBQUAD const &color, float const surf, float &rr, float &gg, float &bb, float &aa) +{ + rr+=color.rgbRed*surf; + gg+=color.rgbGreen*surf; + bb+=color.rgbBlue*surf; +#if CXIMAGE_SUPPORT_ALPHA + aa+=color.rgbReserved*surf; +#endif +} +//////////////////////////////////////////////////////////////////////////////// +/** + * This method is similar to GetPixelColorInterpolated, but this method also properly handles + * subsampling. + * If you need to sample original image with interval of more than 1 pixel (as when shrinking an image), + * you should use this method instead of GetPixelColorInterpolated or aliasing will occur. + * When area width and height are both less than pixel, this method gets pixel color by interpolating + * color of frame center with selected (inMethod) interpolation by calling GetPixelColorInterpolated. + * If width and height are more than 1, method calculates color by averaging color of pixels within area. + * Interpolation method is not used in this case. Pixel color is interpolated by averaging instead. + * If only one of both is more than 1, method uses combination of interpolation and averaging. + * Chosen interpolation method is used, but since it is averaged later on, there is little difference + * between IM_BILINEAR (perhaps best for this case) and better methods. IM_NEAREST_NEIGHBOUR again + * leads to aliasing artifacts. + * This method is a bit slower than GetPixelColorInterpolated and when aliasing is not a problem, you should + * simply use the later. + * + * \param xc, yc - center of (rectangular) area + * \param w, h - width and height of area + * \param inMethod - interpolation method that is used, when interpolation is used (see above) + * \param ofMethod - overflow method used when retrieving individual pixel colors + * \param rplColor - replacement colour to use, in OM_COLOR + * + * \author ***bd*** 2.2004 + */ +RGBQUAD CxImage::GetAreaColorInterpolated( + float const xc, float const yc, float const w, float const h, + InterpolationMethod const inMethod, + OverflowMethod const ofMethod, + RGBQUAD* const rplColor) +{ + RGBQUAD color; //calculated colour + + if (h<=1 && w<=1) { + //both width and height are less than one... we will use interpolation of center point + return GetPixelColorInterpolated(xc, yc, inMethod, ofMethod, rplColor); + } else { + //area is wider and/or taller than one pixel: + CxRect2 area(xc-w/2.0f, yc-h/2.0f, xc+w/2.0f, yc+h/2.0f); //area + int xi1=(int)(area.botLeft.x+0.49999999f); //low x + int yi1=(int)(area.botLeft.y+0.49999999f); //low y + + + int xi2=(int)(area.topRight.x+0.5f); //top x + int yi2=(int)(area.topRight.y+0.5f); //top y (for loops) + + float rr,gg,bb,aa; //red, green, blue and alpha components + rr=gg=bb=aa=0; + int x,y; //loop counters + float s=0; //surface of all pixels + float cps; //surface of current crosssection + if (h>1 && w>1) { + //width and height of area are greater than one pixel, so we can employ "ordinary" averaging + CxRect2 intBL, intTR; //bottom left and top right intersection + intBL=area.CrossSection(CxRect2(((float)xi1)-0.5f, ((float)yi1)-0.5f, ((float)xi1)+0.5f, ((float)yi1)+0.5f)); + intTR=area.CrossSection(CxRect2(((float)xi2)-0.5f, ((float)yi2)-0.5f, ((float)xi2)+0.5f, ((float)yi2)+0.5f)); + float wBL, wTR, hBL, hTR; + wBL=intBL.Width(); //width of bottom left pixel-area intersection + hBL=intBL.Height(); //height of bottom left... + wTR=intTR.Width(); //width of top right... + hTR=intTR.Height(); //height of top right... + + AddAveragingCont(GetPixelColorWithOverflow(xi1,yi1,ofMethod,rplColor), wBL*hBL, rr, gg, bb, aa); //bottom left pixel + AddAveragingCont(GetPixelColorWithOverflow(xi2,yi1,ofMethod,rplColor), wTR*hBL, rr, gg, bb, aa); //bottom right pixel + AddAveragingCont(GetPixelColorWithOverflow(xi1,yi2,ofMethod,rplColor), wBL*hTR, rr, gg, bb, aa); //top left pixel + AddAveragingCont(GetPixelColorWithOverflow(xi2,yi2,ofMethod,rplColor), wTR*hTR, rr, gg, bb, aa); //top right pixel + //bottom and top row + for (x=xi1+1; x255) rr=255; if (rr<0) rr=0; color.rgbRed=(BYTE) rr; + if (gg>255) gg=255; if (gg<0) gg=0; color.rgbGreen=(BYTE) gg; + if (bb>255) bb=255; if (bb<0) bb=0; color.rgbBlue=(BYTE) bb; +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) { + if (aa>255) aa=255; if (aa<0) aa=0; color.rgbReserved=(BYTE) aa; + }//if +#endif + }//if + return color; +} + +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelBSpline(const float x) +{ + if (x>2.0f) return 0.0f; + // thanks to Kristian Kratzenstein + float a, b, c, d; + float xm1 = x - 1.0f; // Was calculatet anyway cause the "if((x-1.0f) < 0)" + float xp1 = x + 1.0f; + float xp2 = x + 2.0f; + + if ((xp2) <= 0.0f) a = 0.0f; else a = xp2*xp2*xp2; // Only float, not float -> double -> float + if ((xp1) <= 0.0f) b = 0.0f; else b = xp1*xp1*xp1; + if (x <= 0) c = 0.0f; else c = x*x*x; + if ((xm1) <= 0.0f) d = 0.0f; else d = xm1*xm1*xm1; + + return (0.16666666666666666667f * (a - (4.0f * b) + (6.0f * c) - (4.0f * d))); + + /* equivalent + if (x < -2.0) + return(0.0f); + if (x < -1.0) + return((2.0f+x)*(2.0f+x)*(2.0f+x)*0.16666666666666666667f); + if (x < 0.0) + return((4.0f+x*x*(-6.0f-3.0f*x))*0.16666666666666666667f); + if (x < 1.0) + return((4.0f+x*x*(-6.0f+3.0f*x))*0.16666666666666666667f); + if (x < 2.0) + return((2.0f-x)*(2.0f-x)*(2.0f-x)*0.16666666666666666667f); + return(0.0f); + */ +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * Bilinear interpolation kernel: + \verbatim + / + | 1-t , if 0 <= t <= 1 + h(t) = | t+1 , if -1 <= t < 0 + | 0 , otherwise + \ + \endverbatim + * ***bd*** 2.2004 + */ +float CxImage::KernelLinear(const float t) +{ +// if (0<=t && t<=1) return 1-t; +// if (-1<=t && t<0) return 1+t; +// return 0; + + // + if (t < -1.0f) + return 0.0f; + if (t < 0.0f) + return 1.0f+t; + if (t < 1.0f) + return 1.0f-t; + return 0.0f; +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * Bicubic interpolation kernel (a=-1): + \verbatim + / + | 1-2|t|**2+|t|**3 , if |t| < 1 + h(t) = | 4-8|t|+5|t|**2-|t|**3 , if 1<=|t|<2 + | 0 , otherwise + \ + \endverbatim + * ***bd*** 2.2004 + */ +float CxImage::KernelCubic(const float t) +{ + float abs_t = (float)fabs(t); + float abs_t_sq = abs_t * abs_t; + if (abs_t<1) return 1-2*abs_t_sq+abs_t_sq*abs_t; + if (abs_t<2) return 4 - 8*abs_t +5*abs_t_sq - abs_t_sq*abs_t; + return 0; +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * Bicubic kernel (for a=-1 it is the same as BicubicKernel): + \verbatim + / + | (a+2)|t|**3 - (a+3)|t|**2 + 1 , |t| <= 1 + h(t) = | a|t|**3 - 5a|t|**2 + 8a|t| - 4a , 1 < |t| <= 2 + | 0 , otherwise + \ + \endverbatim + * Often used values for a are -1 and -1/2. + */ +float CxImage::KernelGeneralizedCubic(const float t, const float a) +{ + float abs_t = (float)fabs(t); + float abs_t_sq = abs_t * abs_t; + if (abs_t<1) return (a+2)*abs_t_sq*abs_t - (a+3)*abs_t_sq + 1; + if (abs_t<2) return a*abs_t_sq*abs_t - 5*a*abs_t_sq + 8*a*abs_t - 4*a; + return 0; +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * Lanczos windowed sinc interpolation kernel with radius r. + \verbatim + / + h(t) = | sinc(t)*sinc(t/r) , if |t| r) return 0; + if (t==0) return 1; + float pit=PI*t; + float pitd=pit/r; + return (float)((sin(pit)/pit) * (sin(pitd)/pitd)); +} + +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelBox(const float x) +{ + if (x < -0.5f) + return 0.0f; + if (x < 0.5f) + return 1.0f; + return 0.0f; +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelHermite(const float x) +{ + if (x < -1.0f) + return 0.0f; + if (x < 0.0f) + return (-2.0f*x-3.0f)*x*x+1.0f; + if (x < 1.0f) + return (2.0f*x-3.0f)*x*x+1.0f; + return 0.0f; +// if (fabs(x)>1) return 0.0f; +// return(0.5f+0.5f*(float)cos(PI*x)); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelHamming(const float x) +{ + if (x < -1.0f) + return 0.0f; + if (x < 0.0f) + return 0.92f*(-2.0f*x-3.0f)*x*x+1.0f; + if (x < 1.0f) + return 0.92f*(2.0f*x-3.0f)*x*x+1.0f; + return 0.0f; +// if (fabs(x)>1) return 0.0f; +// return(0.54f+0.46f*(float)cos(PI*x)); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelSinc(const float x) +{ + if (x == 0.0) + return(1.0); + return((float)sin(PI*x)/(PI*x)); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelBlackman(const float x) +{ + //if (fabs(x)>1) return 0.0f; + return (0.42f+0.5f*(float)cos(PI*x)+0.08f*(float)cos(2.0f*PI*x)); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelBessel_J1(const float x) +{ + double p, q; + + register long i; + + static const double + Pone[] = + { + 0.581199354001606143928050809e+21, + -0.6672106568924916298020941484e+20, + 0.2316433580634002297931815435e+19, + -0.3588817569910106050743641413e+17, + 0.2908795263834775409737601689e+15, + -0.1322983480332126453125473247e+13, + 0.3413234182301700539091292655e+10, + -0.4695753530642995859767162166e+7, + 0.270112271089232341485679099e+4 + }, + Qone[] = + { + 0.11623987080032122878585294e+22, + 0.1185770712190320999837113348e+20, + 0.6092061398917521746105196863e+17, + 0.2081661221307607351240184229e+15, + 0.5243710262167649715406728642e+12, + 0.1013863514358673989967045588e+10, + 0.1501793594998585505921097578e+7, + 0.1606931573481487801970916749e+4, + 0.1e+1 + }; + + p = Pone[8]; + q = Qone[8]; + for (i=7; i >= 0; i--) + { + p = p*x*x+Pone[i]; + q = q*x*x+Qone[i]; + } + return (float)(p/q); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelBessel_P1(const float x) +{ + double p, q; + + register long i; + + static const double + Pone[] = + { + 0.352246649133679798341724373e+5, + 0.62758845247161281269005675e+5, + 0.313539631109159574238669888e+5, + 0.49854832060594338434500455e+4, + 0.2111529182853962382105718e+3, + 0.12571716929145341558495e+1 + }, + Qone[] = + { + 0.352246649133679798068390431e+5, + 0.626943469593560511888833731e+5, + 0.312404063819041039923015703e+5, + 0.4930396490181088979386097e+4, + 0.2030775189134759322293574e+3, + 0.1e+1 + }; + + p = Pone[5]; + q = Qone[5]; + for (i=4; i >= 0; i--) + { + p = p*(8.0/x)*(8.0/x)+Pone[i]; + q = q*(8.0/x)*(8.0/x)+Qone[i]; + } + return (float)(p/q); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelBessel_Q1(const float x) +{ + double p, q; + + register long i; + + static const double + Pone[] = + { + 0.3511751914303552822533318e+3, + 0.7210391804904475039280863e+3, + 0.4259873011654442389886993e+3, + 0.831898957673850827325226e+2, + 0.45681716295512267064405e+1, + 0.3532840052740123642735e-1 + }, + Qone[] = + { + 0.74917374171809127714519505e+4, + 0.154141773392650970499848051e+5, + 0.91522317015169922705904727e+4, + 0.18111867005523513506724158e+4, + 0.1038187585462133728776636e+3, + 0.1e+1 + }; + + p = Pone[5]; + q = Qone[5]; + for (i=4; i >= 0; i--) + { + p = p*(8.0/x)*(8.0/x)+Pone[i]; + q = q*(8.0/x)*(8.0/x)+Qone[i]; + } + return (float)(p/q); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelBessel_Order1(float x) +{ + float p, q; + + if (x == 0.0) + return (0.0f); + p = x; + if (x < 0.0) + x=(-x); + if (x < 8.0) + return(p*KernelBessel_J1(x)); + q = (float)sqrt(2.0f/(PI*x))*(float)(KernelBessel_P1(x)*(1.0f/sqrt(2.0f)*(sin(x)-cos(x)))-8.0f/x*KernelBessel_Q1(x)* + (-1.0f/sqrt(2.0f)*(sin(x)+cos(x)))); + if (p < 0.0f) + q = (-q); + return (q); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelBessel(const float x) +{ + if (x == 0.0f) + return(PI/4.0f); + return(KernelBessel_Order1(PI*x)/(2.0f*x)); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelGaussian(const float x) +{ + return (float)(exp(-2.0f*x*x)*0.79788456080287f/*sqrt(2.0f/PI)*/); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelQuadratic(const float x) +{ + if (x < -1.5f) + return(0.0f); + if (x < -0.5f) + return(0.5f*(x+1.5f)*(x+1.5f)); + if (x < 0.5f) + return(0.75f-x*x); + if (x < 1.5f) + return(0.5f*(x-1.5f)*(x-1.5f)); + return(0.0f); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelMitchell(const float x) +{ +#define KM_B (1.0f/3.0f) +#define KM_C (1.0f/3.0f) +#define KM_P0 (( 6.0f - 2.0f * KM_B ) / 6.0f) +#define KM_P2 ((-18.0f + 12.0f * KM_B + 6.0f * KM_C) / 6.0f) +#define KM_P3 (( 12.0f - 9.0f * KM_B - 6.0f * KM_C) / 6.0f) +#define KM_Q0 (( 8.0f * KM_B + 24.0f * KM_C) / 6.0f) +#define KM_Q1 ((-12.0f * KM_B - 48.0f * KM_C) / 6.0f) +#define KM_Q2 (( 6.0f * KM_B + 30.0f * KM_C) / 6.0f) +#define KM_Q3 (( -1.0f * KM_B - 6.0f * KM_C) / 6.0f) + + if (x < -2.0) + return(0.0f); + if (x < -1.0) + return(KM_Q0-x*(KM_Q1-x*(KM_Q2-x*KM_Q3))); + if (x < 0.0f) + return(KM_P0+x*x*(KM_P2-x*KM_P3)); + if (x < 1.0f) + return(KM_P0+x*x*(KM_P2+x*KM_P3)); + if (x < 2.0f) + return(KM_Q0+x*(KM_Q1+x*(KM_Q2+x*KM_Q3))); + return(0.0f); +} +//////////////////////////////////////////////////////////////////////////////// +float CxImage::KernelCatrom(const float x) +{ + if (x < -2.0) + return(0.0f); + if (x < -1.0) + return(0.5f*(4.0f+x*(8.0f+x*(5.0f+x)))); + if (x < 0.0) + return(0.5f*(2.0f+x*x*(-5.0f-3.0f*x))); + if (x < 1.0) + return(0.5f*(2.0f+x*x*(-5.0f+3.0f*x))); + if (x < 2.0) + return(0.5f*(4.0f+x*(-8.0f+x*(5.0f-x)))); + return(0.0f); +} +//////////////////////////////////////////////////////////////////////////////// + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximaiter.h b/SlnkDWFImpl/CxImage/CxImage/ximaiter.h new file mode 100644 index 0000000..d706ca4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximaiter.h @@ -0,0 +1,252 @@ +/* + * File: ImaIter.h + * Purpose: Declaration of the Platform Independent Image Base Class + * Author: Alejandro Aguilar Sierra + * Created: 1995 + * Copyright: (c) 1995, Alejandro Aguilar Sierra + * + * 07/08/2001 Davide Pizzolato - www.xdp.it + * - removed slow loops + * - added safe checks + * + * Permission is given by the author to freely redistribute and include + * this code in any program as long as this credit is given where due. + * + * COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES + * THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE + * OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED + * CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT + * THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY + * SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL + * PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. + * + * Use at your own risk! + * ========================================================== + */ + +#if !defined(__ImaIter_h) +#define __ImaIter_h + +#include "ximage.h" +#include "ximadef.h" + +class CImageIterator +{ +friend class CxImage; +protected: + int Itx, Ity; // Counters + int Stepx, Stepy; + BYTE* IterImage; // Image pointer + CxImage *ima; +public: + // Constructors + CImageIterator ( void ); + CImageIterator ( CxImage *image ); + operator CxImage* (); + + // Iterators + BOOL ItOK (); + void Reset (); + void Upset (); + void SetRow(BYTE *buf, int n); + void GetRow(BYTE *buf, int n); + BYTE GetByte( ) { return IterImage[Itx]; } + void SetByte(BYTE b) { IterImage[Itx] = b; } + BYTE* GetRow(void); + BYTE* GetRow(int n); + BOOL NextRow(); + BOOL PrevRow(); + BOOL NextByte(); + BOOL PrevByte(); + + void SetSteps(int x, int y=0) { Stepx = x; Stepy = y; } + void GetSteps(int *x, int *y) { *x = Stepx; *y = Stepy; } + BOOL NextStep(); + BOOL PrevStep(); + + void SetY(int y); /* AD - for interlace */ + int GetY() {return Ity;} + BOOL GetCol(BYTE* pCol, DWORD x); + BOOL SetCol(BYTE* pCol, DWORD x); +}; + +///////////////////////////////////////////////////////////////////// +inline +CImageIterator::CImageIterator(void) +{ + ima = 0; + IterImage = 0; + Itx = Ity = 0; + Stepx = Stepy = 0; +} +///////////////////////////////////////////////////////////////////// +inline +CImageIterator::CImageIterator(CxImage *imageImpl): ima(imageImpl) +{ + if (ima) IterImage = ima->GetBits(); + Itx = Ity = 0; + Stepx = Stepy = 0; +} +///////////////////////////////////////////////////////////////////// +inline +CImageIterator::operator CxImage* () +{ + return ima; +} +///////////////////////////////////////////////////////////////////// +inline BOOL CImageIterator::ItOK () +{ + if (ima) return ima->IsInside(Itx, Ity); + else return FALSE; +} +///////////////////////////////////////////////////////////////////// +inline void CImageIterator::Reset() +{ + if (ima) IterImage = ima->GetBits(); + else IterImage=0; + Itx = Ity = 0; +} +///////////////////////////////////////////////////////////////////// +inline void CImageIterator::Upset() +{ + Itx = 0; + Ity = ima->GetHeight()-1; + IterImage = ima->GetBits() + ima->GetEffWidth()*(ima->GetHeight()-1); +} +///////////////////////////////////////////////////////////////////// +inline BOOL CImageIterator::NextRow() +{ + if (++Ity >= (int)ima->GetHeight()) return 0; + IterImage += ima->GetEffWidth(); + return 1; +} +///////////////////////////////////////////////////////////////////// +inline BOOL CImageIterator::PrevRow() +{ + if (--Ity < 0) return 0; + IterImage -= ima->GetEffWidth(); + return 1; +} +/* AD - for interlace */ +inline void CImageIterator::SetY(int y) +{ + if ((y < 0) || (y > (int)ima->GetHeight())) return; + Ity = y; + IterImage = ima->GetBits() + ima->GetEffWidth()*y; +} +///////////////////////////////////////////////////////////////////// +inline void CImageIterator::SetRow(BYTE *buf, int n) +{ + if (n<0) n = (int)ima->GetEffWidth(); + else n = min(n,(int)ima->GetEffWidth()); + + if ((IterImage!=NULL)&&(buf!=NULL)&&(n>0)) memcpy(IterImage,buf,n); +} +///////////////////////////////////////////////////////////////////// +inline void CImageIterator::GetRow(BYTE *buf, int n) +{ + if ((IterImage!=NULL)&&(buf!=NULL)&&(n>0)) memcpy(buf,IterImage,n); +} +///////////////////////////////////////////////////////////////////// +inline BYTE* CImageIterator::GetRow() +{ + return IterImage; +} +///////////////////////////////////////////////////////////////////// +inline BYTE* CImageIterator::GetRow(int n) +{ + SetY(n); + return IterImage; +} +///////////////////////////////////////////////////////////////////// +inline BOOL CImageIterator::NextByte() +{ + if (++Itx < (int)ima->GetEffWidth()) return 1; + else + if (++Ity < (int)ima->GetHeight()){ + IterImage += ima->GetEffWidth(); + Itx = 0; + return 1; + } else + return 0; +} +///////////////////////////////////////////////////////////////////// +inline BOOL CImageIterator::PrevByte() +{ + if (--Itx >= 0) return 1; + else + if (--Ity >= 0){ + IterImage -= ima->GetEffWidth(); + Itx = 0; + return 1; + } else + return 0; +} +///////////////////////////////////////////////////////////////////// +inline BOOL CImageIterator::NextStep() +{ + Itx += Stepx; + if (Itx < (int)ima->GetEffWidth()) return 1; + else { + Ity += Stepy; + if (Ity < (int)ima->GetHeight()){ + IterImage += ima->GetEffWidth(); + Itx = 0; + return 1; + } else + return 0; + } +} +///////////////////////////////////////////////////////////////////// +inline BOOL CImageIterator::PrevStep() +{ + Itx -= Stepx; + if (Itx >= 0) return 1; + else { + Ity -= Stepy; + if (Ity >= 0 && Ity < (int)ima->GetHeight()) { + IterImage -= ima->GetEffWidth(); + Itx = 0; + return 1; + } else + return 0; + } +} +///////////////////////////////////////////////////////////////////// +inline BOOL CImageIterator::GetCol(BYTE* pCol, DWORD x) +{ + if ((pCol==0)||(ima->GetBpp()<8)||(x>=ima->GetWidth())) + return 0; + DWORD h = ima->GetHeight(); + //DWORD line = ima->GetEffWidth(); + BYTE bytes = ima->GetBpp()>>3; + BYTE* pSrc; + for (DWORD y=0;yGetBits(y) + x*bytes; + for (BYTE w=0;wGetBpp()<8)||(x>=ima->GetWidth())) + return 0; + DWORD h = ima->GetHeight(); + //DWORD line = ima->GetEffWidth(); + BYTE bytes = ima->GetBpp()>>3; + BYTE* pSrc; + for (DWORD y=0;yGetBits(y) + x*bytes; + for (BYTE w=0;wSize(); + src=(BYTE*)malloc(len); + hFile->Read(src, len, 1); + + if (!j2k_decode(src, len, &img, &cp)) { + free(src); + throw "failed to decode J2K image!"; + } + + free(src); + + if (img->numcomps==3 && + img->comps[0].dx==img->comps[1].dx && + img->comps[1].dx==img->comps[2].dx && + img->comps[0].dy==img->comps[1].dy && + img->comps[1].dy==img->comps[2].dy && + img->comps[0].prec==img->comps[1].prec && + img->comps[1].prec==img->comps[2].prec) + { + w=CEILDIV(img->x1-img->x0, img->comps[0].dx); + h=CEILDIV(img->y1-img->y0, img->comps[0].dy); + max=(1<comps[0].prec)-1; + + Create(w,h,24,CXIMAGE_FORMAT_J2K); + + RGBQUAD c; + for (i=0,y=0; ycomps[0].data[i]; + c.rgbGreen = img->comps[1].data[i]; + c.rgbBlue = img->comps[2].data[i]; + SetPixelColor(x,h-1-y,c); + } + } + } else { + int compno; + info.nNumFrames = img->numcomps; + if ((info.nFrame<0)||(info.nFrame>=info.nNumFrames)){ + j2k_destroy(&img,&cp); + throw "wrong frame!"; + } + for (compno=0; compno<=info.nFrame; compno++) { + w=CEILDIV(img->x1-img->x0, img->comps[compno].dx); + h=CEILDIV(img->y1-img->y0, img->comps[compno].dy); + max=(1<comps[compno].prec)-1; + Create(w,h,8,CXIMAGE_FORMAT_J2K); + SetGrayPalette(); + for (i=0,y=0; ycomps[compno].data[i]); + } + } + } + } + + j2k_destroy(&img,&cp); + + } catch (char *message) { + strncpy(info.szLastError,message,255); + return FALSE; + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImageJ2K::Encode(CxFile * hFile) +{ + if (EncodeSafeCheck(hFile)) return false; + + if (head.biClrUsed!=0 && !IsGrayScale()){ + strcpy(info.szLastError,"J2K can save only RGB or GrayScale images"); + return false; + } + + int i,x,y; + j2k_image_t *img; + j2k_cp_t *cp; + j2k_tcp_t *tcp; + j2k_tccp_t *tccp; + + img = (j2k_image_t *)calloc(sizeof(j2k_image_t),1); + cp = (j2k_cp_t *)calloc(sizeof(j2k_cp_t),1); + + cp->tx0=0; cp->ty0=0; + cp->tw=1; cp->th=1; + cp->tcps=(j2k_tcp_t*)calloc(sizeof(j2k_tcp_t),1); + tcp=&cp->tcps[0]; + + long w=head.biWidth; + long h=head.biHeight; + + tcp->numlayers=1; + for (i=0;inumlayers;i++) tcp->rates[i]=(w*h*GetJpegQuality())/600; + + + if (IsGrayScale()) { + img->x0=0; + img->y0=0; + img->x1=w; + img->y1=h; + img->numcomps=1; + img->comps=(j2k_comp_t*)calloc(sizeof(j2k_comp_t),1); + img->comps[0].data=(int*)calloc(w*h*sizeof(int),1); + img->comps[0].prec=8; + img->comps[0].sgnd=0; + img->comps[0].dx=1; + img->comps[0].dy=1; + for (i=0,y=0; ycomps[0].data[i]=GetPixelIndex(x,h-1-y); + } + } + } else if (!IsIndexed()) { + img->x0=0; + img->y0=0; + img->x1=w; + img->y1=h; + img->numcomps=3; + img->comps=(j2k_comp_t*)calloc(img->numcomps*sizeof(j2k_comp_t),1); + for (i=0; inumcomps; i++) { + img->comps[i].data=(int*)calloc(w*h*sizeof(int),1); + img->comps[i].prec=8; + img->comps[i].sgnd=0; + img->comps[i].dx=1; + img->comps[i].dy=1; + } + RGBQUAD c; + for (i=0,y=0; ycomps[0].data[i]=c.rgbRed; + img->comps[1].data[i]=c.rgbGreen; + img->comps[2].data[i]=c.rgbBlue; + } + } + } else { + return 0; + } + + cp->tdx=img->x1-img->x0; + cp->tdy=img->y1-img->y0; + + tcp->csty=0; + tcp->prg=0; + tcp->mct=img->numcomps==3?1:0; + tcp->tccps=(j2k_tccp_t*)calloc(img->numcomps*sizeof(j2k_tccp_t),1); + + int ir=0; /* or 1 ???*/ + + for (i=0; inumcomps; i++) { + tccp=&tcp->tccps[i]; + tccp->csty=0; + tccp->numresolutions=6; + tccp->cblkw=6; + tccp->cblkh=6; + tccp->cblksty=0; + tccp->qmfbid=ir?0:1; + tccp->qntsty=ir?J2K_CCP_QNTSTY_SEQNT:J2K_CCP_QNTSTY_NOQNT; + tccp->numgbits=2; + tccp->roishift=0; + j2k_calc_explicit_stepsizes(tccp, img->comps[i].prec); + } + + BYTE* dest=(BYTE*)calloc(tcp->rates[tcp->numlayers-1]+2,1); + long len = j2k_encode(img, cp, dest, tcp->rates[tcp->numlayers-1]+2); + + if (len==0) { + strcpy(info.szLastError,"J2K failed to encode image"); + } else { + hFile->Write(dest, len, 1); + } + + free(dest); + j2k_destroy(&img,&cp); + + return (len!=0); +} +//////////////////////////////////////////////////////////////////////////////// + +static const double dwt_norms_97[4][10]={ + {1.000, 1.965, 4.177, 8.403, 16.90, 33.84, 67.69, 135.3, 270.6, 540.9}, + {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0}, + {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0}, + {2.080, 3.865, 8.307, 17.18, 34.71, 69.59, 139.3, 278.6, 557.2} +}; + +//////////////////////////////////////////////////////////////////////////////// +void CxImageJ2K::j2k_calc_explicit_stepsizes(j2k_tccp_t *tccp, int prec) { + int numbands, bandno; + numbands=3*tccp->numresolutions-2; + for (bandno=0; bandnonumresolutions-1-resno; + gain=tccp->qmfbid==0?0:(orient==0?0:(orient==1||orient==2?1:2)); + if (tccp->qntsty==J2K_CCP_QNTSTY_NOQNT) { + stepsize=1.0; + } else { + double norm=dwt_norms_97[orient][level]; + stepsize=(1<<(gain+1))/norm; + } + j2k_encode_stepsize((int)floor(stepsize*8192.0), prec+gain, &tccp->stepsizes[bandno].expn, &tccp->stepsizes[bandno].mant); + } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageJ2K::j2k_encode_stepsize(int stepsize, int numbps, int *expn, int *mant) { + int p, n; + p=j2k_floorlog2(stepsize)-13; + n=11-j2k_floorlog2(stepsize); + *mant=(n<0?stepsize>>-n:stepsize<1; l++) { + a>>=1; + } + return l; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_J2K diff --git a/SlnkDWFImpl/CxImage/CxImage/ximaj2k.h b/SlnkDWFImpl/CxImage/CxImage/ximaj2k.h new file mode 100644 index 0000000..4273fb9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximaj2k.h @@ -0,0 +1,46 @@ +/* + * File: ximaj2k.h + * Purpose: J2K Image Class Loader and Writer + */ +/* ========================================================== + * CxImageJ2K (c) 04/Aug/2002 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * based on LIBJ2K Copyright (c) 2001-2002, David Janssens - All rights reserved. + * ========================================================== + */ +#if !defined(__ximaJ2K_h) +#define __ximaJ2K_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_J2K + +#define LIBJ2K_EXPORTS +extern "C" { +#include "../j2k/j2k.h" +}; + +class CxImageJ2K: public CxImage +{ +public: + CxImageJ2K(): CxImage(CXIMAGE_FORMAT_J2K) {} + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_J2K);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_J2K);} + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE +protected: + void j2k_calc_explicit_stepsizes(j2k_tccp_t *tccp, int prec); + void j2k_encode_stepsize(int stepsize, int numbps, int *expn, int *mant); + int j2k_floorlog2(int a); +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximajas.cpp b/SlnkDWFImpl/CxImage/CxImage/ximajas.cpp new file mode 100644 index 0000000..b6b8def --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximajas.cpp @@ -0,0 +1,265 @@ +/* + * File: ximajas.cpp + * Purpose: Platform Independent JasPer Image Class Loader and Writer + * 12/Apr/2003 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximajas.h" + +#if CXIMAGE_SUPPORT_JASPER + +//////////////////////////////////////////////////////////////////////////////// +bool CxImageJAS::Decode(CxFile *hFile, DWORD imagetype) +{ + if (hFile == NULL) return false; + + jas_image_t *image=0; + jas_stream_t *in=0; + jas_matrix_t **bufs=0; + long i,error=0; + //jas_setdbglevel(0); + + try + { + if (jas_init()) + throw "cannot initialize jasper"; + + if (!(in = jas_stream_fdopen(0, "rb"))) + throw "error: cannot open standard input"; + + CxFileJas src(hFile,in); + + if (!(image = jas_image_decode(in, -1, 0))) + throw "error: cannot load image data"; + + long x,y,w,h,depth,cmptno; + + w = jas_image_cmptwidth(image,0); + h = jas_image_cmptheight(image,0); + depth = jas_image_cmptprec(image,0); + + if (image->numcmpts_ > 64 || image->numcmpts_ < 0) + throw "error: too much components"; + + if (depth!=1 && depth!=4 && depth!=8){ + jas_image_t *newimage; + jas_cmprof_t *outprof; + //jas_eprintf("forcing conversion to sRGB\n"); + if (!(outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB))) { + throw "cannot create sRGB profile"; + } + if (!(newimage = jas_image_chclrspc(image, outprof, JAS_CMXFORM_INTENT_PER))) { + throw "cannot convert to sRGB"; + } + jas_image_destroy(image); + jas_cmprof_destroy(outprof); + image = newimage; + } + + bufs = (jas_matrix_t **)calloc(image->numcmpts_, sizeof(jas_matrix_t**)); + for (i = 0; i < image->numcmpts_; ++i) { + if (!(bufs[i] = jas_matrix_create(1, w))) { + throw "error: cannot allocate memory"; + } + } + + if (image->numcmpts_==3 && + image->cmpts_[0]->width_ == image->cmpts_[1]->width_ && + image->cmpts_[1]->width_ == image->cmpts_[2]->width_ && + image->cmpts_[0]->height_ == image->cmpts_[1]->height_ && + image->cmpts_[1]->height_ == image->cmpts_[2]->height_ && + image->cmpts_[0]->prec_ == image->cmpts_[1]->prec_ && + image->cmpts_[1]->prec_ == image->cmpts_[2]->prec_ ) + { + + if(!Create(w,h,24,imagetype)) + throw "Can't allocate memory"; + + RGBQUAD c; + for (y=0; ynumcmpts_; ++cmptno) { + jas_image_readcmpt(image, cmptno, 0, y, w, 1, bufs[cmptno]); + } + + for (x=0; xnumcmpts_; + if ((info.nFrame<0)||(info.nFrame>=info.nNumFrames)){ + throw "wrong frame!"; + } + for (cmptno=0; cmptno<=info.nFrame; cmptno++) { + w = jas_image_cmptwidth(image,cmptno); + h = jas_image_cmptheight(image,cmptno); + depth = jas_image_cmptprec(image,cmptno); + if (depth>8) depth=8; + if(!Create(w,h,depth,imagetype)) + throw "Can't allocate memory"; + SetGrayPalette(); + for (y=0; ynumcmpts_; ++i){ if (bufs[i]) jas_matrix_destroy(bufs[i]);} + free(bufs); + } + jas_cleanup(); + if (image) jas_image_destroy(image); + if (in) jas_stream_close(in); + return (error==0); +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImageJAS::Encode(CxFile * hFile, DWORD imagetype) +{ + if (EncodeSafeCheck(hFile)) return false; + + if (head.biClrUsed!=0 && !IsGrayScale()){ + strcpy(info.szLastError,"JasPer can save only RGB or GrayScale images"); + return false; + } + + jas_image_t *image=0; + jas_stream_t *out=0; + jas_matrix_t *cmpts[3]; + long x,y,yflip,error=0; + uint_fast16_t cmptno, numcmpts; + jas_image_cmptparm_t cmptparms[3], *cmptparm; + + try + { + + if (jas_init()) + throw "cannot initialize jasper"; + + if (!(out = jas_stream_fdopen(0, "wb"))) + throw "error: cannot open standard output"; + + CxFileJas src(hFile,out); + + numcmpts = head.biClrUsed==0 ? 3 : 1; + + for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { + cmptparm->tlx = 0; + cmptparm->tly = 0; + cmptparm->hstep = 1; + cmptparm->vstep = 1; + cmptparm->width = head.biWidth; + cmptparm->height = head.biHeight; + cmptparm->prec = 8; + cmptparm->sgnd = false; + } + + /* Create image object. */ + if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) + throw "error : jas_image_create"; + + if (numcmpts == 3) { + jas_image_setclrspc(image, JAS_CLRSPC_SRGB); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); + jas_image_setcmpttype(image, 1, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); + jas_image_setcmpttype(image, 2, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); + } else { + jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); + } + + + for (x = 0; x < numcmpts; ++x) { cmpts[x] = 0; } + /* Create temporary matrices to hold component data. */ + for (x = 0; x < numcmpts; ++x) { + if (!(cmpts[x] = jas_matrix_create(1, head.biWidth))) { + throw "error : can't allocate memory"; + } + } + + RGBQUAD c; + for (y = 0; y < head.biHeight; ++y) { + for (x = 0; x < head.biWidth; ++x) { + if (head.biClrUsed==0){ + c = GetPixelColor(x,y); + jas_matrix_setv(cmpts[0], x, c.rgbRed); + jas_matrix_setv(cmpts[1], x, c.rgbGreen); + jas_matrix_setv(cmpts[2], x, c.rgbBlue); + } else { + jas_matrix_setv(cmpts[0], x, GetPixelIndex(x,y)); + } + } + yflip = head.biHeight - 1 - y; + for (cmptno = 0; cmptno < numcmpts; ++cmptno) { + if (jas_image_writecmpt(image, cmptno, 0, yflip, head.biWidth, 1, cmpts[cmptno])) { + throw "error : jas_image_writecmpt"; + } + } + } + + char szfmt[4]; + *szfmt = '\0'; +#if CXIMAGE_SUPPORT_JP2 + if (imagetype == CXIMAGE_FORMAT_JP2) strcpy(szfmt,"jp2"); +#endif +#if CXIMAGE_SUPPORT_JPC + if (imagetype == CXIMAGE_FORMAT_JPC) strcpy(szfmt,"jpc"); +#endif +#if CXIMAGE_SUPPORT_RAS + if (imagetype == CXIMAGE_FORMAT_RAS) strcpy(szfmt,"ras"); +#endif +#if CXIMAGE_SUPPORT_PNM + if (imagetype == CXIMAGE_FORMAT_PNM) strcpy(szfmt,"pnm"); +#endif +#if CXIMAGE_SUPPORT_PGX + if (imagetype == CXIMAGE_FORMAT_PGX){ + strcpy(szfmt,"pgx"); + if (head.biClrUsed==0) throw "PGX can save only GrayScale images"; + } +#endif + int outfmt = jas_image_strtofmt(szfmt); + + char szoutopts[16]; + sprintf(szoutopts,"rate=%.3f", info.nQuality/100.0f); + + if (jas_image_encode(image, out, outfmt, szoutopts)) { + throw "error: cannot encode image\n"; + } + jas_stream_flush(out); + + } catch (char *message) { + strncpy(info.szLastError,message,255); + error = 1; + } + + for (x = 0; x < numcmpts; ++x) { if (cmpts[x]) { jas_matrix_destroy(cmpts[x]); } } + jas_cleanup(); + if (image) jas_image_destroy(image); + if (out) jas_stream_close(out); + + return (error==0); +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_JASPER + diff --git a/SlnkDWFImpl/CxImage/CxImage/ximajas.h b/SlnkDWFImpl/CxImage/CxImage/ximajas.h new file mode 100644 index 0000000..a433711 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximajas.h @@ -0,0 +1,84 @@ +/* + * File: ximajas.h + * Purpose: Jasper Image Class Loader and Writer + */ +/* ========================================================== + * CxImageJAS (c) 12/Apr/2003 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * based on JasPer Copyright (c) 2001-2003 Michael David Adams - All rights reserved. + * ========================================================== + */ +#if !defined(__ximaJAS_h) +#define __ximaJAS_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_JASPER + +#include "../jasper/include/jasper/jasper.h" + +class CxImageJAS: public CxImage +{ +public: + CxImageJAS(): CxImage((DWORD)0) {} // cast to DWORD + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,0);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,0);} + bool Decode(CxFile * hFile, DWORD imagetype = 0); + bool Decode(FILE *hFile, DWORD imagetype = 0) { CxIOFile file(hFile); return Decode(&file,imagetype); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile, DWORD imagetype = 0); + bool Encode(FILE *hFile, DWORD imagetype = 0) { CxIOFile file(hFile); return Encode(&file,imagetype); } +#endif // CXIMAGE_SUPPORT_ENCODE +protected: + + class CxFileJas + { + public: + CxFileJas(CxFile* pFile,jas_stream_t *stream) + { + if (stream->obj_) jas_free(stream->obj_); + stream->obj_ = pFile; + + // - cannot set the stream->ops_->functions here, + // because this overwrites a static structure in the Jasper library. + // This structure is used by Jasper for internal operations too, e.g. tempfile. + // However the ops_ pointer in the stream can be overwritten. + + //stream->ops_->close_ = JasClose; + //stream->ops_->read_ = JasRead; + //stream->ops_->seek_ = JasSeek; + //stream->ops_->write_ = JasWrite; + + jas_stream_CxFile.close_ = JasClose; + jas_stream_CxFile.read_ = JasRead; + jas_stream_CxFile.seek_ = JasSeek; + jas_stream_CxFile.write_ = JasWrite; + + stream->ops_ = &jas_stream_CxFile; + + // - end + } + static int JasRead(jas_stream_obj_t *obj, char *buf, int cnt) + { return ((CxFile*)obj)->Read(buf,1,cnt); } + static int JasWrite(jas_stream_obj_t *obj, char *buf, int cnt) + { return ((CxFile*)obj)->Write(buf,1,cnt); } + static long JasSeek(jas_stream_obj_t *obj, long offset, int origin) + { return ((CxFile*)obj)->Seek(offset,origin); } + static int JasClose(jas_stream_obj_t *obj) + { return 1; } + + // + private: + jas_stream_ops_t jas_stream_CxFile; + // - end + + }; + +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximajbg.cpp b/SlnkDWFImpl/CxImage/CxImage/ximajbg.cpp new file mode 100644 index 0000000..d855ffd --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximajbg.cpp @@ -0,0 +1,162 @@ +/* + * File: ximajbg.cpp + * Purpose: Platform Independent JBG Image Class Loader and Writer + * 18/Aug/2002 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximajbg.h" + +#if CXIMAGE_SUPPORT_JBG + +#include "ximaiter.h" + +#define JBIG_BUFSIZE 8192 + +//////////////////////////////////////////////////////////////////////////////// +bool CxImageJBG::Decode(CxFile *hFile) +{ + if (hFile == NULL) return false; + + struct jbg_dec_state jbig_state; + unsigned long xmax = 4294967295UL, ymax = 4294967295UL; + unsigned int len, cnt; + BYTE *buffer,*p; + int result; + + try + { + jbg_dec_init(&jbig_state); + jbg_dec_maxsize(&jbig_state, xmax, ymax); + + buffer = (BYTE*)malloc(JBIG_BUFSIZE); + if (!buffer) throw "Sorry, not enough memory available!"; + + result = JBG_EAGAIN; + do { + len = hFile->Read(buffer, 1, JBIG_BUFSIZE); + if (!len) break; + cnt = 0; + p = buffer; + while (len > 0 && (result == JBG_EAGAIN || result == JBG_EOK)) { + result = jbg_dec_in(&jbig_state, p, len, &cnt); + p += cnt; + len -= cnt; + } + } while (result == JBG_EAGAIN || result == JBG_EOK); + + if (hFile->Error()) + throw "Problem while reading input file"; + if (result != JBG_EOK && result != JBG_EOK_INTR) + throw "Problem with input file"; + + int w, h, bpp, planes, ew; + + w = jbg_dec_getwidth(&jbig_state); + h = jbg_dec_getheight(&jbig_state); + planes = jbg_dec_getplanes(&jbig_state); + bpp = (planes+7)>>3; + ew = (w + 7)>>3; + + switch (planes){ + case 1: + { + BYTE* binary_image = jbg_dec_getimage(&jbig_state, 0); + + if (!Create(w,h,1,CXIMAGE_FORMAT_JBG)) + throw "Can't allocate memory"; + + SetPaletteColor(0,255,255,255); + SetPaletteColor(1,0,0,0); + + CImageIterator iter(this); + iter.Upset(); + for (int i=0;i>3; + ew = (w + 7)>>3; + + BYTE mask; + RGBQUAD *rgb = GetPalette(); + if (CompareColors(&rgb[0],&rgb[1])<0) mask=255; else mask=0; + + BYTE *buffer = (BYTE*)malloc(ew*h*2); + if (!buffer) { + strcpy(info.szLastError,"Sorry, not enough memory available!"); + return false; + } + + for (y=0; yError()){ + strcpy(info.szLastError,"Problem while writing JBG file"); + return false; + } + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_JBG + diff --git a/SlnkDWFImpl/CxImage/CxImage/ximajbg.h b/SlnkDWFImpl/CxImage/CxImage/ximajbg.h new file mode 100644 index 0000000..c25e5be --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximajbg.h @@ -0,0 +1,44 @@ +/* + * File: ximajbg.h + * Purpose: JBG Image Class Loader and Writer + */ +/* ========================================================== + * CxImageJBG (c) 18/Aug/2002 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * based on LIBJBG Copyright (c) 2002, Markus Kuhn - All rights reserved. + * ========================================================== + */ +#if !defined(__ximaJBG_h) +#define __ximaJBG_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_JBG + +extern "C" { +#include "../jbig/jbig.h" +}; + +class CxImageJBG: public CxImage +{ +public: + CxImageJBG(): CxImage(CXIMAGE_FORMAT_JBG) {} + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_JBG);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_JBG);} + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE +protected: + static void jbig_data_out(BYTE *buffer, unsigned int len, void *file) + {((CxFile*)file)->Write(buffer,len,1);} +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximajpg.cpp b/SlnkDWFImpl/CxImage/CxImage/ximajpg.cpp new file mode 100644 index 0000000..afba6d0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximajpg.cpp @@ -0,0 +1,454 @@ +/* + * File: ximajpg.cpp + * Purpose: Platform Independent JPEG Image Class Loader and Writer + * 07/Aug/2001 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximajpg.h" + +#if CXIMAGE_SUPPORT_JPG + +#include "../jpeg/jmorecfg.h" + +#include "ximaiter.h" + +#include + +struct jpg_error_mgr { + struct jpeg_error_mgr pub; /* "public" fields */ + jmp_buf setjmp_buffer; /* for return to caller */ + char* buffer; /* error message */ +}; +typedef jpg_error_mgr *jpg_error_ptr; + +//////////////////////////////////////////////////////////////////////////////// +// Here's the routine that will replace the standard error_exit method: +//////////////////////////////////////////////////////////////////////////////// +static void +ima_jpeg_error_exit (j_common_ptr cinfo) +{ + /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */ + jpg_error_ptr myerr = (jpg_error_ptr) cinfo->err; + /* Create the message */ + myerr->pub.format_message (cinfo, myerr->buffer); + /* Send it to stderr, adding a newline */ + /* Return control to the setjmp point */ + longjmp(myerr->setjmp_buffer, 1); +} +//////////////////////////////////////////////////////////////////////////////// +CxImageJPG::CxImageJPG(): CxImage(CXIMAGE_FORMAT_JPG) +{ +#if CXIMAGEJPG_SUPPORT_EXIF + m_exif = NULL; + memset(&m_exifinfo, 0, sizeof(EXIFINFO)); +#endif +} +//////////////////////////////////////////////////////////////////////////////// +CxImageJPG::~CxImageJPG() +{ +#if CXIMAGEJPG_SUPPORT_EXIF + if (m_exif) delete m_exif; +#endif +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGEJPG_SUPPORT_EXIF +bool CxImageJPG::DecodeExif(CxFile * hFile) +{ + m_exif = new CxExifInfo(&m_exifinfo); + if (m_exif){ + long pos=hFile->Tell(); + m_exif->DecodeExif(hFile); + hFile->Seek(pos,SEEK_SET); + return m_exif->m_exifinfo->IsExif; + } else { + return false; + } +} +#endif //CXIMAGEJPG_SUPPORT_EXIF +//////////////////////////////////////////////////////////////////////////////// +bool CxImageJPG::Decode(CxFile * hFile) +{ + + bool is_exif = false; +#if CXIMAGEJPG_SUPPORT_EXIF + is_exif = DecodeExif(hFile); +#endif + + CImageIterator iter(this); + /* This struct contains the JPEG decompression parameters and pointers to + * working space (which is allocated as needed by the JPEG library). + */ + struct jpeg_decompress_struct cinfo; + /* We use our private extension JPEG error handler. */ + struct jpg_error_mgr jerr; + jerr.buffer=info.szLastError; + /* More stuff */ + JSAMPARRAY buffer; /* Output row buffer */ + int row_stride; /* physical row width in output buffer */ + + /* In this example we want to open the input file before doing anything else, + * so that the setjmp() error recovery below can assume the file is open. + * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that + * requires it in order to read binary files. + */ + + /* Step 1: allocate and initialize JPEG decompression object */ + /* We set up the normal JPEG error routines, then override error_exit. */ + cinfo.err = jpeg_std_error(&jerr.pub); + jerr.pub.error_exit = ima_jpeg_error_exit; + + /* Establish the setjmp return context for my_error_exit to use. */ + if (setjmp(jerr.setjmp_buffer)) { + /* If we get here, the JPEG code has signaled an error. + * We need to clean up the JPEG object, close the input file, and return. + */ + jpeg_destroy_decompress(&cinfo); + return 0; + } + /* Now we can initialize the JPEG decompression object. */ + jpeg_create_decompress(&cinfo); + + /* Step 2: specify data source (eg, a file) */ + //jpeg_stdio_src(&cinfo, infile); + CxFileJpg src(hFile); + cinfo.src = &src; + + /* Step 3: read file parameters with jpeg_read_header() */ + (void) jpeg_read_header(&cinfo, TRUE); + + /* Step 4 handle decoder options*/ + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_GRAYSCALE) != 0) + cinfo.out_color_space = JCS_GRAYSCALE; + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_QUANTIZE) != 0) { + cinfo.quantize_colors = TRUE; + cinfo.desired_number_of_colors = info.nQuality; + } + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_DITHER) != 0) + cinfo.dither_mode = m_nDither; + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_ONEPASS) != 0) + cinfo.two_pass_quantize = FALSE; + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_NOSMOOTH) != 0) + cinfo.do_fancy_upsampling = FALSE; + +//: Load true color images as RGB (no quantize) +/* Step 4: set parameters for decompression */ +/* if (cinfo.jpeg_color_space!=JCS_GRAYSCALE) { + * cinfo.quantize_colors = TRUE; + * cinfo.desired_number_of_colors = 128; + *} + */ // + + // Set the scale + cinfo.scale_denom = GetJpegScale(); + + // Borrowed the idea from GIF implementation + if (info.nEscape == -1) { + // Return output dimensions only + jpeg_calc_output_dimensions(&cinfo); + head.biWidth = cinfo.output_width; + head.biHeight = cinfo.output_height; + jpeg_destroy_decompress(&cinfo); + return true; + } + + /* Step 5: Start decompressor */ + jpeg_start_decompress(&cinfo); + + /* We may need to do some setup of our own at this point before reading + * the data. After jpeg_start_decompress() we have the correct scaled + * output image dimensions available, as well as the output colormap + * if we asked for color quantization. + */ + //Create the image using output dimensions + //Create(cinfo.image_width, cinfo.image_height, 8*cinfo.output_components, CXIMAGE_FORMAT_JPG); + Create(cinfo.output_width, cinfo.output_height, 8*cinfo.output_components, CXIMAGE_FORMAT_JPG); + + if (!pDib) longjmp(jerr.setjmp_buffer, 1); // check if the image has been created + + if (is_exif){ +#if CXIMAGEJPG_SUPPORT_EXIF + if ((m_exifinfo.Xresolution != 0.0) && (m_exifinfo.ResolutionUnit != 0)) + SetXDPI((long)(m_exifinfo.Xresolution/m_exifinfo.ResolutionUnit)); + if ((m_exifinfo.Yresolution != 0.0) && (m_exifinfo.ResolutionUnit != 0)) + SetYDPI((long)(m_exifinfo.Yresolution/m_exifinfo.ResolutionUnit)); +#endif + } else { + if (cinfo.density_unit==2){ + SetXDPI((long)floor(cinfo.X_density * 254.0 / 10000.0 + 0.5)); + SetYDPI((long)floor(cinfo.Y_density * 254.0 / 10000.0 + 0.5)); + } else { + SetXDPI(cinfo.X_density); + SetYDPI(cinfo.Y_density); + } + } + + if (cinfo.out_color_space==JCS_GRAYSCALE){ + SetGrayPalette(); + head.biClrUsed =256; + } else { + if (cinfo.quantize_colors==TRUE){ + SetPalette(cinfo.actual_number_of_colors, cinfo.colormap[0], cinfo.colormap[1], cinfo.colormap[2]); + head.biClrUsed=cinfo.actual_number_of_colors; + } else { + head.biClrUsed=0; + } + } + + /* JSAMPLEs per row in output buffer */ + row_stride = cinfo.output_width * cinfo.output_components; + + /* Make a one-row-high sample array that will go away when done with image */ + buffer = (*cinfo.mem->alloc_sarray) + ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); + + /* Step 6: while (scan lines remain to be read) */ + /* jpeg_read_scanlines(...); */ + /* Here we use the library's state variable cinfo.output_scanline as the + * loop counter, so that we don't have to keep track ourselves. + */ + iter.Upset(); + while (cinfo.output_scanline < cinfo.output_height) { + + if (info.nEscape) longjmp(jerr.setjmp_buffer, 1); // - cancel decoding + + (void) jpeg_read_scanlines(&cinfo, buffer, 1); + // info.nProgress = (long)(100*cinfo.output_scanline/cinfo.output_height); + // Step 6a: CMYK->RGB */ + if ((cinfo.num_components==4)&&(cinfo.quantize_colors==FALSE)){ + BYTE k,*dst,*src; + dst=iter.GetRow(); + src=buffer[0]; + for(long x3=0,x4=0; x3<(long)info.dwEffWidth && x4 Step 7A: Swap red and blue components + // not necessary if swapped red and blue definition in jmorecfg.h;ln322 + if ((cinfo.num_components==3)&&(cinfo.quantize_colors==FALSE)){ + BYTE* r0=GetBits(); + for(long y=0;y - cancel decoding + RGBtoBGR(r0,3*head.biWidth); + r0+=info.dwEffWidth; + } + } + + /* Step 8: Release JPEG decompression object */ + /* This is an important step since it will release a good deal of memory. */ + jpeg_destroy_decompress(&cinfo); + + /* At this point you may want to check to see whether any corrupt-data + * warnings occurred (test whether jerr.pub.num_warnings is nonzero). + */ + + /* And we're done! */ + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImageJPG::Encode(CxFile * hFile) +{ + if (EncodeSafeCheck(hFile)) return false; + + if (head.biClrUsed!=0 && !IsGrayScale()){ + strcpy(info.szLastError,"JPEG can save only RGB or GreyScale images"); + return false; + } + + // necessary for EXIF, and for roll backs + long pos=hFile->Tell(); + + /* This struct contains the JPEG compression parameters and pointers to + * working space (which is allocated as needed by the JPEG library). + * It is possible to have several such structures, representing multiple + * compression/decompression processes, in existence at once. We refer + * to any one struct (and its associated working data) as a "JPEG object". + */ + struct jpeg_compress_struct cinfo; + /* This struct represents a JPEG error handler. It is declared separately + * because applications often want to supply a specialized error handler + * (see the second half of this file for an example). But here we just + * take the easy way out and use the standard error handler, which will + * print a message on stderr and call exit() if compression fails. + * Note that this struct must live as long as the main JPEG parameter + * struct, to avoid dangling-pointer problems. + */ + //struct jpeg_error_mgr jerr; + /* We use our private extension JPEG error handler. */ + struct jpg_error_mgr jerr; + jerr.buffer=info.szLastError; + /* More stuff */ + int row_stride; /* physical row width in image buffer */ + JSAMPARRAY buffer; /* Output row buffer */ + + /* Step 1: allocate and initialize JPEG compression object */ + /* We have to set up the error handler first, in case the initialization + * step fails. (Unlikely, but it could happen if you are out of memory.) + * This routine fills in the contents of struct jerr, and returns jerr's + * address which we place into the link field in cinfo. + */ + //cinfo.err = jpeg_std_error(&jerr); + /* We set up the normal JPEG error routines, then override error_exit. */ + cinfo.err = jpeg_std_error(&jerr.pub); + jerr.pub.error_exit = ima_jpeg_error_exit; + + /* Establish the setjmp return context for my_error_exit to use. */ + if (setjmp(jerr.setjmp_buffer)) { + /* If we get here, the JPEG code has signaled an error. + * We need to clean up the JPEG object, close the input file, and return. + */ + strcpy(info.szLastError, jerr.buffer); // + jpeg_destroy_compress(&cinfo); + return 0; + } + + /* Now we can initialize the JPEG compression object. */ + jpeg_create_compress(&cinfo); + /* Step 2: specify data destination (eg, a file) */ + /* Note: steps 2 and 3 can be done in either order. */ + /* Here we use the library-supplied code to send compressed data to a + * stdio stream. You can also write your own code to do something else. + * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that + * requires it in order to write binary files. + */ + + //jpeg_stdio_dest(&cinfo, outfile); + CxFileJpg dest(hFile); + cinfo.dest = &dest; + + /* Step 3: set parameters for compression */ + /* First we supply a description of the input image. + * Four fields of the cinfo struct must be filled in: + */ + cinfo.image_width = GetWidth(); // image width and height, in pixels + cinfo.image_height = GetHeight(); + + if (IsGrayScale()){ + cinfo.input_components = 1; // # of color components per pixel + cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */ + } else { + cinfo.input_components = 3; // # of color components per pixel + cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ + } + + /* Now use the library's routine to set default compression parameters. + * (You must set at least cinfo.in_color_space before calling this, + * since the defaults depend on the source color space.) + */ + jpeg_set_defaults(&cinfo); + /* Now you can set any non-default parameters you wish to. + * Here we just illustrate the use of quality (quantization table) scaling: + */ + +//#ifdef C_ARITH_CODING_SUPPORTED + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & ENCODE_ARITHMETIC) != 0) + cinfo.arith_code = TRUE; +//#endif + +//#ifdef ENTROPY_OPT_SUPPORTED + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & ENCODE_OPTIMIZE) != 0) + cinfo.optimize_coding = TRUE; +//#endif + + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & ENCODE_GRAYSCALE) != 0) + jpeg_set_colorspace(&cinfo, JCS_GRAYSCALE); + + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & ENCODE_SMOOTHING) != 0) + cinfo.smoothing_factor = m_nSmoothing; + + jpeg_set_quality(&cinfo, GetJpegQuality(), (GetCodecOption(CXIMAGE_FORMAT_JPG) & ENCODE_BASELINE) != 0); + +//#ifdef C_PROGRESSIVE_SUPPORTED + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & ENCODE_PROGRESSIVE) != 0) + jpeg_simple_progression(&cinfo); +//#endif + +#ifdef C_LOSSLESS_SUPPORTED + if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & ENCODE_LOSSLESS) != 0) + jpeg_simple_lossless(&cinfo, m_nPredictor, m_nPointTransform); +#endif + + cinfo.density_unit=1; + cinfo.X_density=(unsigned short)GetXDPI(); + cinfo.Y_density=(unsigned short)GetYDPI(); + + /* Step 4: Start compressor */ + /* TRUE ensures that we will write a complete interchange-JPEG file. + * Pass TRUE unless you are very sure of what you're doing. + */ + jpeg_start_compress(&cinfo, TRUE); + + /* Step 5: while (scan lines remain to be written) */ + /* jpeg_write_scanlines(...); */ + /* Here we use the library's state variable cinfo.next_scanline as the + * loop counter, so that we don't have to keep track ourselves. + * To keep things simple, we pass one scanline per call; you can pass + * more if you wish, though. + */ + row_stride = info.dwEffWidth; /* JSAMPLEs per row in image_buffer */ + + // "8+row_stride" fix heap deallocation problem during debug??? + buffer = (*cinfo.mem->alloc_sarray) + ((j_common_ptr) &cinfo, JPOOL_IMAGE, 8+row_stride, 1); + + CImageIterator iter(this); + + iter.Upset(); + while (cinfo.next_scanline < cinfo.image_height) { + // info.nProgress = (long)(100*cinfo.next_scanline/cinfo.image_height); + iter.GetRow(buffer[0], row_stride); + // not necessary if swapped red and blue definition in jmorecfg.h;ln322 + if (head.biClrUsed==0){ // swap R & B for RGB images + RGBtoBGR(buffer[0], row_stride); // Lance : 1998/09/01 : Bug ID: EXP-2.1.1-9 + } + iter.PrevRow(); + (void) jpeg_write_scanlines(&cinfo, buffer, 1); + } + + /* Step 6: Finish compression */ + jpeg_finish_compress(&cinfo); + + /* Step 7: release JPEG compression object */ + /* This is an important step since it will release a good deal of memory. */ + jpeg_destroy_compress(&cinfo); + + +#if CXIMAGEJPG_SUPPORT_EXIF + if (m_exif && m_exif->m_exifinfo->IsExif){ + // discard useless sections (if any) read from original image + m_exif->DiscardAllButExif(); + // read new created image, to split the sections + hFile->Seek(pos,SEEK_SET); + m_exif->DecodeExif(hFile,EXIF_READ_IMAGE); + // save back the image, adding EXIF section + hFile->Seek(pos,SEEK_SET); + m_exif->EncodeExif(hFile); + } +#endif + + + /* And we're done! */ + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_JPG + diff --git a/SlnkDWFImpl/CxImage/CxImage/ximajpg.h b/SlnkDWFImpl/CxImage/CxImage/ximajpg.h new file mode 100644 index 0000000..4f5d05a --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximajpg.h @@ -0,0 +1,315 @@ +/* + * File: ximajpg.h + * Purpose: JPG Image Class Loader and Writer + */ +/* ========================================================== + * CxImageJPG (c) 07/Aug/2001 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * Special thanks to Troels Knakkergaard for new features, enhancements and bugfixes + * + * Special thanks to Chris Shearer Cooper for CxFileJpg tips & code + * + * EXIF support based on jhead-1.8 by Matthias Wandel + * + * original CImageJPG and CImageIterator implementation are: + * Copyright: (c) 1995, Alejandro Aguilar Sierra + * + * This software is based in part on the work of the Independent JPEG Group. + * Copyright (C) 1991-1998, Thomas G. Lane. + * ========================================================== + */ +#if !defined(__ximaJPEG_h) +#define __ixmaJPEG_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_JPG + +#define CXIMAGEJPG_SUPPORT_EXIF 1 + +extern "C" { + #include "../jpeg/jpeglib.h" + #include "../jpeg/jerror.h" +} + +class DLL_EXP CxImageJPG: public CxImage +{ +public: + CxImageJPG(); + ~CxImageJPG(); + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_JPG);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_JPG);} + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE + +/* + * EXIF support based on jhead-1.8 by Matthias Wandel + */ + +#if CXIMAGEJPG_SUPPORT_EXIF + +#define MAX_COMMENT 1000 +#define MAX_SECTIONS 20 + +typedef struct tag_ExifInfo { + char Version [5]; + char CameraMake [32]; + char CameraModel [40]; + char DateTime [20]; + int Height, Width; + int Orientation; + int IsColor; + int Process; + int FlashUsed; + float FocalLength; + float ExposureTime; + float ApertureFNumber; + float Distance; + float CCDWidth; + float ExposureBias; + int Whitebalance; + int MeteringMode; + int ExposureProgram; + int ISOequivalent; + int CompressionLevel; + float FocalplaneXRes; + float FocalplaneYRes; + float FocalplaneUnits; + float Xresolution; + float Yresolution; + float ResolutionUnit; + float Brightness; + char Comments[MAX_COMMENT]; + + unsigned char * ThumbnailPointer; /* Pointer at the thumbnail */ + unsigned ThumbnailSize; /* Size of thumbnail. */ + + bool IsExif; +} EXIFINFO; + +//-------------------------------------------------------------------------- +// JPEG markers consist of one or more 0xFF bytes, followed by a marker +// code byte (which is not an FF). Here are the marker codes of interest +// in this program. (See jdmarker.c for a more complete list.) +//-------------------------------------------------------------------------- + +#define M_SOF0 0xC0 // Start Of Frame N +#define M_SOF1 0xC1 // N indicates which compression process +#define M_SOF2 0xC2 // Only SOF0-SOF2 are now in common use +#define M_SOF3 0xC3 +#define M_SOF5 0xC5 // NB: codes C4 and CC are NOT SOF markers +#define M_SOF6 0xC6 +#define M_SOF7 0xC7 +#define M_SOF9 0xC9 +#define M_SOF10 0xCA +#define M_SOF11 0xCB +#define M_SOF13 0xCD +#define M_SOF14 0xCE +#define M_SOF15 0xCF +#define M_SOI 0xD8 // Start Of Image (beginning of datastream) +#define M_EOI 0xD9 // End Of Image (end of datastream) +#define M_SOS 0xDA // Start Of Scan (begins compressed data) +#define M_JFIF 0xE0 // Jfif marker +#define M_EXIF 0xE1 // Exif marker +#define M_COM 0xFE // COMment + +#define PSEUDO_IMAGE_MARKER 0x123; // Extra value. + +#define EXIF_READ_EXIF 0x01 +#define EXIF_READ_IMAGE 0x02 +#define EXIF_READ_ALL 0x03 + +class DLL_EXP CxExifInfo +{ + +typedef struct tag_Section_t{ + BYTE* Data; + int Type; + unsigned Size; +} Section_t; + +public: + EXIFINFO* m_exifinfo; + char m_szLastError[256]; + CxExifInfo(EXIFINFO* info = NULL); + ~CxExifInfo(); + bool DecodeExif(CxFile * hFile, int nReadMode = EXIF_READ_EXIF); + bool EncodeExif(CxFile * hFile); + void DiscardAllButExif(); +protected: + bool process_EXIF(unsigned char * CharBuf, unsigned int length); + void process_COM (const BYTE * Data, int length); + void process_SOFn (const BYTE * Data, int marker); + int Get16u(void * Short); + int Get16m(void * Short); + long Get32s(void * Long); + unsigned long Get32u(void * Long); + double ConvertAnyFormat(void * ValuePtr, int Format); + void* FindSection(int SectionType); + bool ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength, + EXIFINFO * const pInfo, unsigned char ** const LastExifRefdP); + int ExifImageWidth; + int MotorolaOrder; + Section_t Sections[MAX_SECTIONS]; + int SectionsRead; + bool freeinfo; +}; + + CxExifInfo* m_exif; + EXIFINFO m_exifinfo; + bool DecodeExif(CxFile * hFile); + bool DecodeExif(FILE * hFile) { CxIOFile file(hFile); return DecodeExif(&file); } + +#endif //CXIMAGEJPG_SUPPORT_EXIF + +//////////////////////////////////////////////////////////////////////////////////////// +////////////////////// C x F i l e J p g //////////////////////////////// +//////////////////////////////////////////////////////////////////////////////////////// + +// thanks to Chris Shearer Cooper +class CxFileJpg : public jpeg_destination_mgr, public jpeg_source_mgr + { +public: + enum { eBufSize = 4096 }; + + CxFileJpg(CxFile* pFile) + { + m_pFile = pFile; + + init_destination = InitDestination; + empty_output_buffer = EmptyOutputBuffer; + term_destination = TermDestination; + + init_source = InitSource; + fill_input_buffer = FillInputBuffer; + skip_input_data = SkipInputData; + resync_to_restart = jpeg_resync_to_restart; // use default method + term_source = TermSource; + next_input_byte = NULL; //* => next byte to read from buffer + bytes_in_buffer = 0; //* # of bytes remaining in buffer + + m_pBuffer = new unsigned char[eBufSize]; + } + ~CxFileJpg() + { + delete [] m_pBuffer; + } + + static void InitDestination(j_compress_ptr cinfo) + { + CxFileJpg* pDest = (CxFileJpg*)cinfo->dest; + pDest->next_output_byte = pDest->m_pBuffer; + pDest->free_in_buffer = eBufSize; + } + + static boolean EmptyOutputBuffer(j_compress_ptr cinfo) + { + CxFileJpg* pDest = (CxFileJpg*)cinfo->dest; + if (pDest->m_pFile->Write(pDest->m_pBuffer,1,eBufSize)!=(size_t)eBufSize) + ERREXIT(cinfo, JERR_FILE_WRITE); + pDest->next_output_byte = pDest->m_pBuffer; + pDest->free_in_buffer = eBufSize; + return TRUE; + } + + static void TermDestination(j_compress_ptr cinfo) + { + CxFileJpg* pDest = (CxFileJpg*)cinfo->dest; + size_t datacount = eBufSize - pDest->free_in_buffer; + /* Write any data remaining in the buffer */ + if (datacount > 0) { + if (!pDest->m_pFile->Write(pDest->m_pBuffer,1,datacount)) + ERREXIT(cinfo, JERR_FILE_WRITE); + } + pDest->m_pFile->Flush(); + /* Make sure we wrote the output file OK */ + if (pDest->m_pFile->Error()) ERREXIT(cinfo, JERR_FILE_WRITE); + return; + } + + static void InitSource(j_decompress_ptr cinfo) + { + CxFileJpg* pSource = (CxFileJpg*)cinfo->src; + pSource->m_bStartOfFile = TRUE; + } + + static boolean FillInputBuffer(j_decompress_ptr cinfo) + { + size_t nbytes; + CxFileJpg* pSource = (CxFileJpg*)cinfo->src; + nbytes = pSource->m_pFile->Read(pSource->m_pBuffer,1,eBufSize); + if (nbytes <= 0){ + if (pSource->m_bStartOfFile) //* Treat empty input file as fatal error + ERREXIT(cinfo, JERR_INPUT_EMPTY); + WARNMS(cinfo, JWRN_JPEG_EOF); + // Insert a fake EOI marker + pSource->m_pBuffer[0] = (JOCTET) 0xFF; + pSource->m_pBuffer[1] = (JOCTET) JPEG_EOI; + nbytes = 2; + } + pSource->next_input_byte = pSource->m_pBuffer; + pSource->bytes_in_buffer = nbytes; + pSource->m_bStartOfFile = FALSE; + return TRUE; + } + + static void SkipInputData(j_decompress_ptr cinfo, long num_bytes) + { + CxFileJpg* pSource = (CxFileJpg*)cinfo->src; + if (num_bytes > 0){ + while (num_bytes > (long)pSource->bytes_in_buffer){ + num_bytes -= (long)pSource->bytes_in_buffer; + FillInputBuffer(cinfo); + // note we assume that fill_input_buffer will never return FALSE, + // so suspension need not be handled. + } + pSource->next_input_byte += (size_t) num_bytes; + pSource->bytes_in_buffer -= (size_t) num_bytes; + } + } + + static void TermSource(j_decompress_ptr cinfo) + { + return; + } +protected: + CxFile *m_pFile; + unsigned char *m_pBuffer; + bool m_bStartOfFile; +}; + +public: + enum CODEC_OPTION + { + ENCODE_BASELINE = 0x1, + ENCODE_ARITHMETIC = 0x2, + ENCODE_GRAYSCALE = 0x4, + ENCODE_OPTIMIZE = 0x8, + ENCODE_PROGRESSIVE = 0x10, + ENCODE_LOSSLESS = 0x20, + ENCODE_SMOOTHING = 0x40, + DECODE_GRAYSCALE = 0x80, + DECODE_QUANTIZE = 0x100, + DECODE_DITHER = 0x200, + DECODE_ONEPASS = 0x400, + DECODE_NOSMOOTH = 0x800 + }; + + int m_nPredictor; + int m_nPointTransform; + int m_nSmoothing; + int m_nQuantize; + J_DITHER_MODE m_nDither; + +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximalpha.cpp b/SlnkDWFImpl/CxImage/CxImage/ximalpha.cpp new file mode 100644 index 0000000..0adfb73 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximalpha.cpp @@ -0,0 +1,321 @@ +// xImalpha.cpp : Alpha channel functions +/* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_ALPHA + +//////////////////////////////////////////////////////////////////////////////// +/** + * \sa AlphaSetMax + */ +BYTE CxImage::AlphaGetMax() const +{ + return info.nAlphaMax; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Sets global Alpha (opacity) value applied to the whole image, + * valid only for painting functions. + * \param nAlphaMax: can be from 0 to 255 + */ +void CxImage::AlphaSetMax(BYTE nAlphaMax) +{ + info.nAlphaMax=nAlphaMax; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Checks if the image has a valid alpha channel. + */ +bool CxImage::AlphaIsValid() +{ + return pAlpha!=0; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Enables the alpha palette, so the Draw() function changes its behavior. + */ +void CxImage::AlphaPaletteEnable(bool enable) +{ + info.bAlphaPaletteEnabled=enable; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * True if the alpha palette is enabled for painting. + */ +bool CxImage::AlphaPaletteIsEnabled() +{ + return info.bAlphaPaletteEnabled; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Inverts the alpha channel. + */ +void CxImage::AlphaClear() +{ + if (pAlpha) memset(pAlpha,0,head.biWidth * head.biHeight); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Sets the alpha level for the whole image + */ +void CxImage::AlphaSet(BYTE level) +{ + if (pAlpha) memset(pAlpha,level,head.biWidth * head.biHeight); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Allocates an empty (opaque) alpha channel. + */ +void CxImage::AlphaCreate() +{ + if (pAlpha==NULL) { + pAlpha = (BYTE*)malloc(head.biWidth * head.biHeight); + if (pAlpha) memset(pAlpha,255,head.biWidth * head.biHeight); + } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImage::AlphaDelete() +{ + if (pAlpha) { free(pAlpha); pAlpha=0; } +} +//////////////////////////////////////////////////////////////////////////////// +void CxImage::AlphaInvert() +{ + if (pAlpha) { + BYTE *iSrc=pAlpha; + long n=head.biHeight*head.biWidth; + for(long i=0; i < n; i++){ + *iSrc=(BYTE)~(*(iSrc)); + iSrc++; + } + } +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Imports an existing alpa channel from another image with the same width and height. + */ +bool CxImage::AlphaCopy(CxImage &from) +{ + if (from.pAlpha == NULL || head.biWidth != from.head.biWidth || head.biHeight != from.head.biHeight) return false; + if (pAlpha==NULL) pAlpha = (BYTE*)malloc(head.biWidth * head.biHeight); + if (pAlpha==NULL) return false; + memcpy(pAlpha,from.pAlpha,head.biWidth * head.biHeight); + info.nAlphaMax=from.info.nAlphaMax; + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Creates the alpha channel from a gray scale image. + */ +bool CxImage::AlphaSet(CxImage &from) +{ + if (!from.IsGrayScale() || head.biWidth != from.head.biWidth || head.biHeight != from.head.biHeight) return false; + if (pAlpha==NULL) pAlpha = (BYTE*)malloc(head.biWidth * head.biHeight); + BYTE* src = from.info.pImage; + BYTE* dst = pAlpha; + if (src==NULL || dst==NULL) return false; + for (long y=0; yTransfer(tmp); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Exports the alpha palette channel in a 8bpp grayscale image. + */ +bool CxImage::AlphaPaletteSplit(CxImage *dest) +{ + if (!AlphaPaletteIsValid() || !dest) return false; + + CxImage tmp(head.biWidth,head.biHeight,8); + if (!tmp.IsValid()) return false; + + for(long y=0; yTransfer(tmp); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_ALPHA diff --git a/SlnkDWFImpl/CxImage/CxImage/ximalyr.cpp b/SlnkDWFImpl/CxImage/CxImage/ximalyr.cpp new file mode 100644 index 0000000..b9df70c --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximalyr.cpp @@ -0,0 +1,105 @@ +// xImaLyr.cpp : Layers functions +/* 21/04/2003 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_LAYERS + +//////////////////////////////////////////////////////////////////////////////// +/** + * If the object is an internal layer, GetParent return its parent in the hierarchy. + */ +CxImage* CxImage::GetParent() const +{ + return info.pParent; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Number of layers allocated directly by the object. + */ +long CxImage::GetNumLayers() const +{ + return info.nNumLayers; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Creates an empty layer. If position is less than 0, the new layer will be placed in the last position + */ +bool CxImage::LayerCreate(long position) +{ + if ( position < 0 || position > info.nNumLayers ) position = info.nNumLayers; + + CxImage** ptmp = (CxImage**)malloc((info.nNumLayers + 1)*sizeof(CxImage**)); + if (ptmp==0) return false; + + int i=0; + for (int n=0; ninfo.pParent = this; + } else { + free(ptmp); + return false; + } + + info.nNumLayers++; + if (pLayers) free(pLayers); + pLayers = ptmp; + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Deletes a layer. If position is less than 0, the last layer will be deleted + */ +bool CxImage::LayerDelete(long position) +{ + if ( position >= info.nNumLayers ) return false; + if ( position < 0) position = info.nNumLayers - 1; + + CxImage** ptmp = (CxImage**)malloc((info.nNumLayers - 1)*sizeof(CxImage**)); + if (ptmp==0) return false; + + int i=0; + for (int n=0; n<(info.nNumLayers - 1); n++){ + if (position == n){ + delete pLayers[n]; + i=1; + } + ptmp[n]=pLayers[n+i]; + } + if (i==0) delete pLayers[info.nNumLayers - 1]; + + info.nNumLayers--; + if (pLayers) free(pLayers); + pLayers = ptmp; + return true; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImage::LayerDeleteAll() +{ + if (pLayers) { + for(long n=0; n= info.nNumLayers ) return 0; + if ( position < 0) position = info.nNumLayers - 1; + return pLayers[position]; +} +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_LAYERS diff --git a/SlnkDWFImpl/CxImage/CxImage/ximamng.cpp b/SlnkDWFImpl/CxImage/CxImage/ximamng.cpp new file mode 100644 index 0000000..c6f316e --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximamng.cpp @@ -0,0 +1,366 @@ +/* + * File: ximamng.cpp + * Purpose: Platform Independent MNG Image Class Loader and Writer + * Author: 07/Aug/2001 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximamng.h" + +#if CXIMAGE_SUPPORT_MNG + +//////////////////////////////////////////////////////////////////////////////// +// callbacks for the mng decoder: +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// memory allocation; data must be zeroed +static mng_ptr +mymngalloc( mng_uint32 size ) +{ + return (mng_ptr)calloc(1, size); +} + +//////////////////////////////////////////////////////////////////////////////// +// memory deallocation +static void mymngfree(mng_ptr p, mng_uint32 size) +{ + free(p); +} + +//////////////////////////////////////////////////////////////////////////////// +// Stream open/close: +// since the user is responsible for opening and closing the file, +// we leave the default implementation open +static mng_bool mymngopenstream(mng_handle mng) { return MNG_TRUE; } +static mng_bool mymngopenstreamwrite(mng_handle mng) { return MNG_TRUE; } +static mng_bool mymngclosestream(mng_handle mng) { return MNG_TRUE; } + +//////////////////////////////////////////////////////////////////////////////// +// feed data to the decoder +static mng_bool mymngreadstream(mng_handle mng, mng_ptr buffer, mng_uint32 size, mng_uint32 *bytesread) +{ + mngstuff *mymng = (mngstuff *)mng_get_userdata(mng); + // read the requested amount of data from the file + *bytesread = mymng->file->Read( buffer, sizeof(BYTE), size); + return MNG_TRUE; +} + +//////////////////////////////////////////////////////////////////////////////// +static mng_bool mymngwritestream (mng_handle mng, mng_ptr pBuf, mng_uint32 iSize, mng_uint32 *iWritten) +{ + mngstuff *mymng = (mngstuff *)mng_get_userdata(mng); + // write it + *iWritten = mymng->file->Write (pBuf, 1, iSize); + return MNG_TRUE; +} + +//////////////////////////////////////////////////////////////////////////////// +// the header's been read. set up the display stuff +static mng_bool mymngprocessheader( mng_handle mng, mng_uint32 width, mng_uint32 height ) +{ + // normally the image buffer is allocated here, + // but in this module we don't know nothing about + // the final environment. + + mngstuff *mymng = (mngstuff *)mng_get_userdata(mng); + + mymng->width = width; + mymng->height = height; + mymng->bpp = 24; + mymng->effwdt = ((((width * mymng->bpp) + 31) >> 5) << 2); + + if (mng->bUseBKGD){ + mymng->nBkgndIndex = 0; + mymng->nBkgndColor.rgbRed = mng->iBGred >> 8; + mymng->nBkgndColor.rgbGreen =mng->iBGgreen >> 8; + mymng->nBkgndColor.rgbBlue = mng->iBGblue >> 8; + } + + mymng->image = (BYTE*)malloc(height * mymng->effwdt); + + // tell the mng decoder about our bit-depth choice + mng_set_canvasstyle( mng, MNG_CANVAS_BGR8 ); + return MNG_TRUE; +} + +//////////////////////////////////////////////////////////////////////////////// +// return a row pointer for the decoder to fill +static mng_ptr mymnggetcanvasline( mng_handle mng, mng_uint32 line ) +{ + mngstuff *mymng = (mngstuff *)mng_get_userdata(mng); + return (mng_ptr)(mymng->image + (mymng->effwdt * (mymng->height - 1 - line))); +} + +//////////////////////////////////////////////////////////////////////////////// +// timer +static mng_uint32 mymnggetticks(mng_handle mng) +{ +#ifdef WIN32 + return (mng_uint32)GetTickCount(); +#else + return 0; +#endif +} + +//////////////////////////////////////////////////////////////////////////////// +// Refresh: actual frame need to be updated (Invalidate) +static mng_bool mymngrefresh(mng_handle mng, mng_uint32 x, mng_uint32 y, mng_uint32 w, mng_uint32 h) +{ +// mngstuff *mymng = (mngstuff *)mng_get_userdata(mng); + return MNG_TRUE; +} + +//////////////////////////////////////////////////////////////////////////////// +// interframe delay callback +static mng_bool mymngsettimer(mng_handle mng, mng_uint32 msecs) +{ + mngstuff *mymng = (mngstuff *)mng_get_userdata(mng); + mymng->delay = msecs; // set the timer for when the decoder wants to be woken + return MNG_TRUE; +} + +//////////////////////////////////////////////////////////////////////////////// +static mng_bool mymngerror(mng_handle mng, mng_int32 code, mng_int8 severity, mng_chunkid chunktype, mng_uint32 chunkseq, mng_int32 extra1, mng_int32 extra2, mng_pchar text) +{ + //throw (const char *)text; + return mng_cleanup(&mng); // +} + +//////////////////////////////////////////////////////////////////////////////// +// CxImage members +//////////////////////////////////////////////////////////////////////////////// +CxImageMNG::CxImageMNG(): CxImage(CXIMAGE_FORMAT_MNG) +{ + hmng = NULL; + memset(&mnginfo,0,sizeof(mngstuff)); + mnginfo.nBkgndIndex = -1; + mnginfo.speed = 1.0f; +} +//////////////////////////////////////////////////////////////////////////////// +CxImageMNG::~CxImageMNG() +{ + // cleanup and return + if (mnginfo.thread){ //close the animation thread + mnginfo.animation_enabled=0; + ResumeThread(mnginfo.thread); + WaitForSingleObject(mnginfo.thread,500); + CloseHandle(mnginfo.thread); + } + // free objects + if (mnginfo.image) free(mnginfo.image); + if (hmng) mng_cleanup(&hmng); //be sure it's not needed any more. (active timers ?) +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageMNG::SetCallbacks(mng_handle mng) +{ + // set the callbacks + mng_setcb_errorproc(mng, mymngerror); + mng_setcb_openstream(mng, mymngopenstream); + mng_setcb_closestream(mng, mymngclosestream); + mng_setcb_readdata(mng, mymngreadstream); + mng_setcb_processheader(mng, mymngprocessheader); + mng_setcb_getcanvasline(mng, mymnggetcanvasline); + mng_setcb_refresh(mng, mymngrefresh); + mng_setcb_gettickcount(mng, mymnggetticks); + mng_setcb_settimer(mng, mymngsettimer); + mng_setcb_refresh(mng, mymngrefresh); +} +//////////////////////////////////////////////////////////////////////////////// +// can't use the CxImage implementation because it looses mnginfo +bool CxImageMNG::Load(const char * imageFileName){ + FILE* hFile; //file handle to read the image + if ((hFile=fopen(imageFileName,"rb"))==NULL) return false; + bool bOK = Decode(hFile); + fclose(hFile); + return bOK; +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImageMNG::Decode(CxFile *hFile) +{ + if (hFile == NULL) return false; + + try { + // set up the mng decoder for our stream + hmng = mng_initialize(&mnginfo, mymngalloc, mymngfree, MNG_NULL); + if (hmng == NULL) throw "could not initialize libmng"; + + // set the file we want to play + mnginfo.file = hFile; + + // Set the colorprofile, lcms uses this: + mng_set_srgb(hmng, MNG_TRUE ); + // Set white as background color: + WORD Red,Green,Blue; + Red = Green = Blue = (255 << 8) + 255; + mng_set_bgcolor(hmng, Red, Green, Blue ); + // If PNG Background is available, use it: + mng_set_usebkgd(hmng, MNG_TRUE ); + + // No need to store chunks: + mng_set_storechunks(hmng, MNG_FALSE); + // No need to wait: straight reading + mng_set_suspensionmode(hmng, MNG_FALSE); + + SetCallbacks(hmng); + + mng_datap pData = (mng_datap)hmng; + + // read in the image + info.nNumFrames=0; + mng_readdisplay(hmng); + + // read all + int retval=MNG_NOERROR; + while(pData->bReading){ + retval = mng_display_resume(hmng); + info.nNumFrames++; + } + + // single frame check: + if (retval != MNG_NEEDTIMERWAIT){ + info.nNumFrames--; + } else { + mnginfo.animation=1; + } + + if (info.nNumFrames<=0) info.nNumFrames=1; + + if (mnginfo.animation_enabled==0){ + // select the frame + if (info.nFrame>=0 && info.nFramewidth,OffsetH=mymng->height; + + BYTE *tmpbuffer = new BYTE[ (mymng->effwdt+1) * mymng->height]; + if( tmpbuffer == 0 ) return; + + // Write DEFI chunk. + mng_putchunk_defi( hMNG, 0, 0, 0, MNG_TRUE, OffsetX, OffsetY, MNG_FALSE, 0, 0, 0, 0 ); + + // Write Header: + mng_putchunk_ihdr( + hMNG, + OffsetW, OffsetH, + MNG_BITDEPTH_8, + MNG_COLORTYPE_RGB, + MNG_COMPRESSION_DEFLATE, + MNG_FILTER_ADAPTIVE, + MNG_INTERLACE_NONE + ); + + // transfer data, add Filterbyte: + for( int Row=0; Row No Filter. + tmpbuffer[Row*(mymng->effwdt+1)]=0; + // Copy the scanline: (reverse order) + memcpy(tmpbuffer+Row*(mymng->effwdt+1)+1, + mymng->image+((OffsetH-1-(OffsetY+Row))*(mymng->effwdt))+OffsetX,mymng->effwdt); + // swap red and blue components + RGBtoBGR(tmpbuffer+Row*(mymng->effwdt+1)+1,mymng->effwdt); + } + + // Compress data with ZLib (Deflate): + BYTE *dstbuffer = new BYTE[(mymng->effwdt+1)*OffsetH]; + if( dstbuffer == 0 ) return; + DWORD dstbufferSize=(mymng->effwdt+1)*OffsetH; + + // Compress data: + if(Z_OK != compress2((Bytef *)dstbuffer,(ULONG *)&dstbufferSize,(const Bytef*)tmpbuffer, + (ULONG) (mymng->effwdt+1)*OffsetH,9 )) return; + + // Write Data into MNG File: + mng_putchunk_idat( hMNG, dstbufferSize, (mng_ptr*)dstbuffer); + mng_putchunk_iend(hMNG); + + // Free the stuff: + delete [] tmpbuffer; + delete [] dstbuffer; +} +//////////////////////////////////////////////////////////////////////////////// +long CxImageMNG::Resume() +{ + if (MNG_NEEDTIMERWAIT == mng_display_resume(hmng)){ + if (info.pImage==NULL) Create(mnginfo.width,mnginfo.height,mnginfo.bpp, CXIMAGE_FORMAT_MNG); + if (IsValid()) memcpy(GetBits(), mnginfo.image, mnginfo.effwdt * mnginfo.height); + } else { + mnginfo.animation_enabled = 0; + } + return mnginfo.animation_enabled; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageMNG::SetSpeed(float speed) +{ + if (speed>10.0) mnginfo.speed = 10.0f; + else if (speed<0.1) mnginfo.speed = 0.1f; + else mnginfo.speed=speed; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_MNG diff --git a/SlnkDWFImpl/CxImage/CxImage/ximamng.h b/SlnkDWFImpl/CxImage/CxImage/ximamng.h new file mode 100644 index 0000000..0a6ba52 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximamng.h @@ -0,0 +1,86 @@ +/* + * File: ximamng.h + * Purpose: Declaration of the MNG Image Class + * Author: Davide Pizzolato - www.xdp.it + * Created: 2001 + */ +/* ========================================================== + * CxImageMNG (c) 07/Aug/2001 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * Special thanks to Frank Haug for suggestions and code. + * + * original mng.cpp code created by Nikolaus Brennig, November 14th, 2000. + * + * LIBMNG Copyright (c) 2000,2001 Gerard Juyn (gerard@libmng.com) + * ========================================================== + */ + +#if !defined(__ximaMNG_h) +#define __ximaMNG_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_MNG + +//#define MNG_NO_CMS +#define MNG_SUPPORT_DISPLAY +#define MNG_SUPPORT_READ +#define MNG_SUPPORT_WRITE +#define MNG_ACCESS_CHUNKS +#define MNG_STORE_CHUNKS + +extern "C" { +#include "../mng/libmng.h" +#include "../mng/libmng_data.h" +} + +//unsigned long _stdcall RunMNGThread(void *lpParam); + +typedef struct tagmngstuff +{ + CxFile *file; + BYTE *image; + HANDLE thread; + mng_uint32 delay; + mng_uint32 width; + mng_uint32 height; + mng_uint32 effwdt; + mng_int16 bpp; + mng_bool animation; + mng_bool animation_enabled; + float speed; + long nBkgndIndex; + RGBQUAD nBkgndColor; +} mngstuff; + +class CxImageMNG: public CxImage +{ +public: + CxImageMNG(); + ~CxImageMNG(); + + bool Load(const char * imageFileName); + bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_MNG);} + + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE + + long Resume(); + void SetSpeed(float speed); + + mng_handle hmng; + mngstuff mnginfo; +protected: + void WritePNG(mng_handle hMNG, int Frame, int FrameCount ); + void SetCallbacks(mng_handle mng); +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximapal.cpp b/SlnkDWFImpl/CxImage/CxImage/ximapal.cpp new file mode 100644 index 0000000..cc09974 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximapal.cpp @@ -0,0 +1,707 @@ +// xImaPal.cpp : Palette and Pixel functions +/* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +//////////////////////////////////////////////////////////////////////////////// +/** + * returns the palette dimension in byte + */ +DWORD CxImage::GetPaletteSize() +{ + return (head.biClrUsed * sizeof(RGBQUAD)); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImage::SetPaletteColor(BYTE idx, BYTE r, BYTE g, BYTE b, BYTE alpha) +{ + if ((pDib)&&(head.biClrUsed)){ + BYTE* iDst = (BYTE*)(pDib) + sizeof(BITMAPINFOHEADER); + if (idx=head.biWidth)||(y>=head.biHeight)) { + if (info.nBkgndIndex != -1) return (BYTE)info.nBkgndIndex; + else return *info.pImage; + } + if (head.biBitCount==8){ + return info.pImage[y*info.dwEffWidth + x]; + } else { + BYTE pos; + BYTE iDst= info.pImage[y*info.dwEffWidth + (x*head.biBitCount >> 3)]; + if (head.biBitCount==4){ + pos = (BYTE)(4*(1-x%2)); + iDst &= (0x0F<> pos); + } else if (head.biBitCount==1){ + pos = (BYTE)(7-x%8); + iDst &= (0x01<> pos); + } + } + return 0; +} +//////////////////////////////////////////////////////////////////////////////// +BYTE CxImage::BlindGetPixelIndex(const long x,const long y) +{ +#ifdef _DEBUG + if ((pDib==NULL) || (head.biClrUsed==0) || !IsInside(x,y)) throw 0; +#endif + + if (head.biBitCount==8){ + return info.pImage[y*info.dwEffWidth + x]; + } else { + BYTE pos; + BYTE iDst= info.pImage[y*info.dwEffWidth + (x*head.biBitCount >> 3)]; + if (head.biBitCount==4){ + pos = (BYTE)(4*(1-x%2)); + iDst &= (0x0F<> pos); + } else if (head.biBitCount==1){ + pos = (BYTE)(7-x%8); + iDst &= (0x01<> pos); + } + } + return 0; +} +//////////////////////////////////////////////////////////////////////////////// +RGBQUAD CxImage::GetPixelColor(long x,long y, bool bGetAlpha) +{ +// RGBQUAD rgb={0,0,0,0}; + RGBQUAD rgb=info.nBkgndColor; // + if ((pDib==NULL)||(x<0)||(y<0)|| + (x>=head.biWidth)||(y>=head.biHeight)){ + if (info.nBkgndIndex != -1){ + if (head.biBitCount<24) return GetPaletteColor((BYTE)info.nBkgndIndex); + else return info.nBkgndColor; + } else if (pDib) return GetPixelColor(0,0); + return rgb; + } + + if (head.biClrUsed){ + rgb = GetPaletteColor(GetPixelIndex(x,y)); + } else { + BYTE* iDst = info.pImage + y*info.dwEffWidth + x*3; + rgb.rgbBlue = *iDst++; + rgb.rgbGreen= *iDst++; + rgb.rgbRed = *iDst; + } +#if CXIMAGE_SUPPORT_ALPHA + if (pAlpha && bGetAlpha) rgb.rgbReserved = AlphaGet(x,y); +#else + rgb.rgbReserved = 0; +#endif //CXIMAGE_SUPPORT_ALPHA + return rgb; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * This is (a bit) faster version of GetPixelColor. + * It tests bounds only in debug mode (_DEBUG defined). + * + * It is an error to request out-of-borders pixel with this method. + * In DEBUG mode an exception will be thrown, and data will be violated in non-DEBUG mode. + * \author ***bd*** 2.2004 + */ +RGBQUAD CxImage::BlindGetPixelColor(const long x,const long y) +{ + RGBQUAD rgb; +#ifdef _DEBUG + if ((pDib==NULL) || !IsInside(x,y)) throw 0; +#endif + + if (head.biClrUsed){ + return GetPaletteColor(BlindGetPixelIndex(x,y)); + } + + BYTE* iDst = info.pImage + y*info.dwEffWidth + x*3; + rgb.rgbBlue = *iDst++; + rgb.rgbGreen= *iDst++; + rgb.rgbRed = *iDst; +#if CXIMAGE_SUPPORT_ALPHA + if (pAlpha) rgb.rgbReserved = pAlpha[x+y*head.biWidth]; +#else + rgb.rgbReserved = 0; +#endif //CXIMAGE_SUPPORT_ALPHA + return rgb; +} +//////////////////////////////////////////////////////////////////////////////// +BYTE CxImage::GetPixelGray(long x, long y) +{ + RGBQUAD color = GetPixelColor(x,y); + return (BYTE)RGB2GRAY(color.rgbRed,color.rgbGreen,color.rgbBlue); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImage::SetPixelIndex(long x,long y,BYTE i) +{ + if ((pDib==NULL)||(head.biClrUsed==0)|| + (x<0)||(y<0)||(x>=head.biWidth)||(y>=head.biHeight)) return ; + + if (head.biBitCount==8){ + info.pImage[y*info.dwEffWidth + x]=i; + return; + } else { + BYTE pos; + BYTE* iDst= info.pImage + y*info.dwEffWidth + (x*head.biBitCount >> 3); + if (head.biBitCount==4){ + pos = (BYTE)(4*(1-x%2)); + *iDst &= ~(0x0F<=head.biWidth)||(y>=head.biHeight)) return; + if (head.biClrUsed) + SetPixelIndex(x,y,GetNearestIndex(c)); + else { + BYTE* iDst = info.pImage + y*info.dwEffWidth + x*3; + *iDst++ = c.rgbBlue; + *iDst++ = c.rgbGreen; + *iDst = c.rgbRed; +#if CXIMAGE_SUPPORT_ALPHA + if (bSetAlpha) AlphaSet(x,y,c.rgbReserved); +#endif //CXIMAGE_SUPPORT_ALPHA + } +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Blends the current pixel color with a new color. + * \param x,y = pixel + * \param c = new color + * \param blend = can be from 0 (no effect) to 1 (full effect). + * \param bSetAlpha = if true, blends also the alpha component stored in c.rgbReserved + */ +void CxImage::BlendPixelColor(long x,long y,RGBQUAD c, float blend, bool bSetAlpha) +{ + if ((pDib==NULL)||(x<0)||(y<0)|| + (x>=head.biWidth)||(y>=head.biHeight)) return; + + int a0 = (int)(256*blend); + int a1 = 256 - a0; + + RGBQUAD c0 = BlindGetPixelColor(x,y); + c.rgbRed = (BYTE)((c.rgbRed * a0 + c0.rgbRed * a1)>>8); + c.rgbBlue = (BYTE)((c.rgbBlue * a0 + c0.rgbBlue * a1)>>8); + c.rgbGreen = (BYTE)((c.rgbGreen * a0 + c0.rgbGreen * a1)>>8); + + if (head.biClrUsed) + SetPixelIndex(x,y,GetNearestIndex(c)); + else { + BYTE* iDst = info.pImage + y*info.dwEffWidth + x*3; + *iDst++ = c.rgbBlue; + *iDst++ = c.rgbGreen; + *iDst = c.rgbRed; +#if CXIMAGE_SUPPORT_ALPHA + if (bSetAlpha) AlphaSet(x,y,c.rgbReserved); +#endif //CXIMAGE_SUPPORT_ALPHA + } +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Returns the best palette index that matches a specified color. + */ +BYTE CxImage::GetNearestIndex(RGBQUAD c) +{ + if ((pDib==NULL)||(head.biClrUsed==0)) return 0; + + // check matching with the previous result + if (info.last_c_isvalid && (*(long*)&info.last_c == *(long*)&c)) return info.last_c_index; + info.last_c = c; + info.last_c_isvalid = true; + + BYTE* iDst = (BYTE*)(pDib) + sizeof(BITMAPINFOHEADER); + long distance=200000; + int i,j = 0; + long k,l; + int m = (int)(head.biClrImportant==0 ? head.biClrUsed : head.biClrImportant); + for(i=0,l=0;i100) perc=100; + for(i=0;i=0){ + if (head.biClrUsed){ + if (GetPixelIndex(x,y) == info.nBkgndIndex) return true; + } else { + RGBQUAD ct = info.nBkgndColor; + RGBQUAD c = GetPixelColor(x,y,false); + if (*(long*)&c==*(long*)&ct) return true; + } + } + +#if CXIMAGE_SUPPORT_ALPHA + if (pAlpha) return AlphaGet(x,y)==0; +#endif + + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Checks if image has the same palette, if any. + * \param img = image to compare. + * \param bCheckAlpha = check also the rgbReserved field. + */ +bool CxImage::IsSamePalette(CxImage &img, bool bCheckAlpha) +{ + if (head.biClrUsed != img.head.biClrUsed) + return false; + if (head.biClrUsed == 0) + return false; + + RGBQUAD c1,c2; + for (DWORD n=0; n256) { + head.biClrImportant = 0; + return; + } + + switch(head.biBitCount){ + case 1: + head.biClrImportant = min(ncolors,2); + break; + case 4: + head.biClrImportant = min(ncolors,16); + break; + case 8: + head.biClrImportant = ncolors; + break; + } + return; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Returns pointer to pixel. Currently implemented only for truecolor images. + * + * \param x,y - coordinates + * + * \return pointer to first byte of pixel data + * + * \author ***bd*** 2.2004 + */ +void* CxImage::BlindGetPixelPointer(const long x, const long y) +{ + if (!IsIndexed()) + return info.pImage + y*info.dwEffWidth + x*3; + else + return 0; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImage::DrawLine(int StartX, int EndX, int StartY, int EndY, COLORREF cr) +{ + DrawLine(StartX, EndX, StartY, EndY, RGBtoRGBQUAD(cr)); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImage::DrawLine(int StartX, int EndX, int StartY, int EndY, RGBQUAD color, bool bSetAlpha) +{ + if (!pDib) return; + ////////////////////////////////////////////////////// + // Draws a line using the Bresenham line algorithm + // Thanks to Jordan DeLozier + ////////////////////////////////////////////////////// + int x1 = StartX; + int y1 = StartY; + int x = x1; // Start x off at the first pixel + int y = y1; // Start y off at the first pixel + int x2 = EndX; + int y2 = EndY; + + int xinc1,xinc2,yinc1,yinc2; // Increasing values + int den, num, numadd,numpixels; + int deltax = abs(x2 - x1); // The difference between the x's + int deltay = abs(y2 - y1); // The difference between the y's + + // Get Increasing Values + if (x2 >= x1) { // The x-values are increasing + xinc1 = 1; + xinc2 = 1; + } else { // The x-values are decreasing + xinc1 = -1; + xinc2 = -1; + } + + if (y2 >= y1) { // The y-values are increasing + yinc1 = 1; + yinc2 = 1; + } else { // The y-values are decreasing + yinc1 = -1; + yinc2 = -1; + } + + // Actually draw the line + if (deltax >= deltay) // There is at least one x-value for every y-value + { + xinc1 = 0; // Don't change the x when numerator >= denominator + yinc2 = 0; // Don't change the y for every iteration + den = deltax; + num = deltax / 2; + numadd = deltay; + numpixels = deltax; // There are more x-values than y-values + } + else // There is at least one y-value for every x-value + { + xinc2 = 0; // Don't change the x for every iteration + yinc1 = 0; // Don't change the y when numerator >= denominator + den = deltay; + num = deltay / 2; + numadd = deltax; + numpixels = deltay; // There are more y-values than x-values + } + + for (int curpixel = 0; curpixel <= numpixels; curpixel++) + { + // Draw the current pixel + SetPixelColor(x,y,color,bSetAlpha); + + num += numadd; // Increase the numerator by the top of the fraction + if (num >= den) // Check if numerator >= denominator + { + num -= den; // Calculate the new numerator value + x += xinc1; // Change the x as appropriate + y += yinc1; // Change the y as appropriate + } + x += xinc2; // Change the x as appropriate + y += yinc2; // Change the y as appropriate + } +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Sets a palette with standard colors for 4 and 8 bpp images. + */ +void CxImage::SetStdPalette() +{ + if (!pDib) return; + switch (head.biBitCount){ + case 8: + { + const BYTE pal256[1024] = {0,0,0,0,0,0,128,0,0,128,0,0,0,128,128,0,128,0,0,0,128,0,128,0,128,128,0,0,192,192,192,0, + 192,220,192,0,240,202,166,0,212,240,255,0,177,226,255,0,142,212,255,0,107,198,255,0, + 72,184,255,0,37,170,255,0,0,170,255,0,0,146,220,0,0,122,185,0,0,98,150,0,0,74,115,0,0, + 50,80,0,212,227,255,0,177,199,255,0,142,171,255,0,107,143,255,0,72,115,255,0,37,87,255,0,0, + 85,255,0,0,73,220,0,0,61,185,0,0,49,150,0,0,37,115,0,0,25,80,0,212,212,255,0,177,177,255,0, + 142,142,255,0,107,107,255,0,72,72,255,0,37,37,255,0,0,0,254,0,0,0,220,0,0,0,185,0,0,0,150,0, + 0,0,115,0,0,0,80,0,227,212,255,0,199,177,255,0,171,142,255,0,143,107,255,0,115,72,255,0, + 87,37,255,0,85,0,255,0,73,0,220,0,61,0,185,0,49,0,150,0,37,0,115,0,25,0,80,0,240,212,255,0, + 226,177,255,0,212,142,255,0,198,107,255,0,184,72,255,0,170,37,255,0,170,0,255,0,146,0,220,0, + 122,0,185,0,98,0,150,0,74,0,115,0,50,0,80,0,255,212,255,0,255,177,255,0,255,142,255,0,255,107,255,0, + 255,72,255,0,255,37,255,0,254,0,254,0,220,0,220,0,185,0,185,0,150,0,150,0,115,0,115,0,80,0,80,0, + 255,212,240,0,255,177,226,0,255,142,212,0,255,107,198,0,255,72,184,0,255,37,170,0,255,0,170,0, + 220,0,146,0,185,0,122,0,150,0,98,0,115,0,74,0,80,0,50,0,255,212,227,0,255,177,199,0,255,142,171,0, + 255,107,143,0,255,72,115,0,255,37,87,0,255,0,85,0,220,0,73,0,185,0,61,0,150,0,49,0,115,0,37,0, + 80,0,25,0,255,212,212,0,255,177,177,0,255,142,142,0,255,107,107,0,255,72,72,0,255,37,37,0,254,0, + 0,0,220,0,0,0,185,0,0,0,150,0,0,0,115,0,0,0,80,0,0,0,255,227,212,0,255,199,177,0,255,171,142,0, + 255,143,107,0,255,115,72,0,255,87,37,0,255,85,0,0,220,73,0,0,185,61,0,0,150,49,0,0,115,37,0, + 0,80,25,0,0,255,240,212,0,255,226,177,0,255,212,142,0,255,198,107,0,255,184,72,0,255,170,37,0, + 255,170,0,0,220,146,0,0,185,122,0,0,150,98,0,0,115,74,0,0,80,50,0,0,255,255,212,0,255,255,177,0, + 255,255,142,0,255,255,107,0,255,255,72,0,255,255,37,0,254,254,0,0,220,220,0,0,185,185,0,0,150,150,0, + 0,115,115,0,0,80,80,0,0,240,255,212,0,226,255,177,0,212,255,142,0,198,255,107,0,184,255,72,0, + 170,255,37,0,170,255,0,0,146,220,0,0,122,185,0,0,98,150,0,0,74,115,0,0,50,80,0,0,227,255,212,0, + 199,255,177,0,171,255,142,0,143,255,107,0,115,255,72,0,87,255,37,0,85,255,0,0,73,220,0,0,61,185,0, + 0,49,150,0,0,37,115,0,0,25,80,0,0,212,255,212,0,177,255,177,0,142,255,142,0,107,255,107,0,72,255,72,0, + 37,255,37,0,0,254,0,0,0,220,0,0,0,185,0,0,0,150,0,0,0,115,0,0,0,80,0,0,212,255,227,0,177,255,199,0, + 142,255,171,0,107,255,143,0,72,255,115,0,37,255,87,0,0,255,85,0,0,220,73,0,0,185,61,0,0,150,49,0,0, + 115,37,0,0,80,25,0,212,255,240,0,177,255,226,0,142,255,212,0,107,255,198,0,72,255,184,0,37,255,170,0, + 0,255,170,0,0,220,146,0,0,185,122,0,0,150,98,0,0,115,74,0,0,80,50,0,212,255,255,0,177,255,255,0, + 142,255,255,0,107,255,255,0,72,255,255,0,37,255,255,0,0,254,254,0,0,220,220,0,0,185,185,0,0, + 150,150,0,0,115,115,0,0,80,80,0,242,242,242,0,230,230,230,0,218,218,218,0,206,206,206,0,194,194,194,0, + 182,182,182,0,170,170,170,0,158,158,158,0,146,146,146,0,134,134,134,0,122,122,122,0,110,110,110,0, + 98,98,98,0,86,86,86,0,74,74,74,0,62,62,62,0,50,50,50,0,38,38,38,0,26,26,26,0,14,14,14,0,240,251,255,0, + 164,160,160,0,128,128,128,0,0,0,255,0,0,255,0,0,0,255,255,0,255,0,0,0,255,0,255,0,255,255,0,0,255,255,255,0}; + memcpy(GetPalette(),pal256,1024); + break; + } + case 4: + { + const BYTE pal16[64]={0,0,0,0,0,0,128,0,0,128,0,0,0,128,128,0,128,0,0,0,128,0,128,0,128,128,0,0,192,192,192,0, + 128,128,128,0,0,0,255,0,0,255,0,0,0,255,255,0,255,0,0,0,255,0,255,0,255,255,0,0,255,255,255,0}; + memcpy(GetPalette(),pal16,64); + break; + } + } + return; +} +//////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/CxImage/ximapcx.cpp b/SlnkDWFImpl/CxImage/CxImage/ximapcx.cpp new file mode 100644 index 0000000..9a22342 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximapcx.cpp @@ -0,0 +1,445 @@ +/* + * File: ximapcx.cpp + * Purpose: Platform Independent PCX Image Class Loader and Writer + * 05/Jan/2002 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + * + * based on ppmtopcx.c - convert a portable pixmap to PCX + * Copyright (C) 1994 by Ingo Wilken (Ingo.Wilken@informatik.uni-oldenburg.de) + * based on ppmtopcx.c by Michael Davidson + */ + +#include "ximapcx.h" + +#if CXIMAGE_SUPPORT_PCX + +#include "xmemfile.h" + +#define PCX_MAGIC 0X0A // PCX magic number +#define PCX_256_COLORS 0X0C // magic number for 256 colors +#define PCX_HDR_SIZE 128 // size of PCX header +#define PCX_MAXCOLORS 256 +#define PCX_MAXPLANES 4 +#define PCX_MAXVAL 255 + +//////////////////////////////////////////////////////////////////////////////// +bool CxImagePCX::Decode(CxFile *hFile) +{ + if (hFile == NULL) return false; + + PCXHEADER pcxHeader; + int i, x, y, y2, nbytes, count, Height, Width; + BYTE c, ColorMap[PCX_MAXCOLORS][3]; + BYTE *pcximage = NULL, *lpHead1 = NULL, *lpHead2 = NULL; + BYTE *pcxplanes, *pcxpixels; + + try + { + if (hFile->Read(&pcxHeader,sizeof(PCXHEADER),1)==0) throw "Can't read PCX image"; + + if (pcxHeader.Manufacturer != PCX_MAGIC) throw "Error: Not a PCX file"; + // Check for PCX run length encoding + if (pcxHeader.Encoding != 1) throw "PCX file has unknown encoding scheme"; + + Width = (pcxHeader.Xmax - pcxHeader.Xmin) + 1; + Height = (pcxHeader.Ymax - pcxHeader.Ymin) + 1; + info.xDPI = pcxHeader.Hres; + info.yDPI = pcxHeader.Vres; + + // Check that we can handle this image format + if (pcxHeader.ColorPlanes > 4) + throw "Can't handle image with more than 4 planes"; + + // Create the image + if (pcxHeader.ColorPlanes >= 3 && pcxHeader.BitsPerPixel == 8){ + Create (Width, Height, 24, CXIMAGE_FORMAT_PCX); +#if CXIMAGE_SUPPORT_ALPHA + if (pcxHeader.ColorPlanes==4) AlphaCreate(); +#endif //CXIMAGE_SUPPORT_ALPHA + } else if (pcxHeader.ColorPlanes == 4 && pcxHeader.BitsPerPixel == 1) + Create (Width, Height, 4, CXIMAGE_FORMAT_PCX); + else + Create (Width, Height, pcxHeader.BitsPerPixel, CXIMAGE_FORMAT_PCX); + + if (info.nEscape) throw "Cancelled"; // - cancel decoding + + //Read the image and check if it's ok + nbytes = pcxHeader.BytesPerLine * pcxHeader.ColorPlanes * Height; + lpHead1 = pcximage = (BYTE*)malloc(nbytes); + while (nbytes > 0){ + if (hFile == NULL || hFile->Eof()) throw "corrupted PCX"; + + hFile->Read(&c,1,1); + if ((c & 0XC0) != 0XC0){ // Repeated group + *pcximage++ = c; + --nbytes; + continue; + } + count = c & 0X3F; // extract count + hFile->Read(&c,1,1); + if (count > nbytes) throw "repeat count spans end of image"; + + nbytes -= count; + while (--count >=0) *pcximage++ = c; + } + pcximage = lpHead1; + + //store the palette + for (i = 0; i < 16; i++){ + ColorMap[i][0] = pcxHeader.ColorMap[i][0]; + ColorMap[i][1] = pcxHeader.ColorMap[i][1]; + ColorMap[i][2] = pcxHeader.ColorMap[i][2]; + } + if (pcxHeader.BitsPerPixel == 8 && pcxHeader.ColorPlanes == 1){ + hFile->Read(&c,1,1); + if (c != PCX_256_COLORS) throw "bad color map signature"; + + for (i = 0; i < PCX_MAXCOLORS; i++){ + hFile->Read(&ColorMap[i][0],1,1); + hFile->Read(&ColorMap[i][1],1,1); + hFile->Read(&ColorMap[i][2],1,1); + } + } + if (pcxHeader.BitsPerPixel == 1 && pcxHeader.ColorPlanes == 1){ + ColorMap[0][0] = ColorMap[0][1] = ColorMap[0][2] = 0; + ColorMap[1][0] = ColorMap[1][1] = ColorMap[1][2] = 255; + } + + for (DWORD idx=0; idx - cancel decoding + + y2=Height-1-y; + pcxpixels = lpHead2; + pcxplanes = pcximage + (y * pcxHeader.BytesPerLine * pcxHeader.ColorPlanes); + + if (pcxHeader.ColorPlanes == 3 && pcxHeader.BitsPerPixel == 8){ + // Deal with 24 bit color image + for (x = 0; x < Width; x++){ + SetPixelColor(x,y2,RGB(pcxplanes[x],pcxplanes[pcxHeader.BytesPerLine + x],pcxplanes[2*pcxHeader.BytesPerLine + x])); + } + continue; +#if CXIMAGE_SUPPORT_ALPHA + } else if (pcxHeader.ColorPlanes == 4 && pcxHeader.BitsPerPixel == 8){ + for (x = 0; x < Width; x++){ + SetPixelColor(x,y2,RGB(pcxplanes[x],pcxplanes[pcxHeader.BytesPerLine + x],pcxplanes[2*pcxHeader.BytesPerLine + x])); + AlphaSet(x,y2,pcxplanes[3*pcxHeader.BytesPerLine + x]); + } + continue; +#endif //CXIMAGE_SUPPORT_ALPHA + } else if (pcxHeader.ColorPlanes == 1) { + PCX_UnpackPixels(pcxpixels, pcxplanes, pcxHeader.BytesPerLine, pcxHeader.ColorPlanes, pcxHeader.BitsPerPixel); + } else { + PCX_PlanesToPixels(pcxpixels, pcxplanes, pcxHeader.BytesPerLine, pcxHeader.ColorPlanes, pcxHeader.BitsPerPixel); + } + for (x = 0; x < Width; x++) SetPixelIndex(x,y2,pcxpixels[x]); + } + + } catch (char *message) { + strncpy(info.szLastError,message,255); + if (lpHead1){ free(lpHead1); lpHead1 = NULL; } + if (lpHead2){ free(lpHead2); lpHead2 = NULL; } + return false; + } + if (lpHead1){ free(lpHead1); lpHead1 = NULL; } + if (lpHead2){ free(lpHead2); lpHead2 = NULL; } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImagePCX::Encode(CxFile * hFile) +{ + if (EncodeSafeCheck(hFile)) return false; + + try { + PCXHEADER pcxHeader; + memset(&pcxHeader,0,sizeof(pcxHeader)); + pcxHeader.Manufacturer = PCX_MAGIC; + pcxHeader.Version = 5; + pcxHeader.Encoding = 1; + pcxHeader.Xmin = 0; + pcxHeader.Ymin = 0; + pcxHeader.Xmax = (WORD)head.biWidth-1; + pcxHeader.Ymax = (WORD)head.biHeight-1; + pcxHeader.Hres = (WORD)info.xDPI; + pcxHeader.Vres = (WORD)info.yDPI; + pcxHeader.Reserved = 0; + pcxHeader.PaletteType = head.biClrUsed==0; + + switch(head.biBitCount){ + case 24: + case 8: + { + pcxHeader.BitsPerPixel = 8; + pcxHeader.ColorPlanes = head.biClrUsed==0 ? 3 : 1; +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid() && head.biClrUsed==0) pcxHeader.ColorPlanes =4; +#endif //CXIMAGE_SUPPORT_ALPHA + pcxHeader.BytesPerLine = (WORD)head.biWidth; + break; + } + default: //(4 1) + pcxHeader.BitsPerPixel = 1; + pcxHeader.ColorPlanes = head.biClrUsed==16 ? 4 : 1; + pcxHeader.BytesPerLine = (WORD)((head.biWidth * pcxHeader.BitsPerPixel + 7)>>3); + } + + if (pcxHeader.BitsPerPixel == 1 && pcxHeader.ColorPlanes == 1){ + pcxHeader.ColorMap[0][0] = pcxHeader.ColorMap[0][1] = pcxHeader.ColorMap[0][2] = 0; + pcxHeader.ColorMap[1][0] = pcxHeader.ColorMap[1][1] = pcxHeader.ColorMap[1][2] = 255; + } + if (pcxHeader.BitsPerPixel == 1 && pcxHeader.ColorPlanes == 4){ + RGBQUAD c; + for (int i = 0; i < 16; i++){ + c=GetPaletteColor(i); + pcxHeader.ColorMap[i][0] = c.rgbRed; + pcxHeader.ColorMap[i][1] = c.rgbGreen; + pcxHeader.ColorMap[i][2] = c.rgbBlue; + } + } + + pcxHeader.BytesPerLine = (pcxHeader.BytesPerLine + 1)&(~1); + + if (hFile->Write(&pcxHeader, sizeof(pcxHeader), 1) == 0 ) + throw "cannot write PCX header"; + + CxMemFile buffer; + buffer.Open(); + + BYTE c,n; + long x,y; + if (head.biClrUsed==0){ + for (y = head.biHeight-1; y >=0 ; y--){ + for (int p=0; pWrite(buffer.GetBuffer(false),buffer.Size(),1); + + } else if (head.biBitCount==8) { + + for (y = head.biHeight-1; y >=0 ; y--){ + c=n=0; + for (x = 0; xWrite(buffer.GetBuffer(false),buffer.Size(),1); + + if (head.biBitCount == 8){ + hFile->PutC(0x0C); + BYTE* pal = (BYTE*)malloc(768); + RGBQUAD c; + for (int i=0;i<256;i++){ + c=GetPaletteColor(i); + pal[3*i+0] = c.rgbRed; + pal[3*i+1] = c.rgbGreen; + pal[3*i+2] = c.rgbBlue; + } + hFile->Write(pal,768,1); + free(pal); + } + } else { //(head.biBitCount==4) || (head.biBitCount==1) + + RGBQUAD *rgb = GetPalette(); + bool binvert = false; + if (CompareColors(&rgb[0],&rgb[1])>0) binvert=(head.biBitCount==1); + + BYTE* plane = (BYTE*)malloc(pcxHeader.BytesPerLine); + BYTE* raw = (BYTE*)malloc(head.biWidth); + + for(y = head.biHeight-1; y >=0 ; y--) { + + for( x = 0; x < head.biWidth; x++) raw[x] = (BYTE)GetPixelIndex(x,y); + + if (binvert) for( x = 0; x < head.biWidth; x++) raw[x] = 1-raw[x]; + + for( x = 0; x < pcxHeader.ColorPlanes; x++ ) { + PCX_PixelsToPlanes(raw, head.biWidth, plane, x); + PCX_PackPlanes(plane, pcxHeader.BytesPerLine, buffer); + } + } + + free(plane); + free(raw); + + hFile->Write(buffer.GetBuffer(false),buffer.Size(),1); + + } + + } catch (char *message) { + strncpy(info.szLastError,message,255); + return false; + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +// Convert multi-plane format into 1 pixel per byte +// from unpacked file data bitplanes[] into pixel row pixels[] +// image Height rows, with each row having planes image planes each +// bytesperline bytes +void CxImagePCX::PCX_PlanesToPixels(BYTE * pixels, BYTE * bitplanes, short bytesperline, short planes, short bitsperpixel) +{ + int i, j, npixels; + BYTE * p; + if (planes > 4) throw "Can't handle more than 4 planes"; + if (bitsperpixel != 1) throw "Can't handle more than 1 bit per pixel"; + + // Clear the pixel buffer + npixels = (bytesperline * 8) / bitsperpixel; + p = pixels; + while (--npixels >= 0) *p++ = 0; + + // Do the format conversion + for (i = 0; i < planes; i++){ + int pixbit, bits, mask; + p = pixels; + pixbit = (1 << i); // pixel bit for this plane + for (j = 0; j < bytesperline; j++){ + bits = *bitplanes++; + for (mask = 0X80; mask != 0; mask >>= 1, p++) + if (bits & mask) *p |= pixbit; + } + } +} +//////////////////////////////////////////////////////////////////////////////// +// convert packed pixel format into 1 pixel per byte +// from unpacked file data bitplanes[] into pixel row pixels[] +// image Height rows, with each row having planes image planes each +// bytesperline bytes +void CxImagePCX::PCX_UnpackPixels(BYTE * pixels, BYTE * bitplanes, short bytesperline, short planes, short bitsperpixel) +{ + register int bits; + if (planes != 1) throw "Can't handle packed pixels with more than 1 plane."; + + if (bitsperpixel == 8){ // 8 bits/pixels, no unpacking needed + while (bytesperline-- > 0) *pixels++ = *bitplanes++; + } else if (bitsperpixel == 4){ // 4 bits/pixel, two pixels per byte + while (bytesperline-- > 0){ + bits = *bitplanes++; + *pixels++ = (BYTE)((bits >> 4) & 0X0F); + *pixels++ = (BYTE)((bits) & 0X0F); + } + } else if (bitsperpixel == 2){ // 2 bits/pixel, four pixels per byte + while (bytesperline-- > 0){ + bits = *bitplanes++; + *pixels++ = (BYTE)((bits >> 6) & 0X03); + *pixels++ = (BYTE)((bits >> 4) & 0X03); + *pixels++ = (BYTE)((bits >> 2) & 0X03); + *pixels++ = (BYTE)((bits) & 0X03); + } + } else if (bitsperpixel == 1){ // 1 bits/pixel, 8 pixels per byte + while (bytesperline-- > 0){ + bits = *bitplanes++; + *pixels++ = ((bits & 0X80) != 0); + *pixels++ = ((bits & 0X40) != 0); + *pixels++ = ((bits & 0X20) != 0); + *pixels++ = ((bits & 0X10) != 0); + *pixels++ = ((bits & 0X08) != 0); + *pixels++ = ((bits & 0X04) != 0); + *pixels++ = ((bits & 0X02) != 0); + *pixels++ = ((bits & 0X01) != 0); + } + } +} +//////////////////////////////////////////////////////////////////////////////// +/* PCX_PackPixels(const long p,BYTE &c, BYTE &n, long &l, CxFile &f) + * p = current pixel (-1 ends the line -2 ends odd line) + * c = previous pixel + * n = number of consecutive pixels + */ +void CxImagePCX::PCX_PackPixels(const long p,BYTE &c, BYTE &n, CxFile &f) +{ + if (p!=c && n){ + if (n==1 && c<0xC0){ + f.PutC(c); + } else { + f.PutC(0xC0|n); + f.PutC(c); + } + n=0; + } + if (n==0x3F) { + f.PutC(0xFF); + f.PutC(c); + n=0; + } + if (p==-2) f.PutC(0); + c=(BYTE)p; + n++; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImagePCX::PCX_PackPlanes(BYTE* buff, const long size, CxFile &f) +{ + BYTE *start,*end; + BYTE c, previous, count; + + start = buff; + end = buff + size; + previous = *start++; + count = 1; + + while (start < end) { + c = *start++; + if (c == previous && count < 63) { + ++count; + continue; + } + + if (count > 1 || (previous & 0xc0) == 0xc0) { + f.PutC( count | 0xc0 ); + } + f.PutC(previous); + previous = c; + count = 1; + } + + if (count > 1 || (previous & 0xc0) == 0xc0) { + count |= 0xc0; + f.PutC(count); + } + f.PutC(previous); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImagePCX::PCX_PixelsToPlanes(BYTE* raw, long width, BYTE* buf, long plane) +{ + int cbit, x, mask; + unsigned char *cp = buf-1; + + mask = 1 << plane; + cbit = -1; + for( x = 0; x < width; x++ ) { + if( cbit < 0 ) { + cbit = 7; + *++cp = 0; + } + if( raw[x] & mask ) + *cp |= (1<jmpbuf, 1); +} +//////////////////////////////////////////////////////////////////////////////// +void CxImagePNG::expand2to4bpp(BYTE* prow) +{ + BYTE *psrc,*pdst; + BYTE pos,idx; + for(long x=head.biWidth-1;x>=0;x--){ + psrc = prow + ((2*x)>>3); + pdst = prow + ((4*x)>>3); + pos = (BYTE)(2*(3-x%4)); + idx = (BYTE)((*psrc & (0x03<>pos); + pos = (BYTE)(4*(1-x%2)); + *pdst &= ~(0x0F<jmpbuf)) { + /* Free all of the memory associated with the png_ptr and info_ptr */ + if (row_pointers) delete[] row_pointers; + png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); + throw ""; + } + /* set up the input control */ + //png_init_io(png_ptr, hFile); + + // use custom I/O functions + png_set_read_fn(png_ptr, hFile, (png_rw_ptr)user_read_data); + png_set_error_fn(png_ptr,info.szLastError,(png_error_ptr)user_error_fn,NULL); + + /* read the file information */ + png_read_info(png_ptr, info_ptr); + + /* allocate the memory to hold the image using the fields of png_info. */ + png_color_16 my_background={ 0, 192, 192, 192, 0 }; + png_color_16 *image_background; + + if (info_ptr->pixel_depth != 32){ + // preserve original background info. + if (png_get_bKGD(png_ptr, info_ptr, &image_background)) + png_set_background(png_ptr, image_background,PNG_BACKGROUND_GAMMA_FILE, 1, 1.0); + else + png_set_background(png_ptr, &my_background,PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0); +// - we call png_set_bgr() below +// // safe check +// if (info_ptr->pixel_depth > 16 ) info_ptr->color_type = COLORTYPE_COLOR; + } + + // hack for images with alpha channel + if (info_ptr->pixel_depth == 32){ +// info.nBkgndIndex = 0; //enable transparency + if (png_get_bKGD(png_ptr, info_ptr, &image_background)){ + info.nBkgndColor.rgbRed = (BYTE)image_background->red; + info.nBkgndColor.rgbGreen = (BYTE)image_background->green; + info.nBkgndColor.rgbBlue = (BYTE)image_background->blue; + info.nBkgndColor.rgbReserved = 0; // + } + } + + /* tell libpng to strip 16 bit depth files down to 8 bits */ + if (info_ptr->bit_depth == 16) png_set_strip_16(png_ptr); + + int pixel_depth=info_ptr->pixel_depth; + if (pixel_depth > 16 ) pixel_depth=24; + if (pixel_depth == 16 ) pixel_depth=8; + + Create(info_ptr->width, info_ptr->height, pixel_depth, CXIMAGE_FORMAT_PNG); + + /* get metrics */ + switch (info_ptr->phys_unit_type) + { + case PNG_RESOLUTION_UNKNOWN: + SetXDPI(info_ptr->x_pixels_per_unit); + SetYDPI(info_ptr->y_pixels_per_unit); + break; + case PNG_RESOLUTION_METER: + SetXDPI((long)floor(info_ptr->x_pixels_per_unit * 254.0 / 10000.0 + 0.5)); + SetYDPI((long)floor(info_ptr->y_pixels_per_unit * 254.0 / 10000.0 + 0.5)); + break; + } + + if (info_ptr->num_palette>0) + SetPalette((rgb_color*)info_ptr->palette,info_ptr->num_palette); + else if (info_ptr->bit_depth ==2) { // needed for 2 bpp grayscale PNGs + SetPaletteColor(0,0,0,0); + SetPaletteColor(1,85,85,85); + SetPaletteColor(2,170,170,170); + SetPaletteColor(3,255,255,255); + } else SetGrayPalette(); // needed for grayscale PNGs + + // simple transparency (the real PGN transparency is more complex) + if (info_ptr->num_trans!=0){ + //palette transparency + RGBQUAD* pal=GetPalette(); + if (pal){ + DWORD ip; + for (ip=0;ipnum_trans);ip++) + pal[ip].rgbReserved=info_ptr->trans[ip]; + if (info_ptr->num_trans==1 && pal[0].rgbReserved==0){ + info.nBkgndIndex = 0; + } else { + info.bAlphaPaletteEnabled=true; + for (;ipcolor_type == PNG_COLOR_TYPE_RGB_ALPHA || //Alpha channel + (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA && info_ptr->pixel_depth == 32)){ + if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA){ + png_set_gray_to_rgb(png_ptr); + png_set_expand(png_ptr); + } +#if CXIMAGE_SUPPORT_ALPHA // + png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER); + AlphaCreate(); +#else + png_set_strip_alpha(png_ptr); +#endif //CXIMAGE_SUPPORT_ALPHA + } + + // - flip the RGB pixels to BGR (or RGBA to BGRA) + if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) png_set_bgr(png_ptr); + + // - handle cancel + if (info.nEscape) longjmp(png_ptr->jmpbuf, 1); + + //allocate the buffer + int row_stride = info_ptr->width * ((info_ptr->pixel_depth+7)>>3); + row_pointers = new BYTE[10+row_stride]; + + // turn on interlace handling + number_passes = png_set_interlace_handling(png_ptr); + + if (number_passes>1){ + SetCodecOption(1); + } else { + SetCodecOption(0); + } + + for (int pass=0; pass< number_passes; pass++) { + iter.Upset(); + int y=0; + do { + + // - handle cancel + if (info.nEscape) longjmp(png_ptr->jmpbuf, 1); + +#if CXIMAGE_SUPPORT_ALPHA // + if (!AlphaIsValid()) +#endif // CXIMAGE_SUPPORT_ALPHA + { + //recover data from previous scan + if (info_ptr->interlace_type && pass>0) + iter.GetRow(row_pointers, info.dwEffWidth); + //read next row + png_read_row(png_ptr, row_pointers, NULL); +// - already done by png_set_bgr() +// //HACK BY OP && ( for interlace, swap only in the last pass) +// if (info_ptr->color_type==COLORTYPE_COLOR && pass==(number_passes-1)) +// RGBtoBGR(row_pointers, info.dwEffWidth); + // expand 2 bpp images only in the last pass + if (info_ptr->bit_depth==2 && pass==(number_passes-1)) + expand2to4bpp(row_pointers); + //copy the pixels + iter.SetRow(row_pointers, info.dwEffWidth); + //go on + iter.PrevRow(); + } +#if CXIMAGE_SUPPORT_ALPHA // + else { //alpha blend + + //compute the correct position of the line + long ax,ay; + ay = head.biHeight-1-y; + BYTE* prow= iter.GetRow(ay); + + //recover data from previous scan + if (info_ptr->interlace_type && pass>0 && pass!=7){ + for(ax=head.biWidth;ax>=0;ax--){ + row_pointers[ax*4]=prow[3*ax]; + row_pointers[ax*4+1]=prow[3*ax+1]; + row_pointers[ax*4+2]=prow[3*ax+2]; + row_pointers[ax*4+3]=AlphaGet(ax,ay); + } + } + + //read next row + png_read_row(png_ptr, row_pointers, NULL); + + //RGBA -> RGB + A + for(ax=0;axjmpbuf)){ + /* If we get here, we had a problem reading the file */ + if (info_ptr->palette) free(info_ptr->palette); + png_destroy_write_struct(&png_ptr, (png_infopp)&info_ptr); + throw "Error saving PNG file"; + } + + int row_stride = info.dwEffWidth; + /* set up the output control */ + //png_init_io(png_ptr, hFile); + + // use custom I/O functions + png_set_write_fn(png_ptr,hFile,(png_rw_ptr)user_write_data,(png_flush_ptr)user_flush_data); + + /* set the file information here */ + info_ptr->width = GetWidth(); + info_ptr->height = GetHeight(); + info_ptr->pixel_depth = (BYTE)GetBpp(); + info_ptr->channels = (GetBpp()>8) ? (BYTE)3: (BYTE)1; + info_ptr->bit_depth = (BYTE)(GetBpp()/info_ptr->channels); + info_ptr->color_type = GetColorType(); + info_ptr->compression_type = info_ptr->filter_type = 0; + info_ptr->valid = 0; + info_ptr->rowbytes = row_stride; + + switch(GetCodecOption(CXIMAGE_FORMAT_PNG)){ + case 1: + info_ptr->interlace_type = PNG_INTERLACE_ADAM7; + break; + default: + info_ptr->interlace_type = PNG_INTERLACE_NONE; + } + + /* set compression level */ + //png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); + +// ######### JGL: MODIFIED VOOR SNELHEID ########## + png_set_filter(png_ptr, 0, PNG_FILTER_NONE); + png_set_compression_level(png_ptr, 4); // Redelijk snel, redelijke compressie + + /* set background */ + png_color_16 image_background={ 0, 255, 255, 255, 0 }; + if (info.nBkgndIndex!=-1) { + image_background.blue = info.nBkgndColor.rgbBlue; + image_background.green = info.nBkgndColor.rgbGreen; + image_background.red = info.nBkgndColor.rgbRed; + } + png_set_bKGD(png_ptr, info_ptr, &image_background); + + /* set metrics */ + png_set_pHYs(png_ptr, info_ptr, head.biXPelsPerMeter, head.biYPelsPerMeter, PNG_RESOLUTION_METER); + + /* set the palette if there is one */ + if (GetPalette()){ + png_set_IHDR(png_ptr, info_ptr, info_ptr->width, info_ptr->height, info_ptr->bit_depth, + PNG_COLOR_TYPE_PALETTE, info_ptr->interlace_type, + PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + info_ptr->valid |= PNG_INFO_PLTE; + + // simple transparency + if (info.nBkgndIndex != -1){ + trans[0]=0; + info_ptr->num_trans = 1; + info_ptr->valid |= PNG_INFO_tRNS; + info_ptr->trans = trans; + // the transparency indexes start from 0 + if (info.nBkgndIndex){ + SwapIndex(0,(BYTE)info.nBkgndIndex); + // the ghost must set the changed attributes in the body + if (info.pGhost) info.pGhost->SetTransIndex(0); + } + } + + int nc = GetNumColors(); + + /* We not need to write unused colors! */ + /* only for small images */ + if ((nc>2)&&((head.biWidth*head.biHeight)<65536)){ + nc = 0; + for (DWORD y=0;ync){ + nc=GetPixelIndex(x,y); + } + } + } + nc++; + } + + if (info.bAlphaPaletteEnabled){ + for(WORD ip=0; ipnum_trans = (WORD)nc; + info_ptr->valid |= PNG_INFO_tRNS; + info_ptr->trans = trans; + } + + // copy the palette colors + info_ptr->palette = new png_color[nc]; + info_ptr->num_palette = (png_uint_16) nc; + for (int i=0; ipalette[i].red, &info_ptr->palette[i].green, &info_ptr->palette[i].blue); + + } + +#if CXIMAGE_SUPPORT_ALPHA // + //Merge the transparent color with the alpha channel + bool bNeedTempAlpha = false; + if (head.biBitCount==24 && info.nBkgndIndex>=0){ + if (!AlphaIsValid()){ + bNeedTempAlpha = true; + AlphaCreate(); + } + RGBQUAD c,ct=GetTransColor(); + for(long y=0; y < head.biHeight; y++){ + for(long x=0; x < head.biWidth ; x++){ + c=GetPixelColor(x,y,false); + if (*(long*)&c==*(long*)&ct) + AlphaSet(x,y,0); + }} + } +#endif // CXIMAGE_SUPPORT_ALPHA // + +#if CXIMAGE_SUPPORT_ALPHA // + if (AlphaIsValid()){ + row_stride = 4 * head.biWidth; + + info_ptr->pixel_depth = 32; + info_ptr->channels = 4; + info_ptr->bit_depth = 8; + info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA; + info_ptr->rowbytes = row_stride; + + /* write the file information */ + png_write_info(png_ptr, info_ptr); + + // "10+row_stride" fix heap deallocation problem during debug??? + BYTE *row_pointers = new BYTE[10+row_stride]; + + //interlace handling + int num_pass = png_set_interlace_handling(png_ptr); + for (int pass = 0; pass < num_pass; pass++){ + + //write image + iter.Upset(); + long ay=head.biHeight-1; + RGBQUAD c; + do { + for (long ax=head.biWidth-1; ax>=0;ax--){ + c=GetPixelColor(ax,ay); + row_pointers[ax*4+3]=(BYTE)((AlphaGet(ax,ay)*info.nAlphaMax)/255); + row_pointers[ax*4+2]=c.rgbBlue; + row_pointers[ax*4+1]=c.rgbGreen; + row_pointers[ax*4]=c.rgbRed; + } + png_write_row(png_ptr, row_pointers); + ay--; + } while(iter.PrevRow()); + } + + delete [] row_pointers; + } + else +#endif //CXIMAGE_SUPPORT_ALPHA // + { + /* write the file information */ + png_write_info(png_ptr, info_ptr); + /* If you are only writing one row at a time, this works */ + BYTE *row_pointers = new BYTE[10+row_stride]; + + //interlace handling + int num_pass = png_set_interlace_handling(png_ptr); + for (int pass = 0; pass < num_pass; pass++){ + + //write image + iter.Upset(); + do { + iter.GetRow(row_pointers, row_stride); + //HACK BY OP + if (info_ptr->color_type == 2 /*COLORTYPE_COLOR*/) + RGBtoBGR(row_pointers, row_stride); + png_write_row(png_ptr, row_pointers); + } while(iter.PrevRow()); + + } + + delete [] row_pointers; + } + +#if CXIMAGE_SUPPORT_ALPHA // + /* remove the temporary alpha channel*/ + if (bNeedTempAlpha) AlphaDelete(); +#endif // CXIMAGE_SUPPORT_ALPHA // + + /* It is REQUIRED to call this to finish writing the rest of the file */ + png_write_end(png_ptr, info_ptr); + + /* if you malloced the palette, free it here */ + if (info_ptr->palette) delete[] (info_ptr->palette); + + /* clean up after the write, and free any memory allocated */ + png_destroy_write_struct(&png_ptr, (png_infopp)&info_ptr); + + } catch (char *message) { + strncpy(info.szLastError,message,255); + return FALSE; + } + /* that's it */ + return TRUE; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_PNG diff --git a/SlnkDWFImpl/CxImage/CxImage/ximapng.h b/SlnkDWFImpl/CxImage/CxImage/ximapng.h new file mode 100644 index 0000000..969c9b2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximapng.h @@ -0,0 +1,73 @@ +/* + * File: ximapng.h + * Purpose: PNG Image Class Loader and Writer + */ +/* ========================================================== + * CxImagePNG (c) 07/Aug/2001 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * Special thanks to Troels Knakkergaard for new features, enhancements and bugfixes + * + * original CImagePNG and CImageIterator implementation are: + * Copyright: (c) 1995, Alejandro Aguilar Sierra + * + * libpng Copyright (c) 1998-2003 Glenn Randers-Pehrson + * ========================================================== + */ +#if !defined(__ximaPNG_h) +#define __ximaPNG_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_PNG + +extern "C" { +#include "../png/png.h" +} + +class CxImagePNG: public CxImage +{ +public: + CxImagePNG(): CxImage(CXIMAGE_FORMAT_PNG) {} + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_PNG);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_PNG);} + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE + +protected: + void ima_png_error(png_struct *png_ptr, char *message); + void expand2to4bpp(BYTE* prow); + + static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length) + { + CxFile* hFile = (CxFile*)png_ptr->io_ptr; + if (hFile->Read(data,1,length) != length) png_error(png_ptr, "Read Error"); + } + + static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length) + { + CxFile* hFile = (CxFile*)png_ptr->io_ptr; + if (hFile->Write(data,1,length) != length) png_error(png_ptr, "Write Error"); + } + + static void user_flush_data(png_structp png_ptr) + { + CxFile* hFile = (CxFile*)png_ptr->io_ptr; + if (!hFile->Flush()) png_error(png_ptr, "Flush Error"); + } + static void user_error_fn(png_structp png_ptr,png_const_charp error_msg) + { + strncpy((char*)png_ptr->error_ptr,error_msg,255); + longjmp(png_ptr->jmpbuf, 1); + } +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximasel.cpp b/SlnkDWFImpl/CxImage/CxImage/ximasel.cpp new file mode 100644 index 0000000..929e36c --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximasel.cpp @@ -0,0 +1,469 @@ +// xImaSel.cpp : Selection functions +/* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_SELECTION + +//////////////////////////////////////////////////////////////////////////////// +/** + * Checks if the image has a valid selection. + */ +bool CxImage::SelectionIsValid() +{ + return pSelection!=0; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Gets the smallest rectangle that contains the selection + */ +void CxImage::SelectionGetBox(RECT& r) +{ + memcpy(&r,&info.rSelectionBox,sizeof(RECT)); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Empties the selection. + */ +bool CxImage::SelectionClear() +{ + if (pSelection){ + memset(pSelection,0,head.biWidth * head.biHeight); + info.rSelectionBox.left = head.biWidth; + info.rSelectionBox.bottom = head.biHeight; + info.rSelectionBox.right = info.rSelectionBox.top = 0; + return true; + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Allocates an empty selection. + */ +bool CxImage::SelectionCreate() +{ + SelectionDelete(); + pSelection = (BYTE*)calloc(head.biWidth * head.biHeight, 1); + return (pSelection!=0); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Deallocates the selction. + */ +bool CxImage::SelectionDelete() +{ + if (pSelection){ free(pSelection); pSelection=NULL; } + info.rSelectionBox.left = head.biWidth; + info.rSelectionBox.bottom = head.biHeight; + info.rSelectionBox.right = info.rSelectionBox.top = 0; + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Checks if the coordinates are inside the selection. + */ +bool CxImage::SelectionIsInside(long x, long y) +{ + if (IsInside(x,y)){ + if (pSelection==NULL) return true; + return pSelection[x+y*head.biWidth]!=0; + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Adds a rectangle to the existing selection. + */ +bool CxImage::SelectionAddRect(RECT r) +{ + if (pSelection==NULL) SelectionCreate(); + if (pSelection==NULL) return false; + + RECT r2; + if (r.left r2.left) info.rSelectionBox.left = max(0L,min(head.biWidth,r2.left)); + if (info.rSelectionBox.right < r2.right) info.rSelectionBox.right = max(0L,min(head.biWidth,r2.right)); + if (info.rSelectionBox.bottom > r2.bottom) info.rSelectionBox.bottom = max(0L,min(head.biHeight,r2.bottom)); + + long ymin = max(0L,min(head.biHeight,r2.bottom)); + long ymax = max(0L,min(head.biHeight,r2.top)); + long xmin = max(0L,min(head.biWidth,r2.left)); + long xmax = max(0L,min(head.biWidth,r2.right)); + + for (long y=ymin; y (xcenter - xradius)) info.rSelectionBox.left = max(0L,min(head.biWidth,(xcenter - xradius))); + if (info.rSelectionBox.right < (xcenter + xradius)) info.rSelectionBox.right = max(0L,min(head.biWidth,(xcenter + xradius))); + if (info.rSelectionBox.bottom > (ycenter - yradius)) info.rSelectionBox.bottom = max(0L,min(head.biHeight,(ycenter - yradius))); + if (info.rSelectionBox.top < (ycenter + yradius)) info.rSelectionBox.top = max(0L,min(head.biHeight,(ycenter + yradius))); + + long xmin = max(0L,min(head.biWidth,xcenter - xradius)); + long xmax = max(0L,min(head.biWidth,xcenter + xradius)); + long ymin = max(0L,min(head.biHeight,ycenter - yradius)); + long ymax = max(0L,min(head.biHeight,ycenter + yradius)); + + long y,yo; + for (y=ymin; yy) pSelection[x + y * head.biWidth] = 255; + } + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Inverts the selection. + */ +bool CxImage::SelectionInvert() +{ + if (pSelection) { + BYTE *iSrc=pSelection; + long n=head.biHeight*head.biWidth; + for(long i=0; i < n; i++){ + *iSrc=(BYTE)~(*(iSrc)); + iSrc++; + } + return true; + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Imports an existing region from another image with the same width and height. + */ +bool CxImage::SelectionCopy(CxImage &from) +{ + if (from.pSelection == NULL || head.biWidth != from.head.biWidth || head.biHeight != from.head.biHeight) return false; + if (pSelection==NULL) pSelection = (BYTE*)malloc(head.biWidth * head.biHeight); + if (pSelection==NULL) return false; + memcpy(pSelection,from.pSelection,head.biWidth * head.biHeight); + memcpy(&info.rSelectionBox,&from.info.rSelectionBox,sizeof(RECT)); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Adds a polygonal region to the existing selection. points points to an array of POINT structures. + * Each structure specifies the x-coordinate and y-coordinate of one vertex of the polygon. + * npoints specifies the number of POINT structures in the array pointed to by points. + */ +bool CxImage::SelectionAddPolygon(POINT *points, long npoints) +{ + if (points==NULL || npoints<3) return false; + + if (pSelection==NULL) SelectionCreate(); + if (pSelection==NULL) return false; + + BYTE* plocal = (BYTE*)calloc(head.biWidth*head.biHeight, 1); + RECT localbox = {head.biWidth,0,0,head.biHeight}; + + long x,y,i=0; + POINT *current,*next,*start; + //trace contour + while (i < npoints){ + current = &points[i]; + if (current->x!=-1){ + if (i==0 || (i>0 && points[i-1].x==-1)) start = &points[i]; + + if ((i+1)==npoints || points[i+1].x==-1) + next = start; + else + next = &points[i+1]; + + float beta; + if (current->x != next->x){ + beta = (float)(next->y - current->y)/(float)(next->x - current->x); + if (current->x < next->x){ + for (x=current->x; x<=next->x; x++){ + y = (long)(current->y + (x - current->x) * beta); + if (IsInside(x,y)) plocal[x + y * head.biWidth] = 255; + } + } else { + for (x=current->x; x>=next->x; x--){ + y = (long)(current->y + (x - current->x) * beta); + if (IsInside(x,y)) plocal[x + y * head.biWidth] = 255; + } + } + } + if (current->y != next->y){ + beta = (float)(next->x - current->x)/(float)(next->y - current->y); + if (current->y < next->y){ + for (y=current->y; y<=next->y; y++){ + x = (long)(current->x + (y - current->y) * beta); + if (IsInside(x,y)) plocal[x + y * head.biWidth] = 255; + } + } else { + for (y=current->y; y>=next->y; y--){ + x = (long)(current->x + (y - current->y) * beta); + if (IsInside(x,y)) plocal[x + y * head.biWidth] = 255; + } + } + } + } + + RECT r2; + if (current->x < next->x) {r2.left=current->x; r2.right=next->x; } else {r2.left=next->x ; r2.right=current->x; } + if (current->y < next->y) {r2.bottom=current->y; r2.top=next->y; } else {r2.bottom=next->y ; r2.top=current->y; } + if (localbox.top < r2.top) localbox.top = max(0L,min(head.biHeight-1,r2.top+1)); + if (localbox.left > r2.left) localbox.left = max(0L,min(head.biWidth-1,r2.left-1)); + if (localbox.right < r2.right) localbox.right = max(0L,min(head.biWidth-1,r2.right+1)); + if (localbox.bottom > r2.bottom) localbox.bottom = max(0L,min(head.biHeight-1,r2.bottom-1)); + + i++; + } + + //fill the outer region + long npix=(localbox.right - localbox.left)*(localbox.top - localbox.bottom); + POINT* pix = (POINT*)calloc(npix,sizeof(POINT)); + BYTE back=0, mark=1; + long fx, fy, fxx, fyy, first, last,xmin,xmax,ymin,ymax; + + for (int side=0; side<4; side++){ + switch(side){ + case 0: + xmin=localbox.left; xmax=localbox.right+1; ymin=localbox.bottom; ymax=localbox.bottom+1; + break; + case 1: + xmin=localbox.right; xmax=localbox.right+1; ymin=localbox.bottom; ymax=localbox.top+1; + break; + case 2: + xmin=localbox.left; xmax=localbox.right+1; ymin=localbox.top; ymax=localbox.top+1; + break; + case 3: + xmin=localbox.left; xmax=localbox.left+1; ymin=localbox.bottom; ymax=localbox.top+1; + break; + } + //fill from the border points + for(y=ymin;y=localbox.left && fxx<=localbox.right && fyy>=localbox.bottom && fyy<=localbox.top ) + { + plocal[fxx + fyy*head.biWidth] = mark; + if (fyy > 0 && plocal[fxx + (fyy - 1)*head.biWidth] == back){ + pix[last].x = fx; + pix[last].y = fy - 1; + last++; + if (last == npix) last = 0; + } + if ((fyy + 1)=localbox.left && fxx<=localbox.right && fyy>=localbox.bottom && fyy<=localbox.top ) + { + plocal[fxx + (y + fy)*head.biWidth] = mark; + if (fyy > 0 && plocal[fxx + (fyy - 1)*head.biWidth] == back){ + pix[last].x = fx; + pix[last].y = fy - 1; + last++; + if (last == npix) last = 0; + } + if ((fyy + 1) localbox.left) info.rSelectionBox.left = localbox.left; + if (info.rSelectionBox.right < localbox.right) info.rSelectionBox.right = localbox.right+1; + if (info.rSelectionBox.bottom > localbox.bottom) info.rSelectionBox.bottom = localbox.bottom; + + free(plocal); + free(pix); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Adds to the selection all the pixels matching the specified color. + */ +bool CxImage::SelectionAddColor(RGBQUAD c) +{ + if (pSelection==NULL) SelectionCreate(); + if (pSelection==NULL) return false; + + RECT localbox = {head.biWidth,0,0,head.biHeight}; + + for (long y = 0; y < head.biHeight; y++){ + for (long x = 0; x < head.biWidth; x++){ + RGBQUAD color = GetPixelColor(x, y); + if (color.rgbRed == c.rgbRed && + color.rgbGreen == c.rgbGreen && + color.rgbBlue == c.rgbBlue) + { + pSelection[x + y * head.biWidth] = 255; // set the correct mask bit + + if (localbox.top < y) localbox.top = y; + if (localbox.left > x) localbox.left = x; + if (localbox.right < x) localbox.right = x; + if (localbox.bottom > y) localbox.bottom = y; + } + } + } + + if (info.rSelectionBox.top < localbox.top) info.rSelectionBox.top = localbox.top; + if (info.rSelectionBox.left > localbox.left) info.rSelectionBox.left = localbox.left; + if (info.rSelectionBox.right < localbox.right) info.rSelectionBox.right = localbox.right; + if (info.rSelectionBox.bottom > localbox.bottom) info.rSelectionBox.bottom = localbox.bottom; + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Adds a single pixel to the existing selection. + */ +bool CxImage::SelectionAddPixel(int x, int y) +{ + if (pSelection==NULL) SelectionCreate(); + if (pSelection==NULL) return false; + + if (IsInside(x,y)) { + pSelection[x + y * head.biWidth] = 255; // set the correct mask bit + return true; + } + + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Exports the selection channel in a 8bpp grayscale image. + */ +bool CxImage::SelectionSplit(CxImage *dest) +{ + if (!pSelection || !dest) return false; + + CxImage tmp(head.biWidth,head.biHeight,8); + if (!tmp.IsValid()) return false; + + for(long y=0; yTransfer(tmp); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_WINDOWS +/** + * Converts the selection in a HRGN object. + */ +bool CxImage::SelectionToHRGN(HRGN& region) +{ + if (pSelection && region){ + for(int y = 0; y < head.biHeight; y++){ + HRGN hTemp = NULL; + int iStart = -1; + int x = 0; + for(; x < head.biWidth; x++){ + if (pSelection[x + y * head.biWidth] == 255){ + if (iStart == -1) iStart = x; + continue; + }else{ + if (iStart >= 0){ + hTemp = CreateRectRgn(iStart, y, x, y + 1); + CombineRgn(region, hTemp, region, RGN_OR); + DeleteObject(hTemp); + iStart = -1; + } + } + } + if (iStart >= 0){ + hTemp = CreateRectRgn(iStart, y, x, y + 1); + CombineRgn(region, hTemp, region, RGN_OR); + DeleteObject(hTemp); + iStart = -1; + } + } + return true; + } + return false; +} +#endif //CXIMAGE_SUPPORT_WINDOWS +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_SELECTION diff --git a/SlnkDWFImpl/CxImage/CxImage/ximatga.cpp b/SlnkDWFImpl/CxImage/CxImage/ximatga.cpp new file mode 100644 index 0000000..441cb83 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximatga.cpp @@ -0,0 +1,300 @@ +/* + * File: ximatga.cpp + * Purpose: Platform Independent TGA Image Class Loader and Writer + * 05/Jan/2001 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximatga.h" + +#if CXIMAGE_SUPPORT_TGA + +#include "ximaiter.h" + +// Definitions for image types. +#define TGA_Null 0 +#define TGA_Map 1 +#define TGA_RGB 2 +#define TGA_Mono 3 +#define TGA_RLEMap 9 +#define TGA_RLERGB 10 +#define TGA_RLEMono 11 +#define TGA_CompMap 32 +#define TGA_CompMap4 33 + +//////////////////////////////////////////////////////////////////////////////// +bool CxImageTGA::Decode(CxFile *hFile) +{ + if (hFile == NULL) return false; + + TGAHEADER tgaHead; + + try + { + if (hFile->Read(&tgaHead,sizeof(tgaHead),1)==0) + throw "Not a TGA"; + + bool bCompressed; + switch (tgaHead.ImageType){ + case TGA_Map: + case TGA_RGB: + case TGA_Mono: + bCompressed = false; + break; + case TGA_RLEMap: + case TGA_RLERGB: + case TGA_RLEMono: + bCompressed = true; + break; + default: + throw "Unknown TGA image type"; + } + + if (tgaHead.ImageWidth==0 || tgaHead.ImageHeight==0 || tgaHead.PixelDepth==0 || tgaHead.CmapLength>256) + throw "bad TGA header"; + + if (tgaHead.PixelDepth!=8 && tgaHead.PixelDepth!=15 && tgaHead.PixelDepth!=16 && tgaHead.PixelDepth!=24 && tgaHead.PixelDepth!=32) + throw "bad TGA header"; + + if (tgaHead.IdLength>0) hFile->Seek(tgaHead.IdLength,SEEK_CUR); //skip descriptor + + Create(tgaHead.ImageWidth, tgaHead.ImageHeight, tgaHead.PixelDepth, CXIMAGE_FORMAT_TGA); +#if CXIMAGE_SUPPORT_ALPHA // + if (tgaHead.PixelDepth==32) AlphaCreate(); // Image has alpha channel +#endif //CXIMAGE_SUPPORT_ALPHA + + if (!IsValid()) throw "TGA Create failed"; + + if (info.nEscape) throw "Cancelled"; // - cancel decoding + + if (tgaHead.CmapType != 0){ // read the palette + rgb_color pal[256]; + hFile->Read(pal,tgaHead.CmapLength*sizeof(rgb_color), 1); + for (int i=0;i - cancel decoding + + if (hFile == NULL || hFile->Eof()) throw "corrupted TGA"; + + if (bYReversed) pDest = iter.GetRow(tgaHead.ImageHeight-y-1); + else pDest = iter.GetRow(y); + + if (bCompressed) rleLeftover = ExpandCompressedLine(pDest,&tgaHead,hFile,tgaHead.ImageWidth,y,rleLeftover); + else ExpandUncompressedLine (pDest,&tgaHead,hFile,tgaHead.ImageWidth,y,0); + } + + if (bXReversed) Mirror(); + +#if CXIMAGE_SUPPORT_ALPHA + if (bYReversed && tgaHead.PixelDepth==32) AlphaFlip(); // +#endif //CXIMAGE_SUPPORT_ALPHA + + } catch (char *message) { + strncpy(info.szLastError,message,255); + return FALSE; + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImageTGA::Encode(CxFile * hFile) +{ + if (EncodeSafeCheck(hFile)) return false; + + if (head.biBitCount<8){ + strcpy(info.szLastError,"Bit depth must be 8 or 24"); + return false; + } + + TGAHEADER tgaHead; + + tgaHead.IdLength = 0; // Image ID Field Length + tgaHead.CmapType = GetPalette()!=0; // Color Map Type + tgaHead.ImageType = (head.biBitCount == 8) ? (BYTE)TGA_Map : (BYTE)TGA_RGB; // Image Type + + tgaHead.CmapIndex=0; // First Entry Index + tgaHead.CmapLength=(head.biBitCount == 8) ? 256 : 0; // Color Map Length + tgaHead.CmapEntrySize=(head.biBitCount == 8) ? (BYTE)24 : (BYTE)0; // Color Map Entry Size + + tgaHead.X_Origin=0; // X-origin of Image + tgaHead.Y_Origin=0; // Y-origin of Image + tgaHead.ImageWidth=(WORD)head.biWidth; // Image Width + tgaHead.ImageHeight=(WORD)head.biHeight; // Image Height + tgaHead.PixelDepth=(BYTE)head.biBitCount; // Pixel Depth + tgaHead.ImagDesc=0; // Image Descriptor + + if (pAlpha && head.biBitCount==24) tgaHead.PixelDepth=32; + + hFile->Write(&tgaHead,sizeof(TGAHEADER),1); + + if (head.biBitCount==8){ + rgb_color pal[256]; + RGBQUAD* ppal = GetPalette(); + for (int i=0;i<256; i++){ + pal[i].r = ppal[i].rgbBlue; + pal[i].g = ppal[i].rgbGreen; + pal[i].b = ppal[i].rgbRed; + } + hFile->Write(&pal,256*sizeof(rgb_color),1); + } + + CImageIterator iter(this); + BYTE* pDest; + if (pAlpha==0 || head.biBitCount==8){ + for (int y=0; y < tgaHead.ImageHeight; y++){ + pDest = iter.GetRow(y); + hFile->Write(pDest,tgaHead.ImageWidth * (head.biBitCount >> 3),1); + } + } else { + pDest = (BYTE*)malloc(4*tgaHead.ImageWidth); + RGBQUAD c; + for (int y=0; y < tgaHead.ImageHeight; y++){ + for(int x=0, x4=0;x + pDest[x4+3]=(BYTE)((AlphaGet(x,y)*info.nAlphaMax)/255); +#else + pDest[x4+3]=0; +#endif //CXIMAGE_SUPPORT_ALPHA + } + hFile->Write(pDest,4*tgaHead.ImageWidth,1); + } + free(pDest); + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +BYTE CxImageTGA::ExpandCompressedLine(BYTE* pDest,TGAHEADER* ptgaHead,CxFile *hFile,int width, int y, BYTE rleLeftover) +{ + try{ + BYTE rle; + long filePos; + for (int x=0; xRead(&rle,1,1); + } + if (rle & 128) { // RLE-Encoded packet + rle -= 127; // Calculate real repeat count. + if ((x+rle)>width){ + rleLeftover = 128 + (rle - (width - x) - 1); + filePos = hFile->Tell(); + rle=width-x; + } + switch (ptgaHead->PixelDepth) + { + case 32: { + RGBQUAD color; + hFile->Read(&color,4,1); + for (int ix = 0; ix < rle; ix++){ + memcpy(&pDest[3*ix],&color,3); +#if CXIMAGE_SUPPORT_ALPHA // + AlphaSet(ix+x,y,color.rgbReserved); +#endif //CXIMAGE_SUPPORT_ALPHA + } + break; + } + case 24: { + rgb_color triple; + hFile->Read(&triple,3,1); + for (int ix = 0; ix < rle; ix++) memcpy(&pDest[3*ix],&triple,3); + break; + } + case 15: + case 16: { + WORD pixel; + hFile->Read(&pixel,2,1); + rgb_color triple; + triple.r = (BYTE)(( pixel & 0x1F ) * 8); // red + triple.g = (BYTE)(( pixel >> 2 ) & 0x0F8); // green + triple.b = (BYTE)(( pixel >> 7 ) & 0x0F8); // blue + for (int ix = 0; ix < rle; ix++){ + memcpy(&pDest[3*ix],&triple,3); + } + break; + } + case 8: { + BYTE pixel; + hFile->Read(&pixel,1,1); + for (int ix = 0; ix < rle; ix++) pDest[ix] = pixel; + } + } + if (rleLeftover!=255) hFile->Seek(filePos, SEEK_SET); + } else { // Raw packet + rle += 1; // Calculate real repeat count. + if ((x+rle)>width){ + rleLeftover = rle - (width - x) - 1; + rle=width-x; + } + ExpandUncompressedLine(pDest,ptgaHead,hFile,rle,y,x); + } + if (head.biBitCount == 24) pDest += rle*3; else pDest += rle; + x += rle; + } + } catch(...){ } + return rleLeftover; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageTGA::ExpandUncompressedLine(BYTE* pDest,TGAHEADER* ptgaHead,CxFile *hFile,int width, int y, int xoffset) +{ + try{ + switch (ptgaHead->PixelDepth){ + case 8: + hFile->Read(pDest,width,1); + break; + case 15: + case 16:{ + BYTE* dst=pDest; + WORD pixel; + for (int x=0; xRead(&pixel,2,1); + *dst++ = (BYTE)(( pixel & 0x1F ) * 8); // blue + *dst++ = (BYTE)(( pixel >> 2 ) & 0x0F8); // green + *dst++ = (BYTE)(( pixel >> 7 ) & 0x0F8); // red + } + break; + } + case 24: + hFile->Read(pDest,3*width,1); + break; + case 32:{ + BYTE* dst=pDest; + for (int x=0; xRead(&pixel,4,1); + *dst++ = pixel.rgbBlue; + *dst++ = pixel.rgbGreen; + *dst++ = pixel.rgbRed; +#if CXIMAGE_SUPPORT_ALPHA // + AlphaSet(x+xoffset,y,pixel.rgbReserved); //alpha +#endif //CXIMAGE_SUPPORT_ALPHA + } + break; + } + } + } catch(...){ } +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_TGA + diff --git a/SlnkDWFImpl/CxImage/CxImage/ximatga.h b/SlnkDWFImpl/CxImage/CxImage/ximatga.h new file mode 100644 index 0000000..3339eef --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximatga.h @@ -0,0 +1,60 @@ +/* + * File: ximatga.h + * Purpose: TARGA Image Class Loader and Writer + */ +/* ========================================================== + * CxImageTGA (c) 05/Jan/2002 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * Parts of the code come from Paintlib : Copyright (c) 1996-1998 Ulrich von Zadow + * ========================================================== + */ +#if !defined(__ximaTGA_h) +#define __ximaTGA_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_TGA + +class CxImageTGA: public CxImage +{ +#pragma pack(1) +typedef struct tagTgaHeader +{ + BYTE IdLength; // Image ID Field Length + BYTE CmapType; // Color Map Type + BYTE ImageType; // Image Type + + WORD CmapIndex; // First Entry Index + WORD CmapLength; // Color Map Length + BYTE CmapEntrySize; // Color Map Entry Size + + WORD X_Origin; // X-origin of Image + WORD Y_Origin; // Y-origin of Image + WORD ImageWidth; // Image Width + WORD ImageHeight; // Image Height + BYTE PixelDepth; // Pixel Depth + BYTE ImagDesc; // Image Descriptor +} TGAHEADER; +#pragma pack() + +public: + CxImageTGA(): CxImage(CXIMAGE_FORMAT_TGA) {} + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_TGA);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_TGA);} + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE +protected: + BYTE ExpandCompressedLine(BYTE* pDest,TGAHEADER* ptgaHead,CxFile *hFile,int width, int y, BYTE rleLeftover); + void ExpandUncompressedLine(BYTE* pDest,TGAHEADER* ptgaHead,CxFile *hFile,int width, int y, int xoffset); +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximath.cpp b/SlnkDWFImpl/CxImage/CxImage/ximath.cpp new file mode 100644 index 0000000..0175184 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximath.cpp @@ -0,0 +1,97 @@ +#include "ximage.h" +#include "ximath.h" +#include + +//this module should contain some classes for geometrical transformations +//usable with selections, etc... once it's done, that is. :) + +CxPoint2::CxPoint2() +{ + x=y=0.0f; +} + +CxPoint2::CxPoint2(float const x_, float const y_) +{ + x=x_; + y=y_; +} + +CxPoint2::CxPoint2(CxPoint2 const &p) +{ + x=p.x; + y=p.y; +} + +float CxPoint2::Distance(CxPoint2 const p2) +{ + return (float)sqrt((x-p2.x)*(x-p2.x)+(y-p2.y)*(y-p2.y)); +} + +float CxPoint2::Distance(float const x_, float const y_) +{ + return (float)sqrt((x-x_)*(x-x_)+(y-y_)*(y-y_)); +} + +CxRect2::CxRect2() +{ +} + +CxRect2::CxRect2(float const x1_, float const y1_, float const x2_, float const y2_) +{ + botLeft.x=x1_; + botLeft.y=y1_; + topRight.x=x2_; + topRight.y=y2_; +} + +CxRect2::CxRect2(CxRect2 const &p) +{ + botLeft=p.botLeft; + topRight=p.topRight; +} + +float CxRect2::Surface() const +/* + * Returns the surface of rectangle. + */ +{ + return (topRight.x-botLeft.x)*(topRight.y-botLeft.y); +} + +CxRect2 CxRect2::CrossSection(CxRect2 const &r2) const +/* + * Returns crossection with another rectangle. + */ +{ + CxRect2 cs; + cs.botLeft.x=max(botLeft.x, r2.botLeft.x); + cs.botLeft.y=max(botLeft.y, r2.botLeft.y); + cs.topRight.x=min(topRight.x, r2.topRight.x); + cs.topRight.y=min(topRight.y, r2.topRight.y); + if (cs.botLeft.x<=cs.topRight.x && cs.botLeft.y<=cs.topRight.y) { + return cs; + } else { + return CxRect2(0,0,0,0); + }//if +} + +CxPoint2 CxRect2::Center() const +/* + * Returns the center point of rectangle. + */ +{ + return CxPoint2((topRight.x+botLeft.x)/2.0f, (topRight.y+botLeft.y)/2.0f); +} + +float CxRect2::Width() const +//returns rectangle width +{ + return topRight.x-botLeft.x; +} + +float CxRect2::Height() const +//returns rectangle height +{ + return topRight.y-botLeft.y; +} + diff --git a/SlnkDWFImpl/CxImage/CxImage/ximath.h b/SlnkDWFImpl/CxImage/CxImage/ximath.h new file mode 100644 index 0000000..014c14b --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximath.h @@ -0,0 +1,39 @@ +#if !defined(__ximath_h) +#define __ximath_h + +#include "ximadef.h" + +//***bd*** simple floating point point +class DLL_EXP CxPoint2 +{ +public: + CxPoint2(); + CxPoint2(float const x_, float const y_); + CxPoint2(CxPoint2 const &p); + + float Distance(CxPoint2 const p2); + float Distance(float const x_, float const y_); + + float x,y; +}; + +//and simple rectangle +class DLL_EXP CxRect2 +{ +public: + CxRect2(); + CxRect2(float const x1_, float const y1_, float const x2_, float const y2_); + CxRect2(CxPoint2 const &bl, CxPoint2 const &tr); + CxRect2(CxRect2 const &p); + + float Surface() const; + CxRect2 CrossSection(CxRect2 const &r2) const; + CxPoint2 Center() const; + float Width() const; + float Height() const; + + CxPoint2 botLeft; + CxPoint2 topRight; +}; + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximatif.cpp b/SlnkDWFImpl/CxImage/CxImage/ximatif.cpp new file mode 100644 index 0000000..89d94ff --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximatif.cpp @@ -0,0 +1,763 @@ +/* + * File: ximatif.cpp + * Purpose: Platform Independent TIFF Image Class Loader and Writer + * 07/Aug/2001 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximatif.h" + +#if CXIMAGE_SUPPORT_TIF + +#include "../tiff/tiffio.h" + +#define CVT(x) (((x) * 255L) / ((1L<<16)-1)) +#define SCALE(x) (((x)*((1L<<16)-1))/255) +#define CalculateLine(width,bitdepth) (((width * bitdepth) + 7) / 8) +#define CalculatePitch(line) (line + 3 & ~3) + +extern "C" TIFF* _TIFFOpenEx(CxFile* stream, const char* mode); + +//////////////////////////////////////////////////////////////////////////////// +CxImageTIF::~CxImageTIF() +{ + if (m_tif2) TIFFClose(m_tif2); +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImageTIF::Decode(CxFile * hFile) +{ + //Comment this line if you need more information on errors + // TIFFSetErrorHandler(NULL); // + + //Open file and fill the TIFF structure + // m_tif = TIFFOpen(imageFileName,"rb"); + TIFF* m_tif = _TIFFOpenEx(hFile, "rb"); + + uint32 height=0; + uint32 width=0; + uint16 bitspersample=1; + uint16 samplesperpixel=1; + uint32 rowsperstrip=(DWORD)-1; + uint16 photometric=0; + uint16 compression=1; + uint16 orientation=ORIENTATION_TOPLEFT; // + uint16 res_unit; // + uint32 x, y; + float resolution, offset; + BOOL isRGB; + BYTE *bits; //pointer to source data + BYTE *bits2; //pointer to destination data + + try{ + //check if it's a tiff file + if (!m_tif) + throw "Error encountered while opening TIFF file"; + + // - 12/2002 : get NumFrames directly, instead of looping + // info.nNumFrames=0; + // while(TIFFSetDirectory(m_tif,(uint16)info.nNumFrames)) info.nNumFrames++; + info.nNumFrames = TIFFNumberOfDirectories(m_tif); + + if (!TIFFSetDirectory(m_tif, (uint16)info.nFrame)) + throw "Error: page not present in TIFF file"; + + //get image info + TIFFGetField(m_tif, TIFFTAG_IMAGEWIDTH, &width); + TIFFGetField(m_tif, TIFFTAG_IMAGELENGTH, &height); + TIFFGetField(m_tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel); + TIFFGetField(m_tif, TIFFTAG_BITSPERSAMPLE, &bitspersample); + TIFFGetField(m_tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); + TIFFGetField(m_tif, TIFFTAG_PHOTOMETRIC, &photometric); + TIFFGetField(m_tif, TIFFTAG_ORIENTATION, &orientation); + + if (info.nEscape == -1) { + // Return output dimensions only + head.biWidth = width; + head.biHeight = height; + throw "output dimensions returned"; + } + + TIFFGetFieldDefaulted(m_tif, TIFFTAG_RESOLUTIONUNIT, &res_unit); + if (TIFFGetField(m_tif, TIFFTAG_XRESOLUTION, &resolution)) + { + if (res_unit == RESUNIT_CENTIMETER) resolution = (float)(resolution*2.54f + 0.5f); + SetXDPI((long)resolution); + } + if (TIFFGetField(m_tif, TIFFTAG_YRESOLUTION, &resolution)) + { + if (res_unit == RESUNIT_CENTIMETER) resolution = (float)(resolution*2.54f + 0.5f); + SetYDPI((long)resolution); + } + + if (TIFFGetField(m_tif, TIFFTAG_XPOSITION, &offset)) info.xOffset = (long)offset; + if (TIFFGetField(m_tif, TIFFTAG_YPOSITION, &offset)) info.yOffset = (long)offset; + + head.biClrUsed=0; + info.nBkgndIndex =-1; + + if (rowsperstrip>height){ + rowsperstrip=height; + TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); + } + + isRGB = (bitspersample >= 8) && + (photometric == PHOTOMETRIC_RGB) || + (photometric == PHOTOMETRIC_YCBCR) || + (photometric == PHOTOMETRIC_SEPARATED) || + (photometric == PHOTOMETRIC_LOGL) || + (photometric == PHOTOMETRIC_LOGLUV); + + if (isRGB){ + head.biBitCount=24; + }else{ + if ((photometric==PHOTOMETRIC_MINISBLACK)||(photometric==PHOTOMETRIC_MINISWHITE)){ + if (bitspersample == 1){ + head.biBitCount=1; //B&W image + head.biClrUsed =2; + } else if (bitspersample == 4) { + head.biBitCount=4; //16 colors gray scale + head.biClrUsed =16; + } else { + head.biBitCount=8; //gray scale + head.biClrUsed =256; + } + } else if (bitspersample == 4) { + head.biBitCount=4; // 16 colors + head.biClrUsed=16; + } else { + head.biBitCount=8; //256 colors + head.biClrUsed=256; + } + } + + if (info.nEscape) throw "Cancelled"; // - cancel decoding + + Create(width,height,head.biBitCount,CXIMAGE_FORMAT_TIF); //image creation + if (!pDib) throw "CxImageTIF can't create image"; + +#if CXIMAGE_SUPPORT_ALPHA + if (samplesperpixel==4) AlphaCreate(); //add alpha support for 32bpp tiffs + if (samplesperpixel==2 && bitspersample==8) AlphaCreate(); //add alpha support for 8bpp + alpha +#endif //CXIMAGE_SUPPORT_ALPHA + + TIFFGetField(m_tif, TIFFTAG_COMPRESSION, &compression); + SetCodecOption(compression); // save original compression type + + if (isRGB) { + // Read the whole image into one big RGBA buffer using + // the traditional TIFFReadRGBAImage() API that we trust. + uint32* raster; // retrieve RGBA image + uint32 *row; + + raster = (uint32*)_TIFFmalloc(width * height * sizeof (uint32)); + if (raster == NULL) throw "No space for raster buffer"; + + // Read the image in one chunk into an RGBA array + if(!TIFFReadRGBAImage(m_tif, width, height, raster, 1)) { + _TIFFfree(raster); + throw "Corrupted TIFF file!"; + } + + // read the raster lines and save them in the DIB + // with RGB mode, we have to change the order of the 3 samples RGB + row = &raster[0]; + bits2 = info.pImage; + for (y = 0; y < height; y++) { + + if (info.nEscape){ // - cancel decoding + _TIFFfree(raster); + throw "Cancelled"; + } + + bits = bits2; + for (x = 0; x < width; x++) { + *bits++ = (BYTE)TIFFGetB(row[x]); + *bits++ = (BYTE)TIFFGetG(row[x]); + *bits++ = (BYTE)TIFFGetR(row[x]); +#if CXIMAGE_SUPPORT_ALPHA + if (samplesperpixel==4) AlphaSet(x,y,(BYTE)TIFFGetA(row[x])); +#endif //CXIMAGE_SUPPORT_ALPHA + } + row += width; + bits2 += info.dwEffWidth; + } + _TIFFfree(raster); + } else { + RGBQUAD *pal; + pal=(RGBQUAD*)calloc(256,sizeof(RGBQUAD)); + if (pal==NULL) throw "Unable to allocate TIFF palette"; + + // set up the colormap based on photometric + switch(photometric) { + case PHOTOMETRIC_MINISBLACK: // bitmap and greyscale image types + case PHOTOMETRIC_MINISWHITE: + if (bitspersample == 1) { // Monochrome image + if (photometric == PHOTOMETRIC_MINISBLACK) { + pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = 255; + } else { + pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = 255; + } + } else { // need to build the scale for greyscale images + if (photometric == PHOTOMETRIC_MINISBLACK) { + for (DWORD i=0; i 0) { + if (red[n] >= 256 || green[n] >= 256 || blue[n] >= 256) { + Palette16Bits=TRUE; + break; + } + } + + // load the palette in the DIB + for (int i = (1 << bitspersample) - 1; i >= 0; i--) { + if (Palette16Bits) { + pal[i].rgbRed =(BYTE) CVT(red[i]); + pal[i].rgbGreen = (BYTE) CVT(green[i]); + pal[i].rgbBlue = (BYTE) CVT(blue[i]); + } else { + pal[i].rgbRed = (BYTE) red[i]; + pal[i].rgbGreen = (BYTE) green[i]; + pal[i].rgbBlue = (BYTE) blue[i]; + } + } + break; + } + SetPalette(pal,head.biClrUsed); //palette assign + free(pal); + + // read the tiff lines and save them in the DIB + uint32 nrow; + uint32 ys; + int line = CalculateLine(width, bitspersample * samplesperpixel); + long bitsize= TIFFStripSize(m_tif); + //verify bitsize: could be wrong if StripByteCounts is missing. + if (bitsize>(long)(head.biSizeImage*samplesperpixel)) bitsize=head.biSizeImage*samplesperpixel; + + int tiled_image = TIFFIsTiled(m_tif); + uint32 tw, tl; + BYTE* tilebuf; + if (tiled_image){ + TIFFGetField(m_tif, TIFFTAG_TILEWIDTH, &tw); + TIFFGetField(m_tif, TIFFTAG_TILELENGTH, &tl); + rowsperstrip = tl; + bitsize = TIFFTileSize(m_tif) * (int)(1+width/tw); + tilebuf = (BYTE*)malloc(TIFFTileSize(m_tif)); + } + + bits = (BYTE*)malloc(bitsize); + if (bits==NULL){ + throw "CxImageTIF can't allocate memory"; + } + + for (ys = 0; ys < height; ys += rowsperstrip) { + + if (info.nEscape){ // - cancel decoding + free(bits); + throw "Cancelled"; + } + + nrow = (ys + rowsperstrip > height ? height - ys : rowsperstrip); + + if (tiled_image){ + uint32 imagew = TIFFScanlineSize(m_tif); + uint32 tilew = TIFFTileRowSize(m_tif); + int iskew = imagew - tilew; + uint8* bufp = (uint8*) bits; + + uint32 colb = 0; + for (uint32 col = 0; col < width; col += tw) { + if (TIFFReadTile(m_tif, tilebuf, col, ys, 0, 0) < 0){ + free(tilebuf); + free(bits); + throw "Corrupted tiled TIFF file!"; + } + + if (colb + tw > imagew) { + uint32 owidth = imagew - colb; + uint32 oskew = tilew - owidth; + TileToStrip(bufp + colb, tilebuf, nrow, owidth, oskew + iskew, oskew ); + } else { + TileToStrip(bufp + colb, tilebuf, nrow, tilew, iskew, 0); + } + colb += tilew; + } + + } else { + if (TIFFReadEncodedStrip(m_tif, TIFFComputeStrip(m_tif, ys, 0), bits, nrow * line) == -1) { + free(bits); + throw "Corrupted TIFF file!"; + } + } + + for (y = 0; y < nrow; y++) { + long offset=(nrow-y-1)*line; + if (bitspersample==16) for (DWORD xi=0;xi=(int)width){ + yi--; + xi=0; + } + } + } else { //photometric==PHOTOMETRIC_CIELAB + if (head.biBitCount!=24){ //fix image + Create(width,height,24,CXIMAGE_FORMAT_TIF); +#if CXIMAGE_SUPPORT_ALPHA + if (samplesperpixel==4) AlphaCreate(); +#endif //CXIMAGE_SUPPORT_ALPHA + } + + int xi=0; + int ii=0; + int yi=height-ys-nrow+y; + RGBQUAD c; + int l,a,b,bitsoffset; + double p,cx,cy,cz,cr,cg,cb; + while (ii127) a-=256; + if (b>127) b-=256; + // lab to xyz + p = (l/2.55 + 16) / 116.0; + cx = pow( p + a * 0.002, 3); + cy = pow( p, 3); + cz = pow( p - b * 0.005, 3); + // white point + cx*=0.95047; + //cy*=1.000; + cz*=1.0883; + // xyz to rgb + cr = 3.240479 * cx - 1.537150 * cy - 0.498535 * cz; + cg = -0.969256 * cx + 1.875992 * cy + 0.041556 * cz; + cb = 0.055648 * cx - 0.204043 * cy + 1.057311 * cz; + + if ( cr > 0.00304 ) cr = 1.055 * pow(cr,0.41667) - 0.055; + else cr = 12.92 * cr; + if ( cg > 0.00304 ) cg = 1.055 * pow(cg,0.41667) - 0.055; + else cg = 12.92 * cg; + if ( cb > 0.00304 ) cb = 1.055 * pow(cb,0.41667) - 0.055; + else cb = 12.92 * cb; + + c.rgbRed =(BYTE)max(0,min(255,(int)(cr*255))); + c.rgbGreen=(BYTE)max(0,min(255,(int)(cg*255))); + c.rgbBlue =(BYTE)max(0,min(255,(int)(cb*255))); + + SetPixelColor(xi,yi,c); +#if CXIMAGE_SUPPORT_ALPHA + if (samplesperpixel==4) AlphaSet(xi,yi,bits[bitsoffset+3]); +#endif //CXIMAGE_SUPPORT_ALPHA + ii++; + xi++; + if (xi>=(int)width){ + yi--; + xi=0; + } + } + } + } + } + free(bits); + if (tiled_image) free(tilebuf); + + switch(orientation){ + case ORIENTATION_TOPRIGHT: /* row 0 top, col 0 rhs */ + Mirror(); + break; + case ORIENTATION_BOTRIGHT: /* row 0 bottom, col 0 rhs */ + Flip(); + Mirror(); + break; + case ORIENTATION_BOTLEFT: /* row 0 bottom, col 0 lhs */ + Flip(); + break; + case ORIENTATION_LEFTTOP: /* row 0 lhs, col 0 top */ + RotateRight(); + Mirror(); + break; + case ORIENTATION_RIGHTTOP: /* row 0 rhs, col 0 top */ + RotateLeft(); + break; + case ORIENTATION_RIGHTBOT: /* row 0 rhs, col 0 bottom */ + RotateLeft(); + Mirror(); + break; + case ORIENTATION_LEFTBOT: /* row 0 lhs, col 0 bottom */ + RotateRight(); + break; + } + + } + } catch (char *message) { + strncpy(info.szLastError,message,255); + if (m_tif) TIFFClose(m_tif); + if (info.nEscape==-1) return true; + return false; + } + TIFFClose(m_tif); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImageTIF::Encode(CxFile * hFile, bool bAppend) +{ + try{ + if (hFile==NULL) throw CXIMAGE_ERR_NOFILE; + if (pDib==NULL) throw CXIMAGE_ERR_NOIMAGE; + + // replaced "w+b" with "a", to append an image directly on an existing file + if (m_tif2==NULL) m_tif2=_TIFFOpenEx(hFile, "a"); + if (m_tif2==NULL) throw "initialization fail"; + + if (bAppend || m_pages) m_multipage=true; + m_pages++; + + if (!EncodeBody(m_tif2,m_multipage,m_pages,m_pages)) throw "Error saving TIFF file"; + if (bAppend) { + if (!TIFFWriteDirectory(m_tif2)) throw "Error saving TIFF directory"; + } + } catch (char *message) { + strncpy(info.szLastError,message,255); + if (m_tif2){ + TIFFClose(m_tif2); + m_tif2=NULL; + m_multipage=false; + m_pages=0; + } + return false; + } + if (!bAppend){ + TIFFClose(m_tif2); + m_tif2=NULL; + m_multipage=false; + m_pages=0; + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +// Thanks to Abe +bool CxImageTIF::Encode(CxFile * hFile, CxImage ** pImages, int pagecount) +{ + try{ + if (hFile==NULL) throw "invalid file pointer"; + if (pImages==NULL || pagecount==0) throw "multipage TIFF, no images!"; + + CxImageTIF ghost; + for (int i=1; i<=pagecount; i++){ + if (pImages[i-1]==NULL) throw "Bad image pointer"; + ghost.Ghost(pImages[i-1]); + if (!ghost.Encode(hFile,true)) throw "Error saving TIFF file"; + } + } catch (char *message) { + strncpy(info.szLastError,message,255); + return false; + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImageTIF::EncodeBody(TIFF *m_tif, bool multipage, int page, int pagecount) +{ + uint32 height=head.biHeight; + uint32 width=head.biWidth; + uint16 bitcount=head.biBitCount; + uint16 bitspersample; + uint16 samplesperpixel; + uint16 photometric=0; + uint16 compression; +// uint16 pitch; +// int line; + uint32 x, y; + + samplesperpixel = ((bitcount == 24) || (bitcount == 32)) ? (BYTE)3 : (BYTE)1; +#if CXIMAGE_SUPPORT_ALPHA + if (bitcount==24 && AlphaIsValid()) { bitcount=32; samplesperpixel=4; } +#endif //CXIMAGE_SUPPORT_ALPHA + + bitspersample = bitcount / samplesperpixel; + + //set the PHOTOMETRIC tag + RGBQUAD *rgb = GetPalette(); + switch (bitcount) { + case 1: + if (CompareColors(&rgb[0],&rgb[1])<0) { + /* some viewers do not handle PHOTOMETRIC_MINISBLACK: + * let's transform the image in PHOTOMETRIC_MINISWHITE + */ + //invert the colors + RGBQUAD tempRGB=GetPaletteColor(0); + SetPaletteColor(0,GetPaletteColor(1)); + SetPaletteColor(1,tempRGB); + //invert the pixels + BYTE *iSrc=info.pImage; + for (unsigned long i=0;irgbRed != x)||(rgb->rgbRed != rgb->rgbGreen)||(rgb->rgbRed != rgb->rgbBlue)){ + photometric = PHOTOMETRIC_PALETTE; + break; + } + rgb++; + } + break; + case 24: + case 32: + photometric = PHOTOMETRIC_RGB; + break; + } + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid() && bitcount==8) samplesperpixel=2; //8bpp + alpha layer +#endif //CXIMAGE_SUPPORT_ALPHA + +// line = CalculateLine(width, bitspersample * samplesperpixel); +// pitch = (uint16)CalculatePitch(line); + + //prepare the palette struct + RGBQUAD pal[256]; + if (GetPalette()){ + BYTE b; + memcpy(pal,GetPalette(),GetPaletteSize()); + for(WORD a=0;a gives better compression + TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); + + // handle metrics + TIFFSetField(m_tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH); + TIFFSetField(m_tif, TIFFTAG_XRESOLUTION, (float)info.xDPI); + TIFFSetField(m_tif, TIFFTAG_YRESOLUTION, (float)info.yDPI); +// TIFFSetField(m_tif, TIFFTAG_XPOSITION, (float)info.xOffset); +// TIFFSetField(m_tif, TIFFTAG_YPOSITION, (float)info.yOffset); + + // multi-paging - Thanks to Abe + if (multipage) + { + char page_number[20]; + sprintf(page_number, "Page %d", page); + + TIFFSetField(m_tif, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE); + TIFFSetField(m_tif, TIFFTAG_PAGENUMBER, page,pagecount); + TIFFSetField(m_tif, TIFFTAG_PAGENAME, page_number); + } else { + TIFFSetField(m_tif, TIFFTAG_SUBFILETYPE, 0); + } + + // palettes (image colormaps are automatically scaled to 16-bits) + if (photometric == PHOTOMETRIC_PALETTE) { + uint16 *r, *g, *b; + r = (uint16 *) _TIFFmalloc(sizeof(uint16) * 3 * 256); + g = r + 256; + b = g + 256; + + for (int i = 255; i >= 0; i--) { + b[i] = (uint16)SCALE((uint16)pal[i].rgbRed); + g[i] = (uint16)SCALE((uint16)pal[i].rgbGreen); + r[i] = (uint16)SCALE((uint16)pal[i].rgbBlue); + } + + TIFFSetField(m_tif, TIFFTAG_COLORMAP, r, g, b); + _TIFFfree(r); + } + + // compression + if (GetCodecOption(CXIMAGE_FORMAT_TIF)) { + compression = (WORD)GetCodecOption(CXIMAGE_FORMAT_TIF); + } else { + switch (bitcount) { + case 1 : + compression = COMPRESSION_CCITTFAX4; + break; + case 4 : + case 8 : + compression = COMPRESSION_LZW; + break; + case 24 : + case 32 : + compression = COMPRESSION_JPEG; + break; + default : + compression = COMPRESSION_NONE; + break; + } + } + TIFFSetField(m_tif, TIFFTAG_COMPRESSION, compression); + + switch (compression) { + case COMPRESSION_JPEG: + TIFFSetField(m_tif, TIFFTAG_JPEGQUALITY, info.nQuality); + TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, ((7+rowsperstrip)>>3)<<3); + break; + case COMPRESSION_LZW: + if (bitcount>=8) TIFFSetField(m_tif, TIFFTAG_PREDICTOR, 2); + break; + } + + // read the DIB lines from bottom to top and save them in the TIF + + BYTE *bits; + switch(bitcount) { + case 1 : + case 4 : + case 8 : + { + if (samplesperpixel==1){ + for (y = 0; y < height; y++) { + bits= info.pImage + (height - y - 1)*info.dwEffWidth; + if (TIFFWriteScanline(m_tif,bits, y, 0)==-1) return false; + } + } +#if CXIMAGE_SUPPORT_ALPHA + else { //8bpp + alpha layer + bits = (BYTE*)malloc(2*width); + if (!bits) return false; + for (y = 0; y < height; y++) { + for (x=0;x 0) { + uint32 j = cols; + while (j-- > 0) + *out++ = *in++; + out += outskew; + in += inskew; + } +} +//////////////////////////////////////////////////////////////////////////////// +TIFF* CxImageTIF::TIFFOpenEx(CxFile * hFile) +{ + if (hFile) return _TIFFOpenEx(hFile, "rb"); + return NULL; +} +//////////////////////////////////////////////////////////////////////////////// +void CxImageTIF::TIFFCloseEx(TIFF* tif) +{ + if (tif) TIFFClose(tif); +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_TIF diff --git a/SlnkDWFImpl/CxImage/CxImage/ximatif.h b/SlnkDWFImpl/CxImage/CxImage/ximatif.h new file mode 100644 index 0000000..7a63f59 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximatif.h @@ -0,0 +1,60 @@ +/* + * File: ximatif.h + * Purpose: TIFF Image Class Loader and Writer + */ +/* ========================================================== + * CxImageTIF (c) 07/Aug/2001 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * + * Special thanks to Troels Knakkergaard for new features, enhancements and bugfixes + * + * Special thanks to Abe for MultiPageTIFF code. + * + * LibTIFF is: + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * ========================================================== + */ + +#if !defined(__ximatif_h) +#define __ximatif_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_TIF + +#include "../tiff/tiffio.h" + +class DLL_EXP CxImageTIF: public CxImage +{ +public: + CxImageTIF(): CxImage(CXIMAGE_FORMAT_TIF) {m_tif2=NULL; m_multipage=false; m_pages=0;} + ~CxImageTIF(); + + TIFF* TIFFOpenEx(CxFile * hFile); + void TIFFCloseEx(TIFF* tif); + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_TIF);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_TIF);} + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile, bool bAppend=false); + bool Encode(CxFile * hFile, CxImage ** pImages, int pagecount); + bool Encode(FILE *hFile, bool bAppend=false) { CxIOFile file(hFile); return Encode(&file,bAppend); } + bool Encode(FILE *hFile, CxImage ** pImages, int pagecount) + { CxIOFile file(hFile); return Encode(&file, pImages, pagecount); } +#endif // CXIMAGE_SUPPORT_ENCODE + +protected: + void TileToStrip(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew); + bool EncodeBody(TIFF *m_tif, bool multipage=false, int page=0, int pagecount=0); + TIFF *m_tif2; + bool m_multipage; + int m_pages; +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximatran.cpp b/SlnkDWFImpl/CxImage/CxImage/ximatran.cpp new file mode 100644 index 0000000..cccaa94 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximatran.cpp @@ -0,0 +1,2439 @@ +// xImaTran.cpp : Transformation functions +/* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" +#include "ximath.h" + +#if CXIMAGE_SUPPORT_BASICTRANSFORMATIONS +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::GrayScale() +{ + if (!pDib) return false; + if (head.biBitCount<=8){ + RGBQUAD* ppal=GetPalette(); + int gray; + //converts the colors to gray, use the blue channel only + for(DWORD i=0;iIsValid()) return false; + BYTE *iSrc,*iDst; + iSrc=info.pImage + (head.biHeight-1)*info.dwEffWidth; + iDst=imatmp->info.pImage; + for(long y=0; y < head.biHeight; y++){ + memcpy(iDst,iSrc,info.dwEffWidth); + iSrc-=info.dwEffWidth; + iDst+=info.dwEffWidth; + } + +#if CXIMAGE_SUPPORT_ALPHA + imatmp->AlphaFlip(); +#endif //CXIMAGE_SUPPORT_ALPHA + + Transfer(*imatmp); + delete imatmp; + return true; +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::Mirror() +{ + if (!pDib) return false; + + CxImage* imatmp = new CxImage(*this,false,false,true); + if (!imatmp) return false; + BYTE *iSrc,*iDst; + long wdt=(head.biWidth-1) * (head.biBitCount==24 ? 3:1); + iSrc=info.pImage + wdt; + iDst=imatmp->info.pImage; + long x,y; + switch (head.biBitCount){ + case 24: + for(y=0; y < head.biHeight; y++){ + for(x=0; x <= wdt; x+=3){ + *(iDst+x)=*(iSrc-x); + *(iDst+x+1)=*(iSrc-x+1); + *(iDst+x+2)=*(iSrc-x+2); + } + iSrc+=info.dwEffWidth; + iDst+=info.dwEffWidth; + } + break; + case 8: + for(y=0; y < head.biHeight; y++){ + for(x=0; x <= wdt; x++) + *(iDst+x)=*(iSrc-x); + iSrc+=info.dwEffWidth; + iDst+=info.dwEffWidth; + } + break; + default: + for(y=0; y < head.biHeight; y++){ + for(x=0; x <= wdt; x++) + imatmp->SetPixelIndex(x,y,GetPixelIndex(wdt-x,y)); + } + } + +#if CXIMAGE_SUPPORT_ALPHA + imatmp->AlphaMirror(); +#endif //CXIMAGE_SUPPORT_ALPHA + + Transfer(*imatmp); + delete imatmp; + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +#define RBLOCK 64 + +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::RotateLeft(CxImage* iDst) +{ + if (!pDib) return false; + + long newWidth = GetHeight(); + long newHeight = GetWidth(); + + CxImage imgDest; + imgDest.CopyInfo(*this); + imgDest.Create(newWidth,newHeight,GetBpp(),GetType()); + imgDest.SetPalette(GetPalette()); + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) imgDest.AlphaCreate(); +#endif + + long x,x2,y,dlineup; + + // Speedy rotate for BW images + if (head.biBitCount == 1) { + + BYTE *sbits, *dbits, *dbitsmax, bitpos, *nrow,*srcdisp; + div_t div_r; + + BYTE *bsrc = GetBits(), *bdest = imgDest.GetBits(); + dbitsmax = bdest + imgDest.head.biSizeImage - 1; + dlineup = 8 * imgDest.info.dwEffWidth - imgDest.head.biWidth; + + imgDest.Clear(0); + for (y = 0; y < head.biHeight; y++) { + // Figure out the Column we are going to be copying to + div_r = div((int)(y + dlineup), (int)8); + // set bit pos of src column byte + bitpos = 1 << div_r.rem; + srcdisp = bsrc + y * info.dwEffWidth; + for (x = 0; x < (long)info.dwEffWidth; x++) { + // Get Source Bits + sbits = srcdisp + x; + // Get destination column + nrow = bdest + (x * 8) * imgDest.info.dwEffWidth + imgDest.info.dwEffWidth - 1 - div_r.quot; + for (long z = 0; z < 8; z++) { + // Get Destination Byte + dbits = nrow + z * imgDest.info.dwEffWidth; + if ((dbits < bdest) || (dbits > dbitsmax)) break; + if (*sbits & (128 >> z)) *dbits |= bitpos; + } + } + }//for y + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) { + for (x = 0; x < newWidth; x++){ + x2=newWidth-x-1; + for (y = 0; y < newHeight; y++){ + imgDest.AlphaSet(x,y,BlindAlphaGet(y, x2)); + }//for y + }//for x + } +#endif //CXIMAGE_SUPPORT_ALPHA + + } else { + //anything other than BW: + //bd, 10. 2004: This optimized version of rotation rotates image by smaller blocks. It is quite + //a bit faster than obvious algorithm, because it produces much less CPU cache misses. + //This optimization can be tuned by changing block size (RBLOCK). 96 is good value for current + //CPUs (tested on Athlon XP and Celeron D). Larger value (if CPU has enough cache) will increase + //speed somehow, but once you drop out of CPU's cache, things will slow down drastically. + //For older CPUs with less cache, lower value would yield better results. + + BYTE *srcPtr, *dstPtr; //source and destionation for 24-bit version + int xs, ys; //x-segment and y-segment + for (xs = 0; xs < newWidth; xs+=RBLOCK) { //for all image blocks of RBLOCK*RBLOCK pixels + for (ys = 0; ys < newHeight; ys+=RBLOCK) { + if (head.biBitCount==24) { + //RGB24 optimized pixel access: + for (x = xs; x < min(newWidth, xs+RBLOCK); x++){ //do rotation + info.nProgress = (long)(100*x/newWidth); + x2=newWidth-x-1; + dstPtr = (BYTE*) imgDest.BlindGetPixelPointer(x,ys); + srcPtr = (BYTE*) BlindGetPixelPointer(ys, x2); + for (y = ys; y < min(newHeight, ys+RBLOCK); y++){ + //imgDest.SetPixelColor(x, y, GetPixelColor(y, x2)); + *(dstPtr) = *(srcPtr); + *(dstPtr+1) = *(srcPtr+1); + *(dstPtr+2) = *(srcPtr+2); + srcPtr += 3; + dstPtr += imgDest.info.dwEffWidth; + }//for y + }//for x + } else { + //anything else than 24bpp (and 1bpp): palette + for (x = xs; x < min(newWidth, xs+RBLOCK); x++){ + info.nProgress = (long)(100*x/newWidth); // + x2=newWidth-x-1; + for (y = ys; y < min(newHeight, ys+RBLOCK); y++){ + imgDest.SetPixelIndex(x, y, BlindGetPixelIndex(y, x2)); + }//for y + }//for x + }//if (version selection) +#if CXIMAGE_SUPPORT_ALPHA + if (pAlpha) { + for (x = xs; x < min(newWidth, xs+RBLOCK); x++){ + x2=newWidth-x-1; + for (y = ys; y < min(newHeight, ys+RBLOCK); y++){ + imgDest.AlphaSet(x,y,BlindAlphaGet(y, x2)); + }//for y + }//for x + }//if (alpha channel) +#endif //CXIMAGE_SUPPORT_ALPHA + }//for ys + }//for xs + }//if + + //select the destination + if (iDst) iDst->Transfer(imgDest); + else Transfer(imgDest); + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::RotateRight(CxImage* iDst) +{ + if (!pDib) return false; + + long newWidth = GetHeight(); + long newHeight = GetWidth(); + + CxImage imgDest; + imgDest.CopyInfo(*this); + imgDest.Create(newWidth,newHeight,GetBpp(),GetType()); + imgDest.SetPalette(GetPalette()); + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) imgDest.AlphaCreate(); +#endif + + long x,y,y2; + // Speedy rotate for BW images + if (head.biBitCount == 1) { + + BYTE *sbits, *dbits, *dbitsmax, bitpos, *nrow,*srcdisp; + div_t div_r; + + BYTE *bsrc = GetBits(), *bdest = imgDest.GetBits(); + dbitsmax = bdest + imgDest.head.biSizeImage - 1; + + imgDest.Clear(0); + for (y = 0; y < head.biHeight; y++) { + // Figure out the Column we are going to be copying to + div_r = div((int)y, (int)8); + // set bit pos of src column byte + bitpos = 128 >> div_r.rem; + srcdisp = bsrc + y * info.dwEffWidth; + for (x = 0; x < (long)info.dwEffWidth; x++) { + // Get Source Bits + sbits = srcdisp + x; + // Get destination column + nrow = bdest + (imgDest.head.biHeight-1-(x*8)) * imgDest.info.dwEffWidth + div_r.quot; + for (long z = 0; z < 8; z++) { + // Get Destination Byte + dbits = nrow - z * imgDest.info.dwEffWidth; + if ((dbits < bdest) || (dbits > dbitsmax)) break; + if (*sbits & (128 >> z)) *dbits |= bitpos; + } + } + } + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()){ + for (y = 0; y < newHeight; y++){ + y2=newHeight-y-1; + for (x = 0; x < newWidth; x++){ + imgDest.AlphaSet(x,y,BlindAlphaGet(y2, x)); + } + } + } +#endif //CXIMAGE_SUPPORT_ALPHA + + } else { + //anything else but BW + BYTE *srcPtr, *dstPtr; //source and destionation for 24-bit version + int xs, ys; //x-segment and y-segment + for (xs = 0; xs < newWidth; xs+=RBLOCK) { + for (ys = 0; ys < newHeight; ys+=RBLOCK) { + if (head.biBitCount==24) { + //RGB24 optimized pixel access: + for (y = ys; y < min(newHeight, ys+RBLOCK); y++){ + info.nProgress = (long)(100*y/newHeight); // + y2=newHeight-y-1; + dstPtr = (BYTE*) imgDest.BlindGetPixelPointer(xs,y); + srcPtr = (BYTE*) BlindGetPixelPointer(y2, xs); + for (x = xs; x < min(newWidth, xs+RBLOCK); x++){ + //imgDest.SetPixelColor(x, y, GetPixelColor(y2, x)); + *(dstPtr) = *(srcPtr); + *(dstPtr+1) = *(srcPtr+1); + *(dstPtr+2) = *(srcPtr+2); + dstPtr += 3; + srcPtr += info.dwEffWidth; + }//for x + }//for y + } else { + //anything else than BW & RGB24: palette + for (y = ys; y < min(newHeight, ys+RBLOCK); y++){ + info.nProgress = (long)(100*y/newHeight); // + y2=newHeight-y-1; + for (x = xs; x < min(newWidth, xs+RBLOCK); x++){ + imgDest.SetPixelIndex(x, y, BlindGetPixelIndex(y2, x)); + }//for x + }//for y + }//if +#if CXIMAGE_SUPPORT_ALPHA + if (pAlpha){ + for (y = ys; y < min(newHeight, ys+RBLOCK); y++){ + y2=newHeight-y-1; + for (x = xs; x < min(newWidth, xs+RBLOCK); x++){ + imgDest.AlphaSet(x,y,BlindAlphaGet(y2, x)); + }//for x + }//for y + }//if (has alpha) +#endif //CXIMAGE_SUPPORT_ALPHA + }//for ys + }//for xs + }//if + + //select the destination + if (iDst) iDst->Transfer(imgDest); + else Transfer(imgDest); + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::Negative() +{ + if (!pDib) return false; + + if (head.biBitCount<=8){ + if (IsGrayScale()){ //GRAYSCALE, selection + if (pSelection){ + for(long y=info.rSelectionBox.bottom; y invert transparent color too + info.nBkgndColor.rgbBlue = (BYTE)(255-info.nBkgndColor.rgbBlue); + info.nBkgndColor.rgbGreen = (BYTE)(255-info.nBkgndColor.rgbGreen); + info.nBkgndColor.rgbRed = (BYTE)(255-info.nBkgndColor.rgbRed); + } + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_BASICTRANSFORMATIONS +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_TRANSFORMATION +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::Rotate(float angle, CxImage* iDst) +{ + if (!pDib) return false; + + // Copyright (c) 1996-1998 Ulrich von Zadow + + // Negative the angle, because the y-axis is negative. + double ang = -angle*acos((float)0)/90; + int newWidth, newHeight; + int nWidth = GetWidth(); + int nHeight= GetHeight(); + double cos_angle = cos(ang); + double sin_angle = sin(ang); + + // Calculate the size of the new bitmap + POINT p1={0,0}; + POINT p2={nWidth,0}; + POINT p3={0,nHeight}; + POINT p4={nWidth-1,nHeight}; + POINT newP1,newP2,newP3,newP4, leftTop, rightTop, leftBottom, rightBottom; + + newP1.x = p1.x; + newP1.y = p1.y; + newP2.x = (long)floor(p2.x*cos_angle - p2.y*sin_angle); + newP2.y = (long)floor(p2.x*sin_angle + p2.y*cos_angle); + newP3.x = (long)floor(p3.x*cos_angle - p3.y*sin_angle); + newP3.y = (long)floor(p3.x*sin_angle + p3.y*cos_angle); + newP4.x = (long)floor(p4.x*cos_angle - p4.y*sin_angle); + newP4.y = (long)floor(p4.x*sin_angle + p4.y*cos_angle); + + leftTop.x = min(min(newP1.x,newP2.x),min(newP3.x,newP4.x)); + leftTop.y = min(min(newP1.y,newP2.y),min(newP3.y,newP4.y)); + rightBottom.x = max(max(newP1.x,newP2.x),max(newP3.x,newP4.x)); + rightBottom.y = max(max(newP1.y,newP2.y),max(newP3.y,newP4.y)); + leftBottom.x = leftTop.x; + leftBottom.y = 2+rightBottom.y; + rightTop.x = 2+rightBottom.x; + rightTop.y = leftTop.y; + + newWidth = rightTop.x - leftTop.x; + newHeight= leftBottom.y - leftTop.y; + CxImage imgDest; + imgDest.CopyInfo(*this); + imgDest.Create(newWidth,newHeight,GetBpp(),GetType()); + imgDest.SetPalette(GetPalette()); + +#if CXIMAGE_SUPPORT_ALPHA + if(AlphaIsValid()) //MTA: Fix for rotation problem when the image has an alpha channel + { + imgDest.AlphaCreate(); + imgDest.AlphaClear(); + } +#endif //CXIMAGE_SUPPORT_ALPHA + + int x,y,newX,newY,oldX,oldY; + + if (head.biClrUsed==0){ //RGB + for (y = leftTop.y, newY = 0; y<=leftBottom.y; y++,newY++){ + info.nProgress = (long)(100*newY/newHeight); + if (info.nEscape) break; + for (x = leftTop.x, newX = 0; x<=rightTop.x; x++,newX++){ + oldX = (long)(x*cos_angle + y*sin_angle - 0.5); + oldY = (long)(y*cos_angle - x*sin_angle - 0.5); + imgDest.SetPixelColor(newX,newY,GetPixelColor(oldX,oldY)); +#if CXIMAGE_SUPPORT_ALPHA + imgDest.AlphaSet(newX,newY,AlphaGet(oldX,oldY)); //MTA: copy the alpha value +#endif //CXIMAGE_SUPPORT_ALPHA + } + } + } else { //PALETTE + for (y = leftTop.y, newY = 0; y<=leftBottom.y; y++,newY++){ + info.nProgress = (long)(100*newY/newHeight); + if (info.nEscape) break; + for (x = leftTop.x, newX = 0; x<=rightTop.x; x++,newX++){ + oldX = (long)(x*cos_angle + y*sin_angle - 0.5); + oldY = (long)(y*cos_angle - x*sin_angle - 0.5); + imgDest.SetPixelIndex(newX,newY,GetPixelIndex(oldX,oldY)); +#if CXIMAGE_SUPPORT_ALPHA + imgDest.AlphaSet(newX,newY,AlphaGet(oldX,oldY)); //MTA: copy the alpha value +#endif //CXIMAGE_SUPPORT_ALPHA + } + } + } + //select the destination + if (iDst) iDst->Transfer(imgDest); + else Transfer(imgDest); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Rotates image around it's center. + * Method can use interpolation with paletted images, but does not change pallete, so results vary. + * (If you have only four colours in a palette, there's not much room for interpolation.) + * + * \param angle - angle in degrees (positive values rotate clockwise) + * \param *iDst - destination image (if null, this image is changed) + * \param inMethod - interpolation method used + * (IM_NEAREST_NEIGHBOUR produces aliasing (fast), IM_BILINEAR softens picture a bit (slower) + * IM_SHARPBICUBIC is slower and produces some halos...) + * \param ofMethod - overflow method (how to choose colour of pixels that have no source) + * \param replColor - replacement colour to use (OM_COLOR, OM_BACKGROUND with no background colour...) + * \param optimizeRightAngles - call faster methods for 90, 180, and 270 degree rotations. Faster methods + * are called for angles, where error (in location of corner pixels) is less + * than 0.25 pixels. + * \param bKeepOriginalSize - rotates the image without resizing. + * + * \author ***bd*** 2.2004 + */ +bool CxImage::Rotate2(float angle, + CxImage *iDst, + InterpolationMethod inMethod, + OverflowMethod ofMethod, + RGBQUAD *replColor, + bool const optimizeRightAngles, + bool const bKeepOriginalSize) +{ + if (!pDib) return false; //no dib no go + + double ang = -angle*acos(0.0f)/90.0f; //convert angle to radians and invert (positive angle performs clockwise rotation) + float cos_angle = (float) cos(ang); //these two are needed later (to rotate) + float sin_angle = (float) sin(ang); + + //Calculate the size of the new bitmap (rotate corners of image) + CxPoint2 p[4]; //original corners of the image + p[0]=CxPoint2(-0.5f,-0.5f); + p[1]=CxPoint2(GetWidth()-0.5f,-0.5f); + p[2]=CxPoint2(-0.5f,GetHeight()-0.5f); + p[3]=CxPoint2(GetWidth()-0.5f,GetHeight()-0.5f); + CxPoint2 newp[4]; //rotated positions of corners + //(rotate corners) + if (bKeepOriginalSize){ + for (int i=0; i<4; i++) { + newp[i].x = p[i].x; + newp[i].y = p[i].y; + }//for + } else { + for (int i=0; i<4; i++) { + newp[i].x = (p[i].x*cos_angle - p[i].y*sin_angle); + newp[i].y = (p[i].x*sin_angle + p[i].y*cos_angle); + }//for i + + if (optimizeRightAngles) { + //For rotations of 90, -90 or 180 or 0 degrees, call faster routines + if (newp[3].Distance(CxPoint2(GetHeight()-0.5f, 0.5f-GetWidth())) < 0.25) + //rotation right for circa 90 degrees (diagonal pixels less than 0.25 pixel away from 90 degree rotation destination) + return RotateRight(iDst); + if (newp[3].Distance(CxPoint2(0.5f-GetHeight(), -0.5f+GetWidth())) < 0.25) + //rotation left for ~90 degrees + return RotateLeft(iDst); + if (newp[3].Distance(CxPoint2(0.5f-GetWidth(), 0.5f-GetHeight())) < 0.25) + //rotation left for ~180 degrees + return Rotate180(iDst); + if (newp[3].Distance(p[3]) < 0.25) { + //rotation not significant + if (iDst) iDst->Copy(*this); //copy image to iDst, if required + return true; //and we're done + }//if + }//if + }//if + + //(read new dimensions from location of corners) + float minx = (float) min(min(newp[0].x,newp[1].x),min(newp[2].x,newp[3].x)); + float miny = (float) min(min(newp[0].y,newp[1].y),min(newp[2].y,newp[3].y)); + float maxx = (float) max(max(newp[0].x,newp[1].x),max(newp[2].x,newp[3].x)); + float maxy = (float) max(max(newp[0].y,newp[1].y),max(newp[2].y,newp[3].y)); + int newWidth = (int) floor(maxx-minx+0.5f); + int newHeight= (int) floor(maxy-miny+0.5f); + float ssx=((maxx+minx)- ((float) newWidth-1))/2.0f; //start for x + float ssy=((maxy+miny)- ((float) newHeight-1))/2.0f; //start for y + + float newxcenteroffset = 0.5f * newWidth; + float newycenteroffset = 0.5f * newHeight; + if (bKeepOriginalSize){ + ssx -= 0.5f * GetWidth(); + ssy -= 0.5f * GetHeight(); + } + + //create destination image + CxImage imgDest; + imgDest.CopyInfo(*this); + imgDest.Create(newWidth,newHeight,GetBpp(),GetType()); + imgDest.SetPalette(GetPalette()); +#if CXIMAGE_SUPPORT_ALPHA + if(AlphaIsValid()) imgDest.AlphaCreate(); //MTA: Fix for rotation problem when the image has an alpha channel +#endif //CXIMAGE_SUPPORT_ALPHA + + RGBQUAD rgb; //pixel colour + RGBQUAD rc; + if (replColor!=0) + rc=*replColor; + else { + rc.rgbRed=255; rc.rgbGreen=255; rc.rgbBlue=255; rc.rgbReserved=0; + }//if + float x,y; //destination location (float, with proper offset) + float origx, origy; //origin location + int destx, desty; //destination location + + y=ssy; //initialize y + if (!IsIndexed()){ //RGB24 + //optimized RGB24 implementation (direct write to destination): + BYTE *pxptr; +#if CXIMAGE_SUPPORT_ALPHA + BYTE *pxptra=0; +#endif //CXIMAGE_SUPPORT_ALPHA + for (desty=0; destyTransfer(imgDest); + else Transfer(imgDest); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::Rotate180(CxImage* iDst) +{ + if (!pDib) return false; + + long wid = GetWidth(); + long ht = GetHeight(); + + CxImage imgDest; + imgDest.CopyInfo(*this); + imgDest.Create(wid,ht,GetBpp(),GetType()); + imgDest.SetPalette(GetPalette()); + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) imgDest.AlphaCreate(); +#endif //CXIMAGE_SUPPORT_ALPHA + + long x,y,y2; + for (y = 0; y < ht; y++){ + info.nProgress = (long)(100*y/ht); // + y2=ht-y-1; + for (x = 0; x < wid; x++){ + if(head.biClrUsed==0)//RGB + imgDest.SetPixelColor(wid-x-1, y2, GetPixelColor(x, y)); + else //PALETTE + imgDest.SetPixelIndex(wid-x-1, y2, GetPixelIndex(x, y)); + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) imgDest.AlphaSet(wid-x-1, y2,AlphaGet(x, y)); +#endif //CXIMAGE_SUPPORT_ALPHA + + } + } + + //select the destination + if (iDst) iDst->Transfer(imgDest); + else Transfer(imgDest); + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +/** + * Resizes the image. mode can be 0 for slow (bilinear) method , + * 1 for fast (nearest pixel) method, or 2 for accurate (bicubic spline interpolation) method. + * The function is faster with 24 and 1 bpp images, slow for 4 bpp images and slowest for 8 bpp images. + */ +bool CxImage::Resample(long newx, long newy, int mode, CxImage* iDst) +{ + if (newx==0 || newy==0) return false; + + if (head.biWidth==newx && head.biHeight==newy){ + if (iDst) iDst->Copy(*this); + return true; + } + + float xScale, yScale, fX, fY; + xScale = (float)head.biWidth / (float)newx; + yScale = (float)head.biHeight / (float)newy; + + CxImage newImage; + newImage.CopyInfo(*this); + newImage.Create(newx,newy,head.biBitCount,GetType()); + newImage.SetPalette(GetPalette()); + if (!newImage.IsValid()) return false; + + switch (mode) { + case 1: // nearest pixel + { + for(long y=0; y=head.biHeight) yy = head.biHeight-1; + for(int n=-1; n<3; n++) { + r2 = r1 * KernelBSpline(b - (float)n); + xx = i_x+n; + if (xx<0) xx=0; + if (xx>=head.biWidth) xx=head.biWidth-1; + + if (head.biClrUsed){ + rgb = GetPixelColor(xx,yy); + } else { + iDst = info.pImage + yy*info.dwEffWidth + xx*3; + rgb.rgbBlue = *iDst++; + rgb.rgbGreen= *iDst++; + rgb.rgbRed = *iDst; + } + + rr += rgb.rgbRed * r2; + gg += rgb.rgbGreen * r2; + bb += rgb.rgbBlue * r2; + } + } + + if (head.biClrUsed) + newImage.SetPixelColor(x,y,RGB(rr,gg,bb)); + else { + iDst = newImage.info.pImage + y*newImage.info.dwEffWidth + x*3; + *iDst++ = (BYTE)bb; + *iDst++ = (BYTE)gg; + *iDst = (BYTE)rr; + } + + } + } + break; + } + default: // bilinear interpolation + if (!(head.biWidth>newx && head.biHeight>newy && head.biBitCount==24)) { + //© 1999 Steve McMahon (steve@dogma.demon.co.uk) + long ifX, ifY, ifX1, ifY1, xmax, ymax; + float ir1, ir2, ig1, ig2, ib1, ib2, dx, dy; + BYTE r,g,b; + RGBQUAD rgb1, rgb2, rgb3, rgb4; + xmax = head.biWidth-1; + ymax = head.biHeight-1; + for(long y=0; y + const long ACCURACY = 1000; + long i,j; // index for faValue + long x,y; // coordinates in source image + BYTE* pSource; + BYTE* pDest = newImage.info.pImage; + long* naAccu = new long[3 * newx + 3]; + long* naCarry = new long[3 * newx + 3]; + long* naTemp; + long nWeightX,nWeightY; + float fEndX; + long nScale = (long)(ACCURACY * xScale * yScale); + + memset(naAccu, 0, sizeof(long) * 3 * newx); + memset(naCarry, 0, sizeof(long) * 3 * newx); + + int u, v = 0; // coordinates in dest image + float fEndY = yScale - 1.0f; + for (y = 0; y < head.biHeight; y++){ + info.nProgress = (long)(100*y/head.biHeight); // + if (info.nEscape) break; + pSource = info.pImage + y * info.dwEffWidth; + u = i = 0; + fEndX = xScale - 1.0f; + if ((float)y < fEndY) { // complete source row goes into dest row + for (x = 0; x < head.biWidth; x++){ + if ((float)x < fEndX){ // complete source pixel goes into dest pixel + for (j = 0; j < 3; j++) naAccu[i + j] += (*pSource++) * ACCURACY; + } else { // source pixel is splitted for 2 dest pixels + nWeightX = (long)(((float)x - fEndX) * ACCURACY); + for (j = 0; j < 3; j++){ + naAccu[i] += (ACCURACY - nWeightX) * (*pSource); + naAccu[3 + i++] += nWeightX * (*pSource++); + } + fEndX += xScale; + u++; + } + } + } else { // source row is splitted for 2 dest rows + nWeightY = (long)(((float)y - fEndY) * ACCURACY); + for (x = 0; x < head.biWidth; x++){ + if ((float)x < fEndX){ // complete source pixel goes into 2 pixel + for (j = 0; j < 3; j++){ + naAccu[i + j] += ((ACCURACY - nWeightY) * (*pSource)); + naCarry[i + j] += nWeightY * (*pSource++); + } + } else { // source pixel is splitted for 4 dest pixels + nWeightX = (int)(((float)x - fEndX) * ACCURACY); + for (j = 0; j < 3; j++) { + naAccu[i] += ((ACCURACY - nWeightY) * (ACCURACY - nWeightX)) * (*pSource) / ACCURACY; + *pDest++ = (BYTE)(naAccu[i] / nScale); + naCarry[i] += (nWeightY * (ACCURACY - nWeightX) * (*pSource)) / ACCURACY; + naAccu[i + 3] += ((ACCURACY - nWeightY) * nWeightX * (*pSource)) / ACCURACY; + naCarry[i + 3] = (nWeightY * nWeightX * (*pSource)) / ACCURACY; + i++; + pSource++; + } + fEndX += xScale; + u++; + } + } + if (u < newx){ // possibly not completed due to rounding errors + for (j = 0; j < 3; j++) *pDest++ = (BYTE)(naAccu[i++] / nScale); + } + naTemp = naCarry; + naCarry = naAccu; + naAccu = naTemp; + memset(naCarry, 0, sizeof(int) * 3); // need only to set first pixel zero + pDest = newImage.info.pImage + (++v * newImage.info.dwEffWidth); + fEndY += yScale; + } + } + if (v < newy){ // possibly not completed due to rounding errors + for (i = 0; i < 3 * newx; i++) *pDest++ = (BYTE)(naAccu[i] / nScale); + } + delete [] naAccu; + delete [] naCarry; + } + } + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()){ + newImage.AlphaCreate(); + for(long y=0; yTransfer(newImage); + else Transfer(newImage); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * New simpler resample. Adds new interpolation methods and simplifies code (using GetPixelColorInterpolated + * and GetAreaColorInterpolated). It also (unlike old method) interpolates alpha layer. + * + * \param newx, newy - size of resampled image + * \param inMethod - interpolation method to use (see comments at GetPixelColorInterpolated) + * If image size is being reduced, averaging is used instead (or simultaneously with) inMethod. + * \param ofMethod - what to replace outside pixels by (only significant for bordering pixels of enlarged image) + * \param iDst - pointer to destination CxImage or NULL. + * \param disableAveraging - force no averaging when shrinking images (Produces aliasing. + * You probably just want to leave this off...) + * + * \author ***bd*** 2.2004 + */ +bool CxImage::Resample2( + long newx, long newy, + InterpolationMethod const inMethod, + OverflowMethod const ofMethod, + CxImage* const iDst, + bool const disableAveraging) +{ + if (newx<=0 || newy<=0 || !pDib) return false; + + if (head.biWidth==newx && head.biHeight==newy) { + //image already correct size (just copy and return) + if (iDst) iDst->Copy(*this); + return true; + }//if + + //calculate scale of new image (less than 1 for enlarge) + float xScale, yScale; + xScale = (float)head.biWidth / (float)newx; + yScale = (float)head.biHeight / (float)newy; + + //create temporary destination image + CxImage newImage; + newImage.CopyInfo(*this); + newImage.Create(newx,newy,head.biBitCount,GetType()); + newImage.SetPalette(GetPalette()); + if (!newImage.IsValid()) return false; + + //and alpha channel if required +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) newImage.AlphaCreate(); +#endif + + float sX, sY; //source location + long dX,dY; //destination pixel (int value) + if ((xScale<=1 && yScale<=1) || disableAveraging) { + //image is being enlarged (or interpolation on demand) + if (!IsIndexed()) { + //RGB24 image (optimized version with direct writes) + RGBQUAD q; //pixel colour + BYTE *pxptr; //pointer to destination pixel +#if CXIMAGE_SUPPORT_ALPHA + BYTE *pxptra; //and destination alpha data +#endif + for(dY=0; dYTransfer(newImage); + else + Transfer(newImage); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Reduces the number of bits per pixel to nbit (1, 4 or 8). + * ppal points to a valid palette for the final image; if not supplied the function will use a standard palette. + * ppal is not necessary for reduction to 1 bpp. + */ +bool CxImage::DecreaseBpp(DWORD nbit, bool errordiffusion, RGBQUAD* ppal, DWORD clrimportant) +{ + if (!pDib) return false; + if (head.biBitCount < nbit) return false; + if (head.biBitCount == nbit){ + if (clrimportant==0) return true; + if (head.biClrImportant && (head.biClrImportant4) return false; + + CxImage tmp; + tmp.CopyInfo(*this); + tmp.Create(head.biWidth,head.biHeight,4,info.dwType); + tmp.SetPalette(GetPalette(),GetNumColors()); + if (!tmp.IsValid()) return false; + + +#if CXIMAGE_SUPPORT_SELECTION + tmp.SelectionCopy(*this); +#endif //CXIMAGE_SUPPORT_SELECTION + +#if CXIMAGE_SUPPORT_ALPHA + tmp.AlphaCopy(*this); +#endif //CXIMAGE_SUPPORT_ALPHA + + for (long y=0;y8) return false; + + CxImage tmp; + tmp.CopyInfo(*this); + tmp.Create(head.biWidth,head.biHeight,8,info.dwType); + tmp.SetPalette(GetPalette(),GetNumColors()); + if (!tmp.IsValid()) return false; + +#if CXIMAGE_SUPPORT_SELECTION + tmp.SelectionCopy(*this); +#endif //CXIMAGE_SUPPORT_SELECTION + +#if CXIMAGE_SUPPORT_ALPHA + tmp.AlphaCopy(*this); +#endif //CXIMAGE_SUPPORT_ALPHA + + for (long y=0;y24) return false; + + CxImage tmp; + tmp.CopyInfo(*this); + tmp.Create(head.biWidth,head.biHeight,24,info.dwType); + if (!tmp.IsValid()) return false; + + if (info.nBkgndIndex>=0) //translate transparency + tmp.info.nBkgndColor=GetPaletteColor((BYTE)info.nBkgndIndex); + +#if CXIMAGE_SUPPORT_SELECTION + tmp.SelectionCopy(*this); +#endif //CXIMAGE_SUPPORT_SELECTION + +#if CXIMAGE_SUPPORT_ALPHA + tmp.AlphaCopy(*this); + if (AlphaPaletteIsValid() && !AlphaIsValid()) tmp.AlphaCreate(); +#endif //CXIMAGE_SUPPORT_ALPHA + + for (long y=0;y 128) { + tmp.SetPixelIndex(x, y, 1); + error = level - 255; + } else { + tmp.SetPixelIndex(x, y, 0); + error = level; + } + + nlevel = GetPixelIndex(x + 1, y) + (error * 8) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + 1, y, level); + nlevel = GetPixelIndex(x + 2, y) + (error * 4) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + 2, y, level); + int i; + for (i = -2; i < 3; i++) { + switch (i) { + case -2: + coeff = 2; + break; + case -1: + coeff = 4; + break; + case 0: + coeff = 8; + break; + case 1: + coeff = 4; + break; + case 2: + coeff = 2; + break; + } + nlevel = GetPixelIndex(x + i, y + 1) + (error * coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + i, y + 1, level); + } + } + } + break; + } + case 3: + { + //Stucki error diffusion (Thanks to Franco Gerevini) + int TotalCoeffSum = 42; + long error, nlevel, coeff; + BYTE level; + + for (long y = 0; y < head.biHeight; y++) { + info.nProgress = (long)(100 * y / head.biHeight); + if (info.nEscape) + break; + for (long x = 0; x < head.biWidth; x++) { + level = GetPixelIndex(x, y); + if (level > 128) { + tmp.SetPixelIndex(x, y, 1); + error = level - 255; + } else { + tmp.SetPixelIndex(x, y, 0); + error = level; + } + + nlevel = GetPixelIndex(x + 1, y) + (error * 8) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + 1, y, level); + nlevel = GetPixelIndex(x + 2, y) + (error * 4) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + 2, y, level); + int i; + for (i = -2; i < 3; i++) { + switch (i) { + case -2: + coeff = 2; + break; + case -1: + coeff = 4; + break; + case 0: + coeff = 8; + break; + case 1: + coeff = 4; + break; + case 2: + coeff = 2; + break; + } + nlevel = GetPixelIndex(x + i, y + 1) + (error * coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + i, y + 1, level); + } + for (i = -2; i < 3; i++) { + switch (i) { + case -2: + coeff = 1; + break; + case -1: + coeff = 2; + break; + case 0: + coeff = 4; + break; + case 1: + coeff = 2; + break; + case 2: + coeff = 1; + break; + } + nlevel = GetPixelIndex(x + i, y + 2) + (error * coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + i, y + 2, level); + } + } + } + break; + } + case 4: + { + //Jarvis, Judice and Ninke error diffusion (Thanks to Franco Gerevini) + int TotalCoeffSum = 48; + long error, nlevel, coeff; + BYTE level; + + for (long y = 0; y < head.biHeight; y++) { + info.nProgress = (long)(100 * y / head.biHeight); + if (info.nEscape) + break; + for (long x = 0; x < head.biWidth; x++) { + level = GetPixelIndex(x, y); + if (level > 128) { + tmp.SetPixelIndex(x, y, 1); + error = level - 255; + } else { + tmp.SetPixelIndex(x, y, 0); + error = level; + } + + nlevel = GetPixelIndex(x + 1, y) + (error * 7) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + 1, y, level); + nlevel = GetPixelIndex(x + 2, y) + (error * 5) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + 2, y, level); + int i; + for (i = -2; i < 3; i++) { + switch (i) { + case -2: + coeff = 3; + break; + case -1: + coeff = 5; + break; + case 0: + coeff = 7; + break; + case 1: + coeff = 5; + break; + case 2: + coeff = 3; + break; + } + nlevel = GetPixelIndex(x + i, y + 1) + (error * coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + i, y + 1, level); + } + for (i = -2; i < 3; i++) { + switch (i) { + case -2: + coeff = 1; + break; + case -1: + coeff = 3; + break; + case 0: + coeff = 5; + break; + case 1: + coeff = 3; + break; + case 2: + coeff = 1; + break; + } + nlevel = GetPixelIndex(x + i, y + 2) + (error * coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + i, y + 2, level); + } + } + } + break; + } + case 5: + { + //Sierra error diffusion (Thanks to Franco Gerevini) + int TotalCoeffSum = 32; + long error, nlevel, coeff; + BYTE level; + + for (long y = 0; y < head.biHeight; y++) { + info.nProgress = (long)(100 * y / head.biHeight); + if (info.nEscape) + break; + for (long x = 0; x < head.biWidth; x++) { + level = GetPixelIndex(x, y); + if (level > 128) { + tmp.SetPixelIndex(x, y, 1); + error = level - 255; + } else { + tmp.SetPixelIndex(x, y, 0); + error = level; + } + + nlevel = GetPixelIndex(x + 1, y) + (error * 5) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + 1, y, level); + nlevel = GetPixelIndex(x + 2, y) + (error * 3) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + 2, y, level); + int i; + for (i = -2; i < 3; i++) { + switch (i) { + case -2: + coeff = 2; + break; + case -1: + coeff = 4; + break; + case 0: + coeff = 5; + break; + case 1: + coeff = 4; + break; + case 2: + coeff = 2; + break; + } + nlevel = GetPixelIndex(x + i, y + 1) + (error * coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + i, y + 1, level); + } + for (i = -1; i < 2; i++) { + switch (i) { + case -1: + coeff = 2; + break; + case 0: + coeff = 3; + break; + case 1: + coeff = 2; + break; + } + nlevel = GetPixelIndex(x + i, y + 2) + (error * coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(x + i, y + 2, level); + } + } + } + break; + } + case 6: + { + //Stevenson and Arce error diffusion (Thanks to Franco Gerevini) + int TotalCoeffSum = 200; + long error, nlevel; + BYTE level; + + for (long y = 0; y < head.biHeight; y++) { + info.nProgress = (long)(100 * y / head.biHeight); + if (info.nEscape) + break; + for (long x = 0; x < head.biWidth; x++) { + level = GetPixelIndex(x, y); + if (level > 128) { + tmp.SetPixelIndex(x, y, 1); + error = level - 255; + } else { + tmp.SetPixelIndex(x, y, 0); + error = level; + } + + int tmp_index_x = x + 2; + int tmp_index_y = y; + int tmp_coeff = 32; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x - 3; + tmp_index_y = y + 1; + tmp_coeff = 12; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x - 1; + tmp_coeff = 26; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x + 1; + tmp_coeff = 30; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x + 3; + tmp_coeff = 16; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x - 2; + tmp_index_y = y + 2; + tmp_coeff = 12; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x; + tmp_coeff = 26; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x + 2; + tmp_coeff = 12; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x - 3; + tmp_index_y = y + 2; + tmp_coeff = 5; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x - 1; + tmp_coeff = 12; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x + 1; + tmp_coeff = 12; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + + tmp_index_x = x + 3; + tmp_coeff = 5; + nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum; + level = (BYTE)min(255, max(0, (int)nlevel)); + SetPixelIndex(tmp_index_x, tmp_index_y, level); + } + } + break; + } + case 7: + { + // Bayer ordered dither + int order = 4; + //create Bayer matrix + if (order>4) order = 4; + int size = (1 << (2*order)); + BYTE* Bmatrix = (BYTE*) malloc(size * sizeof(BYTE)); + for(int i = 0; i < size; i++) { + int n = order; + int x = i / n; + int y = i % n; + int dither = 0; + while (n-- > 0){ + dither = (((dither<<1)|((x&1) ^ (y&1)))<<1) | (y&1); + x >>= 1; + y >>= 1; + } + Bmatrix[i] = dither; + } + + int scale = max(0,(8-2*order)); + int level; + for (long y=0;y> scale; + if(level > Bmatrix[ (x % order) + order * (y % order) ]){ + tmp.SetPixelIndex(x,y,1); + } else { + tmp.SetPixelIndex(x,y,0); + } + } + } + + free(Bmatrix); + + break; + } + default: + { + // Floyd-Steinberg error diffusion (Thanks to Steve McMahon) + long error,nlevel,coeff; + BYTE level; + + for (long y=0;y 128){ + tmp.SetPixelIndex(x,y,1); + error = level-255; + } else { + tmp.SetPixelIndex(x,y,0); + error = level; + } + + nlevel = GetPixelIndex(x+1,y) + (error * 7)/16; + level = (BYTE)min(255,max(0,(int)nlevel)); + SetPixelIndex(x+1,y,level); + for(int i=-1; i<2; i++){ + switch(i){ + case -1: + coeff=3; break; + case 0: + coeff=5; break; + case 1: + coeff=1; break; + } + nlevel = GetPixelIndex(x+i,y+1) + (error * coeff)/16; + level = (BYTE)min(255,max(0,(int)nlevel)); + SetPixelIndex(x+i,y+1,level); + } + } + } + } + } + + tmp.SetPaletteColor(0,0,0,0); + tmp.SetPaletteColor(1,255,255,255); + Transfer(tmp); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * CropRotatedRectangle + * \param topx,topy : topmost and leftmost point of the rectangle + (topmost, and if there are 2 topmost points, the left one) + * \param width : size of the right hand side of rect, from (topx,topy) roundwalking clockwise + * \param height : size of the left hand side of rect, from (topx,topy) roundwalking clockwise + * \param angle : angle of the right hand side of rect, from (topx,topy) + * \param iDst : pointer to destination image (if 0, this image is modified) + * \author [VATI] + */ +bool CxImage::CropRotatedRectangle( long topx, long topy, long width, long height, float angle, CxImage* iDst) +{ + if (!pDib) return false; + + + long startx,starty,endx,endy; + double cos_angle = cos(angle/*/57.295779513082320877*/); + double sin_angle = sin(angle/*/57.295779513082320877*/); + + // if there is nothing special, call the original Crop(): + if ( fabs(angle)<0.0002 ) + return Crop( topx, topy, topx+width, topy+height, iDst); + + startx = min(topx, topx - (long)(sin_angle*(double)height)); + endx = topx + (long)(cos_angle*(double)width); + endy = topy + (long)(cos_angle*(double)height + sin_angle*(double)width); + // check: corners of the rectangle must be inside + if ( IsInside( startx, topy )==false || + IsInside( endx, endy ) == false ) + return false; + + // first crop to bounding rectangle + CxImage tmp(*this,false/*pSelection!=0*/,true,true); + tmp.Copy(*this, true, false, true); + if (!tmp.IsValid()) return false; + if ( false == tmp.Crop( startx, topy, endx, endy ) ) + return false; + + // the midpoint of the image now became the same as the midpoint of the rectangle + // rotate new image with minus angle amount + if ( false == tmp.Rotate( (float)(-angle*57.295779513082320877) ) ) // Rotate expects angle in degrees + return false; + + // crop rotated image to the original selection rectangle + endx = (tmp.head.biWidth+width)/2; + startx = (tmp.head.biWidth-width)/2; + starty = (tmp.head.biHeight+height)/2; + endy = (tmp.head.biHeight-height)/2; + if ( false == tmp.Crop( startx, starty, endx, endy ) ) + return false; + + if (iDst) iDst->Transfer(tmp); + else Transfer(tmp); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::Crop(const RECT& rect, CxImage* iDst) +{ + return Crop(rect.left, rect.top, rect.right, rect.bottom, iDst); +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::Crop(long left, long top, long right, long bottom, CxImage* iDst) +{ + if (!pDib) return false; + + long startx = max(0L,min(left,head.biWidth)); + long endx = max(0L,min(right,head.biWidth)); + long starty = head.biHeight - max(0L,min(top,head.biHeight)); + long endy = head.biHeight - max(0L,min(bottom,head.biHeight)); + + if (startx==endx || starty==endy) return false; + + if (startx>endx) {long tmp=startx; startx=endx; endx=tmp;} + if (starty>endy) {long tmp=starty; starty=endy; endy=tmp;} + + CxImage tmp(endx-startx,endy-starty,head.biBitCount,info.dwType); + if (!tmp.IsValid()) return false; + tmp.SetPalette(GetPalette(),head.biClrUsed); + tmp.info.nBkgndIndex = info.nBkgndIndex; + tmp.info.nBkgndColor = info.nBkgndColor; + + switch (head.biBitCount) { + case 1: + case 4: + { + for(long y=starty, yd=0; y + for(long x=startx, xd=0; x> 3; + BYTE* pDest = tmp.info.pImage; + BYTE* pSrc = info.pImage + starty * info.dwEffWidth + (startx*head.biBitCount >> 3); + for(long y=starty; y + memcpy(pDest,pSrc,linelen); + pDest+=tmp.info.dwEffWidth; + pSrc+=info.dwEffWidth; + } + } + } + +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()){ // + tmp.AlphaCreate(); + if (!tmp.AlphaIsValid()) return false; + BYTE* pDest = tmp.pAlpha; + BYTE* pSrc = pAlpha + startx + starty*head.biWidth; + for (long y=starty; yTransfer(tmp); + else Transfer(tmp); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * \param xgain, ygain : can be from 0 to 1. + * \param xpivot, ypivot : is the center of the transformation. + * \param bEnableInterpolation : if true, enables bilinear interpolation. + * \return true if everything is ok + */ +bool CxImage::Skew(float xgain, float ygain, long xpivot, long ypivot, bool bEnableInterpolation) +{ + if (!pDib) return false; + float nx,ny; + + CxImage tmp(*this,pSelection!=0,true,true); + if (!tmp.IsValid()) return false; + + long xmin,xmax,ymin,ymax; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + for(long y=ymin; y top) || (x < left) || (x > right)) { + tmp.SetPixelIndex(x,y, pixel); + } else { + tmp.SetPixelIndex(x,y,GetPixelIndex(x-left,y-bottom)); + } + } + } + break; + } + case 8: + case 24: + { + if (head.biBitCount == 8) { + BYTE pixel = tmp.GetNearestIndex( canvascolor); + memset(tmp.info.pImage, pixel, + (tmp.info.dwEffWidth * newHeight)); + } else { + for (long y = 0; y < newHeight; ++y) { + BYTE *pDest = tmp.info.pImage + (y * tmp.info.dwEffWidth); + for (long x = 0; x < newWidth; ++x) { + *pDest++ = canvascolor.rgbBlue; + *pDest++ = canvascolor.rgbGreen; + *pDest++ = canvascolor.rgbRed; + } + } + } + + BYTE* pDest = tmp.info.pImage + (tmp.info.dwEffWidth * bottom) + (left*(head.biBitCount >> 3)); + BYTE* pSrc = info.pImage; + for(long y=bottom; y <= top; y++){ + info.nProgress = (long)(100*y/(1 + top - bottom)); + memcpy(pDest,pSrc,(head.biBitCount >> 3) * (right - left + 1)); + pDest+=tmp.info.dwEffWidth; + pSrc+=info.dwEffWidth; + } + } + } + //select the destination + if (iDst) iDst->Transfer(tmp); + else Transfer(tmp); + + return true; +} +//////////////////////////////////////////////////////////////////////////////// +bool CxImage::Expand(long newx, long newy, RGBQUAD canvascolor, CxImage* iDst) +{ + //thanks to + + if (!pDib) return false; + + if ((newx < head.biWidth) || (newy < head.biHeight)) return false; + + int nAddLeft = (newx - head.biWidth) / 2; + int nAddTop = (newy - head.biHeight) / 2; + + return Expand(nAddLeft, nAddTop, newx - (head.biWidth + nAddLeft), newy - (head.biHeight + nAddTop), canvascolor, iDst); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Resamples the image with the correct aspect ratio, and fills the borders. + * \param newx, newy = thumbnail size. + * \param canvascolor = border color. + * \param iDst = pointer to destination image (if it's 0, this image is modified). + * \return true if everything is ok. + * \author [Colin Urquhart] + */ +bool CxImage::Thumbnail(long newx, long newy, RGBQUAD canvascolor, CxImage* iDst) +{ + if (!pDib) return false; + + if ((newx <= 0) || (newy <= 0)) return false; + + CxImage tmp(*this); + if (!tmp.IsValid()) return false; + + // determine whether we need to shrink the image + if ((head.biWidth > newx) || (head.biHeight > newy)) { + float fScale; + float fAspect = (float) newx / (float) newy; + if (fAspect * head.biHeight > head.biWidth) { + fScale = (float) newy / head.biHeight; + } else { + fScale = (float) newx / head.biWidth; + } + tmp.Resample((long) (fScale * head.biWidth), (long) (fScale * head.biHeight), 0); + } + + // expand the frame + tmp.Expand(newx, newy, canvascolor, iDst); + + //select the destination + if (iDst) iDst->Transfer(tmp); + else Transfer(tmp); + return true; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Perform circle_based transformations. + * \param type - for different transformations + * - 0 for normal (proturberant) FishEye + * - 1 for reverse (concave) FishEye + * - 2 for Swirle + * - 3 for Cilinder mirror + * - 4 for bathroom + * + * \param rmax - effect radius. If 0, the whole image is processed + * \param Koeff - only for swirle + * \author Arkadiy Olovyannikov ark(at)msun(dot)ru + */ +bool CxImage::CircleTransform(int type,long rmax,float Koeff) +{ + if (!pDib) return false; + + long nx,ny; + double angle,radius,rnew; + + CxImage tmp(*this,pSelection!=0,true,true); + if (!tmp.IsValid()) return false; + + long xmin,xmax,ymin,ymax,xmid,ymid; + if (pSelection){ + xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right; + ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top; + } else { + xmin = ymin = 0; + xmax = head.biWidth; ymax=head.biHeight; + } + + xmid = (long) (tmp.GetWidth()/2); + ymid = (long) (tmp.GetHeight()/2); + + if (!rmax) rmax=(long)sqrt((float)((xmid-xmin)*(xmid-xmin)+(ymid-ymin)*(ymid-ymin))); + if (Koeff==0.0f) Koeff=1.0f; + + for(long y=ymin; yhead.biWidth || newy>head.biHeight) { + //let me repeat... this method can't enlarge image + strcpy(info.szLastError,"QIShrink can't enlarge image"); + return false; + } + + if (newx==head.biWidth && newy==head.biHeight) { + //image already correct size (just copy and return) + if (iDst) iDst->Copy(*this); + return true; + }//if + + //create temporary destination image + CxImage newImage; + newImage.CopyInfo(*this); + newImage.Create(newx,newy,head.biBitCount,GetType()); + newImage.SetPalette(GetPalette()); + if (!newImage.IsValid()) return false; + + //and alpha channel if required +#if CXIMAGE_SUPPORT_ALPHA + if (AlphaIsValid()) newImage.AlphaCreate(); +#endif + + const int oldx = head.biWidth; + const int oldy = head.biHeight; + + int accuCellSize = 4; +#if CXIMAGE_SUPPORT_ALPHA + BYTE *alphaPtr; + if (AlphaIsValid()) accuCellSize=5; +#endif + + unsigned int *accu = new unsigned int[newx*accuCellSize]; //array for suming pixels... one pixel for every destination column + unsigned int *accuPtr; //pointer for walking through accu + //each cell consists of blue, red, green component and count of pixels summed in this cell + memset(accu, 0, newx * accuCellSize * sizeof(unsigned int)); //clear accu + + if (!IsIndexed()) { + //RGB24 version with pointers + BYTE *destPtr, *srcPtr, *destPtrS, *srcPtrS; //destination and source pixel, and beginnings of current row + srcPtrS=(BYTE*)BlindGetPixelPointer(0,0); + destPtrS=(BYTE*)newImage.BlindGetPixelPointer(0,0); + int ex=0, ey=0; //ex and ey replace division... + int dy=0; + //(we just add pixels, until by adding newx or newy we get a number greater than old size... then + // it's time to move to next pixel) + + for(int y=0; yoldx) { //when we reach oldx, it's time to move to new slot + accuPtr += accuCellSize; + ex -= oldx; //(substract oldx from ex and resume from there on) + }//if (ex overflow) + }//for x + + if (ey>=oldy) { //now when this happens + ey -= oldy; //it's time to move to new destination row + destPtr = destPtrS; //reset pointers to proper initial values + accuPtr = accu; +#if CXIMAGE_SUPPORT_ALPHA + alphaPtr = newImage.AlphaGetPointer(0, dy++); +#endif + for (int k=0; koldx) { //when we reach oldx, it's time to move to new slot + accuPtr += accuCellSize; + ex -= oldx; //(substract oldx from ex and resume from there on) + }//if (ex overflow) + }//for x + + if (ey>=oldy) { //now when this happens + ey -= oldy; //it's time to move to new destination row + accuPtr = accu; + for (int dx=0; dxTransfer(newImage); + else + Transfer(newImage); + return true; + +} + +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_TRANSFORMATION diff --git a/SlnkDWFImpl/CxImage/CxImage/ximawbmp.cpp b/SlnkDWFImpl/CxImage/CxImage/ximawbmp.cpp new file mode 100644 index 0000000..e7a4ce6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximawbmp.cpp @@ -0,0 +1,85 @@ +/* + * File: ximawbmp.cpp + * Purpose: Platform Independent WBMP Image Class Loader and Writer + * 12/Jul/2002 Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximawbmp.h" + +#if CXIMAGE_SUPPORT_WBMP + +#include "ximaiter.h" + +//////////////////////////////////////////////////////////////////////////////// +bool CxImageWBMP::Decode(CxFile *hFile) +{ + if (hFile == NULL) return false; + + WBMPHEADER wbmpHead; + + try + { + if (hFile->Read(&wbmpHead,sizeof(wbmpHead),1)==0) + throw "Not a WBMP"; + + if (wbmpHead.Type != 0) + throw "Unsupported WBMP type"; + + if (wbmpHead.ImageHeight==0 || wbmpHead.ImageWidth==0) + throw "Corrupted WBMP"; + + Create(wbmpHead.ImageWidth, wbmpHead.ImageHeight, 1, CXIMAGE_FORMAT_WBMP); + if (!IsValid()) throw "WBMP Create failed"; + SetGrayPalette(); + + int linewidth=(wbmpHead.ImageWidth+7)/8; + CImageIterator iter(this); + iter.Upset(); + for (int y=0; y < wbmpHead.ImageHeight; y++){ + hFile->Read(iter.GetRow(),linewidth,1); + iter.PrevRow(); + } + + } catch (char *message) { + strncpy(info.szLastError,message,255); + return FALSE; + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +bool CxImageWBMP::Encode(CxFile * hFile) +{ + if (EncodeSafeCheck(hFile)) return false; + + //check format limits + if ((head.biWidth>255)||(head.biHeight>255)||(head.biBitCount!=1)){ + strcpy(info.szLastError,"Can't save this image as WBMP"); + return false; + } + + WBMPHEADER wbmpHead; + wbmpHead.Type=0; + wbmpHead.FixHeader=0; + wbmpHead.ImageWidth=(BYTE)head.biWidth; + wbmpHead.ImageHeight=(BYTE)head.biHeight; + + // Write the file header + hFile->Write(&wbmpHead,sizeof(wbmpHead),1); + // Write the pixels + int linewidth=(wbmpHead.ImageWidth+7)/8; + CImageIterator iter(this); + iter.Upset(); + for (int y=0; y < wbmpHead.ImageHeight; y++){ + hFile->Write(iter.GetRow(),linewidth,1); + iter.PrevRow(); + } + return true; +} +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_ENCODE +//////////////////////////////////////////////////////////////////////////////// +#endif // CXIMAGE_SUPPORT_WBMP + diff --git a/SlnkDWFImpl/CxImage/CxImage/ximawbmp.h b/SlnkDWFImpl/CxImage/CxImage/ximawbmp.h new file mode 100644 index 0000000..31cc7ca --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximawbmp.h @@ -0,0 +1,44 @@ +/* + * File: ximawbmp.h + * Purpose: WBMP Image Class Loader and Writer + */ +/* ========================================================== + * CxImageWBMP (c) 12/Jul/2002 Davide Pizzolato - www.xdp.it + * For conditions of distribution and use, see copyright notice in ximage.h + * ========================================================== + */ +#if !defined(__ximaWBMP_h) +#define __ximaWBMP_h + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_WBMP + +class CxImageWBMP: public CxImage +{ +#pragma pack(1) +typedef struct tagWbmpHeader +{ + BYTE Type; // 0 + BYTE FixHeader; // 0 + BYTE ImageWidth; // Image Width + BYTE ImageHeight; // Image Height +} WBMPHEADER; +#pragma pack() +public: + CxImageWBMP(): CxImage(CXIMAGE_FORMAT_WBMP) {} + +// bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_WBMP);} +// bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_WBMP);} + bool Decode(CxFile * hFile); + bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE +}; + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximawmf.cpp b/SlnkDWFImpl/CxImage/CxImage/ximawmf.cpp new file mode 100644 index 0000000..1e27af2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximawmf.cpp @@ -0,0 +1,458 @@ +/* +********************************************************************* + * File: ximawmf.cpp + * Purpose: Windows Metafile Class Loader and Writer + * Author: Volker Horch - vhorch@gmx.de + * created: 13-Jun-2002 + * + * Note: If the code below works, i wrote it. + * If it doesn't work, i don't know who wrote it. +********************************************************************* + */ + +/* +********************************************************************* + Note by Author: +********************************************************************* + + Metafile Formats: + ================= + + There are 2 kinds of Windows Metafiles: + - Standard Windows Metafile + - Placeable Windows Metafile + + A StandardWindows Metafile looks like: + - Metafile Header (MEATAHEADER) + - Metafile Records + + A Placeable Metafile looks like: + - Aldus Header (METAFILEHEADER) + - Metafile Header (METAHEADER) + - Metafile Records + + The "Metafile Header" and the "Metafile Records" are the same + for both formats. However, the Standard Metafile does not contain any + information about the original dimensions or x/y ratio of the Metafile. + + I decided, to allow only placeable Metafiles here. If you also want to + enable Standard Metafiles, you will have to guess the dimensions of + the image. + +********************************************************************* + Limitations: see ximawmf.h + you may configure some stuff there +********************************************************************* +*/ + +#include "ximawmf.h" + +#if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS + +///////////////////////////////////////////////////////////////////// +bool CxImageWMF::Decode(CxFile *hFile, long nForceWidth, long nForceHeight) +{ + if (hFile == NULL) return false; + + HENHMETAFILE hMeta; + HDC hDC; + int cx,cy; + + //save the current position of the file + long pos = hFile->Tell(); + + // Read the Metafile and convert to an Enhanced Metafile + METAFILEHEADER mfh; + hMeta = ConvertWmfFiletoEmf(hFile, &mfh); + if (hMeta) { // ok, it's a WMF + +///////////////////////////////////////////////////////////////////// +// We use the original WMF size information, because conversion to +// EMF adjusts the Metafile to Full Screen or does not set rclBounds at all +// ENHMETAHEADER emh; +// UINT uRet; +// uRet = GetEnhMetaFileHeader(hMeta, // handle of enhanced metafile +// sizeof(ENHMETAHEADER), // size of buffer, in bytes +// &emh); // address of buffer to receive data +// if (!uRet){ +// DeleteEnhMetaFile(hMeta); +// return false; +// } +// // calculate size +// cx = emh.rclBounds.right - emh.rclBounds.left; +// cy = emh.rclBounds.bottom - emh.rclBounds.top; +///////////////////////////////////////////////////////////////////// + + // calculate size + // scale the metafile (pixels/inch of metafile => pixels/inch of display) + // mfh.inch already checked to be <> 0 + + hDC = ::GetDC(0); + int cx1 = ::GetDeviceCaps(hDC, LOGPIXELSX); + int cy1 = ::GetDeviceCaps(hDC, LOGPIXELSY); + ::ReleaseDC(0, hDC); + + cx = (mfh.bbox.right - mfh.bbox.left) * cx1 / mfh.inch; + cy = (mfh.bbox.bottom - mfh.bbox.top) * cy1 / mfh.inch; + + } else { // maybe it's an EMF... + + hFile->Seek(pos,SEEK_SET); + + ENHMETAHEADER emh; + hMeta = ConvertEmfFiletoEmf(hFile, &emh); + + if (!hMeta){ + strcpy(info.szLastError,"corrupted WMF"); + return false; // definitively give up + } + // ok, it's an EMF + // calculate size + cx = emh.rclBounds.right - emh.rclBounds.left; + cy = emh.rclBounds.bottom - emh.rclBounds.top; + } + + if (info.nEscape) { // Check if cancelled + DeleteEnhMetaFile(hMeta); + strcpy(info.szLastError,"Cancelled"); + return false; + } + + if (!cx || !cy) { + DeleteEnhMetaFile(hMeta); + strcpy(info.szLastError,"empty WMF"); + return false; + } + + if (nForceWidth) cx=nForceWidth; + if (nForceHeight) cy=nForceHeight; + ShrinkMetafile(cx, cy); // !! Otherwise Bitmap may have bombastic size + + HDC hDC0 = GetDC(0); // DC of screen + HBITMAP hBitmap = CreateCompatibleBitmap(hDC0, cx, cy); // has # colors of display + hDC = CreateCompatibleDC(hDC0); // memory dc compatible with screen + ReleaseDC(0, hDC0); // don't need anymore. get rid of it. + + if (hDC){ + if (hBitmap){ + RECT rc = {0,0,cx,cy}; + int bpp = ::GetDeviceCaps(hDC, BITSPIXEL); + + HBITMAP hBitmapOld = (HBITMAP)SelectObject(hDC, hBitmap); + + // clear out the entire bitmap with windows background + // because the MetaFile may not contain background information + DWORD dwBack = XMF_COLOR_BACK; +#if XMF_SUPPORT_TRANSPARENCY + if (bpp == 24) dwBack = XMF_COLOR_TRANSPARENT; +#endif + DWORD OldColor = SetBkColor(hDC, dwBack); + ExtTextOut(hDC, 0, 0, ETO_OPAQUE, &rc, NULL, 0, NULL); + SetBkColor(hDC, OldColor); + + //retrieves optional palette entries from the specified enhanced metafile + PLOGPALETTE plogPal; + PBYTE pjTmp; + HPALETTE hPal; + int iEntries = GetEnhMetaFilePaletteEntries(hMeta, 0, NULL); + if (iEntries) { + if ((plogPal = (PLOGPALETTE)GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT, + sizeof(DWORD) + sizeof(PALETTEENTRY)*iEntries )) == NULL) { + DeleteObject(hBitmap); + DeleteDC(hDC); + DeleteEnhMetaFile(hMeta); + strcpy(info.szLastError,"Cancelled"); + return false; + } + + plogPal->palVersion = 0x300; + plogPal->palNumEntries = (WORD) iEntries; + pjTmp = (PBYTE) plogPal; + pjTmp += 4; + + GetEnhMetaFilePaletteEntries(hMeta, iEntries, (PPALETTEENTRY)pjTmp); + hPal = CreatePalette(plogPal); + GlobalFree(plogPal); + + SelectPalette(hDC, hPal, FALSE); + RealizePalette(hDC); + } + + // Play the Metafile into Memory DC + BOOL bRet = PlayEnhMetaFile(hDC, // handle to a device context + hMeta, // handle to an enhanced metafile + &rc); // pointer to bounding rectangle + + SelectObject(hDC, hBitmapOld); + DeleteEnhMetaFile(hMeta); // we are done with this one + + if (info.nEscape) { // Check if cancelled + DeleteObject(hBitmap); + DeleteDC(hDC); + strcpy(info.szLastError,"Cancelled"); + return false; + } + + // the Bitmap now has the image. + // Create our DIB and convert the DDB into DIB + if (!Create(cx, cy, bpp, CXIMAGE_FORMAT_WMF)) { + DeleteObject(hBitmap); + DeleteDC(hDC); + return false; + } + +#if XMF_SUPPORT_TRANSPARENCY + if (bpp == 24) { + RGBQUAD rgbTrans = { XMF_RGBQUAD_TRANSPARENT }; + SetTransColor(rgbTrans); + } +#endif + // We're finally ready to get the DIB. Call the driver and let + // it party on our bitmap. It will fill in the color table, + // and bitmap bits of our global memory block. + bRet = GetDIBits(hDC, hBitmap, 0, + (UINT)cy, GetBits(), (LPBITMAPINFO)pDib, DIB_RGB_COLORS); + + DeleteObject(hBitmap); + DeleteDC(hDC); + + return (bRet!=0); + } else { + DeleteDC(hDC); + } + } else { + if (hBitmap) DeleteObject(hBitmap); + } + + DeleteEnhMetaFile(hMeta); + + return false; +} + +/********************************************************************** + Function: CheckMetafileHeader + Purpose: Check if the Metafileheader of a file is valid +**********************************************************************/ +BOOL CxImageWMF::CheckMetafileHeader(METAFILEHEADER *metafileheader) +{ + WORD *pw; + WORD cs; + int i; + + // check magic # + if (metafileheader->key != 0x9ac6cdd7L) return false; + + // test checksum of header + pw = (WORD *)metafileheader; + cs = *pw; + pw++; + for (i = 0; i < 9; i++) { + cs ^= *pw; + pw++; + } + + if (cs != metafileheader->checksum) return false; + + // check resolution + if ((metafileheader->inch <= 0) || (metafileheader->inch > 2540)) return false; + + return true; +} + +/********************************************************************** + Function: ConvertWmfFiletoEmf + Purpose: Converts a Windows Metafile into an Enhanced Metafile +**********************************************************************/ +HENHMETAFILE CxImageWMF::ConvertWmfFiletoEmf(CxFile *fp, METAFILEHEADER *metafileheader) +{ + HENHMETAFILE hMeta; + long lenFile; + long len; + BYTE *p; + METAHEADER mfHeader; + DWORD seekpos; + + hMeta = 0; + + // get length of the file + lenFile = fp->Size(); + + // a placeable metafile starts with a METAFILEHEADER + // read it and check metafileheader + len = fp->Read(metafileheader, 1, sizeof(METAFILEHEADER)); + if (len < sizeof(METAFILEHEADER)) return (hMeta); + + if (CheckMetafileHeader(metafileheader)) { + // This is a placeable metafile + // Convert the placeable format into something that can + // be used with GDI metafile functions + seekpos = sizeof(METAFILEHEADER); + } else { + // Not a placeable wmf. A windows metafile? + // at least not scaleable. + // we could try to convert, but would loose ratio. don't allow this + return (hMeta); + + //metafileheader->bbox.right = ?; + //metafileheader->bbox.left = ?; + //metafileheader->bbox.bottom = ?; + //metafileheader->bbox.top = ?; + //metafileheader->inch = ?; + // + //seekpos = 0; + // fp->Seek(0, SEEK_SET); // rewind + } + + // At this point we have a metaheader regardless of whether + // the metafile was a windows metafile or a placeable metafile + // so check to see if it is valid. There is really no good + // way to do this so just make sure that the mtType is either + // 1 or 2 (memory or disk file) + // in addition we compare the length of the METAHEADER against + // the length of the file. if filelength < len => no Metafile + + len = fp->Read(&mfHeader, 1, sizeof(METAHEADER)); + if (len < sizeof(METAHEADER)) return (hMeta); + + if ((mfHeader.mtType != 1) && (mfHeader.mtType != 2)) return (hMeta); + + // Length in Bytes from METAHEADER + len = mfHeader.mtSize * 2; + if (len > lenFile) return (hMeta); + + // Allocate memory for the metafile bits + p = (BYTE *)malloc(len); + if (!p) return (hMeta); + + // seek back to METAHEADER and read all the stuff at once + fp->Seek(seekpos, SEEK_SET); + lenFile = fp->Read(p, 1, len); + if (lenFile != len) { + free(p); + return (hMeta); + } + + // the following (commented code) works, but adjusts rclBound of the + // Enhanced Metafile to full screen. + // the METAFILEHEADER from above is needed to scale the image + +// hMeta = SetWinMetaFileBits(len, p, NULL, NULL); + + // scale the metafile (pixels/inch of metafile => pixels/inch of display) + + METAFILEPICT mfp; + int cx1, cy1; + HDC hDC; + + hDC = ::GetDC(0); + cx1 = ::GetDeviceCaps(hDC, LOGPIXELSX); + cy1 = ::GetDeviceCaps(hDC, LOGPIXELSY); + + memset(&mfp, 0, sizeof(mfp)); + + mfp.mm = MM_ANISOTROPIC; + mfp.xExt = (metafileheader->bbox.right - metafileheader->bbox.left) * cx1 / metafileheader->inch; + mfp.yExt = (metafileheader->bbox.bottom - metafileheader->bbox.top) * cy1 / metafileheader->inch; + mfp.hMF = 0; + + // in MM_ANISOTROPIC mode xExt and yExt are in MM_HIENGLISH + // MM_HIENGLISH means: Each logical unit is converted to 0.001 inch + //mfp.xExt *= 1000; + //mfp.yExt *= 1000; + // ???? + //int k = 332800 / ::GetSystemMetrics(SM_CXSCREEN); + //mfp.xExt *= k; mfp.yExt *= k; + + // fix for Win9x + while ((mfp.xExt < 6554) && (mfp.yExt < 6554)) + { + mfp.xExt *= 10; + mfp.yExt *= 10; + } + + hMeta = SetWinMetaFileBits(len, p, hDC, &mfp); + + if (!hMeta){ //try 2nd conversion using a different mapping + mfp.mm = MM_TEXT; + hMeta = SetWinMetaFileBits(len, p, hDC, &mfp); + } + + ::ReleaseDC(0, hDC); + + // Free Memory + free(p); + + return (hMeta); +} +///////////////////////////////////////////////////////////////////// +HENHMETAFILE CxImageWMF::ConvertEmfFiletoEmf(CxFile *pFile, ENHMETAHEADER *pemfh) +{ + HENHMETAFILE hMeta; + long iLen = pFile->Size(); + + BYTE* pBuff = (BYTE *)malloc(iLen); + if (!pBuff) return (FALSE); + + // Read the Enhanced Metafile + long iLenRead = pFile->Read(pBuff, 1, iLen); + if (iLenRead != iLen) { + free(pBuff); + return (FALSE); + } + + // Make it a Memory Metafile + hMeta = SetEnhMetaFileBits(iLen, pBuff); + + free(pBuff); // finished with this one + + if (!hMeta) return (FALSE); // oops. + + // Get the Enhanced Metafile Header + UINT uRet = GetEnhMetaFileHeader(hMeta, // handle of enhanced metafile + sizeof(ENHMETAHEADER), // size of buffer, in bytes + pemfh); // address of buffer to receive data + + if (!uRet) { + DeleteEnhMetaFile(hMeta); + return (FALSE); + } + + return (hMeta); +} + + +///////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_ENCODE +///////////////////////////////////////////////////////////////////// +bool CxImageWMF::Encode(CxFile * hFile) +{ + if (hFile == NULL) return false; + strcpy(info.szLastError, "Save WMF not supported"); + return false; +} +#endif // CXIMAGE_SUPPORT_ENCODE +///////////////////////////////////////////////////////////////////// + +/********************************************************************** +Function: ShrinkMetafile +Purpose: Shrink the size of a metafile to be not larger than + the definition +**********************************************************************/ +void CxImageWMF::ShrinkMetafile(int &cx, int &cy) +{ + int xScreen = XMF_MAXSIZE_CX; + int yScreen = XMF_MAXSIZE_CY; + + if (cx > xScreen){ + cy = cy * xScreen / cx; + cx = xScreen; + } + + if (cy > yScreen){ + cx = cx * yScreen / cy; + cy = yScreen; + } +} + +#endif // CIMAGE_SUPPORT_WMF + diff --git a/SlnkDWFImpl/CxImage/CxImage/ximawmf.h b/SlnkDWFImpl/CxImage/CxImage/ximawmf.h new file mode 100644 index 0000000..fb59452 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximawmf.h @@ -0,0 +1,154 @@ +/* +********************************************************************* + * File: ximawmf.h + * Purpose: Windows Metafile Class Loader and Writer + * Author: Volker Horch - vhorch@gmx.de + * created: 13-Jun-2002 +********************************************************************* + */ + +/* +********************************************************************* + Notes by Author: +********************************************************************* + + Limitations: + ============ + + a) Transparency: + + A Metafile is vector graphics, which has transparency by design. + This class always converts into a Bitmap format. Transparency is + supported, but there is no good way to find out, which parts + of the Metafile are transparent. There are two ways how we can + handle this: + + - Clear the Background of the Bitmap with the background color + you like (i have used COLOR_WINDOW) and don't support transparency. + + below #define XMF_SUPPORT_TRANSPARENCY 0 + #define XMF_COLOR_BACK RGB(Background color you like) + + - Clear the Background of the Bitmap with a very unusual color + (which one ?) and use this color as the transparent color + + below #define XMF_SUPPORT_TRANSPARENCY 1 + #define XMF_COLOR_TRANSPARENT_R ... + #define XMF_COLOR_TRANSPARENT_G ... + #define XMF_COLOR_TRANSPARENT_B ... + + b) Resolution + + Once we have converted the Metafile into a Bitmap and we zoom in + or out, the image may not look very good. If we still had the + original Metafile, zooming would produce good results always. + + c) Size + + Although the filesize of a Metafile may be very small, it might + produce a Bitmap with a bombastic size. Assume you have a Metafile + with an image size of 6000*4000, which contains just one Metafile + record ((e.g. a line from (0,0) to (6000, 4000)). The filesize + of this Metafile would be let's say 100kB. If we convert it to + a 6000*4000 Bitmap with 24 Bits/Pixes, the Bitmap would consume + about 68MB of memory. + + I have choosen, to limit the size of the Bitmap to max. + screensize, to avoid memory problems. + + If you want something else, + modify #define XMF_MAXSIZE_CX / XMF_MAXSIZE_CY below + +********************************************************************* +*/ + +#ifndef _XIMAWMF_H +#define _XIMAWMF_H + +#include "ximage.h" + +#if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS + +class CxImageWMF: public CxImage +{ + +#pragma pack(1) + +typedef struct tagRECT16 +{ + short int left; + short int top; + short int right; + short int bottom; +} RECT16; + +// taken from Windos 3.11 SDK Documentation (Programmer's Reference Volume 4: Resources) +typedef struct tagMETAFILEHEADER +{ + DWORD key; // always 0x9ac6cdd7 + WORD reserved1; // reserved = 0 + RECT16 bbox; // bounding rectangle in metafile units as defined in "inch" + WORD inch; // number of metafile units per inch (should be < 1440) + DWORD reserved2; // reserved = 0 + WORD checksum; // sum of the first 10 WORDS (using XOR operator) +} METAFILEHEADER; + +#pragma pack() + +public: + CxImageWMF(): CxImage(CXIMAGE_FORMAT_WMF) { } + + bool Decode(CxFile * hFile, long nForceWidth=0, long nForceHeight=0); + bool Decode(FILE *hFile, long nForceWidth=0, long nForceHeight=0) + { CxIOFile file(hFile); return Decode(&file,nForceWidth,nForceHeight); } + +#if CXIMAGE_SUPPORT_ENCODE + bool Encode(CxFile * hFile); + bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } +#endif // CXIMAGE_SUPPORT_ENCODE + +protected: + void ShrinkMetafile(int &cx, int &cy); + BOOL CheckMetafileHeader(METAFILEHEADER *pmetafileheader); + HENHMETAFILE ConvertWmfFiletoEmf(CxFile *pFile, METAFILEHEADER *pmetafileheader); + HENHMETAFILE ConvertEmfFiletoEmf(CxFile *pFile, ENHMETAHEADER *pemfh); + +}; + +#define METAFILEKEY 0x9ac6cdd7L + +// Background color definition (if no transparency). see Notes above +#define XMF_COLOR_BACK GetSysColor(COLOR_WINDOW) +// alternatives +//#define XMF_COLOR_BACK RGB(192, 192, 192) // lite gray +//#define XMF_COLOR_BACK RGB( 0, 0, 0) // black +//#define XMF_COLOR_BACK RGB(255, 255, 255) // white + + +// transparency support. see Notes above +#define XMF_SUPPORT_TRANSPARENCY 0 +#define XMF_COLOR_TRANSPARENT_R 211 +#define XMF_COLOR_TRANSPARENT_G 121 +#define XMF_COLOR_TRANSPARENT_B 112 +// don't change +#define XMF_COLOR_TRANSPARENT RGB (XMF_COLOR_TRANSPARENT_R, \ + XMF_COLOR_TRANSPARENT_G, \ + XMF_COLOR_TRANSPARENT_B) +// don't change +#define XMF_RGBQUAD_TRANSPARENT XMF_COLOR_TRANSPARENT_B, \ + XMF_COLOR_TRANSPARENT_G, \ + XMF_COLOR_TRANSPARENT_R, \ + 0 +// max. size. see Notes above +// alternatives +//#define XMF_MAXSIZE_CX (GetSystemMetrics(SM_CXSCREEN)-10) +//#define XMF_MAXSIZE_CY (GetSystemMetrics(SM_CYSCREEN)-50) +//#define XMF_MAXSIZE_CX (2*GetSystemMetrics(SM_CXSCREEN)/3) +//#define XMF_MAXSIZE_CY (2*GetSystemMetrics(SM_CYSCREEN)/3) +#define XMF_MAXSIZE_CX 4000 +#define XMF_MAXSIZE_CY 4000 + + +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/ximawnd.cpp b/SlnkDWFImpl/CxImage/CxImage/ximawnd.cpp new file mode 100644 index 0000000..9dfd0d3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/ximawnd.cpp @@ -0,0 +1,1110 @@ +// xImaWnd.cpp : Windows functions +/* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it + * CxImage version 5.99c 17/Oct/2004 + */ + +#include "ximage.h" + +#include "ximaiter.h" +#include "ximabmp.h" + +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_WINCE +//////////////////////////////////////////////////////////////////////////////// +long CxImage::Blt(HDC pDC, long x, long y) +{ + if((pDib==0)||(pDC==0)||(!info.bEnabled)) return 0; + + HBRUSH brImage = CreateDIBPatternBrushPt(pDib, DIB_RGB_COLORS); + HBRUSH brOld = (HBRUSH) SelectObject(pDC, brImage); + PatBlt(pDC, 0, 0, head.biWidth, head.biHeight, PATCOPY); + SelectObject(pDC, brOld); + DeleteObject(brImage); + return 1; +} +#endif //CXIMAGE_SUPPORT_WINCE +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_SUPPORT_WINDOWS +//////////////////////////////////////////////////////////////////////////////// +/** + * Transfer the image in a global bitmap handle (clipboard copy) + */ +HANDLE CxImage::CopyToHandle() +{ + HANDLE hMem=NULL; + if (pDib){ + hMem= GlobalAlloc(GHND, GetSize()); + if (hMem){ + BYTE* pDst=(BYTE*)GlobalLock(hMem); + if (pDst){ + memcpy(pDst,pDib,GetSize()); + } + GlobalUnlock(hMem); + } + } + return hMem; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Global object (clipboard paste) constructor + * \param hMem: source bitmap object, the clipboard format must be CF_DIB + * \return true if everything is ok + */ +bool CxImage::CreateFromHANDLE(HANDLE hMem) +{ + if (!Destroy()) + return false; + + DWORD dwSize = GlobalSize(hMem); + if (!dwSize) return false; + + BYTE *lpVoid; //pointer to the bitmap + lpVoid = (BYTE *)GlobalLock(hMem); + BITMAPINFOHEADER *pHead; //pointer to the bitmap header + pHead = (BITMAPINFOHEADER *)lpVoid; + if (lpVoid){ + + //CxMemFile hFile(lpVoid,dwSize); + + //copy the bitmap header + memcpy(&head,pHead,sizeof(BITMAPINFOHEADER)); + //create the image + if(!Create(head.biWidth,head.biHeight,head.biBitCount)){ + GlobalUnlock(lpVoid); + return false; + } + //preserve DPI + if (head.biXPelsPerMeter) SetXDPI((long)floor(head.biXPelsPerMeter * 254.0 / 10000.0 + 0.5)); else SetXDPI(96); + if (head.biYPelsPerMeter) SetYDPI((long)floor(head.biYPelsPerMeter * 254.0 / 10000.0 + 0.5)); else SetYDPI(96); + + /*//copy the pixels (old way) + if((pHead->biCompression != BI_RGB) || (pHead->biBitCount == 32)){ // + // BITFIELD case + // set the internal header in the dib + memcpy(pDib,&head,sizeof(head)); + // get the bitfield masks + DWORD bf[3]; + memcpy(bf,lpVoid+pHead->biSize,12); + // transform into RGB + Bitfield2RGB(lpVoid+pHead->biSize+12,(WORD)bf[0],(WORD)bf[1],(WORD)bf[2],(BYTE)pHead->biBitCount); + } else { //normal bitmap + memcpy(pDib,lpVoid,GetSize()); + }*/ + + // + // fill in color map + bool bIsOldBmp = (head.biSize == sizeof(BITMAPCOREHEADER)); + RGBQUAD *pRgb = GetPalette(); + if (pRgb) { + // number of colors to fill in + int nColors = DibNumColors(pHead); + if (bIsOldBmp) { + /* get pointer to BITMAPCOREINFO (old style 1.x) */ + LPBITMAPCOREINFO lpbmc = (LPBITMAPCOREINFO)lpVoid; + for (int i = nColors - 1; i >= 0; i--) { + pRgb[i].rgbRed = lpbmc->bmciColors[i].rgbtRed; + pRgb[i].rgbGreen = lpbmc->bmciColors[i].rgbtGreen; + pRgb[i].rgbBlue = lpbmc->bmciColors[i].rgbtBlue; + pRgb[i].rgbReserved = (BYTE)0; + } + } else { + /* get pointer to BITMAPINFO (new style 3.x) */ + LPBITMAPINFO lpbmi = (LPBITMAPINFO)lpVoid; + for (int i = nColors - 1; i >= 0; i--) { + pRgb[i].rgbRed = lpbmi->bmiColors[i].rgbRed; + pRgb[i].rgbGreen = lpbmi->bmiColors[i].rgbGreen; + pRgb[i].rgbBlue = lpbmi->bmiColors[i].rgbBlue; + pRgb[i].rgbReserved = (BYTE)0; + } + } + } + + // + DWORD dwCompression = pHead->biCompression; + // compressed bitmap ? + if(dwCompression!=BI_RGB || pHead->biBitCount==32) { + // get the bitmap bits + LPSTR lpDIBBits = (LPSTR)((BYTE*)pHead + *(DWORD*)pHead + (WORD)(GetNumColors() * sizeof(RGBQUAD))); + // decode and copy them to our image + switch (pHead->biBitCount) { + case 32 : + { + // BITFIELD case + if (dwCompression == BI_BITFIELDS || dwCompression == BI_RGB) { + // get the bitfield masks + DWORD bf[3]; + memcpy(bf,lpVoid+pHead->biSize,12); + // transform into RGB + Bitfield2RGB(lpVoid+pHead->biSize+12,(WORD)bf[0],(WORD)bf[1],(WORD)bf[2],(BYTE)pHead->biBitCount); + } else + throw "unknown compression"; + } + break; + case 16 : + { + // get the bitfield masks + long offset=0; + DWORD bf[3]; + if (dwCompression == BI_BITFIELDS) { + memcpy(bf,lpVoid+pHead->biSize,12); + offset= 12; + } else { + bf[0] = 0x7C00; + bf[1] = 0x3E0; + bf[2] = 0x1F; // RGB555 + } + // copy the pixels + memcpy(info.pImage, lpDIBBits + offset, head.biHeight*((head.biWidth+1)/2)*4); + // transform into RGB + Bitfield2RGB(info.pImage, (WORD)bf[0], (WORD)bf[1], (WORD)bf[2], 16); + } + break; + case 8 : + case 4 : + case 1 : + { + switch (dwCompression) { + case BI_RLE4: + { + BYTE status_byte = 0; + BYTE second_byte = 0; + int scanline = 0; + int bits = 0; + BOOL low_nibble = FALSE; + CImageIterator iter(this); + + for (BOOL bContinue = TRUE; bContinue; ) { + status_byte = *(lpDIBBits++); + switch (status_byte) { + case RLE_COMMAND : + status_byte = *(lpDIBBits++); + switch (status_byte) { + case RLE_ENDOFLINE : + bits = 0; + scanline++; + low_nibble = FALSE; + break; + case RLE_ENDOFBITMAP : + bContinue = FALSE; + break; + case RLE_DELTA : + { + // read the delta values + BYTE delta_x; + BYTE delta_y; + delta_x = *(lpDIBBits++); + delta_y = *(lpDIBBits++); + // apply them + bits += delta_x / 2; + scanline += delta_y; + break; + } + default : + second_byte = *(lpDIBBits++); + BYTE* sline = iter.GetRow(scanline); + for (int i = 0; i < status_byte; i++) { + if (low_nibble) { + if ((DWORD)(sline + bits) < (DWORD)(info.pImage + head.biSizeImage)) { + *(sline + bits) |= second_byte & 0x0F; + } + if (i != status_byte - 1) + second_byte = *(lpDIBBits++); + bits++; + } else { + if ((DWORD)(sline + bits) <(DWORD)(info.pImage + head.biSizeImage)) { + *(sline + bits) = (BYTE)(second_byte & 0xF0); + } + } + low_nibble = !low_nibble; + } + if ((((status_byte+1) >> 1) & 1 )== 1) + second_byte = *(lpDIBBits++); + break; + }; + break; + default : + { + BYTE* sline = iter.GetRow(scanline); + second_byte = *(lpDIBBits++); + for (unsigned i = 0; i < status_byte; i++) { + if (low_nibble) { + if ((DWORD)(sline + bits) <(DWORD)(info.pImage + head.biSizeImage)) { + *(sline + bits) |= second_byte & 0x0F; + } + bits++; + } else { + if ((DWORD)(sline + bits) <(DWORD)(info.pImage + head.biSizeImage)) { + *(sline + bits) = (BYTE)(second_byte & 0xF0); + } + } + low_nibble = !low_nibble; + } + } + break; + }; + } + } + break; + case BI_RLE8 : + { + BYTE status_byte = 0; + BYTE second_byte = 0; + int scanline = 0; + int bits = 0; + CImageIterator iter(this); + + for (BOOL bContinue = TRUE; bContinue; ) { + status_byte = *(lpDIBBits++); + if (status_byte==RLE_COMMAND) { + status_byte = *(lpDIBBits++); + switch (status_byte) { + case RLE_ENDOFLINE : + bits = 0; + scanline++; + break; + case RLE_ENDOFBITMAP : + bContinue = FALSE; + break; + case RLE_DELTA : + { + // read the delta values + BYTE delta_x; + BYTE delta_y; + delta_x = *(lpDIBBits++); + delta_y = *(lpDIBBits++); + // apply them + bits += delta_x; + scanline += delta_y; + } + break; + default : + int nNumBytes = sizeof(BYTE) * status_byte; + memcpy((void *)(iter.GetRow(scanline) + bits), lpDIBBits, nNumBytes); + lpDIBBits += nNumBytes; + // align run length to even number of bytes + if ((status_byte & 1) == 1) + second_byte = *(lpDIBBits++); + bits += status_byte; + break; + }; + } else { + BYTE *sline = iter.GetRow(scanline); + second_byte = *(lpDIBBits++); + for (unsigned i = 0; i < status_byte; i++) { + if ((DWORD)bits + // // Create a device-independent bitmap + // return CreateBitmap(head.biWidth,head.biHeight, 1, head.biBitCount, GetBits()); + // use instead this code + HDC hMemDC = CreateCompatibleDC(NULL); + LPVOID pBit32; + HBITMAP bmp = CreateDIBSection(hMemDC,(LPBITMAPINFO)pDib,DIB_RGB_COLORS, &pBit32, NULL, 0); + if (pBit32) memcpy(pBit32, GetBits(), head.biSizeImage); + DeleteDC(hMemDC); + return bmp; + } + + // this single line seems to work very well + HBITMAP bmp = CreateDIBitmap(hdc, (LPBITMAPINFOHEADER)pDib, CBM_INIT, + GetBits(), (LPBITMAPINFO)pDib, DIB_RGB_COLORS); + + return bmp; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Bitmap resource constructor + * \param hbmp : bitmap resource handle + * \param hpal : (optional) palette, useful for 8bpp DC + * \return true if everything is ok + */ +bool CxImage::CreateFromHBITMAP(HBITMAP hbmp, HPALETTE hpal) +{ + if (!Destroy()) + return false; + + if (hbmp) { + BITMAP bm; + // get informations about the bitmap + GetObject(hbmp, sizeof(BITMAP), (LPSTR) &bm); + // create the image + if (!Create(bm.bmWidth, bm.bmHeight, bm.bmBitsPixel, 0)) + return false; + // create a device context for the bitmap + HDC dc = ::GetDC(NULL); + if (!dc) + return false; + + if (hpal){ + SelectObject(dc,hpal); //the palette you should get from the user or have a stock one + RealizePalette(dc); + } + + // copy the pixels + if (GetDIBits(dc, hbmp, 0, head.biHeight, info.pImage, + (LPBITMAPINFO)pDib, DIB_RGB_COLORS) == 0){ //replace &head with pDib + strcpy(info.szLastError,"GetDIBits failed"); + ::ReleaseDC(NULL, dc); + return false; + } + ::ReleaseDC(NULL, dc); + return true; + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * icon resource constructor + * \param hico : icon resource handle + * \return true if everything is ok + */ +bool CxImage::CreateFromHICON(HICON hico) +{ + if (!Destroy()) + return false; + + if (hico) { + ICONINFO iinfo; + GetIconInfo(hico,&iinfo); + if (!CreateFromHBITMAP(iinfo.hbmColor)) + return false; +#if CXIMAGE_SUPPORT_ALPHA + CxImage mask; + mask.CreateFromHBITMAP(iinfo.hbmMask); + mask.GrayScale(); + mask.Negative(); + AlphaSet(mask); +#endif + DeleteObject(iinfo.hbmColor); // + DeleteObject(iinfo.hbmMask); // + return true; + } + return false; +} +//////////////////////////////////////////////////////////////////////////////// +long CxImage::Draw(HDC hdc, const RECT& rect, RECT* pClipRect, bool bSmooth) +{ + return Draw(hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, pClipRect,bSmooth); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Draws the image in the specified device context, with support for alpha channel, alpha palette, transparency, opacity. + * \param hdc : destination device context + * \param x,y : (optional) offset + * \param cx,cy : (optional) size. + * - If cx or cy are not specified (or less than 0), the normal width or height will be used + * - If cx or cy are different than width or height, the image will be stretched + * + * \param pClipRect : limit the drawing operations inside a given rectangle in the output device context. + * \param bSmooth : activates a bilinear filter that will enhance the appearence for zommed pictures. + * Quite slow. Needs CXIMAGE_SUPPORT_INTERPOLATION. + * \return true if everything is ok + */ +long CxImage::Draw(HDC hdc, long x, long y, long cx, long cy, RECT* pClipRect, bool bSmooth) +{ + if((pDib==0)||(hdc==0)||(cx==0)||(cy==0)||(!info.bEnabled)) return 0; + + if (cx < 0) cx = head.biWidth; + if (cy < 0) cy = head.biHeight; + bool bTransparent = info.nBkgndIndex != -1; + bool bAlpha = pAlpha != 0; + + RECT mainbox; // (experimental) + if (pClipRect){ + GetClipBox(hdc,&mainbox); + HRGN rgn = CreateRectRgnIndirect(pClipRect); + ExtSelectClipRgn(hdc,rgn,RGN_AND); + DeleteObject(rgn); + } + + //find the smallest area to paint + RECT clipbox,paintbox; + GetClipBox(hdc,&clipbox); + + paintbox.top = min(clipbox.bottom,max(clipbox.top,y)); + paintbox.left = min(clipbox.right,max(clipbox.left,x)); + paintbox.right = max(clipbox.left,min(clipbox.right,x+cx)); + paintbox.bottom = max(clipbox.top,min(clipbox.bottom,y+cy)); + + long destw = paintbox.right - paintbox.left; + long desth = paintbox.bottom - paintbox.top; + + if (!(bTransparent || bAlpha || info.bAlphaPaletteEnabled)){ + if (cx==head.biWidth && cy==head.biHeight){ //NORMAL + SetStretchBltMode(hdc,COLORONCOLOR); + SetDIBitsToDevice(hdc, x, y, cx, cy, 0, 0, 0, cy, + info.pImage,(BITMAPINFO*)pDib,DIB_RGB_COLORS); + } else { //STRETCH + //pixel informations + RGBQUAD c={0,0,0,0}; + //Preparing Bitmap Info + BITMAPINFO bmInfo; + memset(&bmInfo.bmiHeader,0,sizeof(BITMAPINFOHEADER)); + bmInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); + bmInfo.bmiHeader.biWidth=destw; + bmInfo.bmiHeader.biHeight=desth; + bmInfo.bmiHeader.biPlanes=1; + bmInfo.bmiHeader.biBitCount=24; + BYTE *pbase; //points to the final dib + BYTE *pdst; //current pixel from pbase + BYTE *ppix; //current pixel from image + //get the background + HDC TmpDC=CreateCompatibleDC(hdc); + HBITMAP TmpBmp=CreateDIBSection(hdc,&bmInfo,DIB_RGB_COLORS,(void**)&pbase,0,0); + HGDIOBJ TmpObj=SelectObject(TmpDC,TmpBmp); + + if (pbase){ + long xx,yy; + long sx,sy; + float dx,dy; + BYTE *psrc; + + long ew = ((((24 * destw) + 31) / 32) * 4); + long ymax = paintbox.bottom; + long xmin = paintbox.left; + float fx=(float)head.biWidth/(float)cx; + float fy=(float)head.biHeight/(float)cy; + + for(yy=0;yy>8); + + if (head.biClrUsed){ + ci = GetPixelIndex(sx,sy); +#if CXIMAGE_SUPPORT_INTERPOLATION + if (bSmooth){ + c = GetPixelColorInterpolated(dx - 0.5f, dy - 0.5f, CxImage::IM_BILINEAR, CxImage::OM_REPEAT); + } else +#endif //CXIMAGE_SUPPORT_INTERPOLATION + { + c = GetPaletteColor(GetPixelIndex(sx,sy)); + } + if (info.bAlphaPaletteEnabled){ + a = (BYTE)((a*(1+c.rgbReserved))>>8); + } + } else { +#if CXIMAGE_SUPPORT_INTERPOLATION + if (bSmooth){ + c = GetPixelColorInterpolated(dx - 0.5f, dy - 0.5f, CxImage::IM_BILINEAR, CxImage::OM_REPEAT); + } else +#endif //CXIMAGE_SUPPORT_INTERPOLATION + { + ppix = psrc + sx*3; + c.rgbBlue = *ppix++; + c.rgbGreen= *ppix++; + c.rgbRed = *ppix; + } + } + //if (*pc!=*pct || !bTransparent){ + //if ((head.biClrUsed && ci!=cit) || ((!head.biClrUsed||bSmooth) && *pc!=*pct) || !bTransparent){ + if ((head.biClrUsed && ci!=cit) || (!head.biClrUsed && *pc!=*pct) || !bTransparent){ + // DJT, assume many pixels are fully transparent or opaque and thus avoid multiplication + if (a == 0) { // Transparent, retain dest + pdst+=3; + } else if (a == 255) { // opaque, ignore dest + *pdst++= c.rgbBlue; + *pdst++= c.rgbGreen; + *pdst++= c.rgbRed; + } else { // semi transparent + a1=(BYTE)~a; + *pdst++=(BYTE)((*pdst * a1 + a * c.rgbBlue)>>8); + *pdst++=(BYTE)((*pdst * a1 + a * c.rgbGreen)>>8); + *pdst++=(BYTE)((*pdst * a1 + a * c.rgbRed)>>8); + } + } else { + pdst+=3; + } + } + } + } else { + //NORMAL + iy=head.biHeight-ymax+y; + for(yy=0;yy>8); + + if (head.biClrUsed){ + ci = GetPixelIndex(ix,iy); + c = GetPaletteColor((BYTE)ci); + if (info.bAlphaPaletteEnabled){ + a = (BYTE)((a*(1+c.rgbReserved))>>8); + } + } else { + c.rgbBlue = *ppix++; + c.rgbGreen= *ppix++; + c.rgbRed = *ppix++; + } + + //if (*pc!=*pct || !bTransparent){ + if ((head.biClrUsed && ci!=cit) || (!head.biClrUsed && *pc!=*pct) || !bTransparent){ + // DJT, assume many pixels are fully transparent or opaque and thus avoid multiplication + if (a == 0) { // Transparent, retain dest + pdst+=3; + } else if (a == 255) { // opaque, ignore dest + *pdst++= c.rgbBlue; + *pdst++= c.rgbGreen; + *pdst++= c.rgbRed; + } else { // semi transparent + a1=(BYTE)~a; + *pdst++=(BYTE)((*pdst * a1 + a * c.rgbBlue)>>8); + *pdst++=(BYTE)((*pdst * a1 + a * c.rgbGreen)>>8); + *pdst++=(BYTE)((*pdst * a1 + a * c.rgbRed)>>8); + } + } else { + pdst+=3; + } + } + } + } + } + //paint the image & cleanup + SetDIBitsToDevice(hdc,paintbox.left,paintbox.top,destw,desth,0,0,0,desth,pbase,&bmInfo,0); + DeleteObject(SelectObject(TmpDC,TmpObj)); + DeleteDC(TmpDC); + } + + if (pClipRect){ // (experimental) + HRGN rgn = CreateRectRgnIndirect(&mainbox); + ExtSelectClipRgn(hdc,rgn,RGN_OR); + DeleteObject(rgn); + } + + return 1; +} +//////////////////////////////////////////////////////////////////////////////// +long CxImage::Draw2(HDC hdc, const RECT& rect) +{ + return Draw2(hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Draws (stretch) the image with single transparency support + * \param hdc : destination device context + * \param x,y : (optional) offset + * \param cx,cy : (optional) size. + * - If cx or cy are not specified (or less than 0), the normal width or height will be used + * - If cx or cy are different than width or height, the image will be stretched + * + * \return true if everything is ok + */ +long CxImage::Draw2(HDC hdc, long x, long y, long cx, long cy) +{ + if((pDib==0)||(hdc==0)||(cx==0)||(cy==0)||(!info.bEnabled)) return 0; + if (cx < 0) cx = head.biWidth; + if (cy < 0) cy = head.biHeight; + bool bTransparent = (info.nBkgndIndex != -1); + + if (!bTransparent){ + SetStretchBltMode(hdc,COLORONCOLOR); + StretchDIBits(hdc, x, y, cx, cy, 0, 0, head.biWidth, head.biHeight, + info.pImage,(BITMAPINFO*)pDib, DIB_RGB_COLORS,SRCCOPY); + } else { + // draw image with transparent background + const int safe = 0; // or else GDI fails in the following - sometimes + RECT rcDst = {x+safe, y+safe, x+cx, y+cy}; + if (RectVisible(hdc, &rcDst)){ + ///////////////////////////////////////////////////////////////// + // True Mask Method - Thanks to Paul Reynolds and Ron Gery + int nWidth = head.biWidth; + int nHeight = head.biHeight; + // Create two memory dcs for the image and the mask + HDC dcImage=CreateCompatibleDC(hdc); + HDC dcTrans=CreateCompatibleDC(hdc); + // Select the image into the appropriate dc + HBITMAP bm = CreateCompatibleBitmap(hdc, nWidth, nHeight); + HBITMAP pOldBitmapImage = (HBITMAP)SelectObject(dcImage,bm); + SetStretchBltMode(dcImage,COLORONCOLOR); + StretchDIBits(dcImage, 0, 0, nWidth, nHeight, 0, 0, nWidth, nHeight, + info.pImage,(BITMAPINFO*)pDib,DIB_RGB_COLORS,SRCCOPY); + + // Create the mask bitmap + HBITMAP bitmapTrans = CreateBitmap(nWidth, nHeight, 1, 1, NULL); + // Select the mask bitmap into the appropriate dc + HBITMAP pOldBitmapTrans = (HBITMAP)SelectObject(dcTrans, bitmapTrans); + // Build mask based on transparent colour + RGBQUAD rgbBG; + if (head.biBitCount<24) rgbBG = GetPaletteColor((BYTE)info.nBkgndIndex); + else rgbBG = info.nBkgndColor; + COLORREF crColour = RGB(rgbBG.rgbRed, rgbBG.rgbGreen, rgbBG.rgbBlue); + COLORREF crOldBack = SetBkColor(dcImage,crColour); + BitBlt(dcTrans,0, 0, nWidth, nHeight, dcImage, 0, 0, SRCCOPY); + + // Do the work - True Mask method - cool if not actual display + StretchBlt(hdc,x, y,cx,cy, dcImage, 0, 0, nWidth, nHeight, SRCINVERT); + StretchBlt(hdc,x, y,cx,cy, dcTrans, 0, 0, nWidth, nHeight, SRCAND); + StretchBlt(hdc,x, y,cx,cy, dcImage, 0, 0, nWidth, nHeight, SRCINVERT); + + // Restore settings + SelectObject(dcImage,pOldBitmapImage); + SelectObject(dcTrans,pOldBitmapTrans); + SetBkColor(hdc,crOldBack); + DeleteObject( bitmapTrans ); // RG 29/01/2002 + DeleteDC(dcImage); + DeleteDC(dcTrans); + DeleteObject(bm); + } + } + return 1; +} +//////////////////////////////////////////////////////////////////////////////// +long CxImage::Stretch(HDC hdc, const RECT& rect, DWORD dwRop) +{ + return Stretch(hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, dwRop); +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Stretch the image. Obsolete: use Draw() or Draw2() + * \param hdc : destination device context + * \param xoffset,yoffset : (optional) offset + * \param xsize,ysize : size. + * \param dwRop : raster operation code (see BitBlt documentation) + * \return true if everything is ok + */ +long CxImage::Stretch(HDC hdc, long xoffset, long yoffset, long xsize, long ysize, DWORD dwRop) +{ + if((pDib)&&(hdc)) { + //palette must be correctly filled + SetStretchBltMode(hdc,COLORONCOLOR); + StretchDIBits(hdc, xoffset, yoffset, + xsize, ysize, 0, 0, head.biWidth, head.biHeight, + info.pImage,(BITMAPINFO*)pDib,DIB_RGB_COLORS,dwRop); + return 1; + } + return 0; +} +//////////////////////////////////////////////////////////////////////////////// +/** + * Tiles the device context in the specified rectangle with the image. + * \param hdc : destination device context + * \param rc : tiled rectangle in the output device context + * \return true if everything is ok + */ +long CxImage::Tile(HDC hdc, RECT *rc) +{ + if((pDib)&&(hdc)&&(rc)) { + int w = rc->right - rc->left; + int h = rc->bottom - rc->top; + int x,y,z; + int bx=head.biWidth; + int by=head.biHeight; + for (y = 0 ; y < h ; y += by){ + if ((y+by)>h) by=h-y; + z=bx; + for (x = 0 ; x < w ; x += z){ + if ((x+z)>w) z=w-x; + RECT r = {rc->left + x,rc->top + y,rc->left + x + z,rc->top + y + by}; + Draw(hdc,rc->left + x, rc->top + y,-1,-1,&r); + } + } + return 1; + } + return 0; +} +//////////////////////////////////////////////////////////////////////////////// +// For UNICODE support: char -> TCHAR +long CxImage::DrawString(HDC hdc, long x, long y, const TCHAR* text, RGBQUAD color, const TCHAR* font, long lSize, long lWeight, BYTE bItalic, BYTE bUnderline, bool bSetAlpha) +//long CxImage::DrawString(HDC hdc, long x, long y, const char* text, RGBQUAD color, const char* font, long lSize, long lWeight, BYTE bItalic, BYTE bUnderline, bool bSetAlpha) +{ + if (IsValid()){ + //get the background + HDC TmpDC=CreateCompatibleDC(hdc); + //choose the font + HFONT m_Font; + LOGFONT* m_pLF; + m_pLF=(LOGFONT*)calloc(1,sizeof(LOGFONT)); + _tcsncpy(m_pLF->lfFaceName,font,31); // For UNICODE support + //strncpy(m_pLF->lfFaceName,font,31); + m_pLF->lfHeight=lSize; + m_pLF->lfWeight=lWeight; + m_pLF->lfItalic=bItalic; + m_pLF->lfUnderline=bUnderline; + m_Font=CreateFontIndirect(m_pLF); + //select the font in the dc + HFONT pOldFont=NULL; + if (m_Font) + pOldFont = (HFONT)SelectObject(TmpDC,m_Font); + else + pOldFont = (HFONT)SelectObject(TmpDC,GetStockObject(DEFAULT_GUI_FONT)); + + //Set text color + SetTextColor(TmpDC,RGB(255,255,255)); + SetBkColor(TmpDC,RGB(0,0,0)); + //draw the text + SetBkMode(TmpDC,OPAQUE); + //Set text position; + RECT pos = {0,0,0,0}; + //long len = (long)strlen(text); + long len = (long)_tcslen(text); // For UNICODE support + ::DrawText(TmpDC,text,len,&pos,DT_CALCRECT); + pos.right+=pos.bottom; //for italics + + //Preparing Bitmap Info + long width=pos.right; + long height=pos.bottom; + BITMAPINFO bmInfo; + memset(&bmInfo.bmiHeader,0,sizeof(BITMAPINFOHEADER)); + bmInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); + bmInfo.bmiHeader.biWidth=width; + bmInfo.bmiHeader.biHeight=height; + bmInfo.bmiHeader.biPlanes=1; + bmInfo.bmiHeader.biBitCount=24; + BYTE *pbase; //points to the final dib + + HBITMAP TmpBmp=CreateDIBSection(TmpDC,&bmInfo,DIB_RGB_COLORS,(void**)&pbase,0,0); + HGDIOBJ TmpObj=SelectObject(TmpDC,TmpBmp); + memset(pbase,0,height*((((24 * width) + 31) / 32) * 4)); + + ::DrawText(TmpDC,text,len,&pos,0); + + CxImage itext; + itext.CreateFromHBITMAP(TmpBmp); + + y=head.biHeight-y-1; + for (long ix=0;ix +long CxImage::DrawStringEx(HDC hdc, long x, long y, CXTEXTINFO *pTextType, bool bSetAlpha ) +{ + if (!IsValid()) + return -1; + + //get the background + HDC pDC; + if (hdc) pDC=hdc; else pDC = ::GetDC(0); + HDC TmpDC=CreateCompatibleDC(pDC); + + //choose the font + HFONT m_Font; + m_Font=CreateFontIndirect( &pTextType->lfont ); + + // get colors in RGBQUAD + RGBQUAD p_forecolor = RGBtoRGBQUAD(pTextType->fcolor); + RGBQUAD p_backcolor = RGBtoRGBQUAD(pTextType->bcolor); + + // check alignment and re-set default if necessary + if ( pTextType->align != DT_CENTER && + pTextType->align != DT_LEFT && + pTextType->align != DT_RIGHT ) + pTextType->align = DT_CENTER; + + // check rounding radius and re-set default if necessary + if ( pTextType->b_round > 50 || pTextType->b_round < 0 ) + pTextType->b_round = 10; + + // check opacity and re-set default if necessary + if ( pTextType->b_opacity > 1. || pTextType->b_opacity < .0 ) + pTextType->b_opacity = 0.; + + //select the font in the dc + HFONT pOldFont=NULL; + if (m_Font) + pOldFont = (HFONT)SelectObject(TmpDC,m_Font); + else + pOldFont = (HFONT)SelectObject(TmpDC,GetStockObject(DEFAULT_GUI_FONT)); + + //Set text color + SetTextColor(TmpDC,RGB(255,255,255)); + SetBkColor(TmpDC,RGB(0,0,0)); + SetBkMode(TmpDC,OPAQUE); + //Set text position; + RECT pos = {0,0,0,0}; + + // get text length and number of lines + long i=0, numlines=1, len=(long)_tcsclen(pTextType->text); + while (itext[i++]==13 ) + numlines++; + } + + ::DrawText(TmpDC, pTextType->text, len, &pos, /*DT_EDITCONTROL|DT_EXTERNALLEADING|*/DT_NOPREFIX | DT_CALCRECT ); + + // increase only if it's really italics, and only one line height + if ( pTextType->lfont.lfItalic ) + pos.right += pos.bottom/2/numlines; + + // background frame and rounding radius + int frame = 0, roundR = 0; + if ( pTextType->opaque ) + { + roundR= (int)(pos.bottom/numlines * pTextType->b_round / 100 ) ; + frame = (int)(/*3.5 + */0.29289*roundR ) ; + pos.right += pos.bottom/numlines/3 ; // JUST FOR BEAUTY + } + + //Preparing Bitmap Info + long width=pos.right +frame*2; + long height=pos.bottom +frame*2; + BITMAPINFO bmInfo; + memset(&bmInfo.bmiHeader,0,sizeof(BITMAPINFOHEADER)); + bmInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); + bmInfo.bmiHeader.biWidth=width; + bmInfo.bmiHeader.biHeight=height; + bmInfo.bmiHeader.biPlanes=1; + bmInfo.bmiHeader.biBitCount=24; + BYTE *pbase; //points to the final dib + + HBITMAP TmpBmp=CreateDIBSection(TmpDC,&bmInfo,DIB_RGB_COLORS,(void**)&pbase,0,0); + HGDIOBJ TmpObj=SelectObject(TmpDC,TmpBmp); + memset(pbase,0,height*((((24 * width) + 31) / 32) * 4)); + + ::DrawText(TmpDC,pTextType->text,len, &pos, /*DT_EDITCONTROL|DT_EXTERNALLEADING|*/DT_NOPREFIX| pTextType->align ); + + CxImage itext; + itext.CreateFromHBITMAP(TmpBmp); + y=head.biHeight-y-1; + + //move the insertion point according to alignment type + // DT_CENTER: cursor points to the center of text rectangle + // DT_RIGHT: cursor points to right side end of text rectangle + // DT_LEFT: cursor points to left end of text rectangle + if ( pTextType->align == DT_CENTER ) + x -= width/2; + else if ( pTextType->align == DT_RIGHT ) + x -= width; + if (x<0) x=0; + + //draw the background first, if it exists + long ix,iy; + if ( pTextType->opaque ) + { + int ixf=0; + for (ix=0;ix=width-roundR-1 ) + ixf = (int)(.5+roundR-sqrt((float)(roundR*roundR-(width-1-ix-roundR)*(width-1-ix-roundR)))); + else + ixf=0; + + for (iy=0;iy height-ixf-1 || iy < ixf )) || + (ix>=width-roundR-1 && ( iy > height-ixf-1 || iy < ixf )) ) + continue; + else + if ( pTextType->b_opacity > 0.0 && pTextType->b_opacity < 1.0 ) + { + RGBQUAD bcolor, pcolor; + // calculate a transition color from original image to background color: + pcolor = GetPixelColor(x+ix,y+iy); + bcolor.rgbBlue = (unsigned char)(pTextType->b_opacity * pcolor.rgbBlue + (1.0-pTextType->b_opacity) * p_backcolor.rgbBlue ); + bcolor.rgbRed = (unsigned char)(pTextType->b_opacity * pcolor.rgbRed + (1.0-pTextType->b_opacity) * p_backcolor.rgbRed ) ; + bcolor.rgbGreen = (unsigned char)(pTextType->b_opacity * pcolor.rgbGreen + (1.0-pTextType->b_opacity) * p_backcolor.rgbGreen ) ; + bcolor.rgbReserved = 0; + SetPixelColor(x+ix,y+iy,bcolor,bSetAlpha); + } + else + SetPixelColor(x+ix,y+iy,p_backcolor,bSetAlpha); + } + } + } + + // draw the text itself + for (ix=0;ixlfont.lfHeight = -36; + txt->lfont.lfCharSet = EASTEUROPE_CHARSET; // just for Central-European users + txt->lfont.lfWeight = FW_NORMAL; + txt->lfont.lfWidth = 0; + txt->lfont.lfEscapement = 0; + txt->lfont.lfOrientation = 0; + txt->lfont.lfItalic = FALSE; + txt->lfont.lfUnderline = FALSE; + txt->lfont.lfStrikeOut = FALSE; + txt->lfont.lfOutPrecision = OUT_DEFAULT_PRECIS; + txt->lfont.lfClipPrecision = CLIP_DEFAULT_PRECIS; + txt->lfont.lfQuality = PROOF_QUALITY; + txt->lfont.lfPitchAndFamily= DEFAULT_PITCH | FF_DONTCARE ; + _stprintf( txt->lfont.lfFaceName, _T("Arial")); //use TCHAR mappings + + // initial colors + txt->fcolor = RGB( 255,255,160 ); // default foreground: light goldyellow + txt->bcolor = RGB( 32, 96, 0 ); // default background: deep green + + // background + txt->opaque = TRUE; // text has a non-transparent background; + txt->b_opacity = 0.0; // default: opaque background + txt->b_outline = 0; // default: no outline (OUTLINE NOT IMPLEMENTED AT THIS TIME) + txt->b_round = 20; // default: rounding radius is 20% of the rectangle height + // the text + _stprintf( txt->text, _T("Sample Text 01234õû")); // text use TCHAR mappings + txt->align = DT_CENTER; + return; +} +//////////////////////////////////////////////////////////////////////////////// +#endif //CXIMAGE_SUPPORT_WINDOWS +//////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/CxImage/xiofile.h b/SlnkDWFImpl/CxImage/CxImage/xiofile.h new file mode 100644 index 0000000..582f425 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/xiofile.h @@ -0,0 +1,112 @@ +#if !defined(__xiofile_h) +#define __xiofile_h + +#include "xfile.h" + +class DLL_EXP CxIOFile : public CxFile + { +public: + CxIOFile(FILE* fp = NULL) + { + m_fp = fp; + m_bCloseFile = (bool)(fp==0); + } + + ~CxIOFile() + { + Close(); + } +////////////////////////////////////////////////////////// + bool Open(const char *filename, const char *mode) + { + if (m_fp) return false; // Can't re-open without closing first + + m_fp = fopen(filename, mode); + if (!m_fp) return false; + + m_bCloseFile = true; + + return true; + } +////////////////////////////////////////////////////////// + virtual bool Close() + { + int iErr = 0; + if ( (m_fp) && (m_bCloseFile) ){ + iErr = fclose(m_fp); + m_fp = NULL; + } + return (bool)(iErr==0); + } +////////////////////////////////////////////////////////// + virtual size_t Read(void *buffer, size_t size, size_t count) + { + if (!m_fp) return 0; + return fread(buffer, size, count, m_fp); + } +////////////////////////////////////////////////////////// + virtual size_t Write(const void *buffer, size_t size, size_t count) + { + if (!m_fp) return 0; + return fwrite(buffer, size, count, m_fp); + } +////////////////////////////////////////////////////////// + virtual bool Seek(long offset, int origin) + { + if (!m_fp) return false; + return (bool)(fseek(m_fp, offset, origin) == 0); + } +////////////////////////////////////////////////////////// + virtual long Tell() + { + if (!m_fp) return 0; + return ftell(m_fp); + } +////////////////////////////////////////////////////////// + virtual long Size() + { + if (!m_fp) return -1; + long pos,size; + pos = ftell(m_fp); + fseek(m_fp, 0, SEEK_END); + size = ftell(m_fp); + fseek(m_fp, pos,SEEK_SET); + return size; + } +////////////////////////////////////////////////////////// + virtual bool Flush() + { + if (!m_fp) return false; + return (bool)(fflush(m_fp) == 0); + } +////////////////////////////////////////////////////////// + virtual bool Eof() + { + if (!m_fp) return true; + return (bool)(feof(m_fp) != 0); + } +////////////////////////////////////////////////////////// + virtual long Error() + { + if (!m_fp) return -1; + return ferror(m_fp); + } +////////////////////////////////////////////////////////// + virtual bool PutC(unsigned char c) + { + if (!m_fp) return false; + return (bool)(fputc(c, m_fp) == c); + } +////////////////////////////////////////////////////////// + virtual long GetC() + { + if (!m_fp) return EOF; + return getc(m_fp); + } +////////////////////////////////////////////////////////// +protected: + FILE *m_fp; + bool m_bCloseFile; + }; + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImage/xmemfile.cpp b/SlnkDWFImpl/CxImage/CxImage/xmemfile.cpp new file mode 100644 index 0000000..cf01254 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/xmemfile.cpp @@ -0,0 +1,173 @@ +#include "xmemfile.h" + +////////////////////////////////////////////////////////// +CxMemFile::CxMemFile(BYTE* pBuffer, DWORD size) +{ + m_pBuffer = pBuffer; + m_Position = 0; + m_Size = m_Edge = size; + m_bFreeOnClose = (bool)(pBuffer==0); +} +////////////////////////////////////////////////////////// +CxMemFile::~CxMemFile() +{ + Close(); +} +////////////////////////////////////////////////////////// +bool CxMemFile::Close() +{ + if ( (m_pBuffer) && (m_bFreeOnClose) ){ + free(m_pBuffer); + m_pBuffer = NULL; + m_Size = 0; + } + return true; +} +////////////////////////////////////////////////////////// +bool CxMemFile::Open() +{ + if (m_pBuffer) return false; // Can't re-open without closing first + + m_Position = m_Size = m_Edge = 0; + m_pBuffer=(BYTE*)malloc(1); + m_bFreeOnClose = true; + + return (m_pBuffer!=0); +} +////////////////////////////////////////////////////////// +BYTE* CxMemFile::GetBuffer(bool bDetachBuffer) +{ + m_bFreeOnClose = !bDetachBuffer; + return m_pBuffer; +} +////////////////////////////////////////////////////////// +size_t CxMemFile::Read(void *buffer, size_t size, size_t count) +{ + if (buffer==NULL) return 0; + + if (m_pBuffer==NULL) return 0; + if (m_Position >= (long)m_Size) return 0; + + long nCount = (long)(count*size); + if (nCount == 0) return 0; + + long nRead; + if (m_Position + nCount > (long)m_Size) + nRead = (m_Size - m_Position); + else + nRead = nCount; + + memcpy(buffer, m_pBuffer + m_Position, nRead); + m_Position += nRead; + + return (size_t)(nRead/size); +} +////////////////////////////////////////////////////////// +size_t CxMemFile::Write(const void *buffer, size_t size, size_t count) +{ + if (m_pBuffer==NULL) return 0; + if (buffer==NULL) return 0; + + long nCount = (long)(count*size); + if (nCount == 0) return 0; + + if (m_Position + nCount > m_Edge) Alloc(m_Position + nCount); + + memcpy(m_pBuffer + m_Position, buffer, nCount); + + m_Position += nCount; + + if (m_Position > (long)m_Size) m_Size = m_Position; + + return count; +} +////////////////////////////////////////////////////////// +bool CxMemFile::Seek(long offset, int origin) +{ + if (m_pBuffer==NULL) return false; + long lNewPos = m_Position; + + if (origin == SEEK_SET) lNewPos = offset; + else if (origin == SEEK_CUR) lNewPos += offset; + else if (origin == SEEK_END) lNewPos = m_Size + offset; + else return false; + + if (lNewPos < 0) lNewPos = 0; + + m_Position = lNewPos; + return true; +} +////////////////////////////////////////////////////////// +long CxMemFile::Tell() +{ + if (m_pBuffer==NULL) return -1; + return m_Position; +} +////////////////////////////////////////////////////////// +long CxMemFile::Size() +{ + if (m_pBuffer==NULL) return -1; + return m_Size; +} +////////////////////////////////////////////////////////// +bool CxMemFile::Flush() +{ + if (m_pBuffer==NULL) return false; + return true; +} +////////////////////////////////////////////////////////// +bool CxMemFile::Eof() +{ + if (m_pBuffer==NULL) return true; + return (m_Position >= (long)m_Size); +} +////////////////////////////////////////////////////////// +long CxMemFile::Error() +{ + if (m_pBuffer==NULL) return -1; + return (m_Position > (long)m_Size); +} +////////////////////////////////////////////////////////// +bool CxMemFile::PutC(unsigned char c) +{ + if (m_pBuffer==NULL) return false; + if (m_Position + 1 > m_Edge) Alloc(m_Position + 1); + + memcpy(m_pBuffer + m_Position, &c, 1); + + m_Position += 1; + + if (m_Position > (long)m_Size) m_Size = m_Position; + + return true; +} +////////////////////////////////////////////////////////// +long CxMemFile::GetC() +{ + if (Eof()) return EOF; + return *(BYTE*)((BYTE*)m_pBuffer + m_Position++); +} +////////////////////////////////////////////////////////// +void CxMemFile::Alloc(DWORD dwNewLen) +{ + if (dwNewLen > (DWORD)m_Edge) + { + // find new buffer size + DWORD dwNewBufferSize = (DWORD)(((dwNewLen>>12)+1)<<12); + + // allocate new buffer + if (m_pBuffer == NULL) m_pBuffer = (BYTE*)malloc(dwNewBufferSize); + else m_pBuffer = (BYTE*)realloc(m_pBuffer, dwNewBufferSize); + // I own this buffer now (caller knows nothing about it) + m_bFreeOnClose = true; + + m_Edge = dwNewBufferSize; + } + return; +} +////////////////////////////////////////////////////////// +void CxMemFile::Free() +{ + Close(); +} +////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/CxImage/xmemfile.h b/SlnkDWFImpl/CxImage/CxImage/xmemfile.h new file mode 100644 index 0000000..19a053e --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImage/xmemfile.h @@ -0,0 +1,39 @@ +#if !defined(__xmemfile_h) +#define __xmemfile_h + +#include "xfile.h" + +////////////////////////////////////////////////////////// +class DLL_EXP CxMemFile : public CxFile +{ +public: + CxMemFile(BYTE* pBuffer = NULL, DWORD size = 0); + ~CxMemFile(); + + bool Open(); + BYTE* GetBuffer(bool bDetachBuffer = true); + + virtual bool Close(); + virtual size_t Read(void *buffer, size_t size, size_t count); + virtual size_t Write(const void *buffer, size_t size, size_t count); + virtual bool Seek(long offset, int origin); + virtual long Tell(); + virtual long Size(); + virtual bool Flush(); + virtual bool Eof(); + virtual long Error(); + virtual bool PutC(unsigned char c); + virtual long GetC(); + +protected: + void Alloc(DWORD nBytes); + void Free(); + + BYTE* m_pBuffer; + DWORD m_Size; + bool m_bFreeOnClose; + long m_Position; //current position + long m_Edge; //buffer size +}; + +#endif diff --git a/SlnkDWFImpl/CxImage/CxImgLib.dsw b/SlnkDWFImpl/CxImage/CxImgLib.dsw new file mode 100644 index 0000000..7a5cae0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/CxImgLib.dsw @@ -0,0 +1,239 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "CxImage"=.\cximage\cximage.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "CxImageCrtDll"=.\CxImage\CxImageDLL\CxImageCrtDll.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name j2k + End Project Dependency + Begin Project Dependency + Project_Dep_Name jbig + End Project Dependency + Begin Project Dependency + Project_Dep_Name jpeg + End Project Dependency + Begin Project Dependency + Project_Dep_Name png + End Project Dependency + Begin Project Dependency + Project_Dep_Name tiff + End Project Dependency + Begin Project Dependency + Project_Dep_Name zlib + End Project Dependency + Begin Project Dependency + Project_Dep_Name jasper + End Project Dependency +}}} + +############################################################################### + +Project: "CxImageMfcDll"=.\CxImage\CxImageDLL\cximagemfcdll.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name j2k + End Project Dependency + Begin Project Dependency + Project_Dep_Name jbig + End Project Dependency + Begin Project Dependency + Project_Dep_Name jpeg + End Project Dependency + Begin Project Dependency + Project_Dep_Name png + End Project Dependency + Begin Project Dependency + Project_Dep_Name tiff + End Project Dependency + Begin Project Dependency + Project_Dep_Name zlib + End Project Dependency + Begin Project Dependency + Project_Dep_Name jasper + End Project Dependency +}}} + +############################################################################### + +Project: "demo"=.\demo\demo.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name CxImage + End Project Dependency + Begin Project Dependency + Project_Dep_Name Jpeg + End Project Dependency + Begin Project Dependency + Project_Dep_Name png + End Project Dependency + Begin Project Dependency + Project_Dep_Name Tiff + End Project Dependency + Begin Project Dependency + Project_Dep_Name zlib + End Project Dependency + Begin Project Dependency + Project_Dep_Name mng + End Project Dependency + Begin Project Dependency + Project_Dep_Name j2000 + End Project Dependency + Begin Project Dependency + Project_Dep_Name jbig + End Project Dependency + Begin Project Dependency + Project_Dep_Name cximagedll + End Project Dependency + Begin Project Dependency + Project_Dep_Name j2k + End Project Dependency + Begin Project Dependency + Project_Dep_Name jasper + End Project Dependency +}}} + +############################################################################### + +Project: "demoDll"=.\demo\demoDLL.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name CxImageCrtDll + End Project Dependency +}}} + +############################################################################### + +Project: "j2k"=.\j2k\j2k.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "jasper"=.\jasper\jasper.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "jbig"=.\jbig\jbig.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "jpeg"=.\jpeg\Jpeg.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "png"=.\png\png.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "tiff"=.\tiff\Tiff.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "zlib"=.\zlib\zlib.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/bin/.gitignore b/SlnkDWFImpl/CxImage/bin/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/bin/Beerok.png b/SlnkDWFImpl/CxImage/bin/Beerok.png new file mode 100644 index 0000000..66ca9a8 Binary files /dev/null and b/SlnkDWFImpl/CxImage/bin/Beerok.png differ diff --git a/SlnkDWFImpl/CxImage/bin/Beerok2.png b/SlnkDWFImpl/CxImage/bin/Beerok2.png new file mode 100644 index 0000000..5d9c68a Binary files /dev/null and b/SlnkDWFImpl/CxImage/bin/Beerok2.png differ diff --git a/SlnkDWFImpl/CxImage/bin/consoled.exe b/SlnkDWFImpl/CxImage/bin/consoled.exe new file mode 100644 index 0000000..8c173eb Binary files /dev/null and b/SlnkDWFImpl/CxImage/bin/consoled.exe differ diff --git a/SlnkDWFImpl/CxImage/demo/BCMenu.cpp b/SlnkDWFImpl/CxImage/demo/BCMenu.cpp new file mode 100644 index 0000000..17b45a3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/BCMenu.cpp @@ -0,0 +1,3153 @@ +//************************************************************************* +// BCMenu.cpp : implementation file +// Version : 3.033 +// Date : April 2002 +// Author : Brent Corkum +// Email : corkum@rocscience.com +// Latest Version : http://www.rocscience.com/~corkum/BCMenu.html +// +// Bug Fixes and portions of code supplied by: +// +// Ben Ashley,Girish Bharadwaj,Jean-Edouard Lachand-Robert, +// Robert Edward Caldecott,Kenny Goers,Leonardo Zide, +// Stefan Kuhr,Reiner Jung,Martin Vladic,Kim Yoo Chul, +// Oz Solomonovich,Tongzhe Cui,Stephane Clog,Warren Stevens, +// Damir Valiulin,David Kinder,Marc Loiry +// +// You are free to use/modify this code but leave this header intact. +// This class is public domain so you are free to use it any of +// your applications (Freeware,Shareware,Commercial). All I ask is +// that you let me know so that if you have a real winner I can +// brag to my buddies that some of my code is in your app. I also +// wouldn't mind if you sent me a copy of your application since I +// like to play with new stuff. +//************************************************************************* + +#include "stdafx.h" // Standard windows header file +#include "BCMenu.h" // BCMenu class declaration +#include //SK: makes A2W and other spiffy AFX macros work + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +#define BCMENU_GAP 1 +#ifndef OBM_CHECK +#define OBM_CHECK 32760 // from winuser.h +#endif + +#if _MFC_VER <0x400 +#error This code does not work on Versions of MFC prior to 4.0 +#endif + +static CPINFO CPInfo; +// how the menu's are drawn in win9x/NT/2000 +UINT BCMenu::original_drawmode=BCMENU_DRAWMODE_XP; +BOOL BCMenu::original_select_disabled=TRUE; +// how the menu's are drawn in winXP +UINT BCMenu::xp_drawmode=BCMENU_DRAWMODE_XP; +BOOL BCMenu::xp_select_disabled=FALSE; +BOOL BCMenu::xp_draw_3D_bitmaps=TRUE; +BOOL BCMenu::hicolor_bitmaps=FALSE; +// Variable to set how accelerators are justified. The default mode (TRUE) right +// justifies them to the right of the longes string in the menu. FALSE +// just right justifies them. +BOOL BCMenu::xp_space_accelerators=TRUE; +BOOL BCMenu::original_space_accelerators=TRUE; + +CImageList BCMenu::m_AllImages; +CArray BCMenu::m_AllImagesID; +int BCMenu::m_iconX = 16; +int BCMenu::m_iconY = 15; + +enum Win32Type{ + Win32s, + WinNT3, + Win95, + Win98, + WinME, + WinNT4, + Win2000, + WinXP +}; + + +Win32Type IsShellType() +{ + Win32Type ShellType; + DWORD winVer; + OSVERSIONINFO *osvi; + + winVer=GetVersion(); + if(winVer<0x80000000){/*NT */ + ShellType=WinNT3; + osvi= (OSVERSIONINFO *)malloc(sizeof(OSVERSIONINFO)); + if (osvi!=NULL){ + memset(osvi,0,sizeof(OSVERSIONINFO)); + osvi->dwOSVersionInfoSize=sizeof(OSVERSIONINFO); + GetVersionEx(osvi); + if(osvi->dwMajorVersion==4L)ShellType=WinNT4; + else if(osvi->dwMajorVersion==5L&&osvi->dwMinorVersion==0L)ShellType=Win2000; + else if(osvi->dwMajorVersion==5L&&osvi->dwMinorVersion==1L)ShellType=WinXP; + free(osvi); + } + } + else if (LOBYTE(LOWORD(winVer))<4) + ShellType=Win32s; + else{ + ShellType=Win95; + osvi= (OSVERSIONINFO *)malloc(sizeof(OSVERSIONINFO)); + if (osvi!=NULL){ + memset(osvi,0,sizeof(OSVERSIONINFO)); + osvi->dwOSVersionInfoSize=sizeof(OSVERSIONINFO); + GetVersionEx(osvi); + if(osvi->dwMajorVersion==4L&&osvi->dwMinorVersion==10L)ShellType=Win98; + else if(osvi->dwMajorVersion==4L&&osvi->dwMinorVersion==90L)ShellType=WinME; + free(osvi); + } + } + return ShellType; +} + +static Win32Type g_Shell=IsShellType(); + +void BCMenuData::SetAnsiString(LPCSTR szAnsiString) +{ + USES_CONVERSION; + SetWideString(A2W(szAnsiString)); //SK: see MFC Tech Note 059 +} + +CString BCMenuData::GetString(void)//returns the menu text in ANSI or UNICODE +//depending on the MFC-Version we are using +{ + CString strText; + if (m_szMenuText) + { +#ifdef UNICODE + strText = m_szMenuText; +#else + USES_CONVERSION; + strText=W2A(m_szMenuText); //SK: see MFC Tech Note 059 +#endif + } + return strText; +} + +CTypedPtrArray BCMenu::m_AllSubMenus; // Stores list of all sub-menus + +IMPLEMENT_DYNAMIC( BCMenu, CMenu ) + +/* +=============================================================================== +BCMenu::BCMenu() +BCMenu::~BCMenu() +----------------- + +Constructor and Destructor. + +=============================================================================== +*/ + +BCMenu::BCMenu() +{ + m_bDynIcons = FALSE; // O.S. - no dynamic icons by default + disable_old_style=FALSE; + m_selectcheck = -1; + m_unselectcheck = -1; + checkmaps=NULL; + checkmapsshare=FALSE; + // set the color used for the transparent background in all bitmaps + m_bitmapBackground=RGB(192,192,192); //gray + m_bitmapBackgroundFlag=FALSE; + GetCPInfo(CP_ACP,&CPInfo); + m_loadmenu=FALSE; +} + + +BCMenu::~BCMenu() +{ + DestroyMenu(); +} + +BOOL BCMenu::IsNewShell () +{ + return (g_Shell>=Win95); +} + +BOOL BCMenu::IsWinXPLuna() +{ + if(g_Shell==WinXP){ + if(IsWindowsClassicTheme())return(FALSE); + else return(TRUE); + } + return(FALSE); +} + +BOOL BCMenu::IsLunaMenuStyle() +{ + if(IsWinXPLuna()){ + if(xp_drawmode==BCMENU_DRAWMODE_XP)return(TRUE); + } + else{ + if(original_drawmode==BCMENU_DRAWMODE_XP)return(TRUE); + } + return(FALSE); +} + +BCMenuData::~BCMenuData() +{ + if(bitmap) + delete(bitmap); + + delete[] m_szMenuText; //Need not check for NULL because ANSI X3J16 allows "delete NULL" +} + + +void BCMenuData::SetWideString(const wchar_t *szWideString) +{ + delete[] m_szMenuText;//Need not check for NULL because ANSI X3J16 allows "delete NULL" + + if (szWideString) + { + m_szMenuText = new wchar_t[sizeof(wchar_t)*(wcslen(szWideString)+1)]; + if (m_szMenuText) + wcscpy(m_szMenuText,szWideString); + } + else + m_szMenuText=NULL;//set to NULL so we need not bother about dangling non-NULL Ptrs +} + +BOOL BCMenu::IsMenu(CMenu *submenu) +{ + int m; + int numSubMenus = m_AllSubMenus.GetUpperBound(); + for(m=0;m<=numSubMenus;++m){ + if(submenu->m_hMenu==m_AllSubMenus[m])return(TRUE); + } + return(FALSE); +} + +BOOL BCMenu::IsMenu(HMENU submenu) +{ + int m; + int numSubMenus = m_AllSubMenus.GetUpperBound(); + for(m=0;m<=numSubMenus;++m){ + if(submenu==m_AllSubMenus[m])return(TRUE); + } + return(FALSE); +} + +BOOL BCMenu::DestroyMenu() +{ + // Destroy Sub menus: + int m,n; + int numAllSubMenus = m_AllSubMenus.GetUpperBound(); + for(n = numAllSubMenus; n>= 0; n--){ + if(m_AllSubMenus[n]==this->m_hMenu)m_AllSubMenus.RemoveAt(n); + } + int numSubMenus = m_SubMenus.GetUpperBound(); + for(m = numSubMenus; m >= 0; m--){ + numAllSubMenus = m_AllSubMenus.GetUpperBound(); + for(n = numAllSubMenus; n>= 0; n--){ + if(m_AllSubMenus[n]==m_SubMenus[m])m_AllSubMenus.RemoveAt(n); + } + CMenu *ptr=FromHandle(m_SubMenus[m]); + BOOL flag=ptr->IsKindOf(RUNTIME_CLASS( BCMenu )); + if(flag)delete((BCMenu *)ptr); + } + m_SubMenus.RemoveAll(); + // Destroy menu data + int numItems = m_MenuList.GetUpperBound(); + for(m = 0; m <= numItems; m++)delete(m_MenuList[m]); + m_MenuList.RemoveAll(); + if(checkmaps&&!checkmapsshare){ + delete checkmaps; + checkmaps=NULL; + } + // Call base-class implementation last: + return(CMenu::DestroyMenu()); +}; + +int BCMenu::GetMenuDrawMode(void) +{ + if(IsWinXPLuna())return(xp_drawmode); + return(original_drawmode); +} + +BOOL BCMenu::GetSelectDisableMode(void) +{ + if(IsLunaMenuStyle())return(xp_select_disabled); + return(original_select_disabled); +} + + +/* +========================================================================== +void BCMenu::DrawItem(LPDRAWITEMSTRUCT) +--------------------------------------- + + Called by the framework when a particular item needs to be drawn. We + overide this to draw the menu item in a custom-fashion, including icons + and the 3D rectangle bar. + ========================================================================== +*/ + +void BCMenu::DrawItem (LPDRAWITEMSTRUCT lpDIS) +{ + ASSERT(lpDIS != NULL); + CDC* pDC = CDC::FromHandle(lpDIS->hDC); + if(pDC->GetDeviceCaps(RASTERCAPS) & RC_PALETTE)DrawItem_Win9xNT2000(lpDIS); + else{ + if(IsWinXPLuna()){ + if(xp_drawmode==BCMENU_DRAWMODE_XP) DrawItem_WinXP(lpDIS); + else DrawItem_Win9xNT2000(lpDIS); + } + else{ + if(original_drawmode==BCMENU_DRAWMODE_XP) DrawItem_WinXP(lpDIS); + else DrawItem_Win9xNT2000(lpDIS); + } + } +} + +void BCMenu::DrawItem_Win9xNT2000 (LPDRAWITEMSTRUCT lpDIS) +{ + ASSERT(lpDIS != NULL); + CDC* pDC = CDC::FromHandle(lpDIS->hDC); + CRect rect; + UINT state = (((BCMenuData*)(lpDIS->itemData))->nFlags); + CBrush m_brBackground; + COLORREF m_clrBack; + + if(IsWinXPLuna())m_clrBack=GetSysColor(COLOR_3DFACE); + else m_clrBack=GetSysColor(COLOR_MENU); + + m_brBackground.CreateSolidBrush(m_clrBack); + + // remove the selected bit if it's grayed out + if(lpDIS->itemState & ODS_GRAYED&&!original_select_disabled){ + if(lpDIS->itemState & ODS_SELECTED)lpDIS->itemState=lpDIS->itemState & ~ODS_SELECTED; + } + + if(state & MF_SEPARATOR){ + rect.CopyRect(&lpDIS->rcItem); + pDC->FillRect (rect,&m_brBackground); + rect.top += (rect.Height()>>1); + pDC->DrawEdge(&rect,EDGE_ETCHED,BF_TOP); + } + else{ + CRect rect2; + BOOL standardflag=FALSE,selectedflag=FALSE,disableflag=FALSE; + BOOL checkflag=FALSE; + COLORREF crText = GetSysColor(COLOR_MENUTEXT); + CBrush m_brSelect; + CPen m_penBack; + int x0,y0,dy; + int nIconNormal=-1,xoffset=-1,global_offset=-1; + CImageList *bitmap=NULL; + + // set some colors + m_penBack.CreatePen (PS_SOLID,0,m_clrBack); + m_brSelect.CreateSolidBrush(GetSysColor(COLOR_HIGHLIGHT)); + + // draw the colored rectangle portion + + rect.CopyRect(&lpDIS->rcItem); + rect2=rect; + + // draw the up/down/focused/disabled state + + UINT state = lpDIS->itemState; + CString strText; + + if(lpDIS->itemData != NULL){ + nIconNormal = (((BCMenuData*)(lpDIS->itemData))->menuIconNormal); + xoffset = (((BCMenuData*)(lpDIS->itemData))->xoffset); + global_offset = (((BCMenuData*)(lpDIS->itemData))->global_offset); + bitmap = (((BCMenuData*)(lpDIS->itemData))->bitmap); + strText = ((BCMenuData*) (lpDIS->itemData))->GetString(); + + if(nIconNormal<0&&global_offset>=0){ + xoffset=global_offset; + nIconNormal=0; + bitmap = &m_AllImages; + } + + if(state&ODS_CHECKED && nIconNormal<0){ + if(state&ODS_SELECTED && m_selectcheck>0)checkflag=TRUE; + else if(m_unselectcheck>0) checkflag=TRUE; + } + else if(nIconNormal != -1){ + standardflag=TRUE; + if(state&ODS_SELECTED && !(state&ODS_GRAYED))selectedflag=TRUE; + else if(state&ODS_GRAYED) disableflag=TRUE; + } + } + else{ + strText.Empty(); + } + + if(state&ODS_SELECTED){ // draw the down edges + + CPen *pOldPen = pDC->SelectObject (&m_penBack); + + // You need only Text highlight and thats what you get + + if(checkflag||standardflag||selectedflag||disableflag||state&ODS_CHECKED) + rect2.SetRect(rect.left+m_iconX+4+BCMENU_GAP,rect.top,rect.right,rect.bottom); + pDC->FillRect (rect2,&m_brSelect); + + pDC->SelectObject (pOldPen); + crText = GetSysColor(COLOR_HIGHLIGHTTEXT); + } + else { + CPen *pOldPen = pDC->SelectObject (&m_penBack); + pDC->FillRect (rect,&m_brBackground); + pDC->SelectObject (pOldPen); + + // draw the up edges + pDC->Draw3dRect (rect,m_clrBack,m_clrBack); + } + + // draw the text if there is any + //We have to paint the text only if the image is nonexistant + + dy = (rect.Height()-4-m_iconY)/2; + dy = dy<0 ? 0 : dy; + + if(checkflag||standardflag||selectedflag||disableflag){ + rect2.SetRect(rect.left+1,rect.top+1+dy,rect.left+m_iconX+3, + rect.top+m_iconY+3+dy); + pDC->Draw3dRect (rect2,m_clrBack,m_clrBack); + if(checkflag && checkmaps){ + pDC->FillRect (rect2,&m_brBackground); + rect2.SetRect(rect.left,rect.top+dy,rect.left+m_iconX+4, + rect.top+m_iconY+4+dy); + + pDC->Draw3dRect (rect2,m_clrBack,m_clrBack); + CPoint ptImage(rect.left+2,rect.top+2+dy); + + if(state&ODS_SELECTED)checkmaps->Draw(pDC,1,ptImage,ILD_TRANSPARENT); + else checkmaps->Draw(pDC,0,ptImage,ILD_TRANSPARENT); + } + else if(disableflag){ + if(!selectedflag){ + CBitmap bitmapstandard; + GetBitmapFromImageList(pDC,bitmap,xoffset,bitmapstandard); + rect2.SetRect(rect.left,rect.top+dy,rect.left+m_iconX+4, + rect.top+m_iconY+4+dy); + pDC->Draw3dRect (rect2,m_clrBack,m_clrBack); + if(disable_old_style) + DitherBlt(lpDIS->hDC,rect.left+2,rect.top+2+dy,m_iconX,m_iconY, + (HBITMAP)(bitmapstandard),0,0,m_clrBack); + else{ + if(hicolor_bitmaps) + DitherBlt3(pDC,rect.left+2,rect.top+2+dy,m_iconX,m_iconY, + bitmapstandard,m_clrBack); + else + DitherBlt2(pDC,rect.left+2,rect.top+2+dy,m_iconX,m_iconY, + bitmapstandard,0,0,m_clrBack); + } + bitmapstandard.DeleteObject(); + } + } + else if(selectedflag){ + pDC->FillRect (rect2,&m_brBackground); + rect2.SetRect(rect.left,rect.top+dy,rect.left+m_iconX+4, + rect.top+m_iconY+4+dy); + if (IsNewShell()){ + if(state&ODS_CHECKED) + pDC->Draw3dRect(rect2,GetSysColor(COLOR_3DSHADOW), + GetSysColor(COLOR_3DHILIGHT)); + else + pDC->Draw3dRect(rect2,GetSysColor(COLOR_3DHILIGHT), + GetSysColor(COLOR_3DSHADOW)); + } + CPoint ptImage(rect.left+2,rect.top+2+dy); + if(bitmap)bitmap->Draw(pDC,xoffset,ptImage,ILD_TRANSPARENT); + } + else{ + if(state&ODS_CHECKED){ + CBrush brush; + COLORREF col = m_clrBack; + col = LightenColor(col,0.6); + brush.CreateSolidBrush(col); + pDC->FillRect(rect2,&brush); + brush.DeleteObject(); + rect2.SetRect(rect.left,rect.top+dy,rect.left+m_iconX+4, + rect.top+m_iconY+4+dy); + if (IsNewShell()) + pDC->Draw3dRect(rect2,GetSysColor(COLOR_3DSHADOW), + GetSysColor(COLOR_3DHILIGHT)); + } + else{ + pDC->FillRect (rect2,&m_brBackground); + rect2.SetRect(rect.left,rect.top+dy,rect.left+m_iconX+4, + rect.top+m_iconY+4+dy); + pDC->Draw3dRect (rect2,m_clrBack,m_clrBack); + } + CPoint ptImage(rect.left+2,rect.top+2+dy); + if(bitmap)bitmap->Draw(pDC,xoffset,ptImage,ILD_TRANSPARENT); + } + } + if(nIconNormal<0 && state&ODS_CHECKED && !checkflag){ + rect2.SetRect(rect.left+1,rect.top+2+dy,rect.left+m_iconX+1, + rect.top+m_iconY+2+dy); + CMenuItemInfo info; + info.fMask = MIIM_CHECKMARKS; + ::GetMenuItemInfo((HMENU)lpDIS->hwndItem,lpDIS->itemID, + MF_BYCOMMAND, &info); + if(state&ODS_CHECKED || info.hbmpUnchecked) { + Draw3DCheckmark(pDC, rect2, state&ODS_SELECTED, + state&ODS_CHECKED ? info.hbmpChecked : + info.hbmpUnchecked); + } + } + + //This is needed always so that we can have the space for check marks + + x0=rect.left;y0=rect.top; + rect.left = rect.left + m_iconX + 8 + BCMENU_GAP; + + if(!strText.IsEmpty()){ + + CRect rectt(rect.left,rect.top-1,rect.right,rect.bottom-1); + + // Find tabs + + CString leftStr,rightStr; + leftStr.Empty();rightStr.Empty(); + int tablocr=strText.ReverseFind(_T('\t')); + if(tablocr!=-1){ + rightStr=strText.Mid(tablocr+1); + leftStr=strText.Left(strText.Find(_T('\t'))); + rectt.right-=m_iconX; + } + else leftStr=strText; + + int iOldMode = pDC->GetBkMode(); + pDC->SetBkMode( TRANSPARENT); + + // Draw the text in the correct colour: + + UINT nFormat = DT_LEFT|DT_SINGLELINE|DT_VCENTER; + UINT nFormatr = DT_RIGHT|DT_SINGLELINE|DT_VCENTER; + if(!(lpDIS->itemState & ODS_GRAYED)){ + pDC->SetTextColor(crText); + pDC->DrawText (leftStr,rectt,nFormat); + if(tablocr!=-1) pDC->DrawText (rightStr,rectt,nFormatr); + } + else{ + + // Draw the disabled text + if(!(state & ODS_SELECTED)){ + RECT offset = *rectt; + offset.left+=1; + offset.right+=1; + offset.top+=1; + offset.bottom+=1; + pDC->SetTextColor(GetSysColor(COLOR_BTNHILIGHT)); + pDC->DrawText(leftStr,&offset, nFormat); + if(tablocr!=-1) pDC->DrawText (rightStr,&offset,nFormatr); + pDC->SetTextColor(GetSysColor(COLOR_GRAYTEXT)); + pDC->DrawText(leftStr,rectt, nFormat); + if(tablocr!=-1) pDC->DrawText (rightStr,rectt,nFormatr); + } + else{ + // And the standard Grey text: + pDC->SetTextColor(m_clrBack); + pDC->DrawText(leftStr,rectt, nFormat); + if(tablocr!=-1) pDC->DrawText (rightStr,rectt,nFormatr); + } + } + pDC->SetBkMode( iOldMode ); + } + + m_penBack.DeleteObject(); + m_brSelect.DeleteObject(); + } + m_brBackground.DeleteObject(); +} + +COLORREF BCMenu::LightenColor(COLORREF col,double factor) +{ + if(factor>0.0&&factor<=1.0){ + BYTE red,green,blue,lightred,lightgreen,lightblue; + red = GetRValue(col); + green = GetGValue(col); + blue = GetBValue(col); + lightred = (BYTE)((factor*(255-red)) + red); + lightgreen = (BYTE)((factor*(255-green)) + green); + lightblue = (BYTE)((factor*(255-blue)) + blue); + col = RGB(lightred,lightgreen,lightblue); + } + return(col); +} + +COLORREF BCMenu::DarkenColor(COLORREF col,double factor) +{ + if(factor>0.0&&factor<=1.0){ + BYTE red,green,blue,lightred,lightgreen,lightblue; + red = GetRValue(col); + green = GetGValue(col); + blue = GetBValue(col); + lightred = (BYTE)(red-(factor*red)); + lightgreen = (BYTE)(green-(factor*green)); + lightblue = (BYTE)(blue-(factor*blue)); + col = RGB(lightred,lightgreen,lightblue); + } + return(col); +} + + +void BCMenu::DrawItem_WinXP (LPDRAWITEMSTRUCT lpDIS) +{ + ASSERT(lpDIS != NULL); + CDC* pDC = CDC::FromHandle(lpDIS->hDC); +#ifdef BCMENU_USE_MEMDC + BCMenuMemDC *pMemDC=NULL; +#endif + CRect rect,rect2; + UINT state = (((BCMenuData*)(lpDIS->itemData))->nFlags); + COLORREF m_newclrBack=GetSysColor(COLOR_3DFACE); + COLORREF m_clrBack=GetSysColor(COLOR_WINDOW); + m_clrBack=DarkenColor(m_clrBack,0.02); + CFont m_fontMenu,*pFont=NULL; + LOGFONT m_lf; + if(!IsWinXPLuna())m_newclrBack=LightenColor(m_newclrBack,0.25); + CBrush m_newbrBackground,m_brBackground; + m_brBackground.CreateSolidBrush(m_clrBack); + m_newbrBackground.CreateSolidBrush(m_newclrBack); + int BCMENU_PAD=4; + if(xp_draw_3D_bitmaps)BCMENU_PAD=7; + int barwidth=m_iconX+BCMENU_PAD; + + // remove the selected bit if it's grayed out + if(lpDIS->itemState & ODS_GRAYED&&!xp_select_disabled){ + if(lpDIS->itemState & ODS_SELECTED)lpDIS->itemState=lpDIS->itemState & ~ODS_SELECTED; +#ifdef BCMENU_USE_MEMDC + pMemDC=new BCMenuMemDC(pDC,&lpDIS->rcItem); + pDC = pMemDC; + ZeroMemory ((PVOID) &m_lf,sizeof (LOGFONT)); + NONCLIENTMETRICS nm; + nm.cbSize = sizeof (NONCLIENTMETRICS); + VERIFY (SystemParametersInfo(SPI_GETNONCLIENTMETRICS,nm.cbSize,&nm,0)); + m_lf = nm.lfMenuFont; + m_fontMenu.CreateFontIndirect (&m_lf); + pFont = pDC->SelectObject (&m_fontMenu); +#endif + + } + + if(state & MF_SEPARATOR){ + rect.CopyRect(&lpDIS->rcItem); + pDC->FillRect (rect,&m_brBackground); + rect2.SetRect(rect.left,rect.top,rect.left+barwidth,rect.bottom); + rect.top+=rect.Height()>>1; + rect.left = rect2.right+BCMENU_PAD; + pDC->DrawEdge(&rect,EDGE_ETCHED,BF_TOP); + pDC->FillRect (rect2,&m_newbrBackground); + pDC->Draw3dRect (rect2,m_newclrBack,m_newclrBack); + } + else{ + BOOL standardflag=FALSE,selectedflag=FALSE,disableflag=FALSE; + BOOL checkflag=FALSE; + COLORREF crText = GetSysColor(COLOR_MENUTEXT); + COLORREF crSelect = GetSysColor(COLOR_HIGHLIGHT); + COLORREF crSelectFill; + if(!IsWinXPLuna())crSelectFill=LightenColor(crSelect,0.85); + else crSelectFill=LightenColor(crSelect,0.7); + CBrush m_brSelect; + CPen m_penBack; + int x0,y0,dx,dy; + int nIconNormal=-1,xoffset=-1,global_offset=-1; + int faded_offset=1,shadow_offset=2,disabled_offset=3; + CImageList *bitmap=NULL; + BOOL CanDraw3D=FALSE; + + // set some colors + m_penBack.CreatePen (PS_SOLID,0,m_clrBack); + m_brSelect.CreateSolidBrush(crSelectFill); + + // draw the colored rectangle portion + + rect.CopyRect(&lpDIS->rcItem); + rect2=rect; + + // draw the up/down/focused/disabled state + + UINT state = lpDIS->itemState; + CString strText; + + if(lpDIS->itemData != NULL){ + nIconNormal = (((BCMenuData*)(lpDIS->itemData))->menuIconNormal); + xoffset = (((BCMenuData*)(lpDIS->itemData))->xoffset); + bitmap = (((BCMenuData*)(lpDIS->itemData))->bitmap); + strText = ((BCMenuData*) (lpDIS->itemData))->GetString(); + global_offset = (((BCMenuData*)(lpDIS->itemData))->global_offset); + + if(xoffset==0&&xp_draw_3D_bitmaps&&bitmap&&bitmap->GetImageCount()>2)CanDraw3D=TRUE; + + if(nIconNormal<0&&xoffset<0&&global_offset>=0){ + xoffset=global_offset; + nIconNormal=0; + bitmap = &m_AllImages; + if(xp_draw_3D_bitmaps&&CanDraw3DImageList(global_offset)){ + CanDraw3D=TRUE; + faded_offset=global_offset+1; + shadow_offset=global_offset+2; + disabled_offset=global_offset+3; + } + } + + + if(state&ODS_CHECKED && nIconNormal<0){ + if(state&ODS_SELECTED && m_selectcheck>0)checkflag=TRUE; + else if(m_unselectcheck>0) checkflag=TRUE; + } + else if(nIconNormal != -1){ + standardflag=TRUE; + if(state&ODS_SELECTED && !(state&ODS_GRAYED))selectedflag=TRUE; + else if(state&ODS_GRAYED) disableflag=TRUE; + } + } + else{ + strText.Empty(); + } + + if(state&ODS_SELECTED){ // draw the down edges + + CPen *pOldPen = pDC->SelectObject (&m_penBack); + + pDC->FillRect (rect,&m_brSelect); + pDC->Draw3dRect (rect,crSelect,crSelect); + + pDC->SelectObject (pOldPen); + } + else { + rect2.SetRect(rect.left,rect.top,rect.left+barwidth,rect.bottom); + CPen *pOldPen = pDC->SelectObject (&m_penBack); + pDC->FillRect (rect,&m_brBackground); + pDC->FillRect (rect2,&m_newbrBackground); + pDC->SelectObject (pOldPen); + + // draw the up edges + + pDC->Draw3dRect (rect,m_clrBack,m_clrBack); + pDC->Draw3dRect (rect2,m_newclrBack,m_newclrBack); + } + + // draw the text if there is any + //We have to paint the text only if the image is nonexistant + + dy = (int)(0.5+(rect.Height()-m_iconY)/2.0); + dy = dy<0 ? 0 : dy; + dx = (int)(0.5+(barwidth-m_iconX)/2.0); + dx = dx<0 ? 0 : dx; + rect2.SetRect(rect.left+1,rect.top+1,rect.left+barwidth-2,rect.bottom-1); + + if(checkflag||standardflag||selectedflag||disableflag){ + if(checkflag && checkmaps){ + pDC->FillRect (rect2,&m_newbrBackground); + CPoint ptImage(rect.left+dx,rect.top+dy); + if(state&ODS_SELECTED)checkmaps->Draw(pDC,1,ptImage,ILD_TRANSPARENT); + else checkmaps->Draw(pDC,0,ptImage,ILD_TRANSPARENT); + } + else if(disableflag){ + if(!selectedflag){ + if(CanDraw3D){ + CPoint ptImage(rect.left+dx,rect.top+dy); + bitmap->Draw(pDC,disabled_offset,ptImage,ILD_TRANSPARENT); + } + else{ + CBitmap bitmapstandard; + GetBitmapFromImageList(pDC,bitmap,xoffset,bitmapstandard); + COLORREF transparentcol=m_newclrBack; + if(state&ODS_SELECTED)transparentcol=crSelectFill; + if(disable_old_style) + DitherBlt(lpDIS->hDC,rect.left+dx,rect.top+dy,m_iconX,m_iconY, + (HBITMAP)(bitmapstandard),0,0,transparentcol); + else + DitherBlt2(pDC,rect.left+dx,rect.top+dy,m_iconX,m_iconY, + bitmapstandard,0,0,transparentcol); + if(state&ODS_SELECTED)pDC->Draw3dRect (rect,crSelect,crSelect); + bitmapstandard.DeleteObject(); + } + } + } + else if(selectedflag){ + CPoint ptImage(rect.left+dx,rect.top+dy); + if(state&ODS_CHECKED){ + CBrush brushin; + brushin.CreateSolidBrush(LightenColor(crSelect,0.55)); + pDC->FillRect(rect2,&brushin); + brushin.DeleteObject(); + pDC->Draw3dRect(rect2,crSelect,crSelect); + ptImage.x-=1;ptImage.y-=1; + } + else pDC->FillRect (rect2,&m_brSelect); + if(bitmap){ + if(CanDraw3D&&!(state&ODS_CHECKED)){ + CPoint ptImage1(ptImage.x+1,ptImage.y+1); + CPoint ptImage2(ptImage.x-1,ptImage.y-1); + bitmap->Draw(pDC,shadow_offset,ptImage1,ILD_TRANSPARENT); + bitmap->Draw(pDC,xoffset,ptImage2,ILD_TRANSPARENT); + } + else bitmap->Draw(pDC,xoffset,ptImage,ILD_TRANSPARENT); + } + } + else{ + if(state&ODS_CHECKED){ + CBrush brushin; + brushin.CreateSolidBrush(LightenColor(crSelect,0.85)); + pDC->FillRect(rect2,&brushin); + brushin.DeleteObject(); + pDC->Draw3dRect(rect2,crSelect,crSelect); + CPoint ptImage(rect.left+dx-1,rect.top+dy-1); + if(bitmap)bitmap->Draw(pDC,xoffset,ptImage,ILD_TRANSPARENT); + } + else{ + pDC->FillRect (rect2,&m_newbrBackground); + pDC->Draw3dRect (rect2,m_newclrBack,m_newclrBack); + CPoint ptImage(rect.left+dx,rect.top+dy); + if(bitmap){ + if(CanDraw3D) + bitmap->Draw(pDC,faded_offset,ptImage,ILD_TRANSPARENT); + else + bitmap->Draw(pDC,xoffset,ptImage,ILD_TRANSPARENT); + } + } + } + } + if(nIconNormal<0 && state&ODS_CHECKED && !checkflag){ + CMenuItemInfo info; + info.fMask = MIIM_CHECKMARKS; + ::GetMenuItemInfo((HMENU)lpDIS->hwndItem,lpDIS->itemID, + MF_BYCOMMAND, &info); + if(state&ODS_CHECKED || info.hbmpUnchecked) { + DrawXPCheckmark(pDC, rect2,state&ODS_CHECKED ? info.hbmpChecked : + info.hbmpUnchecked,crSelect,state&ODS_SELECTED); + } + } + + //This is needed always so that we can have the space for check marks + + x0=rect.left;y0=rect.top; + rect.left = rect.left + barwidth + 8; + + if(!strText.IsEmpty()){ + + CRect rectt(rect.left,rect.top-1,rect.right,rect.bottom-1); + + // Find tabs + + CString leftStr,rightStr; + leftStr.Empty();rightStr.Empty(); + int tablocr=strText.ReverseFind(_T('\t')); + if(tablocr!=-1){ + rightStr=strText.Mid(tablocr+1); + leftStr=strText.Left(strText.Find(_T('\t'))); + rectt.right-=m_iconX; + } + else leftStr=strText; + + int iOldMode = pDC->GetBkMode(); + pDC->SetBkMode( TRANSPARENT); + + // Draw the text in the correct colour: + + UINT nFormat = DT_LEFT|DT_SINGLELINE|DT_VCENTER; + UINT nFormatr = DT_RIGHT|DT_SINGLELINE|DT_VCENTER; + if(!(lpDIS->itemState & ODS_GRAYED)){ + pDC->SetTextColor(crText); + pDC->DrawText (leftStr,rectt,nFormat); + if(tablocr!=-1) pDC->DrawText (rightStr,rectt,nFormatr); + } + else{ + RECT offset = *rectt; + offset.left+=1; + offset.right+=1; + offset.top+=1; + offset.bottom+=1; + if(!IsWinXPLuna()){ + COLORREF graycol=GetSysColor(COLOR_GRAYTEXT); + if(!(state&ODS_SELECTED))graycol = LightenColor(graycol,0.4); + pDC->SetTextColor(graycol); + } + else pDC->SetTextColor(GetSysColor(COLOR_GRAYTEXT)); + pDC->DrawText(leftStr,rectt, nFormat); + if(tablocr!=-1) pDC->DrawText (rightStr,rectt,nFormatr); + } + pDC->SetBkMode( iOldMode ); + } + + m_penBack.DeleteObject(); + m_brSelect.DeleteObject(); + } + m_brBackground.DeleteObject(); + m_newbrBackground.DeleteObject(); +#ifdef BCMENU_USE_MEMDC + if(pFont)pDC->SelectObject (pFont); //set it to the old font + m_fontMenu.DeleteObject(); + if(pMemDC)delete pMemDC; +#endif +} + +BOOL BCMenu::GetBitmapFromImageList(CDC* pDC,CImageList *imglist,int nIndex,CBitmap &bmp) +{ + HICON hIcon = imglist->ExtractIcon(nIndex); + CDC dc; + dc.CreateCompatibleDC(pDC); + bmp.CreateCompatibleBitmap(pDC,m_iconX,m_iconY); + CBitmap* pOldBmp = dc.SelectObject(&bmp); + CBrush brush ; + COLORREF m_newclrBack; + m_newclrBack=GetSysColor(COLOR_3DFACE); + brush.CreateSolidBrush(m_newclrBack); + ::DrawIconEx( + dc.GetSafeHdc(), + 0, + 0, + hIcon, + m_iconX, + m_iconY, + 0, + (HBRUSH)brush, + DI_NORMAL + ); + dc.SelectObject( pOldBmp ); + dc.DeleteDC(); + // the icon is not longer needed + ::DestroyIcon(hIcon); + return(TRUE); +} + +/* +========================================================================== +void BCMenu::MeasureItem(LPMEASUREITEMSTRUCT) +--------------------------------------------- + + Called by the framework when it wants to know what the width and height + of our item will be. To accomplish this we provide the width of the + icon plus the width of the menu text, and then the height of the icon. + + ========================================================================== +*/ + +void BCMenu::MeasureItem( LPMEASUREITEMSTRUCT lpMIS ) +{ + UINT state = (((BCMenuData*)(lpMIS->itemData))->nFlags); + int BCMENU_PAD=4; + if(IsLunaMenuStyle()&&xp_draw_3D_bitmaps)BCMENU_PAD=7; + if(state & MF_SEPARATOR){ + lpMIS->itemWidth = 0; + int temp = GetSystemMetrics(SM_CYMENU)>>1; + if(IsLunaMenuStyle()) + lpMIS->itemHeight = 3; + else + lpMIS->itemHeight = temp>(m_iconY+BCMENU_PAD)/2 ? temp : (m_iconY+BCMENU_PAD)/2; + } + else{ + CFont m_fontMenu; + LOGFONT m_lf; + ZeroMemory ((PVOID) &m_lf,sizeof (LOGFONT)); + NONCLIENTMETRICS nm; + nm.cbSize = sizeof (NONCLIENTMETRICS); + VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, + nm.cbSize,&nm,0)); + m_lf = nm.lfMenuFont; + m_fontMenu.CreateFontIndirect (&m_lf); + + // Obtain the width of the text: + CWnd *pWnd = AfxGetMainWnd(); // Get main window + if (pWnd == NULL) pWnd = CWnd::GetDesktopWindow(); + CDC *pDC = pWnd->GetDC(); // Get device context + CFont* pFont=NULL; // Select menu font in... + + if (IsNewShell()) + pFont = pDC->SelectObject (&m_fontMenu);// Select menu font in... + + //Get pointer to text SK + const wchar_t *lpstrText = ((BCMenuData*)(lpMIS->itemData))->GetWideString();//SK: we use const to prevent misuse + + SIZE size; + size.cx=size.cy=0; + + if (Win32s!=g_Shell) + VERIFY(::GetTextExtentPoint32W(pDC->m_hDC,lpstrText, + wcslen(lpstrText),&size)); //SK should also work on 95 +#ifndef UNICODE //can't be UNICODE for Win32s + else{//it's Win32suckx + RECT rect; + rect.left=rect.top=0; + size.cy=DrawText(pDC->m_hDC,(LPCTSTR)lpstrText, + wcslen(lpstrText),&rect, + DT_SINGLELINE|DT_LEFT|DT_VCENTER|DT_CALCRECT); + //+3 makes at least three pixels space to the menu border + size.cx=rect.right-rect.left+3; + size.cx += 3*(size.cx/wcslen(lpstrText)); + } +#endif + + CSize t = CSize(size); + if(IsNewShell()) + pDC->SelectObject (pFont); // Select old font in + pWnd->ReleaseDC(pDC); // Release the DC + + // Set width and height: + + if(IsLunaMenuStyle())lpMIS->itemWidth = m_iconX+BCMENU_PAD+8+t.cx; + else lpMIS->itemWidth = m_iconX + t.cx + m_iconX + BCMENU_GAP; + int temp = GetSystemMetrics(SM_CYMENU); + lpMIS->itemHeight = temp>m_iconY+BCMENU_PAD ? temp : m_iconY+BCMENU_PAD; + m_fontMenu.DeleteObject(); + } +} + +void BCMenu::SetIconSize (int width, int height) +{ + m_iconX = width; + m_iconY = height; +} + +BOOL BCMenu::AppendODMenuA(LPCSTR lpstrText,UINT nFlags,UINT nID, + int nIconNormal) +{ + USES_CONVERSION; + return AppendODMenuW(A2W(lpstrText),nFlags,nID,nIconNormal);//SK: See MFC Tech Note 059 +} + + +BOOL BCMenu::AppendODMenuW(wchar_t *lpstrText,UINT nFlags,UINT nID, + int nIconNormal) +{ + // Add the MF_OWNERDRAW flag if not specified: + if(!nID){ + if(nFlags&MF_BYPOSITION)nFlags=MF_SEPARATOR|MF_OWNERDRAW|MF_BYPOSITION; + else nFlags=MF_SEPARATOR|MF_OWNERDRAW; + } + else if(!(nFlags & MF_OWNERDRAW))nFlags |= MF_OWNERDRAW; + + if(nFlags & MF_POPUP){ + m_AllSubMenus.Add((HMENU)nID); + m_SubMenus.Add((HMENU)nID); + } + + BCMenuData *mdata = new BCMenuData; + m_MenuList.Add(mdata); + mdata->SetWideString(lpstrText); //SK: modified for dynamic allocation + + mdata->menuIconNormal = -1; + mdata->xoffset = -1; + + if(nIconNormal>=0){ + CImageList bitmap; + int xoffset=0; + LoadFromToolBar(nID,nIconNormal,xoffset); + if(mdata->bitmap){ + mdata->bitmap->DeleteImageList(); + mdata->bitmap=NULL; + } + bitmap.Create(m_iconX,m_iconY,ILC_COLORDDB|ILC_MASK,1,1); + if(AddBitmapToImageList(&bitmap,nIconNormal)){ + mdata->global_offset = AddToGlobalImageList(&bitmap,xoffset,nID); + } + } + else mdata->global_offset = GlobalImageListOffset(nID); + + mdata->nFlags = nFlags; + mdata->nID = nID; + BOOL returnflag=CMenu::AppendMenu(nFlags, nID, (LPCTSTR)mdata); + if(m_loadmenu)RemoveTopLevelOwnerDraw(); + return(returnflag); +} + +BOOL BCMenu::AppendODMenuA(LPCSTR lpstrText,UINT nFlags,UINT nID, + CImageList *il,int xoffset) +{ + USES_CONVERSION; + return AppendODMenuW(A2W(lpstrText),nFlags,nID,il,xoffset); +} + +BOOL BCMenu::AppendODMenuW(wchar_t *lpstrText,UINT nFlags,UINT nID, + CImageList *il,int xoffset) +{ + // Add the MF_OWNERDRAW flag if not specified: + if(!nID){ + if(nFlags&MF_BYPOSITION)nFlags=MF_SEPARATOR|MF_OWNERDRAW|MF_BYPOSITION; + else nFlags=MF_SEPARATOR|MF_OWNERDRAW; + } + else if(!(nFlags & MF_OWNERDRAW))nFlags |= MF_OWNERDRAW; + + if(nFlags & MF_POPUP){ + m_AllSubMenus.Add((HMENU)nID); + m_SubMenus.Add((HMENU)nID); + } + + BCMenuData *mdata = new BCMenuData; + m_MenuList.Add(mdata); + mdata->SetWideString(lpstrText); //SK: modified for dynamic allocation + + if(il){ + mdata->menuIconNormal = 0; + mdata->xoffset=0; + if(mdata->bitmap)mdata->bitmap->DeleteImageList(); + else mdata->bitmap=new(CImageList); + ImageListDuplicate(il,xoffset,mdata->bitmap); + } + else{ + mdata->menuIconNormal = -1; + mdata->xoffset = -1; + } + mdata->nFlags = nFlags; + mdata->nID = nID; + return(CMenu::AppendMenu(nFlags, nID, (LPCTSTR)mdata)); +} + +BOOL BCMenu::InsertODMenuA(UINT nPosition,LPCSTR lpstrText,UINT nFlags,UINT nID, + int nIconNormal) +{ + USES_CONVERSION; + return InsertODMenuW(nPosition,A2W(lpstrText),nFlags,nID,nIconNormal); +} + + +BOOL BCMenu::InsertODMenuW(UINT nPosition,wchar_t *lpstrText,UINT nFlags,UINT nID, + int nIconNormal) +{ + if(!(nFlags & MF_BYPOSITION)){ + int iPosition =0; + BCMenu* pMenu = FindMenuOption(nPosition,iPosition); + if(pMenu){ + return(pMenu->InsertODMenuW(iPosition,lpstrText,nFlags|MF_BYPOSITION,nID,nIconNormal)); + } + else return(FALSE); + } + + if(!nID)nFlags=MF_SEPARATOR|MF_OWNERDRAW|MF_BYPOSITION; + else if(!(nFlags & MF_OWNERDRAW))nFlags |= MF_OWNERDRAW; + + int menustart=0; + + if(nFlags & MF_POPUP){ + if(m_loadmenu){ + menustart=GetMenuStart(); + if(nPosition<(UINT)menustart)menustart=0; + } + m_AllSubMenus.Add((HMENU)nID); + m_SubMenus.InsertAt(nPosition,(HMENU)nID); + } + + //Stephane Clog suggested adding this, believe it or not it's in the help + if(nPosition==(UINT)-1)nPosition=GetMenuItemCount(); + + BCMenuData *mdata = new BCMenuData; + m_MenuList.InsertAt(nPosition-menustart,mdata); + mdata->SetWideString(lpstrText); //SK: modified for dynamic allocation + + mdata->menuIconNormal = nIconNormal; + mdata->xoffset=-1; + if(nIconNormal>=0){ + CImageList bitmap; + int xoffset=0; + LoadFromToolBar(nID,nIconNormal,xoffset); + if(mdata->bitmap){ + mdata->bitmap->DeleteImageList(); + mdata->bitmap=NULL; + } + bitmap.Create(m_iconX,m_iconY,ILC_COLORDDB|ILC_MASK,1,1); + if(AddBitmapToImageList(&bitmap,nIconNormal)){ + mdata->global_offset = AddToGlobalImageList(&bitmap,xoffset,nID); + } + } + else mdata->global_offset = GlobalImageListOffset(nID); + mdata->nFlags = nFlags; + mdata->nID = nID; + BOOL returnflag=CMenu::InsertMenu(nPosition,nFlags,nID,(LPCTSTR)mdata); + if(m_loadmenu)RemoveTopLevelOwnerDraw(); + return(returnflag); +} + +BOOL BCMenu::InsertODMenuA(UINT nPosition,LPCSTR lpstrText,UINT nFlags,UINT nID, + CImageList *il,int xoffset) +{ + USES_CONVERSION; + return InsertODMenuW(nPosition,A2W(lpstrText),nFlags,nID,il,xoffset); +} + +BOOL BCMenu::InsertODMenuW(UINT nPosition,wchar_t *lpstrText,UINT nFlags,UINT nID, + CImageList *il,int xoffset) +{ + if(!(nFlags & MF_BYPOSITION)){ + int iPosition =0; + BCMenu* pMenu = FindMenuOption(nPosition,iPosition); + if(pMenu){ + return(pMenu->InsertODMenuW(iPosition,lpstrText,nFlags|MF_BYPOSITION,nID,il,xoffset)); + } + else return(FALSE); + } + + if(!nID)nFlags=MF_SEPARATOR|MF_OWNERDRAW|MF_BYPOSITION; + else if(!(nFlags & MF_OWNERDRAW))nFlags |= MF_OWNERDRAW; + + if(nFlags & MF_POPUP){ + m_AllSubMenus.Add((HMENU)nID); + m_SubMenus.InsertAt(nPosition,(HMENU)nID); + } + + //Stephane Clog suggested adding this, believe it or not it's in the help + if(nPosition==(UINT)-1)nPosition=GetMenuItemCount(); + + BCMenuData *mdata = new BCMenuData; + m_MenuList.InsertAt(nPosition,mdata); + mdata->SetWideString(lpstrText); //SK: modified for dynamic allocation + + mdata->menuIconNormal = -1; + mdata->xoffset = -1; + + if(il){ + if(mdata->bitmap){ + mdata->bitmap->DeleteImageList(); + mdata->bitmap=NULL; + } + mdata->global_offset = AddToGlobalImageList(il,xoffset,nID); + } + mdata->nFlags = nFlags; + mdata->nID = nID; + return(CMenu::InsertMenu(nPosition,nFlags,nID,(LPCTSTR)mdata)); +} + +BOOL BCMenu::ModifyODMenuA(const char * lpstrText,UINT nID,int nIconNormal) +{ + USES_CONVERSION; + return ModifyODMenuW(A2W(lpstrText),nID,nIconNormal);//SK: see MFC Tech Note 059 +} + +BOOL BCMenu::ModifyODMenuW(wchar_t *lpstrText,UINT nID,int nIconNormal) +{ + int nLoc; + BCMenuData *mdata; + CArraybcsubs; + CArraybclocs; + + // Find the old BCMenuData structure: + BCMenu *psubmenu = FindMenuOption(nID,nLoc); + do{ + if(psubmenu && nLoc>=0)mdata = psubmenu->m_MenuList[nLoc]; + else{ + // Create a new BCMenuData structure: + mdata = new BCMenuData; + m_MenuList.Add(mdata); + } + + ASSERT(mdata); + if(lpstrText) + mdata->SetWideString(lpstrText); //SK: modified for dynamic allocation + mdata->menuIconNormal = -1; + mdata->xoffset = -1; + if(nIconNormal>=0){ + CImageList bitmap; + int xoffset=0; + LoadFromToolBar(nID,nIconNormal,xoffset); + if(mdata->bitmap){ + mdata->bitmap->DeleteImageList(); + mdata->bitmap=NULL; + } + bitmap.Create(m_iconX,m_iconY,ILC_COLORDDB|ILC_MASK,1,1); + if(AddBitmapToImageList(&bitmap,nIconNormal)){ + mdata->global_offset = AddToGlobalImageList(&bitmap,xoffset,nID); + } + } + else mdata->global_offset = GlobalImageListOffset(nID); + mdata->nFlags &= ~(MF_BYPOSITION); + mdata->nFlags |= MF_OWNERDRAW; + mdata->nID = nID; + bcsubs.Add(psubmenu); + bclocs.Add(nLoc); + if(psubmenu && nLoc>=0)psubmenu = FindAnotherMenuOption(nID,nLoc,bcsubs,bclocs); + else psubmenu=NULL; + }while(psubmenu); + return (CMenu::ModifyMenu(nID,mdata->nFlags,nID,(LPCTSTR)mdata)); +} + +BOOL BCMenu::ModifyODMenuA(const char * lpstrText,UINT nID,CImageList *il,int xoffset) +{ + USES_CONVERSION; + return ModifyODMenuW(A2W(lpstrText),nID,il,xoffset); +} + +BOOL BCMenu::ModifyODMenuW(wchar_t *lpstrText,UINT nID,CImageList *il,int xoffset) +{ + int nLoc; + BCMenuData *mdata; + CArraybcsubs; + CArraybclocs; + + // Find the old BCMenuData structure: + BCMenu *psubmenu = FindMenuOption(nID,nLoc); + do{ + if(psubmenu && nLoc>=0)mdata = psubmenu->m_MenuList[nLoc]; + else{ + // Create a new BCMenuData structure: + mdata = new BCMenuData; + m_MenuList.Add(mdata); + } + + ASSERT(mdata); + if(lpstrText) + mdata->SetWideString(lpstrText); //SK: modified for dynamic allocation + mdata->menuIconNormal = -1; + mdata->xoffset = -1; + if(il){ + if(mdata->bitmap){ + mdata->bitmap->DeleteImageList(); + mdata->bitmap=NULL; + } + mdata->global_offset = AddToGlobalImageList(il,xoffset,nID); + } + mdata->nFlags &= ~(MF_BYPOSITION); + mdata->nFlags |= MF_OWNERDRAW; + mdata->nID = nID; + bcsubs.Add(psubmenu); + bclocs.Add(nLoc); + if(psubmenu && nLoc>=0)psubmenu = FindAnotherMenuOption(nID,nLoc,bcsubs,bclocs); + else psubmenu=NULL; + }while(psubmenu); + return (CMenu::ModifyMenu(nID,mdata->nFlags,nID,(LPCTSTR)mdata)); +} + +BOOL BCMenu::ModifyODMenuA(const char * lpstrText,UINT nID,CBitmap *bmp) +{ + USES_CONVERSION; + return ModifyODMenuW(A2W(lpstrText),nID,bmp); +} + +BOOL BCMenu::ModifyODMenuW(wchar_t *lpstrText,UINT nID,CBitmap *bmp) +{ + if(bmp){ + CImageList temp; + temp.Create(m_iconX,m_iconY,ILC_COLORDDB|ILC_MASK,1,1); + if(m_bitmapBackgroundFlag)temp.Add(bmp,m_bitmapBackground); + else temp.Add(bmp,GetSysColor(COLOR_3DFACE)); + return ModifyODMenuW(lpstrText,nID,&temp,0); + } + return ModifyODMenuW(lpstrText,nID,NULL,0); +} + +// courtesy of Warren Stevens +BOOL BCMenu::ModifyODMenuA(const char * lpstrText,UINT nID,COLORREF fill,COLORREF border,int hatchstyle,CSize *pSize) +{ + USES_CONVERSION; + return ModifyODMenuW(A2W(lpstrText),nID,fill,border,hatchstyle,pSize); +} + +BOOL BCMenu::ModifyODMenuW(wchar_t *lpstrText,UINT nID,COLORREF fill,COLORREF border,int hatchstyle,CSize *pSize) +{ + CWnd *pWnd = AfxGetMainWnd(); // Get main window + CDC *pDC = pWnd->GetDC(); // Get device context + SIZE sz; + if(!pSize){ + sz.cx = m_iconX; + sz.cy = m_iconY; + } + else{ + sz.cx = pSize->cx; + sz.cy = pSize->cy; + } + CSize bitmap_size(sz); + CSize icon_size(m_iconX,m_iconY); + CBitmap bmp; + ColorBitmap(pDC,bmp,bitmap_size,icon_size,fill,border,hatchstyle); + pWnd->ReleaseDC(pDC); + return ModifyODMenuW(lpstrText,nID,&bmp); +} + + +BOOL BCMenu::ModifyODMenuA(const char *lpstrText,const char *OptionText, + int nIconNormal) +{ + USES_CONVERSION; + return ModifyODMenuW(A2W(lpstrText),A2W(OptionText),nIconNormal);//SK: see MFC Tech Note 059 +} + +BOOL BCMenu::ModifyODMenuW(wchar_t *lpstrText,wchar_t *OptionText, + int nIconNormal) +{ + BCMenuData *mdata; + + // Find the old BCMenuData structure: + CString junk=OptionText; + mdata=FindMenuOption(OptionText); + if(mdata){ + if(lpstrText) + mdata->SetWideString(lpstrText);//SK: modified for dynamic allocation + mdata->menuIconNormal = nIconNormal; + mdata->xoffset=-1; + if(nIconNormal>=0){ + mdata->xoffset=0; + if(mdata->bitmap)mdata->bitmap->DeleteImageList(); + else mdata->bitmap=new(CImageList); + mdata->bitmap->Create(m_iconX,m_iconY,ILC_COLORDDB|ILC_MASK,1,1); + if(!AddBitmapToImageList(mdata->bitmap,nIconNormal)){ + mdata->bitmap->DeleteImageList(); + delete mdata->bitmap; + mdata->bitmap=NULL; + mdata->menuIconNormal = nIconNormal = -1; + mdata->xoffset = -1; + } + } + return(TRUE); + } + return(FALSE); +} + +BCMenuData *BCMenu::NewODMenu(UINT pos,UINT nFlags,UINT nID,CString string) +{ + BCMenuData *mdata; + + mdata = new BCMenuData; + mdata->menuIconNormal = -1; + mdata->xoffset=-1; +#ifdef UNICODE + mdata->SetWideString((LPCTSTR)string);//SK: modified for dynamic allocation +#else + mdata->SetAnsiString(string); +#endif + mdata->nFlags = nFlags; + mdata->nID = nID; + +// if(nFlags & MF_POPUP)m_AllSubMenus.Add((HMENU)nID); + + if (nFlags&MF_OWNERDRAW){ + ASSERT(!(nFlags&MF_STRING)); + ModifyMenu(pos,nFlags,nID,(LPCTSTR)mdata); + } + else if (nFlags&MF_STRING){ + ASSERT(!(nFlags&MF_OWNERDRAW)); + ModifyMenu(pos,nFlags,nID,mdata->GetString()); + } + else{ + ASSERT(nFlags&MF_SEPARATOR); + ModifyMenu(pos,nFlags,nID); + } + + return(mdata); +}; + +BOOL BCMenu::LoadToolbars(const UINT *arID,int n) +{ + ASSERT(arID); + BOOL returnflag=TRUE; + for(int i=0;i=0){ + bar.GetButtonInfo(xoffset,nID,nStyle,xset); + if(xset>0)xoffset=xset; + } + ModifyODMenu(NULL,nID,&imglist,xoffset); + } + } + } + } + return(returnflag); +} + +BOOL BCMenu::LoadFromToolBar(UINT nID,UINT nToolBar,int& xoffset) +{ + int xset,offset; + UINT nStyle; + BOOL returnflag=FALSE; + CToolBar bar; + + CWnd* pWnd = AfxGetMainWnd(); + if (pWnd == NULL)pWnd = CWnd::GetDesktopWindow(); + bar.Create(pWnd); + if(bar.LoadToolBar(nToolBar)){ + offset=bar.CommandToIndex(nID); + if(offset>=0){ + bar.GetButtonInfo(offset,nID,nStyle,xset); + if(xset>0)xoffset=xset; + returnflag=TRUE; + } + } + return(returnflag); +} + +// O.S. +BCMenuData *BCMenu::FindMenuItem(UINT nID) +{ + BCMenuData *pData = NULL; + int i; + + for(i = 0; i <= m_MenuList.GetUpperBound(); i++){ + if (m_MenuList[i]->nID == nID){ + pData = m_MenuList[i]; + break; + } + } + if (!pData){ + int loc; + BCMenu *pMenu = FindMenuOption(nID, loc); + ASSERT(pMenu != this); + if (loc >= 0){ + return pMenu->FindMenuItem(nID); + } + } + return pData; +} + + +BCMenu *BCMenu::FindAnotherMenuOption(int nId,int& nLoc,CArray&bcsubs, + CArray&bclocs) +{ + int i,numsubs,j; + BCMenu *psubmenu,*pgoodmenu; + BOOL foundflag; + + for(i=0;i<(int)(GetMenuItemCount());++i){ +#ifdef _CPPRTTI + psubmenu=dynamic_cast(GetSubMenu(i)); +#else + psubmenu=(BCMenu *)GetSubMenu(i); +#endif + if(psubmenu){ + pgoodmenu=psubmenu->FindAnotherMenuOption(nId,nLoc,bcsubs,bclocs); + if(pgoodmenu)return(pgoodmenu); + } + else if(nId==(int)GetMenuItemID(i)){ + numsubs=bcsubs.GetSize(); + foundflag=TRUE; + for(j=0;j(GetSubMenu(i)); +#else + psubmenu=(BCMenu *)GetSubMenu(i); +#endif + if(psubmenu){ + pgoodmenu=psubmenu->FindMenuOption(nId,nLoc); + if(pgoodmenu)return(pgoodmenu); + } + else if(nId==(int)GetMenuItemID(i)){ + nLoc=i; + return(this); + } + } + nLoc = -1; + return(NULL); +} + +BCMenuData *BCMenu::FindMenuOption(wchar_t *lpstrText) +{ + int i,j; + BCMenu *psubmenu; + BCMenuData *pmenulist; + + for(i=0;i<(int)(GetMenuItemCount());++i){ +#ifdef _CPPRTTI + psubmenu=dynamic_cast(GetSubMenu(i)); +#else + psubmenu=(BCMenu *)GetSubMenu(i); +#endif + if(psubmenu){ + pmenulist=psubmenu->FindMenuOption(lpstrText); + if(pmenulist)return(pmenulist); + } + else{ + const wchar_t *szWide;//SK: we use const to prevent misuse of this Ptr + for(j=0;j<=m_MenuList.GetUpperBound();++j){ + szWide = m_MenuList[j]->GetWideString (); + if(szWide && !wcscmp(lpstrText,szWide))//SK: modified for dynamic allocation + return(m_MenuList[j]); + } + } + } + return(NULL); +} + + +BOOL BCMenu::LoadMenu(int nResource) +{ + return(BCMenu::LoadMenu(MAKEINTRESOURCE(nResource))); +}; + +BOOL BCMenu::LoadMenu(LPCTSTR lpszResourceName) +{ + ASSERT_VALID(this); + ASSERT(lpszResourceName != NULL); + + // Find the Menu Resource: + HINSTANCE hInst = AfxFindResourceHandle(lpszResourceName,RT_MENU); + HRSRC hRsrc = ::FindResource(hInst,lpszResourceName,RT_MENU); + if (hRsrc == NULL){ + hInst = NULL; + hRsrc = ::FindResource(hInst,lpszResourceName,RT_MENU); + } + if(hRsrc == NULL)return FALSE; + + // Load the Menu Resource: + + HGLOBAL hGlobal = LoadResource(hInst, hRsrc); + if(hGlobal == NULL)return FALSE; + + // first destroy the menu if we're trying to loadmenu again + DestroyMenu(); + + // Attempt to create us as a menu... + if(!CMenu::CreateMenu())return FALSE; + + // Get Item template Header, and calculate offset of MENUITEMTEMPLATES + + MENUITEMTEMPLATEHEADER *pTpHdr= + (MENUITEMTEMPLATEHEADER*)LockResource(hGlobal); + BYTE* pTp=(BYTE*)pTpHdr + + (sizeof(MENUITEMTEMPLATEHEADER) + pTpHdr->offset); + + + // Variables needed during processing of Menu Item Templates: + + int j=0; + WORD dwFlags = 0; // Flags of the Menu Item + WORD dwID = 0; // ID of the Menu Item + UINT uFlags; // Actual Flags. + wchar_t *szCaption=NULL; + int nLen = 0; // Length of caption + CTypedPtrArray m_Stack; // Popup menu stack + CArray m_StackEnd; // Popup menu stack + m_Stack.Add(this); // Add it to this... + m_StackEnd.Add(FALSE); + + do{ + // Obtain Flags and (if necessary), the ID... + memcpy(&dwFlags, pTp, sizeof(WORD));pTp+=sizeof(WORD);// Obtain Flags + if(!(dwFlags & MF_POPUP)){ + memcpy(&dwID, pTp, sizeof(WORD)); // Obtain ID + pTp+=sizeof(WORD); + } + else dwID = 0; + + uFlags = (UINT)dwFlags; // Remove MF_END from the flags that will + if(uFlags & MF_END) // be passed to the Append(OD)Menu functions. + uFlags -= MF_END; + + // Obtain Caption (and length) + + nLen = 0; + szCaption=new wchar_t[wcslen((wchar_t *)pTp)+1]; + wcscpy(szCaption,(wchar_t *)pTp); + pTp=&pTp[(wcslen((wchar_t *)pTp)+1)*sizeof(wchar_t)];//modified SK + + // Handle popup menus first.... + + //WideCharToMultiByte + if(dwFlags & MF_POPUP){ + if(dwFlags & MF_END)m_StackEnd.SetAt(m_Stack.GetUpperBound(),TRUE); + BCMenu* pSubMenu = new BCMenu; + pSubMenu->m_unselectcheck=m_unselectcheck; + pSubMenu->m_selectcheck=m_selectcheck; + pSubMenu->checkmaps=checkmaps; + pSubMenu->checkmapsshare=TRUE; + pSubMenu->CreatePopupMenu(); + + // Append it to the top of the stack: + + m_Stack[m_Stack.GetUpperBound()]->AppendODMenuW(szCaption,uFlags, + (UINT)pSubMenu->m_hMenu, -1); + m_Stack.Add(pSubMenu); + m_StackEnd.Add(FALSE); + } + else { + m_Stack[m_Stack.GetUpperBound()]->AppendODMenuW(szCaption, uFlags, + dwID, -1); + if(dwFlags & MF_END)m_StackEnd.SetAt(m_Stack.GetUpperBound(),TRUE); + j = m_Stack.GetUpperBound(); + while(j>=0 && m_StackEnd.GetAt(j)){ + m_Stack[m_Stack.GetUpperBound()]->InsertSpaces(); + m_Stack.RemoveAt(j); + m_StackEnd.RemoveAt(j); + --j; + } + } + + delete[] szCaption; + }while(m_Stack.GetUpperBound() != -1); + + for(int i=0;i<(int)GetMenuItemCount();++i){ + CString str=m_MenuList[i]->GetString(); + if(GetSubMenu(i)){ + m_MenuList[i]->nFlags=MF_POPUP|MF_BYPOSITION; + ModifyMenu(i,MF_POPUP|MF_BYPOSITION, + (UINT)GetSubMenu(i)->m_hMenu,str); + } + else{ + m_MenuList[i]->nFlags=MF_STRING|MF_BYPOSITION; + ModifyMenu(i,MF_STRING|MF_BYPOSITION,m_MenuList[i]->nID,str); + } + } + + m_loadmenu=TRUE; + + return(TRUE); +} + +int BCMenu::GetMenuStart(void) +{ + if(!m_loadmenu)return(0); + + CString name,str; + int menuloc=-1,listloc=-1,menustart=0,i=0,j=0; + int nummenulist=m_MenuList.GetSize(); + int nummenu=(int)GetMenuItemCount(); + + while(i0){ + for(j=0;jGetString(); + if(name==str){ + menuloc=i; + listloc=j; + break; + } + } + } + ++i; + } + if(menuloc>=0&&listloc>=0&&menuloc>=listloc)menustart=menuloc-listloc; + return(menustart); +} + +void BCMenu::RemoveTopLevelOwnerDraw(void) +{ + CString str; + int i=0,j=0; + int nummenulist=m_MenuList.GetSize(),menustart; + + menustart=GetMenuStart(); + for(i=menustart,j=0;i<(int)GetMenuItemCount();++i,++j){ + if(jGetString(); + if(GetSubMenu(i)){ + m_MenuList[j]->nFlags=MF_POPUP|MF_BYPOSITION; + ModifyMenu(i,MF_POPUP|MF_BYPOSITION, + (UINT)GetSubMenu(i)->m_hMenu,str); + } + } + } + +} + +void BCMenu::InsertSpaces(void) +{ + if(IsLunaMenuStyle()) + if(!xp_space_accelerators)return; + else + if(!original_space_accelerators)return; + + int i,j,numitems,maxlength; + CString string,newstring; + CSize t; + CFont m_fontMenu; + LOGFONT m_lf; + + ZeroMemory ((PVOID) &m_lf,sizeof (LOGFONT)); + NONCLIENTMETRICS nm; + nm.cbSize = sizeof (NONCLIENTMETRICS); + VERIFY (SystemParametersInfo (SPI_GETNONCLIENTMETRICS,nm.cbSize,&nm,0)); + m_lf = nm.lfMenuFont; + m_fontMenu.CreateFontIndirect (&m_lf); + + CWnd *pWnd = AfxGetMainWnd(); + if (pWnd == NULL)pWnd = CWnd::GetDesktopWindow(); + CDC *pDC = pWnd->GetDC(); + CFont* pFont = pDC->SelectObject (&m_fontMenu); + + numitems=GetMenuItemCount(); + maxlength = -1; + for(i=0;iGetString(); + j=string.Find((char)9); + newstring.Empty(); + if(j!=-1)newstring=string.Left(j); + else newstring=string; + newstring+=_T(" ");//SK: modified for Unicode correctness. + LPCTSTR lpstrText = (LPCTSTR)newstring; + t=pDC->GetTextExtent(lpstrText,_tcslen(lpstrText)); + if(t.cx>maxlength)maxlength = t.cx; + } + for(i=0;iGetString(); + j=string.Find((char)9); + if(j!=-1){ + newstring.Empty(); + newstring=string.Left(j); + LPCTSTR lpstrText = (LPCTSTR)(newstring); + t=pDC->GetTextExtent(lpstrText,_tcslen(lpstrText)); + while(t.cxGetTextExtent(lpstrText,_tcslen(lpstrText)); + } + newstring+=string.Mid(j); +#ifdef UNICODE + m_MenuList[i]->SetWideString(newstring);//SK: modified for dynamic allocation +#else + m_MenuList[i]->SetAnsiString(newstring); +#endif + } + } + pDC->SelectObject (pFont); // Select old font in + pWnd->ReleaseDC(pDC); // Release the DC + m_fontMenu.DeleteObject(); +} + +void BCMenu::LoadCheckmarkBitmap(int unselect, int select) +{ + if(unselect>0 && select>0){ + m_selectcheck=select; + m_unselectcheck=unselect; + if(checkmaps)checkmaps->DeleteImageList(); + else checkmaps=new(CImageList); + checkmaps->Create(m_iconX,m_iconY,ILC_MASK,2,1); + BOOL flag1=AddBitmapToImageList(checkmaps,unselect); + BOOL flag2=AddBitmapToImageList(checkmaps,select); + if(!flag1||!flag2){ + checkmaps->DeleteImageList(); + delete checkmaps; + checkmaps=NULL; + } + } +} + +//-------------------------------------------------------------------------- +//[18.06.99 rj] +BOOL BCMenu::GetMenuText(UINT id, CString& string, UINT nFlags/*= MF_BYPOSITION*/) +{ + BOOL returnflag=FALSE; + + if(MF_BYPOSITION&nFlags){ + UINT numMenuItems = m_MenuList.GetUpperBound(); + if(id<=numMenuItems){ + string=m_MenuList[id]->GetString(); + returnflag=TRUE; + } + } + else{ + int uiLoc; + BCMenu* pMenu = FindMenuOption(id,uiLoc); + if(NULL!=pMenu) returnflag = pMenu->GetMenuText(uiLoc,string); + } + return(returnflag); +} + + +void BCMenu::DrawRadioDot(CDC *pDC,int x,int y,COLORREF color) +{ + CRect rcDot(x,y,x+6,y+6); + CBrush brush; + CPen pen; + brush.CreateSolidBrush(color); + pen.CreatePen(PS_SOLID,0,color); + CBrush *pOldBrush=pDC->SelectObject(&brush); + CPen *pOldPen=pDC->SelectObject(&pen); + pDC->Ellipse(&rcDot); + pDC->SelectObject(pOldBrush); + pDC->SelectObject(pOldPen); + pen.DeleteObject(); + brush.DeleteObject(); +} + +void BCMenu::DrawCheckMark(CDC* pDC,int x,int y,COLORREF color,BOOL narrowflag) +{ + int dp=0; + CPen m_penBack; + m_penBack.CreatePen (PS_SOLID,0,color); + CPen *pOldPen = pDC->SelectObject (&m_penBack); + if(narrowflag)dp=1; + + pDC->MoveTo(x,y+2); + pDC->LineTo(x,y+5-dp); + + pDC->MoveTo(x+1,y+3); + pDC->LineTo(x+1,y+6-dp); + + pDC->MoveTo(x+2,y+4); + pDC->LineTo(x+2,y+7-dp); + + pDC->MoveTo(x+3,y+3); + pDC->LineTo(x+3,y+6-dp); + + pDC->MoveTo(x+4,y+2); + pDC->LineTo(x+4,y+5-dp); + + pDC->MoveTo(x+5,y+1); + pDC->LineTo(x+5,y+4-dp); + + pDC->MoveTo(x+6,y); + pDC->LineTo(x+6,y+3-dp); + + pDC->SelectObject (pOldPen); + m_penBack.DeleteObject(); +} + +BCMenuData *BCMenu::FindMenuList(UINT nID) +{ + for(int i=0;i<=m_MenuList.GetUpperBound();++i){ + if(m_MenuList[i]->nID==nID && !m_MenuList[i]->syncflag){ + m_MenuList[i]->syncflag=1; + return(m_MenuList[i]); + } + } + return(NULL); +} + +void BCMenu::InitializeMenuList(int value) +{ + for(int i=0;i<=m_MenuList.GetUpperBound();++i) + m_MenuList[i]->syncflag=value; +} + +void BCMenu::DeleteMenuList(void) +{ + for(int i=0;i<=m_MenuList.GetUpperBound();++i){ + if(!m_MenuList[i]->syncflag){ + delete m_MenuList[i]; + } + } +} + +void BCMenu::SynchronizeMenu(void) +{ + CTypedPtrArray temp; + BCMenuData *mdata; + CString string; + UINT submenu,nID=0,state,j; + + InitializeMenuList(0); + for(j=0;jm_hMenu; + mdata=FindMenuList(submenu); + GetMenuString(j,string,MF_BYPOSITION); + if(!mdata)mdata=NewODMenu(j, + (state&0xFF)|MF_BYPOSITION|MF_POPUP|MF_OWNERDRAW,submenu,string); + else if(string.GetLength()>0) +#ifdef UNICODE + mdata->SetWideString(string); //SK: modified for dynamic allocation +#else + mdata->SetAnsiString(string); +#endif + } + else if(state&MF_SEPARATOR){ + mdata=FindMenuList(0); + if(!mdata)mdata=NewODMenu(j, + state|MF_BYPOSITION|MF_SEPARATOR|MF_OWNERDRAW,0,_T(""));//SK: modified for Unicode correctness + else ModifyMenu(j,mdata->nFlags,nID,(LPCTSTR)mdata); + } + else{ + nID=GetMenuItemID(j); + mdata=FindMenuList(nID); + GetMenuString(j,string,MF_BYPOSITION); + if(!mdata)mdata=NewODMenu(j,state|MF_BYPOSITION|MF_OWNERDRAW, + nID,string); + else{ + mdata->nFlags=state|MF_BYPOSITION|MF_OWNERDRAW; + if(string.GetLength()>0) +#ifdef UNICODE + mdata->SetWideString(string);//SK: modified for dynamic allocation +#else + mdata->SetAnsiString(string); +#endif + + ModifyMenu(j,mdata->nFlags,nID,(LPCTSTR)mdata); + } + } + if(mdata)temp.Add(mdata); + } + DeleteMenuList(); + m_MenuList.RemoveAll(); + m_MenuList.Append(temp); + temp.RemoveAll(); +} + +void BCMenu::UpdateMenu(CMenu *pmenu) +{ +#ifdef _CPPRTTI + BCMenu *psubmenu = dynamic_cast(pmenu); +#else + BCMenu *psubmenu = (BCMenu *)pmenu; +#endif + if(psubmenu)psubmenu->SynchronizeMenu(); +} + +LRESULT BCMenu::FindKeyboardShortcut(UINT nChar, UINT nFlags, + CMenu *pMenu) +{ +#ifdef _CPPRTTI + BCMenu *pBCMenu = dynamic_cast(pMenu); +#else + BCMenu *pBCMenu = (BCMenu *)pMenu; +#endif + if(pBCMenu && nFlags&MF_POPUP){ + CString key(_T('&'),2);//SK: modified for Unicode correctness + key.SetAt(1,(TCHAR)nChar); + key.MakeLower(); + CString menutext; + int menusize = (int)pBCMenu->GetMenuItemCount(); + if(menusize!=(pBCMenu->m_MenuList.GetUpperBound()+1)) + pBCMenu->SynchronizeMenu(); + for(int i=0;iGetMenuText(i,menutext)){ + menutext.MakeLower(); + if(menutext.Find(key)>=0)return(MAKELRESULT(i,2)); + } + } + } + return(0); +} + +void BCMenu::DitherBlt (HDC hdcDest, int nXDest, int nYDest, int nWidth, + int nHeight, HBITMAP hbm, int nXSrc, int nYSrc, + COLORREF bgcolor) +{ + ASSERT(hdcDest && hbm); + ASSERT(nWidth > 0 && nHeight > 0); + + // Create a generic DC for all BitBlts + HDC hDC = CreateCompatibleDC(hdcDest); + ASSERT(hDC); + + if (hDC) + { + // Create a DC for the monochrome DIB section + HDC bwDC = CreateCompatibleDC(hDC); + ASSERT(bwDC); + + if (bwDC) + { + // Create the monochrome DIB section with a black and white palette + struct { + BITMAPINFOHEADER bmiHeader; + RGBQUAD bmiColors[2]; + } RGBBWBITMAPINFO = { + + { // a BITMAPINFOHEADER + sizeof(BITMAPINFOHEADER), // biSize + nWidth, // biWidth; + nHeight, // biHeight; + 1, // biPlanes; + 1, // biBitCount + BI_RGB, // biCompression; + 0, // biSizeImage; + 0, // biXPelsPerMeter; + 0, // biYPelsPerMeter; + 0, // biClrUsed; + 0 // biClrImportant; + }, + { + { 0x00, 0x00, 0x00, 0x00 }, { 0xFF, 0xFF, 0xFF, 0x00 } + } + }; + VOID *pbitsBW; + HBITMAP hbmBW = CreateDIBSection(bwDC, + (LPBITMAPINFO)&RGBBWBITMAPINFO, DIB_RGB_COLORS, &pbitsBW, NULL, 0); + ASSERT(hbmBW); + + if (hbmBW) + { + // Attach the monochrome DIB section and the bitmap to the DCs + HBITMAP olddib = (HBITMAP)SelectObject(bwDC, hbmBW); + HBITMAP hdcolddib = (HBITMAP)SelectObject(hDC, hbm); + + // BitBlt the bitmap into the monochrome DIB section + BitBlt(bwDC, 0, 0, nWidth, nHeight, hDC, nXSrc, nYSrc, SRCCOPY); + + // Paint the destination rectangle in gray + FillRect(hdcDest, CRect(nXDest, nYDest, nXDest + nWidth, nYDest + + nHeight), GetSysColorBrush(bgcolor)); + //SK: looks better on the old shell + // BitBlt the black bits in the monochrome bitmap into COLOR_3DHILIGHT + // bits in the destination DC + // The magic ROP comes from the Charles Petzold's book + HBRUSH hb = CreateSolidBrush(GetSysColor(COLOR_3DHILIGHT)); + HBRUSH oldBrush = (HBRUSH)SelectObject(hdcDest, hb); + BitBlt(hdcDest,nXDest+1,nYDest+1,nWidth,nHeight,bwDC,0,0,0xB8074A); + + // BitBlt the black bits in the monochrome bitmap into COLOR_3DSHADOW + // bits in the destination DC + hb = CreateSolidBrush(GetSysColor(COLOR_3DSHADOW)); + DeleteObject(SelectObject(hdcDest, hb)); + BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight,bwDC,0,0,0xB8074A); + DeleteObject(SelectObject(hdcDest, oldBrush)); + VERIFY(DeleteObject(SelectObject(bwDC, olddib))); + SelectObject(hDC, hdcolddib); + } + + VERIFY(DeleteDC(bwDC)); + } + + VERIFY(DeleteDC(hDC)); + } +} + +void BCMenu::GetFadedBitmap(CBitmap &bmp) +{ + CDC ddc; + COLORREF bgcol,col; + BITMAP BitMap; + + bmp.GetBitmap(&BitMap); + ddc.CreateCompatibleDC(NULL); + CBitmap * pddcOldBmp = ddc.SelectObject(&bmp); + + // use this to get the background color, takes into account color shifting + CDC ddc2; + CBrush brush; + CBitmap bmp2; + ddc2.CreateCompatibleDC(NULL); + bmp2.CreateCompatibleBitmap(&ddc,BitMap.bmWidth,BitMap.bmHeight); + col=GetSysColor(COLOR_3DFACE); + brush.CreateSolidBrush(col); + CBitmap * pddcOldBmp2 = ddc2.SelectObject(&bmp2); + CRect rect(0,0,BitMap.bmWidth,BitMap.bmHeight); + ddc2.FillRect(rect,&brush); + bgcol=ddc2.GetPixel(1,1); + brush.DeleteObject(); + ddc2.SelectObject(pddcOldBmp2); + + for(int i=0;iAdd((HICON)nResourceID); + bReturn=TRUE; + } + else{ + HBITMAP hbmp=LoadSysColorBitmap(nResourceID); + if(hbmp){ + CBitmap bmp; + bmp.Attach(hbmp); + if(m_bitmapBackgroundFlag){ + if(bmplist->Add(&bmp,m_bitmapBackground)>=0)bReturn=TRUE; + } + else{ + if(bmplist->Add(&bmp,GetSysColor(COLOR_3DFACE))>=0)bReturn=TRUE; + } + bmp.Detach(); + DeleteObject(hbmp); + } + else{ // a hicolor bitmap + CBitmap mybmp; + if(mybmp.LoadBitmap(nResourceID)){ + hicolor_bitmaps=TRUE; + GetTransparentBitmap(mybmp); + if(m_bitmapBackgroundFlag){ + if(bmplist->Add(&mybmp,m_bitmapBackground)>=0)bReturn=TRUE; + } + else{ + if(bmplist->Add(&mybmp,GetSysColor(COLOR_3DFACE))>=0)bReturn=TRUE; + } + } + } + } + if(bReturn&&IsLunaMenuStyle()&&xp_draw_3D_bitmaps){ + CWnd *pWnd = AfxGetMainWnd(); // Get main window + if (pWnd == NULL) pWnd = CWnd::GetDesktopWindow(); + CDC *pDC = pWnd->GetDC(); // Get device context + CBitmap bmp,bmp2,bmp3; + GetBitmapFromImageList(pDC,bmplist,0,bmp); + GetFadedBitmap(bmp); + bmplist->Add(&bmp,GetSysColor(COLOR_3DFACE)); + GetBitmapFromImageList(pDC,bmplist,0,bmp2); + GetShadowBitmap(bmp2); + bmplist->Add(&bmp2,GetSysColor(COLOR_3DFACE)); + GetBitmapFromImageList(pDC,bmplist,0,bmp3); + GetDisabledBitmap(bmp3); + bmplist->Add(&bmp3,GetSysColor(COLOR_3DFACE)); + pWnd->ReleaseDC(pDC); // Release the DC + } + return(bReturn); +} + +void BCMenu::SetBitmapBackground(COLORREF color) +{ + m_bitmapBackground=color; + m_bitmapBackgroundFlag=TRUE; +} + +void BCMenu::UnSetBitmapBackground(void) +{ + m_bitmapBackgroundFlag=FALSE; +} + +// Given a toolbar, append all the options from it to this menu +// Passed a ptr to the toolbar object and the toolbar ID +// Author : Robert Edward Caldecott +void BCMenu::AddFromToolBar(CToolBar* pToolBar, int nResourceID) +{ + for (int i = 0; i < pToolBar->GetCount(); i++) { + UINT nID = pToolBar->GetItemID(i); + // See if this toolbar option + // appears as a command on this + // menu or is a separator + if (nID == 0 || GetMenuState(nID, MF_BYCOMMAND) == 0xFFFFFFFF) + continue; // Item doesn't exist + UINT nStyle; + int nImage; + // Get the toolbar button info + pToolBar->GetButtonInfo(i, nID, nStyle, nImage); + // OK, we have the command ID of the toolbar + // option, and the tollbar bitmap offset + int nLoc; + BCMenuData* pData; + BCMenu *pSubMenu = FindMenuOption(nID, nLoc); + if (pSubMenu && nLoc >= 0)pData = pSubMenu->m_MenuList[nLoc]; + else { + // Create a new BCMenuData structure + pData = new BCMenuData; + m_MenuList.Add(pData); + } + // Set some default structure members + pData->menuIconNormal = nResourceID; + pData->nID = nID; + pData->nFlags = MF_BYCOMMAND | MF_OWNERDRAW; + pData->xoffset = nImage; + if (pData->bitmap)pData->bitmap->DeleteImageList(); + else pData->bitmap = new CImageList; + pData->bitmap->Create(m_iconX, m_iconY,ILC_COLORDDB|ILC_MASK, 1, 1); + + if(!AddBitmapToImageList(pData->bitmap, nResourceID)){ + pData->bitmap->DeleteImageList(); + delete pData->bitmap; + pData->bitmap=NULL; + pData->menuIconNormal = -1; + pData->xoffset = -1; + } + + // Modify our menu + ModifyMenu(nID,pData->nFlags,nID,(LPCTSTR)pData); + } +} + +BOOL BCMenu::Draw3DCheckmark(CDC *dc, const CRect& rc, + BOOL bSelected, HBITMAP hbmCheck) +{ + CRect rcDest = rc; + CBrush brush; + COLORREF col; + if(IsWinXPLuna())col=GetSysColor(COLOR_3DFACE); + else col=GetSysColor(COLOR_MENU); + if(!bSelected)col = LightenColor(col,0.6); + brush.CreateSolidBrush(col); + dc->FillRect(rcDest,&brush); + brush.DeleteObject(); + if (IsNewShell()) //SK: looks better on the old shell + dc->DrawEdge(&rcDest, BDR_SUNKENOUTER, BF_RECT); + if (!hbmCheck)DrawCheckMark(dc,rc.left+4,rc.top+4,GetSysColor(COLOR_MENUTEXT)); + else DrawRadioDot(dc,rc.left+5,rc.top+4,GetSysColor(COLOR_MENUTEXT)); + return TRUE; +} + +BOOL BCMenu::DrawXPCheckmark(CDC *dc, const CRect& rc, HBITMAP hbmCheck,COLORREF &colorout,BOOL selected) +{ + CBrush brushin; + COLORREF col; + int dx,dy; + dy = (rc.Height()>>1)-3; + dy = dy<0 ? 0 : dy; + dx = (rc.Width()>>1)-3; + dx = dx<0 ? 0 : dx; + + if(selected) col = LightenColor(colorout,0.55); + else col = LightenColor(colorout,0.85); + brushin.CreateSolidBrush(col); + dc->FillRect(rc,&brushin); + brushin.DeleteObject(); + dc->Draw3dRect (rc,colorout,colorout); + + if (!hbmCheck)DrawCheckMark(dc,rc.left+dx,rc.top+dy,GetSysColor(COLOR_MENUTEXT),TRUE); + else DrawRadioDot(dc,rc.left+dx,rc.top+dy,GetSysColor(COLOR_MENUTEXT)); + return TRUE; +} + +void BCMenu::DitherBlt2(CDC *drawdc, int nXDest, int nYDest, int nWidth, + int nHeight, CBitmap &bmp, int nXSrc, int nYSrc, + COLORREF bgcolor) +{ + // create a monochrome memory DC + CDC ddc; + ddc.CreateCompatibleDC(0); + CBitmap bwbmp; + bwbmp.CreateCompatibleBitmap(&ddc, nWidth, nHeight); + CBitmap * pddcOldBmp = ddc.SelectObject(&bwbmp); + + CDC dc; + dc.CreateCompatibleDC(0); + CBitmap * pdcOldBmp = dc.SelectObject(&bmp); + + // build a mask + ddc.PatBlt(0, 0, nWidth, nHeight, WHITENESS); + dc.SetBkColor(GetSysColor(COLOR_BTNFACE)); + ddc.BitBlt(0, 0, nWidth, nHeight, &dc, nXSrc,nYSrc, SRCCOPY); + dc.SetBkColor(GetSysColor(COLOR_BTNHILIGHT)); + ddc.BitBlt(0, 0, nWidth, nHeight, &dc, nXSrc,nYSrc, SRCPAINT); + + // Copy the image from the toolbar into the memory DC + // and draw it (grayed) back into the toolbar. + dc.FillSolidRect(0,0, nWidth, nHeight, bgcolor); + //SK: Looks better on the old shell + dc.SetBkColor(RGB(0, 0, 0)); + dc.SetTextColor(RGB(255, 255, 255)); + CBrush brShadow, brHilight; + brHilight.CreateSolidBrush(GetSysColor(COLOR_BTNHILIGHT)); + brShadow.CreateSolidBrush(GetSysColor(COLOR_BTNSHADOW)); + CBrush * pOldBrush = dc.SelectObject(&brHilight); + dc.BitBlt(0,0, nWidth, nHeight, &ddc, 0, 0, 0x00E20746L); + drawdc->BitBlt(nXDest+1,nYDest+1,nWidth, nHeight, &dc,0,0,SRCCOPY); + dc.BitBlt(1,1, nWidth, nHeight, &ddc, 0, 0, 0x00E20746L); + dc.SelectObject(&brShadow); + dc.BitBlt(0,0, nWidth, nHeight, &ddc, 0, 0, 0x00E20746L); + drawdc->BitBlt(nXDest,nYDest,nWidth, nHeight, &dc,0,0,SRCCOPY); + // reset DCs + ddc.SelectObject(pddcOldBmp); + ddc.DeleteDC(); + dc.SelectObject(pOldBrush); + dc.SelectObject(pdcOldBmp); + dc.DeleteDC(); + + brShadow.DeleteObject(); + brHilight.DeleteObject(); + bwbmp.DeleteObject(); +} + +void BCMenu::DitherBlt3(CDC *drawdc, int nXDest, int nYDest, int nWidth, + int nHeight, CBitmap &bmp,COLORREF bgcolor) +{ + GetDisabledBitmap(bmp,bgcolor); + CDC dc; + dc.CreateCompatibleDC(NULL); + CBitmap * pdcOldBmp = dc.SelectObject(&bmp); + drawdc->BitBlt(nXDest,nYDest,nWidth, nHeight, &dc,0,0,SRCCOPY); + // reset DCs + dc.SelectObject(pdcOldBmp); + dc.DeleteDC(); +} + +void BCMenu::SetDisableOldStyle(void) +{ + disable_old_style=TRUE; +} + +void BCMenu::UnSetDisableOldStyle(void) +{ + disable_old_style=FALSE; +} + +BOOL BCMenu::GetDisableOldStyle(void) +{ + return(disable_old_style); +} + + +WORD BCMenu::NumBitmapColors(LPBITMAPINFOHEADER lpBitmap) +{ + if ( lpBitmap->biClrUsed != 0) + return (WORD)lpBitmap->biClrUsed; + + switch (lpBitmap->biBitCount){ + case 1: + return 2; + case 4: + return 16; + case 8: + return 256; + default: + return 0; + } + return 0; +} + +HBITMAP BCMenu::LoadSysColorBitmap(int nResourceId) +{ + HINSTANCE hInst = + AfxFindResourceHandle(MAKEINTRESOURCE(nResourceId),RT_BITMAP); + HRSRC hRsrc = + ::FindResource(hInst,MAKEINTRESOURCE(nResourceId),RT_BITMAP); + if (hRsrc == NULL){ + hInst = NULL; + hRsrc = ::FindResource(hInst,MAKEINTRESOURCE(nResourceId),RT_BITMAP); + } + if (hRsrc == NULL)return NULL; + + // determine how many colors in the bitmap + HGLOBAL hglb; + if ((hglb = LoadResource(hInst, hRsrc)) == NULL) + return NULL; + LPBITMAPINFOHEADER lpBitmap = (LPBITMAPINFOHEADER)LockResource(hglb); + if (lpBitmap == NULL)return NULL; + WORD numcol = NumBitmapColors(lpBitmap); + ::FreeResource(hglb); + + if(numcol!=16)return(NULL); + + return AfxLoadSysColorBitmap(hInst, hRsrc, FALSE); +} + +BOOL BCMenu::RemoveMenu(UINT uiId,UINT nFlags) +{ + if(MF_BYPOSITION&nFlags){ + UINT uint = GetMenuState(uiId,MF_BYPOSITION); + if(uint&MF_SEPARATOR && !(uint&MF_POPUP)){ + delete m_MenuList.GetAt(uiId); + m_MenuList.RemoveAt(uiId); + } + else{ + BCMenu* pSubMenu = (BCMenu*) GetSubMenu(uiId); + if(NULL==pSubMenu){ + UINT uiCommandId = GetMenuItemID(uiId); + for(int i=0;inID==uiCommandId){ + delete m_MenuList.GetAt(i); + m_MenuList.RemoveAt(i); + break; + } + } + } + else{ + int numSubMenus = m_SubMenus.GetUpperBound(); + for(int m = numSubMenus; m >= 0; m--){ + if(m_SubMenus[m]==pSubMenu->m_hMenu){ + int numAllSubMenus = m_AllSubMenus.GetUpperBound(); + for(int n = numAllSubMenus; n>= 0; n--){ + if(m_AllSubMenus[n]==m_SubMenus[m])m_AllSubMenus.RemoveAt(n); + } + m_SubMenus.RemoveAt(m); + } + } + int num = pSubMenu->GetMenuItemCount(); + for(int i=num-1;i>=0;--i)pSubMenu->RemoveMenu(i,MF_BYPOSITION); + for(i=m_MenuList.GetUpperBound();i>=0;i--){ + if(m_MenuList[i]->nID==(UINT)pSubMenu->m_hMenu){ + delete m_MenuList.GetAt(i); + m_MenuList.RemoveAt(i); + break; + } + } + delete pSubMenu; + } + } + } + else{ + int iPosition =0; + BCMenu* pMenu = FindMenuOption(uiId,iPosition); + // bug fix RIA 14th September 2000 + // failed to return correct value on call to remove menu as the item was + // removed twice. The second time its not found + // so a value of 0 was being returned + if(pMenu) return pMenu->RemoveMenu(iPosition,MF_BYPOSITION); // added return + } + return CMenu::RemoveMenu(uiId,nFlags); +} + +BOOL BCMenu::DeleteMenu(UINT uiId,UINT nFlags) +{ + if(MF_BYPOSITION&nFlags){ + UINT uint = GetMenuState(uiId,MF_BYPOSITION); + if(uint&MF_SEPARATOR && !(uint&MF_POPUP)){ + // make sure it's a separator + int menulistsize=m_MenuList.GetSize(); + if(uiId<(UINT)menulistsize){ + CString str=m_MenuList[uiId]->GetString(); + if(str==""){ + delete m_MenuList.GetAt(uiId); + m_MenuList.RemoveAt(uiId); + } + } + } + else{ + BCMenu* pSubMenu = (BCMenu*) GetSubMenu(uiId); + if(NULL==pSubMenu){ + UINT uiCommandId = GetMenuItemID(uiId); + for(int i=0;inID==uiCommandId){ + delete m_MenuList.GetAt(i); + m_MenuList.RemoveAt(i); + break; + } + } + } + else{ + int numSubMenus = m_SubMenus.GetUpperBound(); + for(int m = numSubMenus; m >= 0; m--){ + if(m_SubMenus[m]==pSubMenu->m_hMenu){ + int numAllSubMenus = m_AllSubMenus.GetUpperBound(); + for(int n = numAllSubMenus; n>= 0; n--){ + if(m_AllSubMenus[n]==m_SubMenus[m])m_AllSubMenus.RemoveAt(n); + } + m_SubMenus.RemoveAt(m); + } + } + int num = pSubMenu->GetMenuItemCount(); + for(int i=num-1;i>=0;--i)pSubMenu->DeleteMenu(i,MF_BYPOSITION); + for(i=m_MenuList.GetUpperBound();i>=0;i--){ + if(m_MenuList[i]->nID==(UINT)pSubMenu->m_hMenu){ + delete m_MenuList.GetAt(i); + m_MenuList.RemoveAt(i); + break; + } + } + delete pSubMenu; + } + } + } + else{ + int iPosition =0; + BCMenu* pMenu = FindMenuOption(uiId,iPosition); + if(pMenu)return pMenu->DeleteMenu(iPosition,MF_BYPOSITION); + } + + return(CMenu::DeleteMenu(uiId,nFlags)); +} + + +BOOL BCMenu::AppendMenuA(UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,int nIconNormal) +{ + USES_CONVERSION; + return AppendMenuW(nFlags,nIDNewItem,A2W(lpszNewItem),nIconNormal); +} + +BOOL BCMenu::AppendMenuW(UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,int nIconNormal) +{ + return AppendODMenuW(lpszNewItem,nFlags,nIDNewItem,nIconNormal); +} + +BOOL BCMenu::AppendMenuA(UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,CImageList *il,int xoffset) +{ + USES_CONVERSION; + return AppendMenuW(nFlags,nIDNewItem,A2W(lpszNewItem),il,xoffset); +} + +BOOL BCMenu::AppendMenuW(UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,CImageList *il,int xoffset) +{ + return AppendODMenuW(lpszNewItem,nFlags,nIDNewItem,il,xoffset); +} + +BOOL BCMenu::AppendMenuA(UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,CBitmap *bmp) +{ + USES_CONVERSION; + return AppendMenuW(nFlags,nIDNewItem,A2W(lpszNewItem),bmp); +} + +BOOL BCMenu::AppendMenuW(UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,CBitmap *bmp) +{ + if(bmp){ + CImageList temp; + temp.Create(m_iconX,m_iconY,ILC_COLORDDB|ILC_MASK,1,1); + if(m_bitmapBackgroundFlag)temp.Add(bmp,m_bitmapBackground); + else temp.Add(bmp,GetSysColor(COLOR_3DFACE)); + return AppendODMenuW(lpszNewItem,nFlags,nIDNewItem,&temp,0); + } + return AppendODMenuW(lpszNewItem,nFlags,nIDNewItem,NULL,0); +} + +BOOL BCMenu::InsertMenuA(UINT nPosition,UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,int nIconNormal) +{ + USES_CONVERSION; + return InsertMenuW(nPosition,nFlags,nIDNewItem,A2W(lpszNewItem),nIconNormal); +} + +BOOL BCMenu::InsertMenuW(UINT nPosition,UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,int nIconNormal) +{ + return InsertODMenuW(nPosition,lpszNewItem,nFlags,nIDNewItem,nIconNormal); +} + +BOOL BCMenu::InsertMenuA(UINT nPosition,UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,CImageList *il,int xoffset) +{ + USES_CONVERSION; + return InsertMenuW(nPosition,nFlags,nIDNewItem,A2W(lpszNewItem),il,xoffset); +} + +BOOL BCMenu::InsertMenuW(UINT nPosition,UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,CImageList *il,int xoffset) +{ + return InsertODMenuW(nPosition,lpszNewItem,nFlags,nIDNewItem,il,xoffset); +} + +BOOL BCMenu::InsertMenuA(UINT nPosition,UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,CBitmap *bmp) +{ + USES_CONVERSION; + return InsertMenuW(nPosition,nFlags,nIDNewItem,A2W(lpszNewItem),bmp); +} + +BOOL BCMenu::InsertMenuW(UINT nPosition,UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,CBitmap *bmp) +{ + if(bmp){ + CImageList temp; + temp.Create(m_iconX,m_iconY,ILC_COLORDDB|ILC_MASK,1,1); + if(m_bitmapBackgroundFlag)temp.Add(bmp,m_bitmapBackground); + else temp.Add(bmp,GetSysColor(COLOR_3DFACE)); + return InsertODMenuW(nPosition,lpszNewItem,nFlags,nIDNewItem,&temp,0); + } + return InsertODMenuW(nPosition,lpszNewItem,nFlags,nIDNewItem,NULL,0); +} + +//-------------------------------------------------------------------------- +//[21.06.99 rj] +BCMenu* BCMenu::AppendODPopupMenuW(wchar_t *lpstrText) +{ + BCMenu* pSubMenu = new BCMenu; + pSubMenu->m_unselectcheck=m_unselectcheck; + pSubMenu->m_selectcheck=m_selectcheck; + pSubMenu->checkmaps=checkmaps; + pSubMenu->checkmapsshare=TRUE; + pSubMenu->CreatePopupMenu(); + AppendODMenuW(lpstrText,MF_POPUP,(UINT)pSubMenu->m_hMenu, -1); + return pSubMenu; +} + +//-------------------------------------------------------------------------- +//[21.06.99 rj] +BCMenu* BCMenu::AppendODPopupMenuA(LPCSTR lpstrText) +{ + USES_CONVERSION; + return AppendODPopupMenuW(A2W(lpstrText)); +} + +BOOL BCMenu::ImageListDuplicate(CImageList *il,int xoffset,CImageList *newlist) +{ + if (il == NULL||newlist==NULL||xoffset<0) return FALSE; + HICON hIcon = il->ExtractIcon(xoffset); + int cx, cy; + ImageList_GetIconSize(il->m_hImageList, &cx, &cy); + newlist->Create(cx,cy,ILC_COLORDDB|ILC_MASK,1,1); + newlist->Add(hIcon); + ::DestroyIcon(hIcon); + if(IsLunaMenuStyle()&&xp_draw_3D_bitmaps){ + CWnd *pWnd = AfxGetMainWnd(); // Get main window + if (pWnd == NULL) pWnd = CWnd::GetDesktopWindow(); + CDC *pDC = pWnd->GetDC(); // Get device context + CBitmap bmp,bmp2,bmp3; + GetBitmapFromImageList(pDC,newlist,0,bmp); + GetFadedBitmap(bmp); + newlist->Add(&bmp,GetSysColor(COLOR_3DFACE)); + GetBitmapFromImageList(pDC,newlist,0,bmp2); + GetShadowBitmap(bmp2); + newlist->Add(&bmp2,GetSysColor(COLOR_3DFACE)); + GetBitmapFromImageList(pDC,newlist,0,bmp3); + GetDisabledBitmap(bmp3); + newlist->Add(&bmp3,GetSysColor(COLOR_3DFACE)); + pWnd->ReleaseDC(pDC); // Release the DC + } + return TRUE; +} + +// 2001-07-12, Damir Valiulin: +// Added GetSubMenu (LPCTSTR lpszSubMenuName) function +// + +CMenu* BCMenu::GetSubMenu(int nPos) +{ + return CMenu::GetSubMenu (nPos); +} + +CMenu* BCMenu::GetSubMenu(LPCTSTR lpszSubMenuName) +{ + int num = GetMenuItemCount (); + CString name; + + for (int i=0; inID; + CMenu *ptr=FromHandle(bchmenu); + BOOL flag=ptr->IsKindOf(RUNTIME_CLASS( BCMenu )); + if(flag)return((BCMenu *)ptr); + } + return NULL; +} + + +// Tongzhe Cui, Functions to remove a popup menu based on its name. Seperators +// before and after the popup menu can also be removed if they exist. +int BCMenu::GetMenuPosition(char* pText) +{ + USES_CONVERSION; + return GetMenuPosition(A2W(pText)); +} + +int BCMenu::GetMenuPosition(wchar_t* pText) +{ + int i,j; + BCMenu* psubmenu; + for(i=0;i<(int)(GetMenuItemCount());++i) + { + psubmenu=(BCMenu *)GetSubMenu(i); + if(!psubmenu) + { + const wchar_t *szWide;//SK: we use const to prevent misuse of this Ptr + for(j=0;j<=m_MenuList.GetUpperBound();++j) + { + szWide = m_MenuList[j]->GetWideString (); + if(szWide && !wcscmp(pText,szWide))//SK: modified for dynamic allocation + return j; + } + } + } + // means no found; + return -1; +} + +int BCMenu::RemoveMenu(char* pText, BC_Seperator sPos) +{ + USES_CONVERSION; + return RemoveMenu(A2W(pText), sPos); +} + +int BCMenu::RemoveMenu(wchar_t* pText, BC_Seperator sPos) +{ + int nPos = GetMenuPosition(pText); + if(nPos != -1) + { + RemoveMenu(nPos, MF_BYPOSITION); + } + if(sPos == BCMENU_HEAD) + { + ASSERT(nPos - 1 >= 0); + RemoveMenu(nPos-1, MF_BYPOSITION); + } + else if(sPos == BCMENU_TAIL) + { + RemoveMenu(nPos-1, MF_BYPOSITION); + } + else if(sPos == BCMENU_BOTH) + { + // remove the end first; + RemoveMenu(nPos-1, MF_BYPOSITION); + // remove the head; + ASSERT(nPos - 1 >= 0); + RemoveMenu(nPos-1, MF_BYPOSITION); + } + return nPos; +} + +int BCMenu::DeleteMenu(char* pText, BC_Seperator sPos) +{ + USES_CONVERSION; + return DeleteMenu(A2W(pText), sPos); +} + +int BCMenu::DeleteMenu(wchar_t* pText, BC_Seperator sPos) +{ + int nPos = GetMenuPosition(pText); + if(nPos != -1) + { + DeleteMenu(nPos, MF_BYPOSITION); + } + if(sPos == BCMENU_HEAD) + { + ASSERT(nPos - 1 >= 0); + DeleteMenu(nPos-1, MF_BYPOSITION); + } + else if(sPos == BCMENU_TAIL) + { + DeleteMenu(nPos-1, MF_BYPOSITION); + } + else if(sPos == BCMENU_BOTH) + { + // remove the end first; + DeleteMenu(nPos-1, MF_BYPOSITION); + // remove the head; + ASSERT(nPos - 1 >= 0); + DeleteMenu(nPos-1, MF_BYPOSITION); + } + return nPos; +} + +// Larry Antram +BOOL BCMenu::SetMenuText(UINT id, CString string, UINT nFlags/*= MF_BYPOSITION*/ ) +{ + BOOL returnflag=FALSE; + + if(MF_BYPOSITION&nFlags) + { + UINT numMenuItems = m_MenuList.GetUpperBound(); + if(id<=numMenuItems){ +#ifdef UNICODE + m_MenuList[id]->SetWideString((LPCTSTR)string); +#else + m_MenuList[id]->SetAnsiString(string); +#endif + returnflag=TRUE; + } + } + else{ + int uiLoc; + BCMenu* pMenu = FindMenuOption(id,uiLoc); + if(NULL!=pMenu) returnflag = pMenu->SetMenuText(uiLoc,string); + } + return(returnflag); +} + +// courtesy of Warren Stevens +void BCMenu::ColorBitmap(CDC* pDC,CBitmap& bmp,CSize bitmap_size,CSize icon_size,COLORREF fill,COLORREF border,int hatchstyle) +{ + CDC bmpdc; + COLORREF m_newclrBack; + int x1=0,y1=0,x2=bitmap_size.cx,y2=bitmap_size.cy; + + if(IsWinXPLuna())m_newclrBack=GetSysColor(COLOR_3DFACE); + else m_newclrBack=GetSysColor(COLOR_MENU); + + bmpdc.CreateCompatibleDC(pDC); + + bmp.CreateCompatibleBitmap(pDC, icon_size.cx, icon_size.cy); + CBitmap* pOldBitmap = bmpdc.SelectObject(&bmp); + + if(bitmap_size!=icon_size){ + CBrush background_brush; + background_brush.CreateSolidBrush(m_newclrBack); + CRect rect(0,0, icon_size.cx, icon_size.cy); + bmpdc.FillRect(rect,&background_brush); + x1 = (icon_size.cx-bitmap_size.cx)/2; + y1 = (icon_size.cy-bitmap_size.cy)/2; + x2 = x1+bitmap_size.cx; + y2 = y1+bitmap_size.cy; + background_brush.DeleteObject(); + } + + CPen border_pen(PS_SOLID, 1, border); + CBrush fill_brush; + if(hatchstyle!=-1) { fill_brush.CreateHatchBrush(hatchstyle, fill); } + else { fill_brush.CreateSolidBrush(fill); } + + CPen* pOldPen = bmpdc.SelectObject(&border_pen); + CBrush* pOldBrush = bmpdc.SelectObject(&fill_brush); + + bmpdc.Rectangle(x1,y1,x2,y2); + + if(NULL!=pOldBrush) { bmpdc.SelectObject(pOldBrush); } + if(NULL!=pOldPen) { bmpdc.SelectObject(pOldPen); } + if(NULL!=pOldBitmap) { bmpdc.SelectObject(pOldBitmap); } +} + +BOOL BCMenu::IsWindowsClassicTheme(void) +{ + TCHAR Buf[_MAX_PATH+10]; + HKEY hKey; + DWORD size,type; + long lRetCode; + static BOOL XPTheme_returnflag=FALSE; + static BOOL XPTheme_checkflag=FALSE; + + if(XPTheme_checkflag)return(XPTheme_returnflag); + + XPTheme_checkflag=TRUE; + lRetCode = RegOpenKeyEx ( HKEY_CURRENT_USER, + _T("Software\\Microsoft\\Plus!\\Themes\\Current"), + 0,KEY_READ,&hKey); + if (lRetCode == ERROR_SUCCESS){ + size = _MAX_PATH;type=REG_SZ; + lRetCode=::RegQueryValueEx(hKey,NULL,NULL,&type, + (unsigned char *)Buf,&size); + if(lRetCode == ERROR_SUCCESS){ + TCHAR szClassicTheme[]=_T("Windows Classic.theme"); + int len=lstrlen(Buf); + if(len>=lstrlen(szClassicTheme)){ + if(!lstrcmpi(&Buf[len-lstrlen(szClassicTheme)],szClassicTheme)){ + XPTheme_returnflag=TRUE; + } + } + } + RegCloseKey(hKey); + } + return(XPTheme_returnflag); +} + +int BCMenu::GlobalImageListOffset(int nID) +{ + int numcurrent=m_AllImagesID.GetSize(); + int existsloc = -1; + for(int i=0;iExtractIcon(xoffset); + if(hIcon){ + CBitmap bmp,bmp2,bmp3; + if(IsLunaMenuStyle()&&xp_draw_3D_bitmaps){ + CWnd *pWnd = AfxGetMainWnd(); // Get main window + if (pWnd == NULL) pWnd = CWnd::GetDesktopWindow(); + CDC *pDC = pWnd->GetDC(); // Get device context + GetBitmapFromImageList(pDC,il,xoffset,bmp); + GetFadedBitmap(bmp); + GetBitmapFromImageList(pDC,il,xoffset,bmp2); + GetShadowBitmap(bmp2); + GetBitmapFromImageList(pDC,il,xoffset,bmp3); + GetDisabledBitmap(bmp3); + pWnd->ReleaseDC(pDC); // Release the DC + } + int numcurrent=m_AllImagesID.GetSize(); + int existsloc = -1; + for(int i=0;i=0){ + m_AllImages.Replace(existsloc,hIcon); + loc = existsloc; + if(IsLunaMenuStyle()&&xp_draw_3D_bitmaps){ + if(existsloc+1 + +// BCMenuData class. Fill this class structure to define a single menu item: +class BCMenuData +{ + wchar_t *m_szMenuText; +public: + BCMenuData () {menuIconNormal=-1;xoffset=-1;bitmap=NULL;pContext=NULL; + nFlags=0;nID=0;syncflag=0;m_szMenuText=NULL;global_offset=-1;}; + void SetAnsiString(LPCSTR szAnsiString); + void SetWideString(const wchar_t *szWideString); + const wchar_t *GetWideString(void) {return m_szMenuText;}; + ~BCMenuData (); + CString GetString(void);//returns the menu text in ANSI or UNICODE + int xoffset,global_offset; + int menuIconNormal; + UINT nFlags,nID,syncflag; + CImageList *bitmap; + void *pContext; // used to attach user data +}; + +//struct CMenuItemInfo : public MENUITEMINFO { +struct CMenuItemInfo : public +//MENUITEMINFO +#ifndef UNICODE //SK: this fixes warning C4097: typedef-name 'MENUITEMINFO' used as synonym for class-name 'tagMENUITEMINFOA' +tagMENUITEMINFOA +#else +tagMENUITEMINFOW +#endif +{ + CMenuItemInfo() + { + memset(this, 0, sizeof(MENUITEMINFO)); + cbSize = sizeof(MENUITEMINFO); + } +}; + +// how the menu's are drawn, either original or XP style +typedef enum {BCMENU_DRAWMODE_ORIGINAL,BCMENU_DRAWMODE_XP} BC_MenuDrawMode; + +// how seperators are handled when removing a menu (Tongzhe Cui) +typedef enum {BCMENU_NONE, BCMENU_HEAD, BCMENU_TAIL, BCMENU_BOTH} BC_Seperator; + +// defines for unicode support +#ifndef UNICODE +#define AppendMenu AppendMenuA +#define InsertMenu InsertMenuA +#define InsertODMenu InsertODMenuA +#define AppendODMenu AppendODMenuA +#define AppendODPopupMenu AppendODPopupMenuA +#define ModifyODMenu ModifyODMenuA +#else +#define AppendMenu AppendMenuW +#define InsertMenu InsertMenuW +#define InsertODMenu InsertODMenuW +#define AppendODMenu AppendODMenuW +#define ModifyODMenu ModifyODMenuW +#define AppendODPopupMenu AppendODPopupMenuW +#endif + + +class BCMenu : public CMenu +{ + DECLARE_DYNAMIC( BCMenu ) +public: + BCMenu(); + virtual ~BCMenu(); + + // Functions for loading and applying bitmaps to menus (see example application) + virtual BOOL LoadMenu(LPCTSTR lpszResourceName); + virtual BOOL LoadMenu(int nResource); + BOOL LoadToolbar(UINT nToolBar); + BOOL LoadToolbars(const UINT *arID,int n); + void AddFromToolBar(CToolBar* pToolBar, int nResourceID); + BOOL LoadFromToolBar(UINT nID,UINT nToolBar,int& xoffset); + BOOL AddBitmapToImageList(CImageList *list,UINT nResourceID); + static HBITMAP LoadSysColorBitmap(int nResourceId); + void LoadCheckmarkBitmap(int unselect,int select); // custom check mark bitmaps + + // functions for appending a menu option, use the AppendMenu call (see above define) + BOOL AppendMenuA(UINT nFlags,UINT nIDNewItem=0,const char *lpszNewItem=NULL,int nIconNormal=-1); + BOOL AppendMenuA(UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,CImageList *il,int xoffset); + BOOL AppendMenuA(UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,CBitmap *bmp); + BOOL AppendMenuW(UINT nFlags,UINT nIDNewItem=0,wchar_t *lpszNewItem=NULL,int nIconNormal=-1); + BOOL AppendMenuW(UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,CImageList *il,int xoffset); + BOOL AppendMenuW(UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,CBitmap *bmp); + BOOL AppendODMenuA(LPCSTR lpstrText,UINT nFlags = MF_OWNERDRAW,UINT nID = 0,int nIconNormal = -1); + BOOL AppendODMenuW(wchar_t *lpstrText,UINT nFlags = MF_OWNERDRAW,UINT nID = 0,int nIconNormal = -1); + BOOL AppendODMenuA(LPCSTR lpstrText,UINT nFlags,UINT nID,CImageList *il,int xoffset); + BOOL AppendODMenuW(wchar_t *lpstrText,UINT nFlags,UINT nID,CImageList *il,int xoffset); + + // for appending a popup menu (see example application) + BCMenu* AppendODPopupMenuA(LPCSTR lpstrText); + BCMenu* AppendODPopupMenuW(wchar_t *lpstrText); + + // functions for inserting a menu option, use the InsertMenu call (see above define) + BOOL InsertMenuA(UINT nPosition,UINT nFlags,UINT nIDNewItem=0,const char *lpszNewItem=NULL,int nIconNormal=-1); + BOOL InsertMenuA(UINT nPosition,UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,CImageList *il,int xoffset); + BOOL InsertMenuA(UINT nPosition,UINT nFlags,UINT nIDNewItem,const char *lpszNewItem,CBitmap *bmp); + BOOL InsertMenuW(UINT nPosition,UINT nFlags,UINT nIDNewItem=0,wchar_t *lpszNewItem=NULL,int nIconNormal=-1); + BOOL InsertMenuW(UINT nPosition,UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,CImageList *il,int xoffset); + BOOL InsertMenuW(UINT nPosition,UINT nFlags,UINT nIDNewItem,wchar_t *lpszNewItem,CBitmap *bmp); + BOOL InsertODMenuA(UINT nPosition,LPCSTR lpstrText,UINT nFlags = MF_OWNERDRAW,UINT nID = 0,int nIconNormal = -1); + BOOL InsertODMenuW(UINT nPosition,wchar_t *lpstrText,UINT nFlags = MF_OWNERDRAW,UINT nID = 0,int nIconNormal = -1); + BOOL InsertODMenuA(UINT nPosition,LPCSTR lpstrText,UINT nFlags,UINT nID,CImageList *il,int xoffset); + BOOL InsertODMenuW(UINT nPosition,wchar_t *lpstrText,UINT nFlags,UINT nID,CImageList *il,int xoffset); + + // functions for modifying a menu option, use the ModifyODMenu call (see above define) + BOOL ModifyODMenuA(const char *lpstrText,UINT nID=0,int nIconNormal=-1); + BOOL ModifyODMenuA(const char *lpstrText,UINT nID,CImageList *il,int xoffset); + BOOL ModifyODMenuA(const char *lpstrText,UINT nID,CBitmap *bmp); + BOOL ModifyODMenuA(const char *lpstrText,const char *OptionText,int nIconNormal); + BOOL ModifyODMenuW(wchar_t *lpstrText,UINT nID=0,int nIconNormal=-1); + BOOL ModifyODMenuW(wchar_t *lpstrText,UINT nID,CImageList *il,int xoffset); + BOOL ModifyODMenuW(wchar_t *lpstrText,UINT nID,CBitmap *bmp); + BOOL ModifyODMenuW(wchar_t *lpstrText,wchar_t *OptionText,int nIconNormal); + // use this method for adding a solid/hatched colored square beside a menu option + // courtesy of Warren Stevens + BOOL ModifyODMenuA(const char *lpstrText,UINT nID,COLORREF fill,COLORREF border,int hatchstyle=-1,CSize *pSize=NULL); + BOOL ModifyODMenuW(wchar_t *lpstrText,UINT nID,COLORREF fill,COLORREF border,int hatchstyle=-1,CSize *pSize=NULL); + + // for deleting and removing menu options + BOOL RemoveMenu(UINT uiId,UINT nFlags); + BOOL DeleteMenu(UINT uiId,UINT nFlags); + // sPos means Seperator's position, since we have no way to find the seperator's position in the menu + // we have to specify them when we call the RemoveMenu to make sure the unused seperators are removed; + // sPos = None no seperator removal; + // = Head seperator in front of this menu item; + // = Tail seperator right after this menu item; + // = Both seperators at both ends; + // remove the menu item based on their text, return -1 if not found, otherwise return the menu position; + int RemoveMenu(char* pText, BC_Seperator sPos=BCMENU_NONE); + int RemoveMenu(wchar_t* pText, BC_Seperator sPos=BCMENU_NONE); + int DeleteMenu(char* pText, BC_Seperator sPos=BCMENU_NONE); + int DeleteMenu(wchar_t* pText, BC_Seperator sPos=BCMENU_NONE); + + // Destoying + virtual BOOL DestroyMenu(); + + // function for retrieving and setting a menu options text (use this function + // because it is ownerdrawn) + BOOL GetMenuText(UINT id,CString &string,UINT nFlags = MF_BYPOSITION); + BOOL SetMenuText(UINT id,CString string, UINT nFlags = MF_BYPOSITION); + + // Getting a submenu from it's name or position + BCMenu* GetSubBCMenu(char* lpszSubMenuName); + BCMenu* GetSubBCMenu(wchar_t* lpszSubMenuName); + CMenu* GetSubMenu (LPCTSTR lpszSubMenuName); + CMenu* GetSubMenu (int nPos); + int GetMenuPosition(char* pText); + int GetMenuPosition(wchar_t* pText); + + // Drawing: + virtual void DrawItem( LPDRAWITEMSTRUCT); // Draw an item + virtual void MeasureItem( LPMEASUREITEMSTRUCT ); // Measure an item + + // Static functions used for handling menu's in the mainframe + static void UpdateMenu(CMenu *pmenu); + static BOOL IsMenu(CMenu *submenu); + static BOOL IsMenu(HMENU submenu); + static LRESULT FindKeyboardShortcut(UINT nChar,UINT nFlags,CMenu *pMenu); + + // Function to set how menu is drawn, either original or XP style + static void SetMenuDrawMode(UINT mode){ + BCMenu::original_drawmode=mode; + BCMenu::xp_drawmode=mode; + }; + // Function to set how disabled items are drawn (mode=FALSE means they are not drawn selected) + static void SetSelectDisableMode(BOOL mode){ + BCMenu::original_select_disabled=mode; + BCMenu::xp_select_disabled=mode; + }; + + static int BCMenu::GetMenuDrawMode(void); + static BOOL BCMenu::GetSelectDisableMode(void); + + // how the bitmaps are drawn in XP Luna mode + static void SetXPBitmap3D(BOOL val){ + BCMenu::xp_draw_3D_bitmaps=val; + }; + static BOOL GetXPBitmap3D(void){return BCMenu::xp_draw_3D_bitmaps;} + + // Customizing: + // Set icon size + static void SetIconSize (int, int); + // set the color in the bitmaps that is the background transparent color + void SetBitmapBackground(COLORREF color); + void UnSetBitmapBackground(void); + // obsolete functions for setting how menu images are dithered for disabled menu options + BOOL GetDisableOldStyle(void); + void SetDisableOldStyle(void); + void UnSetDisableOldStyle(void); + static COLORREF LightenColor(COLORREF col,double factor); + static COLORREF DarkenColor(COLORREF col,double factor); + +// Miscellaneous Protected Member functions +protected: + static BOOL IsNewShell(void); + static BOOL IsWinXPLuna(void); + static BOOL IsLunaMenuStyle(void); + static BOOL IsWindowsClassicTheme(void); + BCMenuData *BCMenu::FindMenuItem(UINT nID); + BCMenu *FindMenuOption(int nId,int& nLoc); + BCMenu *FindAnotherMenuOption(int nId,int& nLoc,CArray&bcsubs, + CArray&bclocs); + BCMenuData *FindMenuOption(wchar_t *lpstrText); + void InsertSpaces(void); + void DrawCheckMark(CDC* pDC,int x,int y,COLORREF color,BOOL narrowflag=FALSE); + void DrawRadioDot(CDC *pDC,int x,int y,COLORREF color); + BCMenuData *NewODMenu(UINT pos,UINT nFlags,UINT nID,CString string); + void SynchronizeMenu(void); + void BCMenu::InitializeMenuList(int value); + void BCMenu::DeleteMenuList(void); + BCMenuData *BCMenu::FindMenuList(UINT nID); + void DrawItem_Win9xNT2000 (LPDRAWITEMSTRUCT lpDIS); + void DrawItem_WinXP (LPDRAWITEMSTRUCT lpDIS); + BOOL Draw3DCheckmark(CDC *dc, const CRect& rc,BOOL bSelected,HBITMAP hbmCheck); + BOOL DrawXPCheckmark(CDC *dc, const CRect& rc, HBITMAP hbmCheck,COLORREF &colorout,BOOL selected); + void DitherBlt(HDC hdcDest, int nXDest, int nYDest, int nWidth, + int nHeight, HBITMAP hbm, int nXSrc, int nYSrc,COLORREF bgcolor); + void DitherBlt2(CDC *drawdc, int nXDest, int nYDest, int nWidth, + int nHeight, CBitmap &bmp, int nXSrc, int nYSrc,COLORREF bgcolor); + void DitherBlt3(CDC *drawdc, int nXDest, int nYDest, int nWidth, + int nHeight, CBitmap &bmp,COLORREF bgcolor); + BOOL GetBitmapFromImageList(CDC* pDC,CImageList *imglist,int nIndex,CBitmap &bmp); + BOOL ImageListDuplicate(CImageList *il,int xoffset,CImageList *newlist); + static WORD NumBitmapColors(LPBITMAPINFOHEADER lpBitmap); + void ColorBitmap(CDC* pDC, CBitmap& bmp,CSize bitmap_size,CSize icon_size,COLORREF fill,COLORREF border,int hatchstyle=-1); + void RemoveTopLevelOwnerDraw(void); + int GetMenuStart(void); + void GetFadedBitmap(CBitmap &bmp); + void GetTransparentBitmap(CBitmap &bmp); + void GetDisabledBitmap(CBitmap &bmp,COLORREF background=0); + void GetShadowBitmap(CBitmap &bmp); + int AddToGlobalImageList(CImageList *il,int xoffset,int nID); + int GlobalImageListOffset(int nID); + BOOL CanDraw3DImageList(int offset); + +// Member Variables +protected: + CTypedPtrArray m_MenuList; // Stores list of menu items + // When loading an owner-drawn menu using a Resource, BCMenu must keep track of + // the popup menu's that it creates. Warning, this list *MUST* be destroyed + // last item first :) + CTypedPtrArray m_SubMenus; // Stores list of sub-menus + // Stores a list of all BCMenu's ever created + static CTypedPtrArray m_AllSubMenus; + // Global ImageList + static CImageList m_AllImages; + static CArray m_AllImagesID; + // icon size + static int m_iconX; + static int m_iconY; + COLORREF m_bitmapBackground; + BOOL m_bitmapBackgroundFlag; + BOOL disable_old_style; + static UINT original_drawmode; + static BOOL original_select_disabled; + static UINT xp_drawmode; + static BOOL xp_select_disabled; + static BOOL xp_draw_3D_bitmaps; + static BOOL hicolor_bitmaps; + static BOOL xp_space_accelerators; + static BOOL original_space_accelerators; + CImageList *checkmaps; + BOOL checkmapsshare; + int m_selectcheck; + int m_unselectcheck; + BOOL m_bDynIcons; + BOOL m_loadmenu; +}; + +#define BCMENU_USE_MEMDC + +#ifdef BCMENU_USE_MEMDC +////////////////////////////////////////////////// +// BCMenuMemDC - memory DC +// +// Author: Keith Rule +// Email: keithr@europa.com +// Copyright 1996-1997, Keith Rule +// +// You may freely use or modify this code provided this +// Copyright is included in all derived versions. +// +// History - 10/3/97 Fixed scrolling bug. +// Added print support. +// 25 feb 98 - fixed minor assertion bug +// +// This class implements a memory Device Context + +class BCMenuMemDC : public CDC +{ +public: + + // constructor sets up the memory DC + BCMenuMemDC(CDC* pDC,LPCRECT lpSrcRect) : CDC() + { + ASSERT(pDC != NULL); + + m_rect.CopyRect(lpSrcRect); + m_pDC = pDC; + m_pOldBitmap = NULL; + m_bMemDC = !pDC->IsPrinting(); + + if (m_bMemDC) // Create a Memory DC + { + CreateCompatibleDC(pDC); + m_bitmap.CreateCompatibleBitmap(pDC, m_rect.Width(), m_rect.Height()); + m_pOldBitmap = SelectObject(&m_bitmap); + SetWindowOrg(m_rect.left, m_rect.top); + } + else // Make a copy of the relevent parts of the current DC for printing + { + m_bPrinting = pDC->m_bPrinting; + m_hDC = pDC->m_hDC; + m_hAttribDC = pDC->m_hAttribDC; + } + } + + // Destructor copies the contents of the mem DC to the original DC + ~BCMenuMemDC() + { + if (m_bMemDC) + { + // Copy the offscreen bitmap onto the screen. + m_pDC->BitBlt(m_rect.left, m_rect.top, m_rect.Width(), m_rect.Height(), + this, m_rect.left, m_rect.top, SRCCOPY); + + //Swap back the original bitmap. + SelectObject(m_pOldBitmap); + } else { + // All we need to do is replace the DC with an illegal value, + // this keeps us from accidently deleting the handles associated with + // the CDC that was passed to the constructor. + m_hDC = m_hAttribDC = NULL; + } + } + + // Allow usage as a pointer + BCMenuMemDC* operator->() {return this;} + + // Allow usage as a pointer + operator BCMenuMemDC*() {return this;} + +private: + CBitmap m_bitmap; // Offscreen bitmap + CBitmap* m_pOldBitmap; // bitmap originally found in BCMenuMemDC + CDC* m_pDC; // Saves CDC passed in constructor + CRect m_rect; // Rectangle of drawing area. + BOOL m_bMemDC; // TRUE if CDC really is a Memory DC. +}; + +#endif + +#endif + +//************************************************************************* diff --git a/SlnkDWFImpl/CxImage/demo/ChildFrm.cpp b/SlnkDWFImpl/CxImage/demo/ChildFrm.cpp new file mode 100644 index 0000000..e09aec6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/ChildFrm.cpp @@ -0,0 +1,54 @@ +// ChildFrm.cpp : implementation of the CChildFrame class + +#include "stdafx.h" +#include "demo.h" + +#include "ChildFrm.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +////////////////////////////////////////////////////////////////////////////// +// CChildFrame +IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd) + +BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd) + //{{AFX_MSG_MAP(CChildFrame) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +////////////////////////////////////////////////////////////////////////////// +// CChildFrame construction/destruction +CChildFrame::CChildFrame() +{ + // TODO: add member initialization code here +} + +CChildFrame::~CChildFrame() +{ +} +////////////////////////////////////////////////////////////////////////////// +BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs) +{ + // TODO: Modify the Window class or styles here by modifying + // the CREATESTRUCT cs + return CMDIChildWnd::PreCreateWindow(cs); +} +////////////////////////////////////////////////////////////////////////////// +// CChildFrame diagnostics +#ifdef _DEBUG +void CChildFrame::AssertValid() const +{ + CMDIChildWnd::AssertValid(); +} +void CChildFrame::Dump(CDumpContext& dc) const +{ + CMDIChildWnd::Dump(dc); +} +#endif //_DEBUG +////////////////////////////////////////////////////////////////////////////// +// CChildFrame message handlers + diff --git a/SlnkDWFImpl/CxImage/demo/ChildFrm.h b/SlnkDWFImpl/CxImage/demo/ChildFrm.h new file mode 100644 index 0000000..a98a774 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/ChildFrm.h @@ -0,0 +1,38 @@ +// ChildFrm.h : interface of the CChildFrame class +// +///////////////////////////////////////////////////////////////////////////// + +class CChildFrame : public CMDIChildWnd +{ + DECLARE_DYNCREATE(CChildFrame) +public: + CChildFrame(); + +// Attributes +public: + +// Operations +public: + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CChildFrame) + virtual BOOL PreCreateWindow(CREATESTRUCT& cs); + //}}AFX_VIRTUAL + +// Implementation +public: + virtual ~CChildFrame(); +#ifdef _DEBUG + virtual void AssertValid() const; + virtual void Dump(CDumpContext& dc) const; +#endif + +// Generated message map functions +protected: + //{{AFX_MSG(CChildFrame) + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +///////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/DlgColorize.cpp b/SlnkDWFImpl/CxImage/demo/DlgColorize.cpp new file mode 100644 index 0000000..9a9a065 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgColorize.cpp @@ -0,0 +1,118 @@ +// DlgColorize.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgColorize.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgColorize dialog + + +DlgColorize::DlgColorize(CWnd* pParent /*=NULL*/) + : CDialog(DlgColorize::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgColorize) + m_hue = 0; + m_sat = 0; + m_r = 0; + m_g = 0; + m_b = 0; + m_blend = 50; + //}}AFX_DATA_INIT +} + + +void DlgColorize::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgColorize) + DDX_Control(pDX, IDC_RADIO3, m_rbHSL); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, IDCOLORS, m_colors); + DDX_Text(pDX, IDC_EDIT1, m_hue); + DDX_Text(pDX, IDC_EDIT2, m_sat); + DDX_Text(pDX, IDC_EDIT3, m_r); + DDX_Text(pDX, IDC_EDIT4, m_g); + DDX_Text(pDX, IDC_EDIT5, m_b); + DDX_Text(pDX, IDC_EDIT8, m_blend); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgColorize, CDialog) + //{{AFX_MSG_MAP(DlgColorize) + ON_BN_CLICKED(IDCOLORS, OnColors) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgColorize message handlers + +BOOL DlgColorize::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + m_colors.SetIcon(IDI_B,BS_LEFT); + + m_rbHSL.SetCheck(1); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgColorize::OnOK() +{ + m_bHSL = m_rbHSL.GetCheck(); + + CDialog::OnOK(); +} + +void DlgColorize::OnColors() +{ + UpdateData(1); + + int bHSL = m_rbHSL.GetCheck(); + + COLORREF c; + RGBQUAD rgb,hsl; + + if (bHSL){ + hsl.rgbRed = m_hue; + hsl.rgbGreen = m_sat; + hsl.rgbBlue = 128; + rgb = CxImage::HSLtoRGB(hsl); + c = RGB(rgb.rgbRed,rgb.rgbGreen,rgb.rgbBlue); + } else { + c = RGB(m_r,m_g,m_b); + } + + CColorDialog dlg(c, CC_FULLOPEN | CC_ANYCOLOR, this); + + if (dlg.DoModal() == IDOK){ + c = dlg.GetColor(); + if (bHSL){ + rgb.rgbRed = GetRValue(c); + rgb.rgbGreen = GetGValue(c); + rgb.rgbBlue = GetBValue(c); + hsl = CxImage::RGBtoHSL(rgb); + m_hue = hsl.rgbRed; + m_sat = hsl.rgbGreen; + } else { + m_r=GetRValue(c); + m_g=GetGValue(c); + m_b=GetBValue(c); + } + } + + UpdateData(0); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgColorize.h b/SlnkDWFImpl/CxImage/demo/DlgColorize.h new file mode 100644 index 0000000..0ebc053 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgColorize.h @@ -0,0 +1,59 @@ +#if !defined(AFX_DLGCOLORIZE_H__CB0FCA81_FBC0_11D5_8DD7_00E07D8144D0__INCLUDED_) +#define AFX_DLGCOLORIZE_H__CB0FCA81_FBC0_11D5_8DD7_00E07D8144D0__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgColorize.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgColorize dialog +class DlgColorize : public CDialog +{ +// Construction +public: + BYTE m_bHSL; + DlgColorize(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgColorize) + enum { IDD = IDD_COLORIZE }; + CButton m_rbHSL; + CxTargetButton m_ok; + CxTargetButton m_canc; + CxTargetButton m_colors; + BYTE m_hue; + BYTE m_sat; + long m_r; + long m_g; + long m_b; + BYTE m_blend; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgColorize) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgColorize) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + afx_msg void OnColors(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGCOLORIZE_H__CB0FCA81_FBC0_11D5_8DD7_00E07D8144D0__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgCombine.cpp b/SlnkDWFImpl/CxImage/demo/DlgCombine.cpp new file mode 100644 index 0000000..32ec325 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgCombine.cpp @@ -0,0 +1,113 @@ +// DlgCombine.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "demoDoc.h" +#include "DlgCombine.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgCombine dialog + + +DlgCombine::DlgCombine(CWnd* pParent /*=NULL*/) + : CDialog(DlgCombine::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgCombine) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void DlgCombine::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgCombine) + DDX_Control(pDX, IDC_COMBO9, m_chs); + DDX_Control(pDX, IDC_COMBO8, m_cha); + DDX_Control(pDX, IDC_COMBO7, m_chb); + DDX_Control(pDX, IDC_COMBO6, m_chg); + DDX_Control(pDX, IDC_COMBO5, m_chr); + DDX_Control(pDX, IDC_COMBO4, m_imga); + DDX_Control(pDX, IDC_COMBO3, m_imgb); + DDX_Control(pDX, IDC_COMBO2, m_imgg); + DDX_Control(pDX, IDC_COMBO1, m_imgr); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgCombine, CDialog) + //{{AFX_MSG_MAP(DlgCombine) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgCombine message handlers + +BOOL DlgCombine::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + + m_imga.AddString("(None)"); + m_imga.SetItemData(m_imga.GetCount()-1, 0); + + POSITION pos = AfxGetApp()->GetFirstDocTemplatePosition(); + while (pos != NULL) { + CDocTemplate* pTemplate = AfxGetApp()->GetNextDocTemplate(pos); + ASSERT(pTemplate->IsKindOf(RUNTIME_CLASS(CDocTemplate))); + POSITION pos2 = pTemplate->GetFirstDocPosition(); + while (pos2 != NULL) { + CDemoDoc* pDoc = (CDemoDoc*) pTemplate->GetNextDoc(pos2); + ASSERT(pDoc->IsKindOf(RUNTIME_CLASS(CDemoDoc))); + CString title = pDoc->GetTitle(); + m_imgr.AddString(title); + m_imgr.SetItemData(m_imgr.GetCount()-1, (DWORD)pDoc); + m_imgg.AddString(title); + m_imgg.SetItemData(m_imgg.GetCount()-1, (DWORD)pDoc); + m_imgb.AddString(title); + m_imgb.SetItemData(m_imgb.GetCount()-1, (DWORD)pDoc); + m_imga.AddString(title); + m_imga.SetItemData(m_imga.GetCount()-1, (DWORD)pDoc); + } + } + m_imgr.SetCurSel(0); + m_imgg.SetCurSel(0); + m_imgb.SetCurSel(0); + m_imga.SetCurSel(0); + m_chr.SetCurSel(1); + m_chg.SetCurSel(2); + m_chb.SetCurSel(3); + m_cha.SetCurSel(0); + m_chs.SetCurSel(0); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgCombine::OnOK() +{ + pDocR = (CDemoDoc*) m_imgr.GetItemData(m_imgr.GetCurSel()); + pDocG = (CDemoDoc*) m_imgg.GetItemData(m_imgg.GetCurSel()); + pDocB = (CDemoDoc*) m_imgb.GetItemData(m_imgb.GetCurSel()); + pDocA = (CDemoDoc*) m_imga.GetItemData(m_imga.GetCurSel()); + + pChR = m_chr.GetCurSel(); + pChG = m_chg.GetCurSel(); + pChB = m_chb.GetCurSel(); + pChA = m_cha.GetCurSel(); + pChS = m_chs.GetCurSel(); + + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgCombine.h b/SlnkDWFImpl/CxImage/demo/DlgCombine.h new file mode 100644 index 0000000..04507a0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgCombine.h @@ -0,0 +1,69 @@ +#if !defined(AFX_DLGCOMBINE_H__6619A9E1_AF0A_11D6_BB83_DFD6D1F64D7F__INCLUDED_) +#define AFX_DLGCOMBINE_H__6619A9E1_AF0A_11D6_BB83_DFD6D1F64D7F__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgCombine.h : header file +// + +#include "xTargetButton.h" + +class CDemoDoc; +///////////////////////////////////////////////////////////////////////////// +// DlgCombine dialog +class DlgCombine : public CDialog +{ +// Construction +public: + CDemoDoc* pDocR; + CDemoDoc* pDocG; + CDemoDoc* pDocB; + CDemoDoc* pDocA; + long pChR; + long pChG; + long pChB; + long pChA; + long pChS; + + DlgCombine(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgCombine) + enum { IDD = IDD_COMBINE }; + CComboBox m_chs; + CComboBox m_cha; + CComboBox m_chb; + CComboBox m_chg; + CComboBox m_chr; + CComboBox m_imga; + CComboBox m_imgb; + CComboBox m_imgg; + CComboBox m_imgr; + CxTargetButton m_ok; + CxTargetButton m_canc; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgCombine) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgCombine) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGCOMBINE_H__6619A9E1_AF0A_11D6_BB83_DFD6D1F64D7F__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgDecBpp.cpp b/SlnkDWFImpl/CxImage/demo/DlgDecBpp.cpp new file mode 100644 index 0000000..de657fd --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgDecBpp.cpp @@ -0,0 +1,104 @@ +// DlgDecBpp.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgDecBpp.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgDecBpp dialog + + +DlgDecBpp::DlgDecBpp(CWnd* pParent /*=NULL*/) + : CDialog(DlgDecBpp::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgDecBpp) + m_maxcolors = 0; + //}}AFX_DATA_INIT +} + + +void DlgDecBpp::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgDecBpp) + DDX_Control(pDX, IDC_CHECK2, m_limitcolors); + DDX_Control(pDX, IDC_CHECK1, m_err); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, IDC_RADIO5, m_opt); + DDX_Control(pDX, IDC_RADIO3, m_r8); + DDX_Control(pDX, IDC_RADIO2, m_r4); + DDX_Control(pDX, IDC_RADIO1, m_r1); + DDX_Text(pDX, IDC_EDIT1, m_maxcolors); + DDV_MinMaxLong(pDX, m_maxcolors, 2, 256); + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(DlgDecBpp, CDialog) + //{{AFX_MSG_MAP(DlgDecBpp) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgDecBpp message handlers + +BOOL DlgDecBpp::OnInitDialog() +{ + CDialog::OnInitDialog(); + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + if (m_bit == 8) m_r8.SetCheck(1); + else if (m_bit == 4) m_r4.SetCheck(1); + else m_r1.SetCheck(1); + + m_opt.SetCheck(1); + m_method=0; + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgDecBpp::OnOK() +{ + if (m_r8.GetCheck()) m_bit=8; + else if (m_r4.GetCheck()) m_bit=4; + else m_bit=1; + + if (m_opt.GetCheck()) m_method=1; + + m_errordiffusion = m_err.GetCheck(); + + UpdateData(1); + + if (m_limitcolors.GetCheck()==0){ + switch (m_bit){ + case 1: + m_maxcolors = 2; break; + case 4: + m_maxcolors = 16; break; + case 8: + m_maxcolors = 256; break; + } + } else { + switch (m_bit){ + case 1: + if (m_maxcolors > 2) m_maxcolors = 2; break; + case 4: + if (m_maxcolors > 16) m_maxcolors = 16; break; + case 8: + if (m_maxcolors > 256) m_maxcolors = 256; break; + } + } + + UpdateData(0); + + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgDecBpp.h b/SlnkDWFImpl/CxImage/demo/DlgDecBpp.h new file mode 100644 index 0000000..ffc7800 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgDecBpp.h @@ -0,0 +1,59 @@ +#if !defined(AFX_DLGDECBPP_H__55B7AF21_BB40_11D5_8DD4_00E07D8144D0__INCLUDED_) +#define AFX_DLGDECBPP_H__55B7AF21_BB40_11D5_8DD4_00E07D8144D0__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgDecBpp.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgDecBpp dialog +class DlgDecBpp : public CDialog +{ +// Construction +public: + long m_method; + long m_bit; + long m_errordiffusion; + DlgDecBpp(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgDecBpp) + enum { IDD = IDD_DECBPP }; + CButton m_limitcolors; + CButton m_err; + CxTargetButton m_ok; + CxTargetButton m_canc; + CButton m_opt; + CButton m_r8; + CButton m_r4; + CButton m_r1; + long m_maxcolors; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgDecBpp) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgDecBpp) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGDECBPP_H__55B7AF21_BB40_11D5_8DD4_00E07D8144D0__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgDither.cpp b/SlnkDWFImpl/CxImage/demo/DlgDither.cpp new file mode 100644 index 0000000..316c329 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgDither.cpp @@ -0,0 +1,83 @@ +// DlgDither.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgDither.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgDither dialog + + +DlgDither::DlgDither(CWnd* pParent /*=NULL*/) + : CDialog(DlgDither::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgDither) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void DlgDither::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgDither) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, IDC_RADIO8, m_r8); + DDX_Control(pDX, IDC_RADIO7, m_r7); + DDX_Control(pDX, IDC_RADIO6, m_r6); + DDX_Control(pDX, IDC_RADIO5, m_r5); + DDX_Control(pDX, IDC_RADIO4, m_r4); + DDX_Control(pDX, IDC_RADIO3, m_r3); + DDX_Control(pDX, IDC_RADIO2, m_r2); + DDX_Control(pDX, IDC_RADIO1, m_r1); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgDither, CDialog) + //{{AFX_MSG_MAP(DlgDither) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgDither message handlers + +BOOL DlgDither::OnInitDialog() +{ + CDialog::OnInitDialog(); + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + m_r1.SetCheck(1); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgDither::OnOK() +{ + if (m_r2.GetCheck()) + m_method = 1; + else if (m_r3.GetCheck()) + m_method = 2; + else if (m_r4.GetCheck()) + m_method = 3; + else if (m_r5.GetCheck()) + m_method = 4; + else if (m_r6.GetCheck()) + m_method = 5; + else if (m_r7.GetCheck()) + m_method = 6; + else if (m_r8.GetCheck()) + m_method = 7; + else m_method = 0; + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgDither.h b/SlnkDWFImpl/CxImage/demo/DlgDither.h new file mode 100644 index 0000000..7694b82 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgDither.h @@ -0,0 +1,58 @@ +#if !defined(AFX_DLGDITHER_H__FCFC4DC1_FB70_11D5_8DD7_00E07D8144D0__INCLUDED_) +#define AFX_DLGDITHER_H__FCFC4DC1_FB70_11D5_8DD7_00E07D8144D0__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgDither.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgDither dialog +class DlgDither : public CDialog +{ +// Construction +public: + long m_method; + DlgDither(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgDither) + enum { IDD = IDD_DITHER }; + CxTargetButton m_ok; + CxTargetButton m_canc; + CButton m_r8; + CButton m_r7; + CButton m_r6; + CButton m_r5; + CButton m_r4; + CButton m_r3; + CButton m_r2; + CButton m_r1; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgDither) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgDither) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGDITHER_H__FCFC4DC1_FB70_11D5_8DD7_00E07D8144D0__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgFFT.cpp b/SlnkDWFImpl/CxImage/demo/DlgFFT.cpp new file mode 100644 index 0000000..044ea22 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgFFT.cpp @@ -0,0 +1,99 @@ +// DlgFFT.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "demoDoc.h" +#include "DlgFFT.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgFFT dialog + + +DlgFFT::DlgFFT(CWnd* pParent /*=NULL*/) + : CDialog(DlgFFT::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgFFT) + //}}AFX_DATA_INIT +} + + +void DlgFFT::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgFFT) + DDX_Control(pDX, IDC_CHECK1, m_cinverse); + DDX_Control(pDX, IDC_CHECK3, m_cmagnitude); + DDX_Control(pDX, IDC_CHECK4, m_cforcefft); + DDX_Control(pDX, IDC_IMAG, m_imag); + DDX_Control(pDX, IDC_REAL, m_real); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, IDOK, m_ok); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgFFT, CDialog) + //{{AFX_MSG_MAP(DlgFFT) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgFFT message handlers + +BOOL DlgFFT::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + m_cforcefft.SetCheck(1); + //m_cmagnitude.SetCheck(1); + + m_real.AddString("(None)"); + m_real.SetItemData(m_real.GetCount()-1, 0); + m_imag.AddString("(None)"); + m_imag.SetItemData(m_imag.GetCount()-1, 0); + + POSITION pos = AfxGetApp()->GetFirstDocTemplatePosition(); + while (pos != NULL) { + CDocTemplate* pTemplate = AfxGetApp()->GetNextDocTemplate(pos); + ASSERT(pTemplate->IsKindOf(RUNTIME_CLASS(CDocTemplate))); + POSITION pos2 = pTemplate->GetFirstDocPosition(); + while (pos2 != NULL) { + CDemoDoc* pDoc = (CDemoDoc*) pTemplate->GetNextDoc(pos2); + ASSERT(pDoc->IsKindOf(RUNTIME_CLASS(CDemoDoc))); + CString title = pDoc->GetTitle(); + m_real.AddString(title); + m_real.SetItemData(m_real.GetCount()-1, (DWORD)pDoc); + m_imag.AddString(title); + m_imag.SetItemData(m_imag.GetCount()-1, (DWORD)pDoc); + } + } + m_real.SetCurSel(0); + m_imag.SetCurSel(0); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgFFT::OnOK() +{ + pDocReal = (CDemoDoc*) m_real.GetItemData(m_real.GetCurSel()); + pDocImag = (CDemoDoc*) m_imag.GetItemData(m_imag.GetCurSel()); + + if (pDocReal==0 && pDocImag==0) return; + + bInverse = m_cinverse.GetCheck() ? -1 : 1; + bForceFFT = m_cforcefft.GetCheck(); + bMagnitude = m_cmagnitude.GetCheck(); + + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgFFT.h b/SlnkDWFImpl/CxImage/demo/DlgFFT.h new file mode 100644 index 0000000..1348548 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgFFT.h @@ -0,0 +1,62 @@ +#if !defined(AFX_DLGFFT_H__B3EB1107_B044_11D6_BB83_EA3D5554237A__INCLUDED_) +#define AFX_DLGFFT_H__B3EB1107_B044_11D6_BB83_EA3D5554237A__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgFFT.h : header file +// + +#include "xTargetButton.h" + +class CDemoDoc; +///////////////////////////////////////////////////////////////////////////// +// DlgFFT dialog +class DlgFFT : public CDialog +{ +// Construction +public: + CDemoDoc* pDocReal; + CDemoDoc* pDocImag; + + long bForceFFT; + long bMagnitude; + long bInverse; + + DlgFFT(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgFFT) + enum { IDD = IDD_FFT }; + CButton m_cinverse; + CButton m_cmagnitude; + CButton m_cforcefft; + CComboBox m_imag; + CComboBox m_real; + CxTargetButton m_canc; + CxTargetButton m_ok; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgFFT) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgFFT) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGFFT_H__B3EB1107_B044_11D6_BB83_EA3D5554237A__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgGamma.cpp b/SlnkDWFImpl/CxImage/demo/DlgGamma.cpp new file mode 100644 index 0000000..e4ea311 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgGamma.cpp @@ -0,0 +1,55 @@ +// DlgGamma.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgGamma.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgGamma dialog + + +DlgGamma::DlgGamma(CWnd* pParent /*=NULL*/) + : CDialog(DlgGamma::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgGamma) + m_gamma = 0.0f; + //}}AFX_DATA_INIT +} + + +void DlgGamma::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgGamma) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_EDIT1, m_gamma); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgGamma, CDialog) + //{{AFX_MSG_MAP(DlgGamma) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgGamma message handlers + +BOOL DlgGamma::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgGamma.h b/SlnkDWFImpl/CxImage/demo/DlgGamma.h new file mode 100644 index 0000000..6b471d1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgGamma.h @@ -0,0 +1,50 @@ +#if !defined(AFX_DLGGAMMA_H__16A60641_A8B3_11D6_BB83_444553540000__INCLUDED_) +#define AFX_DLGGAMMA_H__16A60641_A8B3_11D6_BB83_444553540000__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgGamma.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgGamma dialog + +class DlgGamma : public CDialog +{ +// Construction +public: + DlgGamma(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgGamma) + enum { IDD = IDD_GAMMA }; + CxTargetButton m_ok; + CxTargetButton m_canc; + float m_gamma; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgGamma) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgGamma) + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGGAMMA_H__16A60641_A8B3_11D6_BB83_444553540000__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgHisto.cpp b/SlnkDWFImpl/CxImage/demo/DlgHisto.cpp new file mode 100644 index 0000000..c2cd573 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgHisto.cpp @@ -0,0 +1,214 @@ +// DlgHisto.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "MainFrm.h" +#include "DlgHisto.h" +#include "demodoc.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgHisto dialog +DlgHisto::DlgHisto() +{ m_initok = false;} +///////////////////////////////////////////////////////////////////////////// +DlgHisto::~DlgHisto() +{ } +///////////////////////////////////////////////////////////////////////////// +BOOL DlgHisto::Create(CWnd* pParentWnd, LPCTSTR lpszTemplateName, UINT nStyle, UINT nID) +{ + BOOL bSuccess = CDialogBar::Create(pParentWnd, lpszTemplateName, nStyle, nID); + InitDlg(); + return bSuccess; +} +///////////////////////////////////////////////////////////////////////////// +BOOL DlgHisto::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID) +{ + BOOL bSuccess = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID); + InitDlg(); + return bSuccess; +} +///////////////////////////////////////////////////////////////////////////// +BEGIN_MESSAGE_MAP(DlgHisto, CDialogBar) + //{{AFX_MSG_MAP(DlgHisto) + ON_WM_PAINT() + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgHisto message handlers +void DlgHisto::InitDlg() +{ + if (m_initok) return; + + RECT r1 = {10,8,59,35}; + m_r.Create("",WS_VISIBLE|WS_TABSTOP,r1,this,0); + m_r.SetButtonStyle(BS_PUSHLIKE|BS_FLAT|BS_AUTOCHECKBOX,0); + m_r.SetWindowText("R"); + m_r.EnableTarget(0); + m_r.SetIcon(IDI_R,BS_LEFT); + m_r.SetCheck(1); + m_r.EnableWindow(1); + + RECT r2 = {60,8,109,35}; + m_g.Create("",WS_VISIBLE|WS_TABSTOP,r2,this,0); + m_g.SetButtonStyle(BS_PUSHLIKE|BS_FLAT|BS_AUTOCHECKBOX,0); + m_g.SetWindowText("G"); + m_g.EnableTarget(0); + m_g.SetIcon(IDI_G,BS_LEFT); + m_g.SetCheck(1); + m_g.EnableWindow(1); + + RECT r3 = {110,8,159,35}; + m_b.Create("",WS_VISIBLE|WS_TABSTOP,r3,this,0); + m_b.SetButtonStyle(BS_PUSHLIKE|BS_FLAT|BS_AUTOCHECKBOX,0); + m_b.SetWindowText("B"); + m_b.EnableTarget(0); + m_b.SetIcon(IDI_B,BS_LEFT); + m_b.SetCheck(1); + m_b.EnableWindow(1); + + RECT r4 = {160,8,209,35}; + m_gray.Create("",WS_VISIBLE|WS_TABSTOP,r4,this,0); + m_gray.SetButtonStyle(BS_PUSHLIKE|BS_FLAT|BS_AUTOCHECKBOX,0); + m_gray.SetWindowText("gray"); + m_gray.EnableTarget(0); + m_gray.SetIcon(IDI_GRAY,BS_LEFT); + m_gray.SetCheck(1); + m_gray.EnableWindow(1); + + m_ren=m_gen=m_ben=m_grayen=1; + + CButton* plog = (CButton*)GetDlgItem(IDC_LOG); + if (plog) { plog->SetCheck(1); m_logen=1; } else m_logen=0; + + m_initok=true; +} + +BOOL DlgHisto::OnCommand(WPARAM wparam, LPARAM lparam) +{ + CDialogBar::OnCommand(wparam, lparam); + + m_ren=m_r.GetCheck(); + m_gen=m_g.GetCheck(); + m_ben=m_b.GetCheck(); + m_grayen=m_gray.GetCheck(); + + CButton* plog = (CButton*)GetDlgItem(IDC_LOG); + m_logen=plog->GetCheck(); + + Invalidate(); + + return TRUE; +} + +void DlgHisto::OnPaint() +{ + CPaintDC dc(this); // device context for painting + + CDemoDoc* pDoc = (CDemoDoc*) ((CMainFrame*)AfxGetMainWnd())->GetActiveFrame()->GetActiveDocument(); + + RECT r; + GetClientRect(&r); + + CPen gridPen(PS_DOT,1,::GetSysColor(COLOR_APPWORKSPACE)); + CPen* pOldPen = dc.SelectObject(&gridPen); + for (int gx=9+32;gx<265;gx+=32){ + dc.MoveTo(gx,40); + dc.LineTo(gx,r.bottom - 6); + } + for (int gy=0;gy<(r.bottom - 40);gy+=((r.bottom - 40)/10)){ + dc.MoveTo(8,r.bottom - 9 - gy); + dc.LineTo(268,r.bottom - 9 - gy); + } + dc.SelectObject(pOldPen); + + CPen axisPen(PS_SOLID, 1, ::GetSysColor(COLOR_3DSHADOW)); + pOldPen = dc.SelectObject(&axisPen); + dc.MoveTo(9, 38); + dc.LineTo(9, r.bottom - 9); + dc.LineTo(266, r.bottom - 9); + dc.LineTo(266, 38); + dc.SelectObject(pOldPen); + + if (pDoc && pDoc->image) { + + if (pDoc->m_hmax){ + int ybase = r.bottom-10; + if (m_logen){ + float yratio = (r.bottom - r.top - 50)/(float)log10((float)(pDoc->m_hmax+1)); + if (m_ren){ + CPen redPen(PS_SOLID, 1, RGB(222, 0, 0)); + pOldPen = dc.SelectObject(&redPen); + dc.MoveTo(10, (int)(ybase-log10((float)(1+pDoc->m_hr[0]))*yratio)); + for (int x=1; x<256; x++) + dc.LineTo(x+10, (int)(ybase-log10((float)(1+pDoc->m_hr[x]))*yratio)); + } + if (m_gen){ + CPen greenPen(PS_SOLID, 1, RGB(0, 222, 0)); + pOldPen = dc.SelectObject(&greenPen); + dc.MoveTo(10, (int)(ybase-log10((float)(1+pDoc->m_hg[0]))*yratio)); + for (int x=1; x<256; x++) + dc.LineTo(x+10, (int)(ybase-log10((float)(1+pDoc->m_hg[x]))*yratio)); + } + if (m_ben){ + CPen bluePen(PS_SOLID, 1, RGB(0, 0, 222)); + pOldPen = dc.SelectObject(&bluePen); + dc.MoveTo(10, (int)(ybase-log10((float)(1+pDoc->m_hb[0]))*yratio)); + for (int x=1; x<256; x++) + dc.LineTo(x+10, (int)(ybase-log10((float)(1+pDoc->m_hb[x]))*yratio)); + } + if (m_grayen){ + CPen grayPen(PS_SOLID, 1, RGB(64, 64, 64)); + pOldPen = dc.SelectObject(&grayPen); + dc.MoveTo(10, (int)(ybase-log10((float)(1+pDoc->m_hgray[0]))*yratio)); + for (int x=1; x<256; x++) + dc.LineTo(x+10, (int)(ybase-log10((float)(1+pDoc->m_hgray[x]))*yratio)); + } + dc.SelectObject(pOldPen); + } else { + float yratio = (r.bottom - r.top - 50)/(float)pDoc->m_hmax; + if (m_ren){ + CPen redPen(PS_SOLID, 1, RGB(222, 0, 0)); + pOldPen = dc.SelectObject(&redPen); + dc.MoveTo(10, (int)(ybase-pDoc->m_hr[0]*yratio)); + for (int x=1; x<256; x++) + dc.LineTo(x+10, (int)(ybase-pDoc->m_hr[x]*yratio)); + } + if (m_gen){ + CPen greenPen(PS_SOLID, 1, RGB(0, 222, 0)); + pOldPen = dc.SelectObject(&greenPen); + dc.MoveTo(10, (int)(ybase-pDoc->m_hg[0]*yratio)); + for (int x=1; x<256; x++) + dc.LineTo(x+10, (int)(ybase-pDoc->m_hg[x]*yratio)); + } + if (m_ben){ + CPen bluePen(PS_SOLID, 1, RGB(0, 0, 222)); + pOldPen = dc.SelectObject(&bluePen); + dc.MoveTo(10, (int)(ybase-pDoc->m_hb[0]*yratio)); + for (int x=1; x<256; x++) + dc.LineTo(x+10, (int)(ybase-pDoc->m_hb[x]*yratio)); + } + if (m_grayen){ + CPen grayPen(PS_SOLID, 1, RGB(64, 64, 64)); + pOldPen = dc.SelectObject(&grayPen); + dc.MoveTo(10, (int)(ybase-pDoc->m_hgray[0]*yratio)); + for (int x=1; x<256; x++) + dc.LineTo(x+10, (int)(ybase-pDoc->m_hgray[x]*yratio)); + } + dc.SelectObject(pOldPen); + } + } + else + { + pDoc->m_hmax=pDoc->GetImage()->Histogram(pDoc->m_hr,pDoc->m_hg,pDoc->m_hb,pDoc->m_hgray); + if (pDoc->m_hmax) Invalidate(); + } + } +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgHisto.h b/SlnkDWFImpl/CxImage/demo/DlgHisto.h new file mode 100644 index 0000000..7f1cf24 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgHisto.h @@ -0,0 +1,53 @@ +#if !defined(AFX_DLGHISTO_H__4EA4FEE4_AE24_11D6_BB83_E5D7B698D37E__INCLUDED_) +#define AFX_DLGHISTO_H__4EA4FEE4_AE24_11D6_BB83_E5D7B698D37E__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgHisto.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgHisto dialog +class DlgHisto : public CDialogBar +{ +// Construction +public: + DlgHisto(); + virtual ~DlgHisto(); + + BOOL Create(CWnd* pParentWnd, LPCTSTR lpszTemplateName, UINT nStyle, UINT nID ); + BOOL Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID ); + + void InitDlg(); + + //{{AFX_VIRTUAL(DlgHisto) + protected: + //}}AFX_VIRTUAL + +// Implementation +protected: + CxTargetButton m_r; + CxTargetButton m_g; + CxTargetButton m_b; + CxTargetButton m_gray; + int m_ren; + int m_gen; + int m_ben; + int m_grayen; + int m_logen; + bool m_initok; + // Generated message map functions + //{{AFX_MSG(DlgHisto) + afx_msg void OnPaint(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam); +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGHISTO_H__4EA4FEE4_AE24_11D6_BB83_E5D7B698D37E__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgIncBpp.cpp b/SlnkDWFImpl/CxImage/demo/DlgIncBpp.cpp new file mode 100644 index 0000000..55eeb28 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgIncBpp.cpp @@ -0,0 +1,68 @@ +// DlgIncBpp.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgIncBpp.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgIncBpp dialog + + +DlgIncBpp::DlgIncBpp(CWnd* pParent /*=NULL*/) + : CDialog(DlgIncBpp::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgIncBpp) + //}}AFX_DATA_INIT +} + + +void DlgIncBpp::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgIncBpp) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, IDC_RADIO1, m_r4); + DDX_Control(pDX, IDC_RADIO3, m_r24); + DDX_Control(pDX, IDC_RADIO2, m_r8); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgIncBpp, CDialog) + //{{AFX_MSG_MAP(DlgIncBpp) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgIncBpp message handlers + +BOOL DlgIncBpp::OnInitDialog() +{ + CDialog::OnInitDialog(); + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + if (m_bit == 4) m_r4.SetCheck(1); + else if (m_bit == 8) m_r8.SetCheck(1); + else m_r24.SetCheck(1); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgIncBpp::OnOK() +{ + if (m_r4.GetCheck()) m_bit=4; + else if (m_r8.GetCheck()) m_bit=8; + else m_bit=24; + + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgIncBpp.h b/SlnkDWFImpl/CxImage/demo/DlgIncBpp.h new file mode 100644 index 0000000..ed66b93 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgIncBpp.h @@ -0,0 +1,53 @@ +#if !defined(AFX_DLGINCBPP_H__55B7AF22_BB40_11D5_8DD4_00E07D8144D0__INCLUDED_) +#define AFX_DLGINCBPP_H__55B7AF22_BB40_11D5_8DD4_00E07D8144D0__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgIncBpp.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgIncBpp dialog +class DlgIncBpp : public CDialog +{ +// Construction +public: + long m_bit; + DlgIncBpp(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgIncBpp) + enum { IDD = IDD_INCBPP }; + CxTargetButton m_ok; + CxTargetButton m_canc; + CButton m_r4; + CButton m_r24; + CButton m_r8; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgIncBpp) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgIncBpp) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGINCBPP_H__55B7AF22_BB40_11D5_8DD4_00E07D8144D0__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgJpeg.cpp b/SlnkDWFImpl/CxImage/demo/DlgJpeg.cpp new file mode 100644 index 0000000..78d4bd1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgJpeg.cpp @@ -0,0 +1,67 @@ +// DlgJpeg.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgJpeg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgJpeg dialog + + +DlgJpeg::DlgJpeg(CWnd* pParent /*=NULL*/) + : CDialog(DlgJpeg::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgJpeg) + m_quality = 0; + //}}AFX_DATA_INIT +} + + +void DlgJpeg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgJpeg) + DDX_Control(pDX, IDC_RADIO1, m_r1); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_EDIT1, m_quality); + DDV_MinMaxLong(pDX, m_quality, 0, 255); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgJpeg, CDialog) + //{{AFX_MSG_MAP(DlgJpeg) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgJpeg message handlers + +BOOL DlgJpeg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + m_r1.SetCheck(1); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgJpeg::OnOK() +{ + if (m_r1.GetCheck()) m_format = 0; + else m_format = 1; + + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgJpeg.h b/SlnkDWFImpl/CxImage/demo/DlgJpeg.h new file mode 100644 index 0000000..e275f4c --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgJpeg.h @@ -0,0 +1,53 @@ +#if !defined(AFX_DLGJPEG_H__578E3AEA_8D08_432D_801C_BA0FA97E9E4C__INCLUDED_) +#define AFX_DLGJPEG_H__578E3AEA_8D08_432D_801C_BA0FA97E9E4C__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgJpeg.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgJpeg dialog + +class DlgJpeg : public CDialog +{ +// Construction +public: + DlgJpeg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgJpeg) + enum { IDD = IDD_JPEG }; + CButton m_r1; + CxTargetButton m_ok; + CxTargetButton m_canc; + long m_quality; + long m_format; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgJpeg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgJpeg) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGJPEG_H__578E3AEA_8D08_432D_801C_BA0FA97E9E4C__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgMix.cpp b/SlnkDWFImpl/CxImage/demo/DlgMix.cpp new file mode 100644 index 0000000..ab3b1bd --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgMix.cpp @@ -0,0 +1,206 @@ +// DlgMix.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "demoDoc.h" +#include "DlgMix.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgMix dialog + + +DlgMix::DlgMix(CWnd* pParent /*=NULL*/) + : CDialog(DlgMix::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgMix) + m_xoffset = 0; + m_yoffset = 0; + m_mixalpha = FALSE; + //}}AFX_DATA_INIT +} + + +void DlgMix::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgMix) + DDX_Control(pDX, IDC_PICTURE, m_picture); + DDX_Control(pDX, IDC_BUTTON1, m_preview); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, IDC_SRC, m_cbSrc); + DDX_Control(pDX, IDC_OP, m_cbOpType); + DDX_Control(pDX, IDC_DST, m_cbDst); + DDX_Text(pDX, IDC_EDIT1, m_xoffset); + DDX_Text(pDX, IDC_EDIT2, m_yoffset); + DDX_Check(pDX, IDC_CHECK1, m_mixalpha); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgMix, CDialog) + //{{AFX_MSG_MAP(DlgMix) + ON_BN_CLICKED(IDC_BUTTON1, OnButton1) + ON_WM_DESTROY() + ON_CBN_SELCHANGE(IDC_DST, OnSelchangeDst) + ON_CBN_SELCHANGE(IDC_SRC, OnSelchangeSrc) + ON_CBN_SELCHANGE(IDC_OP, OnSelchangeOp) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgMix message handlers + +BOOL DlgMix::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_bitmap=0; + m_ratio=1.0f; + m_xoffset=m_yoffset=0; + pDocSrc = pDocDst = 0; + OpType=0; + m_mixalpha = 0; + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + POSITION pos = AfxGetApp()->GetFirstDocTemplatePosition(); + while (pos != NULL) { + CDocTemplate* pTemplate = AfxGetApp()->GetNextDocTemplate(pos); + ASSERT(pTemplate->IsKindOf(RUNTIME_CLASS(CDocTemplate))); + POSITION pos2 = pTemplate->GetFirstDocPosition(); + while (pos2 != NULL) { + CDemoDoc* pDoc = (CDemoDoc*) pTemplate->GetNextDoc(pos2); + ASSERT(pDoc->IsKindOf(RUNTIME_CLASS(CDemoDoc))); + CString title = pDoc->GetTitle(); + m_cbSrc.AddString(title); + m_cbSrc.SetItemData(m_cbSrc.GetCount()-1, (DWORD)pDoc); + m_cbDst.AddString(title); + m_cbDst.SetItemData(m_cbDst.GetCount()-1, (DWORD)pDoc); + } + } + m_cbSrc.SetCurSel(0); + + if (m_cbDst.GetCount()>1){ + m_cbDst.SetCurSel(1); + } else { + m_cbDst.SetCurSel(0); + } + + m_cbOpType.AddString("OpAdd"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpAdd); + m_cbOpType.AddString("OpAnd"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpAnd); + m_cbOpType.AddString("OpXor"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpXor); + m_cbOpType.AddString("OpOr"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpOr); + m_cbOpType.AddString("OpScreen"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpScreen); + m_cbOpType.AddString("OpMask"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpMask); + m_cbOpType.AddString("OpSrcCopy"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpSrcCopy); + m_cbOpType.AddString("OpDstCopy"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpDstCopy); + m_cbOpType.AddString("OpSub"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpSub); + m_cbOpType.AddString("OpSrcBlend"); + m_cbOpType.SetItemData(m_cbOpType.GetCount()-1, (DWORD)CxImage::ImageOpType::OpSrcBlend); + m_cbOpType.SetCurSel(1); + + + SetMix(); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgMix::OnButton1() +{ + UpdateData(1); + SetMix(); +} + +void DlgMix::OnDestroy() +{ + CDialog::OnDestroy(); + + if (m_bitmap) DeleteObject(m_bitmap); +} + +void DlgMix::OnSelchangeDst() +{ + UpdateData(1); + SetMix(); +} + +void DlgMix::OnSelchangeSrc() +{ + UpdateData(1); + SetMix(); +} + +void DlgMix::OnSelchangeOp() +{ + UpdateData(1); + SetMix(); +} + +void DlgMix::SetThumbs(CxImage* pSrc, CxImage* pDst) +{ + if (pSrc==0 || pDst==0) return; + + if (pDst->GetWidth() > pDst->GetHeight()){ + m_ratio = 200.0f/pDst->GetWidth(); + } else { + m_ratio = 200.0f/pDst->GetHeight(); + } + if (m_ratio > 1.0f) m_ratio = 1.0f; + + pSrc->Resample((long)(pSrc->GetWidth()*m_ratio),(long)(pSrc->GetHeight()*m_ratio),1,&m_imageSrc); + pDst->Resample((long)(pDst->GetWidth()*m_ratio),(long)(pDst->GetHeight()*m_ratio),1,&m_imageDst); +} + +void DlgMix::SetMix() +{ + pDocSrc = (CDemoDoc*) m_cbSrc.GetItemData(m_cbSrc.GetCurSel()); + pDocDst = (CDemoDoc*) m_cbDst.GetItemData(m_cbDst.GetCurSel()); + OpType = m_cbOpType.GetItemData(m_cbOpType.GetCurSel()); + + if (pDocSrc==0 || pDocDst==0) return; + + CxImage* pImageSrc = pDocSrc->GetImage(); + CxImage* pImageDst = pDocDst->GetImage(); + + SetThumbs(pImageSrc,pImageDst); + + CxImage tmp; + tmp.Copy(m_imageDst); + tmp.Mix(m_imageSrc,(CxImage::ImageOpType)OpType,(long)(m_xoffset*m_ratio),(long)(m_yoffset*m_ratio),m_mixalpha!=0); + + if (m_mixalpha!=0){ + RGBQUAD c={255,255,255,0}; + tmp.SetTransColor(c); + tmp.AlphaStrip(); + } + + if (m_bitmap) DeleteObject(m_bitmap); + m_bitmap = tmp.MakeBitmap(m_picture.GetDC()->m_hDC); + m_picture.SetBitmap(m_bitmap); +} + + +void DlgMix::OnOK() +{ + SetMix(); + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgMix.h b/SlnkDWFImpl/CxImage/demo/DlgMix.h new file mode 100644 index 0000000..33aa533 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgMix.h @@ -0,0 +1,73 @@ +#if !defined(AFX_DLGMIX_H__51F87317_7FCC_4396_8D88_1CFB0ACEEF90__INCLUDED_) +#define AFX_DLGMIX_H__51F87317_7FCC_4396_8D88_1CFB0ACEEF90__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgMix.h : header file +// + +#include "xTargetButton.h" + +class CDemoDoc; +///////////////////////////////////////////////////////////////////////////// +// DlgMix dialog +class DlgMix : public CDialog +{ +// Construction +public: + CDemoDoc* pDocSrc; + CDemoDoc* pDocDst; + int OpType; + + DlgMix(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgMix) + enum { IDD = IDD_MIX }; + CStatic m_picture; + CxTargetButton m_preview; + CxTargetButton m_ok; + CxTargetButton m_canc; + CComboBox m_cbSrc; + CComboBox m_cbOpType; + CComboBox m_cbDst; + int m_xoffset; + int m_yoffset; + BOOL m_mixalpha; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgMix) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + HBITMAP m_bitmap; + CxImage m_imageSrc,m_imageDst; + void SetThumbs(CxImage* pSrc, CxImage* pDst); + float m_ratio; + void SetMix(); + + // Generated message map functions + //{{AFX_MSG(DlgMix) + virtual BOOL OnInitDialog(); + afx_msg void OnButton1(); + afx_msg void OnDestroy(); + afx_msg void OnSelchangeDst(); + afx_msg void OnSelchangeSrc(); + afx_msg void OnSelchangeOp(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGMIX_H__51F87317_7FCC_4396_8D88_1CFB0ACEEF90__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgOpacity.cpp b/SlnkDWFImpl/CxImage/demo/DlgOpacity.cpp new file mode 100644 index 0000000..0a3151e --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgOpacity.cpp @@ -0,0 +1,55 @@ +// DlgOpacity.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgOpacity.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgOpacity dialog + + +DlgOpacity::DlgOpacity(CWnd* pParent /*=NULL*/) + : CDialog(DlgOpacity::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgOpacity) + m_level = 0; + //}}AFX_DATA_INIT +} + + +void DlgOpacity::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgOpacity) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_EDIT1, m_level); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgOpacity, CDialog) + //{{AFX_MSG_MAP(DlgOpacity) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgOpacity message handlers + +BOOL DlgOpacity::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgOpacity.h b/SlnkDWFImpl/CxImage/demo/DlgOpacity.h new file mode 100644 index 0000000..9b6e5e0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgOpacity.h @@ -0,0 +1,49 @@ +#if !defined(AFX_DLGOPACITY_H__B7012944_0790_11D6_8DD7_00E07D8144D0__INCLUDED_) +#define AFX_DLGOPACITY_H__B7012944_0790_11D6_8DD7_00E07D8144D0__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgOpacity.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgOpacity dialog +class DlgOpacity : public CDialog +{ +// Construction +public: + DlgOpacity(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgOpacity) + enum { IDD = IDD_OPACITY }; + CxTargetButton m_ok; + CxTargetButton m_canc; + BYTE m_level; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgOpacity) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgOpacity) + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGOPACITY_H__B7012944_0790_11D6_8DD7_00E07D8144D0__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgOptions.cpp b/SlnkDWFImpl/CxImage/demo/DlgOptions.cpp new file mode 100644 index 0000000..c495cc9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgOptions.cpp @@ -0,0 +1,368 @@ +// DlgOptions.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgOptions.h" + +#include "ximajpg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgOptions dialog + + +DlgOptions::DlgOptions(CWnd* pParent /*=NULL*/) + : CDialog(DlgOptions::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgOptions) + m_quality = 0; + m_xres = 0; + m_yres = 0; + //}}AFX_DATA_INIT +} + + +void DlgOptions::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgOptions) + DDX_Control(pDX, IDC_CHECK5, m_chkJpgOpt); + DDX_Control(pDX, IDEXIF, m_info); + DDX_Control(pDX, IDC_RADIO14,m_rEnc14); + DDX_Control(pDX, IDC_RADIO13,m_rEnc13); + DDX_Control(pDX, IDC_RADIO12,m_rEnc12); + DDX_Control(pDX, IDC_RADIO11,m_rEnc11); + DDX_Control(pDX, IDC_RADIO10,m_rEnc10); + DDX_Control(pDX, IDC_RADIO9, m_rEnc9); + DDX_Control(pDX, IDC_RADIO8, m_rEnc8); + DDX_Control(pDX, IDC_RADIO7, m_rEnc7); + DDX_Control(pDX, IDC_RADIO6, m_rEnc5); + DDX_Control(pDX, IDC_RADIO5, m_rEnc4); + DDX_Control(pDX, IDC_RADIO4, m_rEnc3); + DDX_Control(pDX, IDC_RADIO3, m_rEnc2); + DDX_Control(pDX, IDC_RADIO2, m_rEnc1); + DDX_Control(pDX, IDC_RADIO1, m_rEnc0); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_EDIT1, m_quality); + DDV_MinMaxByte(pDX, m_quality, 1, 255); + DDX_Text(pDX, IDC_EDIT2, m_xres); + DDV_MinMaxLong(pDX, m_xres, 0, 10000); + DDX_Text(pDX, IDC_EDIT3, m_yres); + DDV_MinMaxDWord(pDX, m_yres, 0, 10000); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgOptions, CDialog) + //{{AFX_MSG_MAP(DlgOptions) + ON_BN_CLICKED(IDEXIF, OnExif) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgOptions message handlers + +BOOL DlgOptions::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + m_info.SetIcon(IDI_B,BS_LEFT); + + m_info.EnableWindow(m_exif->m_exifinfo.IsExif); + + switch(m_Opt_tif) + { + case 1: + m_rEnc1.SetCheck(1); + break; + case 2: + m_rEnc2.SetCheck(1); + break; + case 3: + case 4: + m_rEnc3.SetCheck(1); + break; + case 5: + m_rEnc7.SetCheck(1); + break; + case 32773: + m_rEnc4.SetCheck(1); + break; + case 7: + m_rEnc5.SetCheck(1); + break; + default: + m_rEnc0.SetCheck(1); + } + + switch(m_Opt_gif) + { + case 1: + m_rEnc9.SetCheck(1); + break; + case 2: + m_rEnc10.SetCheck(1); + break; + default: + m_rEnc8.SetCheck(1); + } + + switch(m_Opt_png) + { + case 1: + m_rEnc12.SetCheck(1); + break; + default: + m_rEnc11.SetCheck(1); + } + + if (m_Opt_jpg & CxImageJPG::ENCODE_PROGRESSIVE){ + m_rEnc14.SetCheck(1); + } else { + m_rEnc13.SetCheck(1); + } + if (m_Opt_jpg & CxImageJPG::ENCODE_OPTIMIZE){ + m_chkJpgOpt.SetCheck(1); + } else { + m_chkJpgOpt.SetCheck(0); + } + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgOptions::OnOK() +{ + if (m_rEnc1.GetCheck()) m_Opt_tif = 1; + if (m_rEnc2.GetCheck()) m_Opt_tif = 2; + if (m_rEnc3.GetCheck()) m_Opt_tif = 4; + if (m_rEnc4.GetCheck()) m_Opt_tif = 32773; + if (m_rEnc5.GetCheck()) m_Opt_tif = 7; + if (m_rEnc7.GetCheck()) m_Opt_tif = 5; + if (m_rEnc0.GetCheck()) m_Opt_tif = 0; + + if (m_rEnc8.GetCheck()) m_Opt_gif = 0; + if (m_rEnc9.GetCheck()) m_Opt_gif = 1; + if (m_rEnc10.GetCheck()) m_Opt_gif = 2; + + if (m_rEnc11.GetCheck()) m_Opt_png = 0; + if (m_rEnc12.GetCheck()) m_Opt_png = 1; + + if (m_rEnc13.GetCheck()) m_Opt_jpg = 0; + if (m_rEnc14.GetCheck()) m_Opt_jpg = CxImageJPG::ENCODE_PROGRESSIVE; + if (m_chkJpgOpt.GetCheck()) m_Opt_jpg |= CxImageJPG::ENCODE_OPTIMIZE; + + CDialog::OnOK(); +} + +void DlgOptions::OnExif() +{ + CString s,t; + s=""; + + if (m_exif->m_exifinfo.CameraMake[0]){ + t.Format("Camera make : %s\n",m_exif->m_exifinfo.CameraMake); s+=t; + t.Format("Camera model : %s\n",m_exif->m_exifinfo.CameraModel); s+=t; + } + if (m_exif->m_exifinfo.DateTime[0]){ + t.Format("Date/Time : %s\n",m_exif->m_exifinfo.DateTime); s+=t; + } + if (m_exif->m_exifinfo.Version[0]){ + t.Format("Exif version : %s\n",m_exif->m_exifinfo.Version); s+=t; + } + + t.Format("Width x Height : %d x %d\n",m_exif->m_exifinfo.Width, m_exif->m_exifinfo.Height); s+=t; + + if ((m_exif->m_exifinfo.ResolutionUnit!=0)&&(m_exif->m_exifinfo.Xresolution!=0)){ + t.Format("X resolution (dpi) : %5.1f\n",m_exif->m_exifinfo.Xresolution/m_exif->m_exifinfo.ResolutionUnit); s+=t; + } + if ((m_exif->m_exifinfo.ResolutionUnit!=0)&&(m_exif->m_exifinfo.Yresolution!=0)){ + t.Format("Y resolution (dpi) : %5.1f\n",m_exif->m_exifinfo.Yresolution/m_exif->m_exifinfo.ResolutionUnit); s+=t; + } + + if (m_exif->m_exifinfo.Orientation > 1){ + t.Format("Orientation : %s\n", m_exif->m_exifinfo.Orientation); s+=t; + } + if (m_exif->m_exifinfo.IsColor == 0){ + t.Format("Color/bw : Black and white\n"); s+=t; + } + if (m_exif->m_exifinfo.FlashUsed >= 0){ + t.Format("Flash used : %s\n",m_exif->m_exifinfo.FlashUsed ? "Yes" :"No"); s+=t; + } + if (m_exif->m_exifinfo.FocalLength){ + t.Format("Focal length : %4.1fmm",(double)m_exif->m_exifinfo.FocalLength); s+=t; + if (m_exif->m_exifinfo.CCDWidth){ + t.Format(" (35mm equivalent: %dmm)", + (int)(m_exif->m_exifinfo.FocalLength/m_exif->m_exifinfo.CCDWidth*36 + 0.5)); s+=t; + } + t.Format("\n"); s+=t; + } + + if (m_exif->m_exifinfo.CCDWidth){ + t.Format("CCD width : %4.2fmm\n",(double)m_exif->m_exifinfo.CCDWidth); s+=t; + } + + if (m_exif->m_exifinfo.ExposureTime){ + t.Format("Exposure time:%6.3f s ",(double)m_exif->m_exifinfo.ExposureTime); s+=t; + if (m_exif->m_exifinfo.ExposureTime <= 0.5){ + t.Format(" (1/%d)",(int)(0.5 + 1/m_exif->m_exifinfo.ExposureTime)); s+=t; + } + t.Format("\n"); s+=t; + } + if (m_exif->m_exifinfo.Brightness){ + t.Format("Brightness : %6.3f\n",m_exif->m_exifinfo.Brightness); s+=t; + } + if (m_exif->m_exifinfo.ApertureFNumber){ + t.Format("Aperture : f/%3.1f\n",(double)m_exif->m_exifinfo.ApertureFNumber); s+=t; + } + if (m_exif->m_exifinfo.Distance){ + if (m_exif->m_exifinfo.Distance < 0){ + t.Format("Focus dist. : Infinite\n"); s+=t; + }else{ + t.Format("Focus dist. : %4.2fm\n",(double)m_exif->m_exifinfo.Distance); s+=t; + } + } + + + if (m_exif->m_exifinfo.ISOequivalent){ // 05-jan-2001 vcs + t.Format("ISO equiv. : %2d\n",(int)m_exif->m_exifinfo.ISOequivalent); s+=t; + } + if (m_exif->m_exifinfo.ExposureBias){ // 05-jan-2001 vcs + t.Format("Exposure bias:%4.2f\n",(double)m_exif->m_exifinfo.ExposureBias); s+=t; + } + + if (m_exif->m_exifinfo.Whitebalance){ // 05-jan-2001 vcs + switch(m_exif->m_exifinfo.Whitebalance) { + case 1: + t.Format("Whitebalance : sunny\n"); s+=t; + break; + case 2: + t.Format("Whitebalance : fluorescent\n"); s+=t; + break; + case 3: + t.Format("Whitebalance : incandescent\n"); s+=t; + break; + default: + t.Format("Whitebalance : cloudy\n"); s+=t; + } + } + if (m_exif->m_exifinfo.MeteringMode){ // 05-jan-2001 vcs + switch(m_exif->m_exifinfo.MeteringMode) { + case 2: + t.Format("Metering Mode: center weight\n"); s+=t; + break; + case 3: + t.Format("Metering Mode: spot\n"); s+=t; + break; + case 5: + t.Format("Metering Mode: matrix\n"); s+=t; + break; + } + } + if (m_exif->m_exifinfo.ExposureProgram){ // 05-jan-2001 vcs + switch(m_exif->m_exifinfo.ExposureProgram) { + case 2: + t.Format("Exposure : program (auto)\n"); s+=t; + break; + case 3: + t.Format("Exposure : aperture priority (semi-auto)\n"); s+=t; + break; + case 4: + t.Format("Exposure : shutter priority (semi-auto)\n"); s+=t; + break; + } + } + if (m_exif->m_exifinfo.CompressionLevel){ // 05-jan-2001 vcs + switch(m_exif->m_exifinfo.CompressionLevel) { + case 1: + t.Format("Jpeg Quality : basic\n"); s+=t; + break; + case 2: + t.Format("Jpeg Quality : normal\n"); s+=t; + break; + case 4: + t.Format("Jpeg Quality : fine\n"); s+=t; + break; + } + } + + t.Format("Encoding : "); s+=t; + switch(m_exif->m_exifinfo.Process){ + case 0xC0: //M_SOF0 + t.Format("Baseline\n"); s+=t; + break; + case 0xC1: //M_SOF1 + t.Format("Extended sequential\n"); s+=t; + break; + case 0xC2: //M_SOF2 + t.Format("Progressive\n"); s+=t; + break; + case 0xC3: //M_SOF3 + t.Format("Lossless\n"); s+=t; + break; + case 0xC5: //M_SOF5 + t.Format("Differential sequential\n"); s+=t; + break; + case 0xC6: //M_SOF6 + t.Format("Differential progressive\n"); s+=t; + break; + case 0xC7: //M_SOF7 + t.Format("Differential lossless\n"); s+=t; + break; + case 0xC9: //M_SOF9 + t.Format("Extended sequential, arithmetic coding\n"); s+=t; + break; + case 0xCA: //M_SOF10 + t.Format("Progressive, arithmetic coding\n"); s+=t; + break; + case 0xCB: //M_SOF11 + t.Format("Lossless, arithmetic coding\n"); s+=t; + break; + case 0xCD: //M_SOF13 + t.Format("Differential sequential, arithmetic coding\n"); s+=t; + break; + case 0xCE: //M_SOF14 + t.Format("Differential progressive, arithmetic coding\n"); s+=t; + break; + case 0xCF: //M_SOF0 + t.Format("Differential lossless, arithmetic coding\n"); s+=t; + break; + default: + t.Format("Unknown\n"); s+=t; + break; + } + + // Print the comment. Print 'Comment:' for each new line of comment. + if (m_exif->m_exifinfo.Comments[0]){ + int a; + char c; + t.Format("Comment : "); s+=t; + for (a=0;am_exifinfo.Comments[a]; + if (c == '\0') break; + if (c == '\n'){ + // Do not start a new line if the string ends with a carriage return. + if (m_exif->m_exifinfo.Comments[a+1] != '\0'){ + t.Format("\nComment : "); s+=t; + }else{ + t.Format("\n"); s+=t; + } + }else{ + s+=c; + } + } + } + + t.Format("\n"); s+=t; + + MessageBox(s,"EXIF",MB_OK|MB_ICONQUESTION); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgOptions.h b/SlnkDWFImpl/CxImage/demo/DlgOptions.h new file mode 100644 index 0000000..c42e642 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgOptions.h @@ -0,0 +1,76 @@ +#if !defined(AFX_DLGOPTIONS_H__218AAA01_FAC3_11D5_8DD7_00E07D8144D0__INCLUDED_) +#define AFX_DLGOPTIONS_H__218AAA01_FAC3_11D5_8DD7_00E07D8144D0__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgOptions.h : header file +// + +#include "xTargetButton.h" + +class CxImageJPG; + +///////////////////////////////////////////////////////////////////////////// +// DlgOptions dialog +class DlgOptions : public CDialog +{ +// Construction +public: + DWORD m_Opt_tif; + DWORD m_Opt_gif; + DWORD m_Opt_jpg; + DWORD m_Opt_png; + CxImageJPG* m_exif; + DlgOptions(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgOptions) + enum { IDD = IDD_OPTIONS }; + CButton m_chkJpgOpt; + CxTargetButton m_info; + CButton m_rEnc14; + CButton m_rEnc13; + CButton m_rEnc12; + CButton m_rEnc11; + CButton m_rEnc10; + CButton m_rEnc9; + CButton m_rEnc8; + CButton m_rEnc7; + CButton m_rEnc5; + CButton m_rEnc4; + CButton m_rEnc3; + CButton m_rEnc2; + CButton m_rEnc1; + CButton m_rEnc0; + CxTargetButton m_ok; + CxTargetButton m_canc; + BYTE m_quality; + long m_xres; + DWORD m_yres; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgOptions) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgOptions) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + afx_msg void OnExif(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGOPTIONS_H__218AAA01_FAC3_11D5_8DD7_00E07D8144D0__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgPalette.cpp b/SlnkDWFImpl/CxImage/demo/DlgPalette.cpp new file mode 100644 index 0000000..4e5ded7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgPalette.cpp @@ -0,0 +1,391 @@ +// DlgPalette.cpp : implementation file +/* Based on CColourPicker and CColourPopup, by Chris Maunder */ + +#include "stdafx.h" +#include "demo.h" +#include "DlgPalette.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgPalette dialog + + +DlgPalette::DlgPalette(CWnd* pParent /*=NULL*/) + : CDialog(DlgPalette::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgPalette) + m_editalpha = FALSE; + //}}AFX_DATA_INIT +} + + +void DlgPalette::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgPalette) + DDX_Control(pDX, IDC_BAR, m_bar); + DDX_Control(pDX, IDC_RADIO3, m_r3); + DDX_Control(pDX, IDC_RADIO2, m_r2); + DDX_Control(pDX, IDC_RADIO1, m_r1); + DDX_Control(pDX, IDC_LOAD, m_load); + DDX_Control(pDX, IDC_SAVE, m_save); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Check(pDX, IDC_CHECK2, m_editalpha); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgPalette, CDialog) + //{{AFX_MSG_MAP(DlgPalette) + ON_WM_PAINT() + ON_BN_CLICKED(IDC_CHECK2, OnEditAlpha) + ON_WM_LBUTTONDBLCLK() + ON_WM_MOUSEMOVE() + ON_BN_CLICKED(IDC_LOAD, OnLoad) + ON_BN_CLICKED(IDC_SAVE, OnSave) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgPalette message handlers + +BOOL DlgPalette::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + m_save.SetIcon(IDI_B,BS_LEFT); + m_load.SetIcon(IDI_B,BS_LEFT); + + m_r1.SetCheck(1); + + m_boxgap=1; + m_boxheight=11; + m_boxwidth=11; + m_yoffset=14; + m_xoffset=14; + m_numcolumns=16; + m_numrows=16; + + m_changed=0; + m_selected=-1; + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} +///////////////////////////////////////////////////////////////////////////// +long DlgPalette::GetColumn(long index) const +{ + return index % m_numcolumns; +} +///////////////////////////////////////////////////////////////////////////// +long DlgPalette::GetRow(long index) const +{ + return index / m_numcolumns; +} +///////////////////////////////////////////////////////////////////////////// +long DlgPalette::GetIndex(long row, long col) const +{ + long i=row*m_numcolumns + col; + if (i >= m_numcolors || row!=GetRow(i) || col!=GetColumn(i)) + return -1; + else + return i; +} +///////////////////////////////////////////////////////////////////////////// +void DlgPalette::DrawCell(CDC *pDC, long index) +{ + CRect rect; + if (!GetCellRect(index, rect)) return; + + CBrush brush; + + if (m_editalpha){ + brush.CreateSolidBrush(RGB(m_pal[index].rgbReserved, + m_pal[index].rgbReserved , + m_pal[index].rgbReserved )); + }else{ + brush.CreateSolidBrush(RGB(m_pal[index].rgbRed , + m_pal[index].rgbGreen , + m_pal[index].rgbBlue )); + } + + CPen pen; + if (index==m_selected) + pen.CreatePen(PS_SOLID, 2, ::GetSysColor(COLOR_3DDKSHADOW)); + else + pen.CreatePen(PS_SOLID, 1, ::GetSysColor(COLOR_3DSHADOW)); + + CBrush* pOldBrush = (CBrush*) pDC->SelectObject(&brush); + CPen* pOldPen = (CPen*) pDC->SelectObject(&pen); + + // Draw the cell colour + pDC->Rectangle(rect); + + // restore DC and cleanup + pDC->SelectObject(pOldBrush); + pDC->SelectObject(pOldPen); + brush.DeleteObject(); + pen.DeleteObject(); +} +///////////////////////////////////////////////////////////////////////////// +bool DlgPalette::GetCellRect(long index, const LPRECT &rect) +{ + if (index < 0 || index >= m_numcolors) return false; + + rect->left = GetColumn(index) * (m_boxwidth+m_boxgap) + m_xoffset; + rect->top = GetRow(index) * (m_boxheight+m_boxgap) + m_yoffset; + rect->right = rect->left + m_boxwidth; + rect->bottom = rect->top + m_boxheight; + + return true; +} +///////////////////////////////////////////////////////////////////////////// + + + +void DlgPalette::OnPaint() +{ + CPaintDC dc(this); // device context for painting + + for (int i = 0; i=0 && y>=0){ + long i = GetIndex(y / (m_boxheight+m_boxgap), x / (m_boxwidth+m_boxgap)); + + if (i>=0 && i=0 && y>=0){ + long i = GetIndex(y / (m_boxheight+m_boxgap), x / (m_boxwidth+m_boxgap)); + + if (i>=0 && i= 0); + } + } + return bRet; +} +////////////////////////////////////////////////////////////////////////////// +void DlgPalette::OnLoad() +{ + CString filename; + if (!PromptForFileName(filename, AFX_IDS_OPENFILE, + OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, TRUE, NULL)) + return; // open cancelled + + FILE* f; + f=fopen(filename,"rb"); + + if (f==NULL) return; + + char key[5]; + fread(key,4,1,f); + key[4]=0; + + if (strcmp(key,"JASC")==0){ + long pos,size; + pos = ftell(f); + fseek(f, 0, SEEK_END); + size = ftell(f); + fseek(f, pos,SEEK_SET); + char* buffer = (char*)malloc(size); + fread(buffer,size,1,f); + fclose(f); + char* token; + token = strtok(buffer,"\n"); + if (token){ + token=strtok(NULL,"\n"); + token=strtok(NULL,"\n"); + long numcolors=atol(token); + if (numcolors>256){ + free(buffer); + AfxMessageBox("Too much colors!"); + return; + } + if (numcolors!=m_numcolors){ + numcolors = min(m_numcolors,numcolors); + AfxMessageBox("Warning: numcolors doesn't match"); + } + long i=0; + while (token && i256){ + fclose(f); + AfxMessageBox("Too much colors!"); + return; + } + if (numcolors!=m_numcolors){ + numcolors = min(m_numcolors,numcolors); + AfxMessageBox("Warning: numcolors doesn't match"); + } + fread(m_pal,numcolors,sizeof(RGBQUAD),f); + for (int i=0;i 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgPalette.h : header file +/* Based on CColourPicker and CColourPopup, by Chris Maunder */ + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgPalette dialog +class DlgPalette : public CDialog +{ +// Construction +public: + long m_selected; + long m_replace; + long m_changed; + long m_boxgap; + long m_boxheight; + long m_boxwidth; + long m_yoffset; + long m_xoffset; + long m_numcolumns; + long m_numrows; + long m_numcolors; + RGBQUAD m_pal[256]; + DlgPalette(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgPalette) + enum { IDD = IDD_PALETTE }; + CStatic m_bar; + CButton m_r3; + CButton m_r2; + CButton m_r1; + CxTargetButton m_load; + CxTargetButton m_save; + CxTargetButton m_ok; + CxTargetButton m_canc; + BOOL m_editalpha; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgPalette) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + bool GetCellRect(long index, const LPRECT& rect); + void DrawCell(CDC* pDC, long index); + long GetColumn(long index) const; + long GetRow(long index) const; + long GetIndex(long row, long col) const; + BOOL PromptForFileName(CString& fileName, UINT nIDSTitle,DWORD dwFlags, BOOL bOpenFileDialog, int* pType); + + // Generated message map functions + //{{AFX_MSG(DlgPalette) + virtual BOOL OnInitDialog(); + afx_msg void OnPaint(); + afx_msg void OnEditAlpha(); + afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); + afx_msg void OnMouseMove(UINT nFlags, CPoint point); + virtual void OnOK(); + afx_msg void OnLoad(); + afx_msg void OnSave(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGPALETTE_H__76ED5361_AECA_11D6_BB83_E2CBB4CAE57F__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgRepair.cpp b/SlnkDWFImpl/CxImage/demo/DlgRepair.cpp new file mode 100644 index 0000000..4676c03 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgRepair.cpp @@ -0,0 +1,67 @@ +// DlgRepair.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgRepair.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgRepair dialog + + +DlgRepair::DlgRepair(CWnd* pParent /*=NULL*/) + : CDialog(DlgRepair::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgRepair) + m_radius = 0.0f; + m_iterations = 0; + //}}AFX_DATA_INIT +} + + +void DlgRepair::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgRepair) + DDX_Control(pDX, IDC_COMBO9, m_cs); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_EDIT2, m_radius); + DDX_Text(pDX, IDC_EDIT3, m_iterations); + DDV_MinMaxInt(pDX, m_iterations, 1, 50); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgRepair, CDialog) + //{{AFX_MSG_MAP(DlgRepair) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgRepair message handlers + +BOOL DlgRepair::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + m_cs.SetCurSel(0); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgRepair::OnOK() +{ + m_ncs = m_cs.GetCurSel(); + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgRepair.h b/SlnkDWFImpl/CxImage/demo/DlgRepair.h new file mode 100644 index 0000000..b4af29a --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgRepair.h @@ -0,0 +1,54 @@ +#if !defined(AFX_DLGREPAIR_H__399C37C1_B3B5_11D6_BB83_93FE8A487F7B__INCLUDED_) +#define AFX_DLGREPAIR_H__399C37C1_B3B5_11D6_BB83_93FE8A487F7B__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgRepair.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgRepair dialog +class DlgRepair : public CDialog +{ +// Construction +public: + long m_ncs; + + DlgRepair(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgRepair) + enum { IDD = IDD_REPAIR }; + CComboBox m_cs; + CxTargetButton m_ok; + CxTargetButton m_canc; + float m_radius; + int m_iterations; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgRepair) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgRepair) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGREPAIR_H__399C37C1_B3B5_11D6_BB83_93FE8A487F7B__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgResample.cpp b/SlnkDWFImpl/CxImage/demo/DlgResample.cpp new file mode 100644 index 0000000..e09f225 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgResample.cpp @@ -0,0 +1,128 @@ +// DlgResample.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgResample.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +////////////////////////////////////////////////////////////////////////////// +// DlgResample dialog + +DlgResample::DlgResample(CWnd* pParent /*=NULL*/) + : CDialog(DlgResample::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgResample) + m_factor = 0.0f; + m_newheight = 0; + m_newwidth = 0; + //}}AFX_DATA_INIT +} + +void DlgResample::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgResample) + DDX_Control(pDX, IDC_EDIT1, m_ed1); + DDX_Control(pDX, IDC_CHECK2, m_ch2); + DDX_Control(pDX, IDC_COMBO_IM, inMethod); + DDX_Control(pDX, IDC_RADIO2, m_r2); + DDX_Control(pDX, IDC_RADIO1, m_r1); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_EDIT1, m_factor); + DDX_Text(pDX, IDC_EDIT3, m_newheight); + DDX_Text(pDX, IDC_EDIT2, m_newwidth); + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(DlgResample, CDialog) + //{{AFX_MSG_MAP(DlgResample) + ON_EN_CHANGE(IDC_EDIT2, OnChangeEdit2) + ON_EN_CHANGE(IDC_EDIT3, OnChangeEdit3) + ON_EN_CHANGE(IDC_EDIT1, OnChangeEdit1) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +////////////////////////////////////////////////////////////////////////////// +// DlgResample message handlers + +BOOL DlgResample::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + m_r1.SetCheck(1); + inMethod.SetCurSel(2); + m_ch2.SetCheck(1); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgResample::OnOK() +{ + m_mode=inMethod.GetCurSel(); + + if (m_r1.GetCheck()) m_sizemode=1; //factor + if (m_r2.GetCheck()) m_sizemode=0; //pixel + + CDialog::OnOK(); +} + +void DlgResample::OnChangeEdit2() +{ + // TODO: If this is a RICHEDIT control, the control will not + // send this notification unless you override the CDialog::OnInitDialog() + // function and call CRichEditCtrl().SetEventMask() + // with the ENM_CHANGE flag ORed into the mask. + + if (m_ch2.GetCheck()){ + UpdateData(1); + m_newheight = (DWORD)(m_newwidth / m_ratio); + UpdateData(0); + } + m_r1.SetCheck(0); + m_r2.SetCheck(1); +} + +void DlgResample::OnChangeEdit3() +{ + // TODO: If this is a RICHEDIT control, the control will not + // send this notification unless you override the CDialog::OnInitDialog() + // function and call CRichEditCtrl().SetEventMask() + // with the ENM_CHANGE flag ORed into the mask. + if (m_ch2.GetCheck()){ + UpdateData(1); + m_newwidth = (DWORD)(m_newheight * m_ratio); + UpdateData(0); + } + m_r1.SetCheck(0); + m_r2.SetCheck(1); +} + +void DlgResample::OnChangeEdit1() +{ + // TODO: If this is a RICHEDIT control, the control will not + // send this notification unless you override the CDialog::OnInitDialog() + // function and call CRichEditCtrl().SetEventMask() + // with the ENM_CHANGE flag ORed into the mask. + CString s; + m_ed1.GetWindowText(s); + bool hasdp = (s.Find('.')>=0); + if (!(s.GetAt(s.GetLength()-1)=='.' || hasdp && s.GetAt(s.GetLength()-1)=='0')){ + UpdateData(1); + m_newwidth = (DWORD)(m_w * fabs(m_factor)); + m_newheight = (DWORD)(m_h * fabs(m_factor)); + UpdateData(0); + } + m_r2.SetCheck(0); + m_r1.SetCheck(1); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgResample.h b/SlnkDWFImpl/CxImage/demo/DlgResample.h new file mode 100644 index 0000000..80cdac4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgResample.h @@ -0,0 +1,65 @@ +#if !defined(AFX_DLGRESAMPLE_H__96A4AF61_B1E5_11D5_8DD4_00E07D8144D0__INCLUDED_) +#define AFX_DLGRESAMPLE_H__96A4AF61_B1E5_11D5_8DD4_00E07D8144D0__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgResample.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgResample dialog +class DlgResample : public CDialog +{ +// Construction +public: + long m_mode; + long m_sizemode; + float m_ratio; + DWORD m_w; + DWORD m_h; + DlgResample(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgResample) + enum { IDD = IDD_RESAMPLE }; + CEdit m_ed1; + CButton m_ch2; + CComboBox inMethod; + CButton m_r2; + CButton m_r1; + CxTargetButton m_ok; + CxTargetButton m_canc; + float m_factor; + DWORD m_newheight; + DWORD m_newwidth; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgResample) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgResample) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + afx_msg void OnChangeEdit2(); + afx_msg void OnChangeEdit3(); + afx_msg void OnChangeEdit1(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGRESAMPLE_H__96A4AF61_B1E5_11D5_8DD4_00E07D8144D0__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgRotate.cpp b/SlnkDWFImpl/CxImage/demo/DlgRotate.cpp new file mode 100644 index 0000000..069bbaf --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgRotate.cpp @@ -0,0 +1,73 @@ +// DlgRotate.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgRotate.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +////////////////////////////////////////////////////////////////////////////// +// DlgRotate dialog + + +DlgRotate::DlgRotate(CWnd* pParent /*=NULL*/) + : CDialog(DlgRotate::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgRotate) + m_angle = 0.0f; + //}}AFX_DATA_INIT +} + + +void DlgRotate::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgRotate) + DDX_Control(pDX, IDC_CHECK1, m_ch1); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_EDIT1, m_angle); + DDX_Control(pDX, IDC_COMBO_IM, inMethod); + DDX_Control(pDX, IDC_COMBO_OM, ofMethod); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgRotate, CDialog) + //{{AFX_MSG_MAP(DlgRotate) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +////////////////////////////////////////////////////////////////////////////// +// DlgRotate message handlers + +BOOL DlgRotate::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + inMethod.SetCurSel(1); + ofMethod.SetCurSel(0); + + m_ch1.SetCheck(1); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgRotate::OnOK() +{ + m_method=inMethod.GetCurSel(); + m_overflow=ofMethod.GetCurSel(); + + m_keepsize=m_ch1.GetCheck(); + + CDialog::OnOK(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgRotate.h b/SlnkDWFImpl/CxImage/demo/DlgRotate.h new file mode 100644 index 0000000..f55304d --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgRotate.h @@ -0,0 +1,56 @@ +#if !defined(AFX_DLGROTATE_H__4DDB3383_9804_11D5_8DD4_D76CCF55323D__INCLUDED_) +#define AFX_DLGROTATE_H__4DDB3383_9804_11D5_8DD4_D76CCF55323D__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgRotate.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgRotate dialog +class DlgRotate : public CDialog +{ +// Construction +public: + long m_method; + long m_overflow; + long m_keepsize; + DlgRotate(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgRotate) + enum { IDD = IDD_ROTATE }; + CButton m_ch1; + CxTargetButton m_ok; + CxTargetButton m_canc; + float m_angle; + CComboBox inMethod; + CComboBox ofMethod; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgRotate) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgRotate) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGROTATE_H__4DDB3383_9804_11D5_8DD4_D76CCF55323D__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgSkew.cpp b/SlnkDWFImpl/CxImage/demo/DlgSkew.cpp new file mode 100644 index 0000000..66a8a6a --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgSkew.cpp @@ -0,0 +1,98 @@ +// DlgSkew.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgSkew.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgSkew dialog + + +DlgSkew::DlgSkew(CWnd* pParent /*=NULL*/) + : CDialog(DlgSkew::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgSkew) + m_bEnableInterpolation = FALSE; + m_pivotx = 0; + m_pivoty = 0; + m_skewx = 5.5f; + m_skewy = -5.0f; + m_anglex = 0.4f; + m_angley = 0.5f; + m_slopex = 0.6f; + m_slopey = 0.7f; + //}}AFX_DATA_INIT +} + + +void DlgSkew::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgSkew) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Check(pDX, IDC_CHECK1, m_bEnableInterpolation); + DDX_Text(pDX, IDC_EDIT1, m_pivotx); + DDX_Text(pDX, IDC_EDIT2, m_pivoty); + DDX_Text(pDX, IDC_EDIT4, m_skewx); + DDX_Text(pDX, IDC_EDIT5, m_skewy); + DDX_Text(pDX, IDC_EDIT6, m_anglex); + DDX_Text(pDX, IDC_EDIT7, m_angley); + DDX_Text(pDX, IDC_EDIT8, m_slopex); + DDX_Text(pDX, IDC_EDIT9, m_slopey); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgSkew, CDialog) + //{{AFX_MSG_MAP(DlgSkew) + ON_EN_CHANGE(IDC_EDIT4, OnChangeEdit4) + ON_EN_CHANGE(IDC_EDIT5, OnChangeEdit5) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgSkew message handlers + +BOOL DlgSkew::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + UpdateMyData(); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgSkew::UpdateMyData() +{ + UpdateData(1); + + m_slopex = m_skewx/m_w; + m_slopey = m_skewy/m_h; + + m_anglex = (float)(180*atan(m_slopex)/3.141592654); + m_angley = (float)(180*atan(m_slopey)/3.141592654); + + UpdateData(0); +} + +void DlgSkew::OnChangeEdit4() +{ + UpdateMyData(); +} + +void DlgSkew::OnChangeEdit5() +{ + UpdateMyData(); +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgSkew.h b/SlnkDWFImpl/CxImage/demo/DlgSkew.h new file mode 100644 index 0000000..806a901 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgSkew.h @@ -0,0 +1,64 @@ +#if !defined(AFX_DLGSKEW_H__1450E80F_B2DF_4EB5_BEDC_4D8C6A609F7C__INCLUDED_) +#define AFX_DLGSKEW_H__1450E80F_B2DF_4EB5_BEDC_4D8C6A609F7C__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgSkew.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgSkew dialog + +class DlgSkew : public CDialog +{ +// Construction +public: + DlgSkew(CWnd* pParent = NULL); // standard constructor + + DWORD m_w; + DWORD m_h; + +// Dialog Data + //{{AFX_DATA(DlgSkew) + enum { IDD = IDD_SKEW }; + CxTargetButton m_ok; + CxTargetButton m_canc; + BOOL m_bEnableInterpolation; + long m_pivotx; + long m_pivoty; + float m_skewx; + float m_skewy; + float m_anglex; + float m_angley; + float m_slopex; + float m_slopey; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgSkew) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + void UpdateMyData(); + + // Generated message map functions + //{{AFX_MSG(DlgSkew) + virtual BOOL OnInitDialog(); + afx_msg void OnChangeEdit4(); + afx_msg void OnChangeEdit5(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGSKEW_H__1450E80F_B2DF_4EB5_BEDC_4D8C6A609F7C__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgText.cpp b/SlnkDWFImpl/CxImage/demo/DlgText.cpp new file mode 100644 index 0000000..79f843a --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgText.cpp @@ -0,0 +1,355 @@ +// DlgText.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgText.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgText dialog + +#ifndef VATI_EXTENSIONS +// original dialog AFX stuff: +DlgText::DlgText(CWnd* pParent /*=NULL*/) + : CDialog(DlgText::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgText) + m_text = _T(""); + //}}AFX_DATA_INIT + memset(&m_font,0,sizeof(m_font)); +} + +void DlgText::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgText) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, ID_FONT, m_bfont); + DDX_Text(pDX, IDC_EDIT1, m_text); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgText, CDialog) + //{{AFX_MSG_MAP(DlgText) + ON_BN_CLICKED(ID_FONT, OnFont) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +// VATI_EXTENSIONS dialog AFX stuff: +#else +DlgText::DlgText(CWnd* pParent /*=NULL*/) + : CDialog(DlgText::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgText) + m_opaque = FALSE; + m_lbl_opac = _T(""); + m_lbl_radius = _T(""); + //}}AFX_DATA_INIT + + // Instantiate and initialize the background brush to black. + m_pEditBkBrush = new CBrush(RGB(0,0,0)); + + // font and color dialog behaviour + m_cfflags = 0 | CF_EFFECTS | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS | CF_ENABLEHOOK; + m_ccflags = 0x00000183 ; // 0 | CC_ANYCOLOR | CC_FULLOPEN | CC_SOLIDCOLOR | CC_RGBINIT ; + + memset(&m_custColors,0,sizeof(COLORREF)*16); + +} + +void DlgText::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgText) + DDX_Control(pDX, IDC_STATIC_RADIUS, m_radiusTxt); + DDX_Control(pDX, IDC_STATIC_OP, m_opacTxt); + DDX_Control(pDX, IDC_SLIDER_RADIUS, m_sldr_radius); + DDX_Control(pDX, IDC_SLIDER_OPACITY, m_sldr_opac); + DDX_Control(pDX, IDC_CHECK1, m_check1); + DDX_Control(pDX, IDC_EDIT1, m_text); + DDX_Control(pDX, IDC_BTN_TXTCOLOR, m_forecolor); + DDX_Control(pDX, IDC_BTN_BCKCOLOR, m_backcolor); + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, ID_FONT, m_bfont); + DDX_Check(pDX, IDC_CHECK1, m_opaque); + DDX_Text(pDX, IDC_STATIC_OP, m_lbl_opac); + DDX_Text(pDX, IDC_STATIC_RADIUS, m_lbl_radius); + DDX_Control(pDX, IDC_RADIO1, m_radio1); + DDX_Control(pDX, IDC_RADIO2, m_radio2); + DDX_Control(pDX, IDC_RADIO3, m_radio3); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgText, CDialog) + //{{AFX_MSG_MAP(DlgText) + ON_BN_CLICKED(ID_FONT, OnFont) + ON_BN_CLICKED(IDC_BTN_BCKCOLOR, OnBtnBckcolor) + ON_BN_CLICKED(IDC_BTN_TXTCOLOR, OnBtnTxtcolor) + ON_WM_CTLCOLOR() + ON_WM_DESTROY() + ON_BN_CLICKED(IDC_CHECK1, OnCheck1) + ON_BN_CLICKED(IDC_RADIO1, OnRadio1) + ON_BN_CLICKED(IDC_RADIO2, OnRadio2) + ON_BN_CLICKED(IDC_RADIO3, OnRadio3) + ON_WM_PAINT() + ON_WM_HSCROLL() + //}}AFX_MSG_MAP +END_MESSAGE_MAP() +// endif VATI_EXTENSIONS: +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgText message handlers + +BOOL DlgText::OnInitDialog() +{ + CDialog::OnInitDialog(); + +#ifndef VATI_EXTENSIONS + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + m_bfont.SetIcon(IDI_B,BS_LEFT); +#else + m_ok.SetIcon(IDI_OK,BS_LEFT); + m_canc.SetIcon(IDI_CANC,BS_LEFT); + m_bfont.SetIcon(IDI_G,BS_LEFT); + m_forecolor.SetIcon(IDI_B,BS_LEFT); + m_backcolor.SetIcon(IDI_B,BS_LEFT); + + //set checkbox + m_check1.SetCheck ( m_textdata.opaque ); + + // set editbox text/font/color settings to the current + cfont.CreateFontIndirect( &(m_textdata.lfont) ); + m_text.SetFont( &cfont, TRUE); + m_text.SetWindowText( m_textdata.text ); + m_text.SetSel(0,9999); + + //radiobuttons and sliders + if ( m_textdata.align==DT_LEFT ) + m_radio2.SetCheck(1); + else if ( m_textdata.align==DT_RIGHT ) + m_radio3.SetCheck(1); + else + m_radio1.SetCheck(1); + + // opacity slider + ChangeCtrlStyle( &m_sldr_opac, TBS_BOTH|TBS_AUTOTICKS, TRUE ); + m_sldr_opac.SetTicFreq( 5 ); // Send TBM_SETTICFREQ + m_sldr_opac.SetLineSize( 10 ); // Send TBM_SETLINESIZE + m_sldr_opac.SetPageSize( 20 ); // Send TBM_SETPAGESIZE + m_sldr_opac.SetPos( (int)(100.*m_textdata.b_opacity) ); + m_sldr_opac.SetRange( 0,100, TRUE ); + m_lbl_opac.Format( "%.0f%%", 100.*m_textdata.b_opacity ); + m_opacTxt.SetWindowText ( m_lbl_opac.GetBuffer(0) ); + m_opacTxt.UpdateWindow (); + + // rounding radius slider + ChangeCtrlStyle( &m_sldr_radius, TBS_BOTH|TBS_AUTOTICKS, TRUE ); + m_sldr_radius.SetTicFreq(5); + m_sldr_radius.SetLineSize(5); + m_sldr_radius.SetPageSize(10); + m_sldr_radius.SetPos( m_textdata.b_round ); + m_sldr_radius.SetRange (0,50,TRUE); + m_lbl_radius.Format( "%d%%", m_textdata.b_round ); + m_radiusTxt.SetWindowText ( m_lbl_radius.GetBuffer(0) ); + m_radiusTxt.UpdateWindow (); + + UpdateData(TRUE); +#endif + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void DlgText::OnFont() +{ +#ifndef VATI_EXTENSIONS + CFontDialog dlg; + memcpy(dlg.m_cf.lpLogFont, &m_font, sizeof(m_font)); + dlg.m_cf.rgbColors = m_color; + if (dlg.DoModal()==IDOK){ + memcpy(&m_font,dlg.m_cf.lpLogFont, sizeof(m_font)); + m_color = dlg.GetColor(); + } +#else + CFontDialog dlg; + LOGFONT tmpLogfont; + memcpy( &tmpLogfont, &(m_textdata.lfont), sizeof(LOGFONT)); + dlg.m_cf.lpLogFont = &tmpLogfont ; + dlg.m_cf.rgbColors = m_textdata.fcolor; + dlg.m_cf.Flags = m_cfflags ; + + if (dlg.DoModal()==IDOK) + { + memcpy( &(m_textdata.lfont), &tmpLogfont, sizeof(LOGFONT)); + // set editbox text/font/color settings to the current + cfont.Detach(); + cfont.CreateFontIndirect( &tmpLogfont ); + m_text.SetFont( &cfont, TRUE); + } + UpdateData(TRUE); +#endif + return; +} + +#ifdef VATI_EXTENSIONS +void DlgText::OnBtnBckcolor() +{ + // TODO: Add your control notification handler code here + CColorDialog dlg( m_textdata.bcolor, m_ccflags, NULL ); + + dlg.m_cc.lpCustColors = m_custColors ; + dlg.m_cc.rgbResult = m_textdata.bcolor ; + + // show the dialog and get the user's response... + if (dlg.DoModal() == IDOK) + { + m_textdata.bcolor = dlg.m_cc.rgbResult; + m_text.SetFont( &cfont, TRUE); + } + UpdateData(TRUE); + +} + +void DlgText::OnBtnTxtcolor() +{ + // TODO: Add your control notification handler code here + CColorDialog dlg( m_textdata.fcolor, m_ccflags, NULL ); + + dlg.m_cc.lpCustColors = m_custColors ; + dlg.m_cc.rgbResult = m_textdata.fcolor ; + + // show the dialog and get the user's response... + if (dlg.DoModal() == IDOK) + { + m_textdata.fcolor = dlg.m_cc.rgbResult; + m_text.SetFont( &cfont, TRUE); + } + UpdateData(TRUE); +} + +HBRUSH DlgText::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) +{ + HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); + + // TODO: Change any attributes of the DC here + switch (nCtlColor) + { + //if painting the edit box in this dialof, change the brush colors + case CTLCOLOR_EDIT: + // Set color to green on black and return the background brush. + pDC->SetTextColor( m_textdata.fcolor ); + pDC->SetBkColor( m_textdata.bcolor ); + return (HBRUSH)(m_pEditBkBrush->GetSafeHandle()); + + default: + return CDialog::OnCtlColor(pDC, pWnd, nCtlColor); + } + // TODO: Return a different brush if the default is not desired + return hbr; +} + +void DlgText::OnDestroy() +{ + CDialog::OnDestroy(); + // TODO: Add your control notification handler code here + // Free the space allocated for the background brush + delete m_pEditBkBrush; +} + +void DlgText::OnOK() +{ + // TODO: Add extra validation here + CString tmpS; + + // copy back control's values + m_text.GetWindowText( tmpS ); + strcpy ( m_textdata.text, tmpS.GetBuffer(0) ); + m_textdata.opaque = m_check1.GetCheck(); + + CDialog::OnOK(); +} + +void DlgText::OnCheck1() +{ + // TODO: Add your control notification handler code here + m_textdata.opaque = ( m_check1.GetCheck() ); + m_backcolor.EnableWindow( m_textdata.opaque == TRUE ); + m_sldr_opac.EnableWindow ( m_textdata.opaque == TRUE ); + m_sldr_radius.EnableWindow ( m_textdata.opaque == TRUE ); + m_opacTxt.EnableWindow( m_textdata.opaque == TRUE ); + m_radiusTxt.EnableWindow( m_textdata.opaque == TRUE ); +} + +void DlgText::OnRadio1() +{ + // TODO: Add your control notification handler code here + m_textdata.align = DT_CENTER; +} + +void DlgText::OnRadio2() +{ + // TODO: Add your control notification handler code here + m_textdata.align = DT_LEFT; +} + +void DlgText::OnRadio3() +{ + // TODO: Add your control notification handler code here + m_textdata.align = DT_RIGHT; +} + +// handle the moving event of the sliders +void DlgText::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) +{ + // TODO: Add your message handler code here and/or call default + if ( nSBCode == SB_THUMBPOSITION || nSBCode == SB_THUMBTRACK ) + { + // if the mouse is on the opacity slider + if ( GetCapture() == GetDlgItem( IDC_SLIDER_OPACITY ) ) + { + m_textdata.b_opacity = (float)( 0.01 * m_sldr_opac.GetPos() ); + m_lbl_opac.Format( "%.0f%%", 100*m_textdata.b_opacity ); + m_opacTxt.SetWindowText ( m_lbl_opac.GetBuffer(0)); + m_opacTxt.UpdateWindow (); + } + // if the mouse is on the outline slider + if ( GetCapture() == GetDlgItem( IDC_SLIDER_RADIUS ) ) + { + m_textdata.b_round = (unsigned char)( m_sldr_radius.GetPos() ); + m_lbl_radius.Format( "%d%%", m_sldr_radius.GetPos() ); + m_radiusTxt.SetWindowText ( m_lbl_radius.GetBuffer(0)); + m_radiusTxt.UpdateWindow (); + } + } + + CDialog::OnHScroll(nSBCode, nPos, pScrollBar); +} + +// change the slider's appearance +void DlgText::ChangeCtrlStyle( CSliderCtrl * pSlider, long lStyle, BOOL bSetBit) +{ + long lStyleOld; + CRect rect; + + lStyleOld = GetWindowLong( pSlider->GetSafeHwnd(), GWL_STYLE ); + if ( bSetBit ) + lStyleOld |= lStyle; + else + lStyleOld &= ~lStyle; + SetWindowLong( pSlider->GetSafeHwnd(), GWL_STYLE, lStyleOld ); + pSlider->GetWindowRect(&rect); + pSlider->InvalidateRect(&rect); +} +#endif \ No newline at end of file diff --git a/SlnkDWFImpl/CxImage/demo/DlgText.h b/SlnkDWFImpl/CxImage/demo/DlgText.h new file mode 100644 index 0000000..d3a665a --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgText.h @@ -0,0 +1,143 @@ +#if !defined(AFX_DLGTEXT_H__1FEA8102_CF4A_11D6_BB84_8B1C37831B77__INCLUDED_) +#define AFX_DLGTEXT_H__1FEA8102_CF4A_11D6_BB84_8B1C37831B77__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgText.h : header file +// + +#include "xTargetButton.h" + +// It seems to be the simplest #ifdef-ing all dialog stuff: +#ifndef VATI_EXTENSIONS + +///////////////////////////////////////////////////////////////////////////// +// DlgText dialog + +class DlgText : public CDialog +{ +// Construction +public: + DlgText(CWnd* pParent = NULL); // standard constructor + LOGFONT m_font; + COLORREF m_color; +// Dialog Data + //{{AFX_DATA(DlgText) + enum { IDD = IDD_TEXT }; + CxTargetButton m_ok; + CxTargetButton m_canc; + CxTargetButton m_bfont; + CString m_text; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgText) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgText) + virtual BOOL OnInitDialog(); + afx_msg void OnFont(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +#else +// if VATI_EXTENSIONS: + +///////////////////////////////////////////////////////////////////////////// +// edit box control, painted with non-default colors +class CMyEdit : public CEdit + + { + public: + BOOL OnChildNotify(UINT message, WPARAM wParam, LPARAM Param, + LRESULT* pLResult); + protected: + static CBrush m_brush; + }; + + +///////////////////////////////////////////////////////////////////////////// +// DlgText dialog + +class DlgText : public CDialog +{ +// Construction +public: + DlgText(CWnd* pParent = NULL); // standard constructor + + CFont cfont; // font for edit control + CBrush* m_pEditBkBrush; // to store the new background brush for edit controls. + + CxImage::CXTEXTINFO m_textdata; // local copy of common text data + DWORD m_ccflags; // color dialog behaviour + DWORD m_cfflags; // font dialog behaviour + + COLORREF m_custColors[16]; // for the color dialog + +// Dialog Data + //{{AFX_DATA(DlgText) + enum { IDD = IDD_TEXT }; + CStatic m_radiusTxt; + CStatic m_opacTxt; + CSliderCtrl m_sldr_radius; + CSliderCtrl m_sldr_opac; + CButton m_check1; + CEdit m_text; + CxTargetButton m_forecolor; + CxTargetButton m_backcolor; + CxTargetButton m_ok; + CxTargetButton m_canc; + CxTargetButton m_bfont; + BOOL m_opaque; + CString m_lbl_opac; + CString m_lbl_radius; + CButton m_radio1; + CButton m_radio2; + CButton m_radio3; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgText) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + void DlgText::ChangeCtrlStyle( CSliderCtrl * m_Slider, long lStyle, BOOL bSetBit); + // Generated message map functions + //{{AFX_MSG(DlgText) + virtual BOOL OnInitDialog(); + afx_msg void OnFont(); + afx_msg void OnBtnBckcolor(); + afx_msg void OnBtnTxtcolor(); + afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); + afx_msg void OnDestroy(); + afx_msg void OnCheck1(); + virtual void OnOK(); + afx_msg void OnRadio1(); + afx_msg void OnRadio2(); + afx_msg void OnRadio3(); + afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; +#endif + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGTEXT_H__1FEA8102_CF4A_11D6_BB84_8B1C37831B77__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgThreshold.cpp b/SlnkDWFImpl/CxImage/demo/DlgThreshold.cpp new file mode 100644 index 0000000..dc1341a --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgThreshold.cpp @@ -0,0 +1,56 @@ +// DlgThreshold.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgThreshold.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgThreshold dialog + + +DlgThreshold::DlgThreshold(CWnd* pParent /*=NULL*/) + : CDialog(DlgThreshold::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgThreshold) + m_level = 0; + //}}AFX_DATA_INIT +} + + +void DlgThreshold::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgThreshold) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_EDIT1, m_level); + DDV_MinMaxByte(pDX, m_level, 0, 255); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgThreshold, CDialog) + //{{AFX_MSG_MAP(DlgThreshold) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgThreshold message handlers + +BOOL DlgThreshold::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgThreshold.h b/SlnkDWFImpl/CxImage/demo/DlgThreshold.h new file mode 100644 index 0000000..2ea41ea --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgThreshold.h @@ -0,0 +1,49 @@ +#if !defined(AFX_DLGTHRESHOLD_H__FCFC4DC2_FB70_11D5_8DD7_00E07D8144D0__INCLUDED_) +#define AFX_DLGTHRESHOLD_H__FCFC4DC2_FB70_11D5_8DD7_00E07D8144D0__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgThreshold.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgThreshold dialog +class DlgThreshold : public CDialog +{ +// Construction +public: + DlgThreshold(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgThreshold) + enum { IDD = IDD_THRESHOLD }; + CxTargetButton m_ok; + CxTargetButton m_canc; + BYTE m_level; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgThreshold) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgThreshold) + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGTHRESHOLD_H__FCFC4DC2_FB70_11D5_8DD7_00E07D8144D0__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/DlgURL.cpp b/SlnkDWFImpl/CxImage/demo/DlgURL.cpp new file mode 100644 index 0000000..93d80b2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgURL.cpp @@ -0,0 +1,204 @@ +// DlgURL.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgURL.h" + +#include +#include + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// DlgURL dialog + + +DlgURL::DlgURL(CWnd* pParent /*=NULL*/) + : CDialog(DlgURL::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgURL) + m_url = _T("http://www.xdp.it/tmp/test.jp2"); + //}}AFX_DATA_INIT + + m_hInternetSession = NULL; + m_hHttpConnection = NULL; + m_hHttpFile = NULL; + + m_bAbort = FALSE; + m_bSafeToClose = TRUE; +} + + +void DlgURL::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgURL) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Text(pDX, IDC_URL, m_url); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(DlgURL, CDialog) + //{{AFX_MSG_MAP(DlgURL) + ON_WM_DESTROY() + ON_WM_CLOSE() + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// DlgURL message handlers +void DlgURL::OnOK() +{ + UpdateData(); + if (m_url.IsEmpty()) return; + m_ok.EnableWindow(0); + m_bSafeToClose = FALSE; + + SetStatus(_T("Connecting to site...")); + CString* m_strBuffer = &m_data; + + CString m_sServer=""; + CString m_sObject; + INTERNET_PORT m_nPort = INTERNET_DEFAULT_HTTP_PORT; + DWORD m_dwServiceType = INTERNET_SERVICE_HTTP; + AfxParseURL(m_url, m_dwServiceType, m_sServer, m_sObject, m_nPort); + + //Create the Internet session handle + m_hInternetSession = ::InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); + + if (m_hInternetSession == NULL){ ThreadError("cannot open internet session"); return; } + + if (m_bAbort) { OnThreadFinished(1); return; } + + //Make the connection to the HTTP server + m_hHttpConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort , NULL, + NULL, m_dwServiceType , 0, (DWORD) this); + + if (m_hHttpConnection == NULL){ ThreadError("cannot connect to remote server"); return; } + + if (m_bAbort) { OnThreadFinished(1); return; } + + //Issue the request to read the file + LPCTSTR ppszAcceptTypes[2]; + ppszAcceptTypes[0] = _T("*/*"); //We support accepting any mime file type since this is a simple download of a file + ppszAcceptTypes[1] = NULL; + + m_hHttpFile = HttpOpenRequest(m_hHttpConnection, NULL, m_sObject, NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD | + INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION, (DWORD) this); + + if (m_hHttpFile == NULL){ ThreadError("Failed in call to HttpOpenRequest"); return; } + + if (m_bAbort) { OnThreadFinished(1); return; } + + //Issue the request + BOOL bSend = ::HttpSendRequest(m_hHttpFile, NULL, 0, NULL, 0); + + // Get the length of the file. + TCHAR szContentLength[32]; + DWORD dwInfoSize = 32; + DWORD dwFileSize = 0; + if (::HttpQueryInfo(m_hHttpFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL)){ + dwFileSize = (DWORD) _ttol(szContentLength); + } + + //Now do the actual read of the file + DWORD dwBytesRead = 0; + char szReadBuf[1025]; + DWORD dwBytesToRead = 1024; + DWORD dwTotalBytesRead = 0; + do { + if (::InternetReadFile(m_hHttpFile, szReadBuf, dwBytesToRead, &dwBytesRead)){ + if (dwBytesRead && !m_bAbort) { + //Write the data to file + szReadBuf[dwBytesRead]=0; + LPTSTR ptr = m_strBuffer->GetBufferSetLength(dwTotalBytesRead + dwBytesRead + 1); + memcpy(ptr+dwTotalBytesRead, szReadBuf, dwBytesRead); + + //Increment the total number of bytes read + dwTotalBytesRead += dwBytesRead; + m_strBuffer->ReleaseBuffer(dwTotalBytesRead+1); + + CString s; + s.Format("%d/%d",dwTotalBytesRead,dwFileSize); + SetStatus(s); + } + } else { ThreadError("An error occurred while downloading the file"); return; } + } while (dwBytesRead && !m_bAbort); + + m_size = dwTotalBytesRead; + + //We're finished + OnThreadFinished(0); +} + +void DlgURL::OnDestroy() +{ + //Free up the internet handles we may be using + if (m_hHttpFile){ + ::InternetCloseHandle(m_hHttpFile); + m_hHttpFile = NULL; + } + if (m_hHttpConnection){ + ::InternetCloseHandle(m_hHttpConnection); + m_hHttpConnection = NULL; + } + if (m_hInternetSession){ + ::InternetCloseHandle(m_hInternetSession); + m_hInternetSession = NULL; + } + CDialog::OnDestroy(); +} + +void DlgURL::OnClose() +{ + if (m_bSafeToClose) CDialog::OnClose(); + else { + //Just set the abort flag to TRUE and disable the cancel button + m_bAbort = TRUE; + m_canc.EnableWindow(0); + SetStatus("Aborting transfer..."); + } +} + +LRESULT DlgURL::OnThreadFinished(WPARAM wParam) +{ + //It's now safe to close since the thread has signaled us + m_bSafeToClose = TRUE; + //If an error occured display the message box + if (m_bAbort) EndDialog(IDCANCEL); + else if (wParam) { + AfxMessageBox(m_sError); + EndDialog(IDCANCEL); + } else EndDialog(IDOK); + return 0L; +} + +void DlgURL::SetStatus(LPCSTR message) +{ + CWnd* statwnd = GetDlgItem(IDC_STATUS); + statwnd->SetWindowText(message); +} + +void DlgURL::ThreadError(LPCSTR message) +{ + m_sError=message; + OnThreadFinished(1); +} + +BOOL DlgURL::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} diff --git a/SlnkDWFImpl/CxImage/demo/DlgURL.h b/SlnkDWFImpl/CxImage/demo/DlgURL.h new file mode 100644 index 0000000..60884e4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/DlgURL.h @@ -0,0 +1,67 @@ +#if !defined(AFX_DLGURL_H__A5267584_6592_11D6_BB82_F6642F586A63__INCLUDED_) +#define AFX_DLGURL_H__A5267584_6592_11D6_BB82_F6642F586A63__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgURL.h : header file +// +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgURL dialog +//const UINT WM_HTTPDOWNLOAD_THREAD_FINISHED = WM_APP + 123; + +class DlgURL : public CDialog +{ +// Construction +public: + DlgURL(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgURL) + enum { IDD = IDD_DWNURL }; + CxTargetButton m_ok; + CxTargetButton m_canc; + CString m_url; + CString m_data; + long m_size; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgURL) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgURL) + virtual void OnOK(); + afx_msg void OnDestroy(); + afx_msg void OnClose(); + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + + void* m_hInternetSession; + void* m_hHttpConnection; + void* m_hHttpFile; + + BOOL m_bAbort; + BOOL m_bSafeToClose; + CString m_sError; + + void SetStatus(LPCSTR message); + void ThreadError(LPCSTR message); + LRESULT OnThreadFinished(WPARAM wParam); +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DLGURL_H__A5267584_6592_11D6_BB82_F6642F586A63__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/MainFrm.cpp b/SlnkDWFImpl/CxImage/demo/MainFrm.cpp new file mode 100644 index 0000000..4f2368b --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/MainFrm.cpp @@ -0,0 +1,457 @@ +// MainFrm.cpp : implementation of the CMainFrame class +// + +#include "stdafx.h" +#include "demo.h" + +#include "MainFrm.h" +#include "demodoc.h" +#include "DlgCapture.h" + +#include "ximage.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +////////////////////////////////////////////////////////////////////////////// +// CMainFrame + +IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd) + +BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd) + //{{AFX_MSG_MAP(CMainFrame) + ON_WM_CREATE() + ON_COMMAND(ID_EDIT_PASTE, OnEditPaste) + ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateEditPaste) + ON_COMMAND(ID_FILE_SELECTSOURCE, OnFileSelectsource) + ON_COMMAND(ID_FILE_ACQUIRE, OnFileAcquire) + ON_WM_CLOSE() + ON_COMMAND(ID_FILE_CAPTURE, OnFileCapture) + ON_WM_SIZE() + ON_WM_MEASUREITEM() + ON_WM_INITMENUPOPUP() + ON_WM_MENUCHAR() + ON_COMMAND(ID_VIEW_MENUSTYLE_NORMAL, OnViewMenustyleNormal) + ON_COMMAND(ID_VIEW_MENUSTYLE_XP, OnViewMenustyleXp) + ON_COMMAND(ID_VIEW_FULLSCREEN, OnViewFullscreen) + ON_UPDATE_COMMAND_UI(ID_VIEW_FULLSCREEN, OnUpdateViewFullscreen) + ON_COMMAND_EX(ID_VIEW_HISTOGRAM, OnBarCheck) + ON_UPDATE_COMMAND_UI(ID_VIEW_HISTOGRAM, OnUpdateControlBarMenu) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +static UINT indicators[] = +{ + ID_SEPARATOR, // status line indicator + ID_INDICATOR1, + ID_INDICATOR2, + ID_INDICATOR3, + ID_INDICATOR4, + ID_INDICATOR_CAPS, + ID_INDICATOR_NUM, + ID_INDICATOR_SCRL, +}; + +////////////////////////////////////////////////////////////////////////////// +// CMainFrame construction/destruction +CMainFrame::CMainFrame() +{ } +CMainFrame::~CMainFrame() +{ } +////////////////////////////////////////////////////////////////////////////// +int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) +{ + if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1) + return -1; + + if (!m_wndToolBar.Create(this) || + !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) + { + TRACE0("Failed to create toolbar\n"); + return -1; // fail to create + } + + if (!m_wndStatusBar.Create(this) || + !m_wndStatusBar.SetIndicators(indicators,sizeof(indicators)/sizeof(UINT))) + { + TRACE0("Failed to create status bar\n"); + return -1; // fail to create + } + +/* if (!m_wndProgressBar.Create(WS_CHILD,CRect(200,2,262,18),&m_wndStatusBar,ID_INDICATOR1)) + { + TRACE0("Failed to create progress bar\n"); + return -1; // fail to create + } + m_wndProgressBar.ShowWindow(SW_SHOW); + m_wndProgressBar.SetRange(0,100); +*/ + // TODO: Remove this if you don't want tool tips or a resizeable toolbar + m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() | + CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); + + // TODO: Delete these three lines if you don't want the toolbar to + // be dockable + m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); + EnableDocking(CBRS_ALIGN_ANY); + DockControlBar(&m_wndToolBar); + + //histogram bar + m_HistoBar.Create(this, IDD_HISTO, CBRS_TOP, ID_VIEW_HISTOGRAM); + m_HistoBar.ShowWindow(0); + m_HistoBar.EnableDocking(0); + + RECT r; + GetWindowRect(&r); + FloatControlBar(&m_HistoBar,CPoint(r.right-300,r.top+80),CBRS_ALIGN_TOP); + + // <<>> + InitTwain(m_hWnd); +// if(!IsValidDriver()) AfxMessageBox("Unable to load Twain Driver."); + + m_fullscreen=false; + +#ifdef VATI_EXTENSIONS + // load the window size and positions + CRect rect; + rect.left = AfxGetApp()->GetProfileInt ( "Screen", "left", 0 ) ; + rect.top = AfxGetApp()->GetProfileInt ( "Screen", "top", 0 ) ; + rect.right = AfxGetApp()->GetProfileInt ( "Screen", "right", 850 ) ; + rect.bottom = AfxGetApp()->GetProfileInt ( "Screen", "bottom", 650 ) ; + + // resize + if (rect.left && rect.top && rect.right && rect.bottom ) + MoveWindow( & rect,0 ); +#endif + + return 0; +} + +BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) +{ + // TODO: Modify the Window class or styles here by modifying + // the CREATESTRUCT cs + return CMDIFrameWnd::PreCreateWindow(cs); +} + +////////////////////////////////////////////////////////////////////////////// +// CMainFrame diagnostics +#ifdef _DEBUG +void CMainFrame::AssertValid() const +{ + CMDIFrameWnd::AssertValid(); +} + +void CMainFrame::Dump(CDumpContext& dc) const +{ + CMDIFrameWnd::Dump(dc); +} +#endif //_DEBUG + +////////////////////////////////////////////////////////////////////////////// +// CMainFrame message handlers +void CMainFrame::OnEditPaste() +{ + CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + + if (NewDoc) { + HANDLE hBitmap=NULL; + CBitmap bmpClip; + if (OpenClipboard()) hBitmap=GetClipboardData(CF_DIB); + if (hBitmap){ + CxImage *newima = new CxImage(); + newima->CreateFromHANDLE(hBitmap); + NewDoc->image = newima; + } + CloseClipboard(); + + CString s; + s.Format("Clipboard Image %d",((CDemoApp*)AfxGetApp())->m_nDocCount++); + NewDoc->SetTitle(s); + NewDoc->UpdateAllViews(0,WM_USER_NEWIMAGE); + NewDoc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnUpdateEditPaste(CCmdUI* pCmdUI) +{ + if(!IsClipboardFormatAvailable(CF_DIB)) pCmdUI->Enable(FALSE); +} +////////////////////////////////////////////////////////////////////////////// +BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) +{ + if (CMDIFrameWnd::OnCreateClient(lpcs, pContext)){ + // Subclass the MDIClient to print the logo in the + // bottom right corner....See CLogoMdi in logomdi.cpp + m_LogoMdiClientWnd.SubclassWindow(m_hWndMDIClient) ; + return TRUE ; + } else { + return FALSE ; + } +} +////////////////////////////////////////////////////////////////////////////// +BOOL CMainFrame::PreTranslateMessage(MSG* pMsg) +{ + if (CTwain::SourceEnabled()) //<<>> + return CTwain::ProcessMessage(*pMsg); //process twain + else + return CMDIFrameWnd::PreTranslateMessage(pMsg); //other message +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnFileSelectsource() +{ + CTwain::SelectSource(); //<<>> +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnFileAcquire() +{ + CTwain::Acquire(TWCPP_ANYCOUNT); //<<>> +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnClose() +{ + CTwain::ReleaseTwain(); //<<>> + +#ifdef VATI_EXTENSIONS + // get the window & save + AfxGetApp()->WriteProfileInt ( "Screen", "maximized", IsZoomed()) ; + if ( !IsZoomed() && !IsIconic() ) + { + CRect rect; + GetWindowRect ( & rect ) ; + + int xScreen = GetSystemMetrics(SM_CXSCREEN) - 100; + int yScreen = GetSystemMetrics(SM_CYSCREEN) - 100; + if (rect.left > xScreen) + rect.left = xScreen; + if (rect.top > yScreen) + rect.top = yScreen; + + AfxGetApp()->WriteProfileInt ( "Screen", "left", rect.left ) ; + AfxGetApp()->WriteProfileInt ( "Screen", "top", rect.top ) ; + AfxGetApp()->WriteProfileInt ( "Screen", "right", rect.right ) ; + AfxGetApp()->WriteProfileInt ( "Screen", "bottom", rect.bottom ) ; + } + // save last used font data for Text tool + AfxGetApp()->WriteProfileString( "TextTool", "lfFaceName", theApp.m_text.lfont.lfFaceName ); + AfxGetApp()->WriteProfileInt( "TextTool", "lfCharSet", theApp.m_text.lfont.lfCharSet ); + AfxGetApp()->WriteProfileInt( "TextTool", "lfWeight", theApp.m_text.lfont.lfWeight ); + AfxGetApp()->WriteProfileInt( "TextTool", "lfItalic", theApp.m_text.lfont.lfItalic ); + AfxGetApp()->WriteProfileInt( "TextTool", "lfUnderline", theApp.m_text.lfont.lfUnderline ); + AfxGetApp()->WriteProfileInt( "TextTool", "fcolor", theApp.m_text.fcolor ); + AfxGetApp()->WriteProfileInt( "TextTool", "bcolor", theApp.m_text.bcolor ); + AfxGetApp()->WriteProfileInt( "TextTool", "opacity", (int)(100.*theApp.m_text.b_opacity) ); + AfxGetApp()->WriteProfileInt( "TextTool", "r_radius", theApp.m_text.b_round ); + AfxGetApp()->WriteProfileInt( "Options" , "JpegQuality",theApp.m_optJpegQuality); + +#endif + + CMDIFrameWnd::OnClose(); +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::SetImage(HANDLE hBitmap,TW_IMAGEINFO& info) +{ //<<>> + CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDoc) { + if (hBitmap){ + CxImage *newima = new CxImage(); + newima->CreateFromHANDLE(hBitmap); + NewDoc->image = newima; + } + CString s; + s.Format("Acquired Image %d",((CDemoApp*)AfxGetApp())->m_nDocCount++); + NewDoc->SetTitle(s); + NewDoc->UpdateAllViews(0,WM_USER_NEWIMAGE); + NewDoc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnFileCapture() +{ + DlgCapture dlg; + if (dlg.DoModal()==IDOK){ + // get the desired window from dialog box + HWND hwnd=dlg.m_SelectedWnd; + // get window size + CRect r; + ::GetWindowRect(hwnd,&r); + + int xScreen,yScreen; //check if the window is out of the screen or maximixed + int xshift = 0, yshift = 0; + xScreen = GetSystemMetrics(SM_CXSCREEN); + yScreen = GetSystemMetrics(SM_CYSCREEN); + if(r.right > xScreen) + r.right = xScreen; + if(r.bottom > yScreen) + r.bottom = yScreen; + if(r.left < 0){ + xshift = -r.left; + r.left = 0; + } + if(r.top < 0){ + yshift = -r.top; + r.top = 0; + } + + CSize sz(r.Width(), r.Height()); + if(sz.cx <= 0 || sz.cy <= 0) return; + + // bring the window at the top most level + ::SetWindowPos(hwnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); + + // prepare the DCs + HDC dstDC = ::GetDC(NULL); + HDC srcDC = ::GetWindowDC(hwnd); //full window (::GetDC(hwnd); = clientarea) + HDC memDC = ::CreateCompatibleDC(dstDC); + + // copy the screen to the bitmap + HBITMAP bm =::CreateCompatibleBitmap(dstDC, sz.cx, sz.cy); + HBITMAP oldbm = (HBITMAP)::SelectObject(memDC,bm); + ::BitBlt(memDC, 0, 0, sz.cx, sz.cy, srcDC, xshift, yshift, SRCCOPY); + + // restore the position + ::SetWindowPos(hwnd,HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); + ::SetWindowPos(m_hWnd,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); + + // prepare the new document + CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDoc) { + CxImage *newima = new CxImage(); + newima->CreateFromHBITMAP(bm); + NewDoc->image = newima; + CString s; + s.Format("Captured Image %d",((CDemoApp*)AfxGetApp())->m_nDocCount++); + NewDoc->SetTitle(s); + NewDoc->UpdateAllViews(0,WM_USER_NEWIMAGE); + NewDoc->UpdateStatusBar(); + } + + // free objects + DeleteObject(SelectObject(memDC,oldbm)); + DeleteObject(memDC); + } +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnSize(UINT nType, int cx, int cy) +{ + CMDIFrameWnd::OnSize(nType, cx, cy); + +// m_wndProgressBar.SetWindowPos(0,max(200,cx-370),2,0,0,SWP_NOZORDER|SWP_NOSIZE); +} +////////////////////////////////////////////////////////////////////////////// +HMENU CMainFrame::NewMenu() +{ + static UINT toolbars[]={ + IDR_MAINFRAME, + IDR_TOOLBAR1 + }; + + // Load the menu from the resources + // ****replace IDR_MENUTYPE with your menu ID**** + m_menu.LoadMenu(IDR_DEMOTYPE); + // One method for adding bitmaps to menu options is + // through the LoadToolbars member function.This method + // allows you to add all the bitmaps in a toolbar object + // to menu options (if they exist). The first function + // parameter is an array of toolbar id's. The second is + // the number of toolbar id's. There is also a function + // called LoadToolbar that just takes an id. + m_menu.LoadToolbars(toolbars,2); + + return(m_menu.Detach()); +} +////////////////////////////////////////////////////////////////////////////// +HMENU CMainFrame::NewDefaultMenu() +{ + m_default.LoadMenu(IDR_MAINFRAME); + m_default.LoadToolbar(IDR_MAINFRAME); + return(m_default.Detach()); +} +////////////////////////////////////////////////////////////////////////////// +//This handler ensure that the popup menu items are +// drawn correctly +void CMainFrame::OnMeasureItem(int nIDCtl, + LPMEASUREITEMSTRUCT lpMeasureItemStruct) +{ + BOOL setflag=FALSE; + if(lpMeasureItemStruct->CtlType==ODT_MENU){ + if(IsMenu((HMENU)lpMeasureItemStruct->itemID)){ + CMenu* cmenu = + CMenu::FromHandle((HMENU)lpMeasureItemStruct->itemID); + + if(m_menu.IsMenu(cmenu)||m_default.IsMenu(cmenu)){ + m_menu.MeasureItem(lpMeasureItemStruct); + setflag=TRUE; + } + } + } + + if(!setflag)CMDIFrameWnd::OnMeasureItem(nIDCtl, + lpMeasureItemStruct); +} +////////////////////////////////////////////////////////////////////////////// +//This handler ensures that keyboard shortcuts work +LRESULT CMainFrame::OnMenuChar(UINT nChar, UINT nFlags, + CMenu* pMenu) +{ + LRESULT lresult; + if(m_menu.IsMenu(pMenu)||m_default.IsMenu(pMenu)) + lresult=BCMenu::FindKeyboardShortcut(nChar, nFlags, pMenu); + else + lresult=CMDIFrameWnd::OnMenuChar(nChar, nFlags, pMenu); + return(lresult); +} +////////////////////////////////////////////////////////////////////////////// +//This handler updates the menus from time to time +void CMainFrame::OnInitMenuPopup(CMenu* pPopupMenu, + UINT nIndex, BOOL bSysMenu) +{ + CMDIFrameWnd::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu); + if(!bSysMenu){ + if(m_menu.IsMenu(pPopupMenu)||m_default.IsMenu(pPopupMenu)) + BCMenu::UpdateMenu(pPopupMenu); + } +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnViewMenustyleNormal() +{ + BCMenu::SetMenuDrawMode(BCMENU_DRAWMODE_ORIGINAL); +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnViewMenustyleXp() +{ + BCMenu::SetMenuDrawMode(BCMENU_DRAWMODE_XP); +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnViewFullscreen() +{ + if (m_fullscreen) + { + ModifyStyle(0,WS_CAPTION|WS_THICKFRAME); + ShowWindow(SW_SHOWNORMAL); + + ShowControlBar(&m_wndToolBar, TRUE, FALSE); + ShowControlBar(&m_wndStatusBar, TRUE, FALSE); + } + else + { + ModifyStyle(WS_CAPTION|WS_THICKFRAME,0); + ShowWindow(SW_MAXIMIZE); + + CFrameWnd* pChild = GetActiveFrame(); + if (pChild) pChild->ShowWindow(SW_MAXIMIZE); + + ShowControlBar(&m_wndToolBar, FALSE, FALSE); + ShowControlBar(&m_wndStatusBar, FALSE, FALSE); + } + m_fullscreen = !m_fullscreen; +} +////////////////////////////////////////////////////////////////////////////// +void CMainFrame::OnUpdateViewFullscreen(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(m_fullscreen); +} +////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/MainFrm.h b/SlnkDWFImpl/CxImage/demo/MainFrm.h new file mode 100644 index 0000000..558c1ae --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/MainFrm.h @@ -0,0 +1,69 @@ +// MainFrm.h : interface of the CMainFrame class +// +///////////////////////////////////////////////////////////////////////////// +//#include "resource.h" +#include "logomdi.h" +#include "TwainCpp.h" //<<>> +#include "BCMenu.h" +#include "DlgHisto.h" + +class CMainFrame : public CMDIFrameWnd, public CTwain +{ + DECLARE_DYNAMIC(CMainFrame) +public: + CMainFrame(); + void SetImage(HANDLE hBitmap,TW_IMAGEINFO& info); //<<>> +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CMainFrame) + public: + virtual BOOL PreCreateWindow(CREATESTRUCT& cs); + virtual BOOL PreTranslateMessage(MSG* pMsg); + protected: + virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); + //}}AFX_VIRTUAL + +// Implementation +public: + virtual ~CMainFrame(); +#ifdef _DEBUG + virtual void AssertValid() const; + virtual void Dump(CDumpContext& dc) const; +#endif + inline CStatusBar& GetStatusBar() { return m_wndStatusBar; } +// inline CProgressCtrl& GetProgressBar() { return m_wndProgressBar; } + HMENU NewMenu(); + HMENU NewDefaultMenu(); + BCMenu m_menu,m_default; + bool m_fullscreen; + DlgHisto m_HistoBar; + +protected: // control bar embedded members + CStatusBar m_wndStatusBar; + CToolBar m_wndToolBar; + CLogoMdi m_LogoMdiClientWnd; +// CProgressCtrl m_wndProgressBar; + +// Generated message map functions +protected: + protected: + //{{AFX_MSG(CMainFrame) + afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); + afx_msg void OnEditPaste(); + afx_msg void OnUpdateEditPaste(CCmdUI* pCmdUI); + afx_msg void OnFileSelectsource(); + afx_msg void OnFileAcquire(); + afx_msg void OnClose(); + afx_msg void OnFileCapture(); + afx_msg void OnSize(UINT nType, int cx, int cy); + afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct); + afx_msg void OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu); + afx_msg LRESULT OnMenuChar(UINT nChar, UINT nFlags, CMenu* pMenu); + afx_msg void OnViewMenustyleNormal(); + afx_msg void OnViewMenustyleXp(); + afx_msg void OnViewFullscreen(); + afx_msg void OnUpdateViewFullscreen(CCmdUI* pCmdUI); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; +///////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/Quantize.cpp b/SlnkDWFImpl/CxImage/demo/Quantize.cpp new file mode 100644 index 0000000..0c74dd5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/Quantize.cpp @@ -0,0 +1,242 @@ +#include +#include "Quantize.h" +///////////////////////////////////////////////////////////////////////////// +CQuantizer::CQuantizer (UINT nMaxColors, UINT nColorBits) +{ + m_nColorBits = nColorBits < 8 ? nColorBits : 8; + + m_pTree = NULL; + m_nLeafCount = 0; + for (int i=0; i<=(int) m_nColorBits; i++) + m_pReducibleNodes[i] = NULL; + m_nMaxColors = m_nOutputMaxColors = nMaxColors; + if (m_nMaxColors<16) m_nMaxColors=16; +} +///////////////////////////////////////////////////////////////////////////// +CQuantizer::~CQuantizer () +{ + if (m_pTree != NULL) + DeleteTree (&m_pTree); +} +///////////////////////////////////////////////////////////////////////////// +BOOL CQuantizer::ProcessImage (HANDLE hImage) +{ + BYTE r, g, b, a; + int i, j; + + BITMAPINFOHEADER ds; + memcpy(&ds,hImage, sizeof(ds)); + int effwdt = ((((ds.biBitCount * ds.biWidth ) + 31) / 32) * 4); + + int nPad = effwdt - (((ds.biWidth * ds.biBitCount) + 7) / 8); + + BYTE* pbBits = (BYTE*)hImage + *(DWORD*)hImage + ds.biClrUsed * sizeof(RGBQUAD); + + switch (ds.biBitCount) { + + case 1: // 1-bit DIB + case 4: // 4-bit DIB + case 8: // 8-bit DIB + for (i=0; i m_nMaxColors) + ReduceTree (m_nColorBits, &m_nLeafCount, + m_pReducibleNodes); + } + } + + break; + case 24: // 24-bit DIB + for (i=0; i m_nMaxColors) + ReduceTree (m_nColorBits, &m_nLeafCount, m_pReducibleNodes); + } + pbBits += nPad; + } + break; + + default: // Unrecognized color format + return FALSE; + } + return TRUE; +} +///////////////////////////////////////////////////////////////////////////// +void CQuantizer::AddColor (NODE** ppNode, BYTE r, BYTE g, BYTE b, BYTE a, + UINT nColorBits, UINT nLevel, UINT* pLeafCount, NODE** pReducibleNodes) +{ + static BYTE mask[8] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; + + // If the node doesn't exist, create it. + if (*ppNode == NULL) + *ppNode = (NODE*)CreateNode (nLevel, nColorBits, pLeafCount, pReducibleNodes); + + // Update color information if it's a leaf node. + if ((*ppNode)->bIsLeaf) { + (*ppNode)->nPixelCount++; + (*ppNode)->nRedSum += r; + (*ppNode)->nGreenSum += g; + (*ppNode)->nBlueSum += b; + (*ppNode)->nAlphaSum += a; + } else { // Recurse a level deeper if the node is not a leaf. + int shift = 7 - nLevel; + int nIndex =(((r & mask[nLevel]) >> shift) << 2) | + (((g & mask[nLevel]) >> shift) << 1) | + (( b & mask[nLevel]) >> shift); + AddColor (&((*ppNode)->pChild[nIndex]), r, g, b, a, nColorBits, + nLevel + 1, pLeafCount, pReducibleNodes); + } +} +///////////////////////////////////////////////////////////////////////////// +void* CQuantizer::CreateNode (UINT nLevel, UINT nColorBits, UINT* pLeafCount, + NODE** pReducibleNodes) +{ + NODE* pNode = (NODE*)calloc(1,sizeof(NODE)); + + if (pNode== NULL) return NULL; + + pNode->bIsLeaf = (nLevel == nColorBits) ? TRUE : FALSE; + if (pNode->bIsLeaf) (*pLeafCount)++; + else { + pNode->pNext = pReducibleNodes[nLevel]; + pReducibleNodes[nLevel] = pNode; + } + return pNode; +} +///////////////////////////////////////////////////////////////////////////// +void CQuantizer::ReduceTree (UINT nColorBits, UINT* pLeafCount, + NODE** pReducibleNodes) +{ + // Find the deepest level containing at least one reducible node. + for (int i=nColorBits - 1; (i>0) && (pReducibleNodes[i] == NULL); i--); + + // Reduce the node most recently added to the list at level i. + NODE* pNode = pReducibleNodes[i]; + pReducibleNodes[i] = pNode->pNext; + + UINT nRedSum = 0; + UINT nGreenSum = 0; + UINT nBlueSum = 0; + UINT nAlphaSum = 0; + UINT nChildren = 0; + + for (i=0; i<8; i++) { + if (pNode->pChild[i] != NULL) { + nRedSum += pNode->pChild[i]->nRedSum; + nGreenSum += pNode->pChild[i]->nGreenSum; + nBlueSum += pNode->pChild[i]->nBlueSum; + nAlphaSum += pNode->pChild[i]->nAlphaSum; + pNode->nPixelCount += pNode->pChild[i]->nPixelCount; + free(pNode->pChild[i]); + pNode->pChild[i] = NULL; + nChildren++; + } + } + + pNode->bIsLeaf = TRUE; + pNode->nRedSum = nRedSum; + pNode->nGreenSum = nGreenSum; + pNode->nBlueSum = nBlueSum; + pNode->nAlphaSum = nAlphaSum; + *pLeafCount -= (nChildren - 1); +} +///////////////////////////////////////////////////////////////////////////// +void CQuantizer::DeleteTree (NODE** ppNode) +{ + for (int i=0; i<8; i++) { + if ((*ppNode)->pChild[i] != NULL) DeleteTree (&((*ppNode)->pChild[i])); + } + free(*ppNode); + *ppNode = NULL; +} +///////////////////////////////////////////////////////////////////////////// +void CQuantizer::GetPaletteColors (NODE* pTree, RGBQUAD* prgb, UINT* pIndex, UINT* pSum) +{ + if (pTree){ + if (pTree->bIsLeaf) { + prgb[*pIndex].rgbRed = (BYTE)((pTree->nRedSum)/(pTree->nPixelCount)); + prgb[*pIndex].rgbGreen = (BYTE)((pTree->nGreenSum)/(pTree->nPixelCount)); + prgb[*pIndex].rgbBlue = (BYTE)((pTree->nBlueSum)/(pTree->nPixelCount)); + prgb[*pIndex].rgbReserved = (BYTE)((pTree->nAlphaSum)/(pTree->nPixelCount)); + if (pSum) pSum[*pIndex] = pTree->nPixelCount; + (*pIndex)++; + } else { + for (int i=0; i<8; i++) { + if (pTree->pChild[i] != NULL) + GetPaletteColors (pTree->pChild[i], prgb, pIndex, pSum); + } + } + } +} +///////////////////////////////////////////////////////////////////////////// +UINT CQuantizer::GetColorCount () +{ + return m_nLeafCount; +} +///////////////////////////////////////////////////////////////////////////// +void CQuantizer::SetColorTable (RGBQUAD* prgb) +{ + UINT nIndex = 0; + if (m_nOutputMaxColors<16){ + UINT nSum[16]; + RGBQUAD tmppal[16]; + GetPaletteColors (m_pTree, tmppal, &nIndex, nSum); + if (m_nLeafCount>m_nOutputMaxColors) { + UINT j,k,nr,ng,nb,na,ns,a,b; + for (j=0;j> 3)]; + if (nbit==4){ + pos = (BYTE)(4*(1-x%2)); + iDst &= (0x0F<> pos); + } else if (nbit==1){ + pos = (BYTE)(7-x%8); + iDst &= (0x01<> pos); + } + } + return 0; +} diff --git a/SlnkDWFImpl/CxImage/demo/Quantize.h b/SlnkDWFImpl/CxImage/demo/Quantize.h new file mode 100644 index 0000000..46d9b7e --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/Quantize.h @@ -0,0 +1,62 @@ +/* === C R E D I T S & D I S C L A I M E R S ============== + * Permission is given by the author to freely redistribute and include + * this code in any program as long as this credit is given where due. + * + * CQuantizer (c) 1996-1997 Jeff Prosise + * + * 31/08/2003 Davide Pizzolato - www.xdp.it + * - fixed minor bug in ProcessImage when bpp<=8 + * - better color reduction to less than 16 colors + * + * COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES + * THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE + * OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED + * CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT + * THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY + * SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL + * PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. + * + * Use at your own risk! + * ========================================================== + */ +class CQuantizer +{ +typedef struct _NODE { + BOOL bIsLeaf; // TRUE if node has no children + UINT nPixelCount; // Number of pixels represented by this leaf + UINT nRedSum; // Sum of red components + UINT nGreenSum; // Sum of green components + UINT nBlueSum; // Sum of blue components + UINT nAlphaSum; // Sum of alpha components + struct _NODE* pChild[8]; // Pointers to child nodes + struct _NODE* pNext; // Pointer to next reducible node +} NODE; +protected: + NODE* m_pTree; + UINT m_nLeafCount; + NODE* m_pReducibleNodes[9]; + UINT m_nMaxColors; + UINT m_nOutputMaxColors; + UINT m_nColorBits; + +public: + CQuantizer (UINT nMaxColors, UINT nColorBits); + virtual ~CQuantizer (); + BOOL ProcessImage (HANDLE hImage); + UINT GetColorCount (); + void SetColorTable (RGBQUAD* prgb); + +protected: + void AddColor (NODE** ppNode, BYTE r, BYTE g, BYTE b, BYTE a, UINT nColorBits, + UINT nLevel, UINT* pLeafCount, NODE** pReducibleNodes); + void* CreateNode (UINT nLevel, UINT nColorBits, UINT* pLeafCount, + NODE** pReducibleNodes); + void ReduceTree (UINT nColorBits, UINT* pLeafCount, + NODE** pReducibleNodes); + void DeleteTree (NODE** ppNode); + void GetPaletteColors (NODE* pTree, RGBQUAD* prgb, UINT* pIndex, UINT* pSum); + BYTE GetPixelIndex(long x,long y, int nbit, long effwdt, BYTE *pimage); +}; + diff --git a/SlnkDWFImpl/CxImage/demo/Res/.gitignore b/SlnkDWFImpl/CxImage/demo/Res/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/demo/Res/Toolbar.bmp b/SlnkDWFImpl/CxImage/demo/Res/Toolbar.bmp new file mode 100644 index 0000000..e277435 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/Toolbar.bmp differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/b1.ico b/SlnkDWFImpl/CxImage/demo/Res/b1.ico new file mode 100644 index 0000000..7b37c6d Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/b1.ico differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/bg.bmp b/SlnkDWFImpl/CxImage/demo/Res/bg.bmp new file mode 100644 index 0000000..26443b8 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/bg.bmp differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/bg.gif b/SlnkDWFImpl/CxImage/demo/Res/bg.gif new file mode 100644 index 0000000..551d01a Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/bg.gif differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/bg.jpg b/SlnkDWFImpl/CxImage/demo/Res/bg.jpg new file mode 100644 index 0000000..77b0c29 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/bg.jpg differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/bg.tif b/SlnkDWFImpl/CxImage/demo/Res/bg.tif new file mode 100644 index 0000000..94bc4aa Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/bg.tif differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/bg2.jpg b/SlnkDWFImpl/CxImage/demo/Res/bg2.jpg new file mode 100644 index 0000000..bfef638 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/bg2.jpg differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/canc.ico b/SlnkDWFImpl/CxImage/demo/Res/canc.ico new file mode 100644 index 0000000..093a780 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/canc.ico differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/demo.ico b/SlnkDWFImpl/CxImage/demo/Res/demo.ico new file mode 100644 index 0000000..0ee88fa Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/demo.ico differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/demo.rc2 b/SlnkDWFImpl/CxImage/demo/Res/demo.rc2 new file mode 100644 index 0000000..aecadd1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/Res/demo.rc2 @@ -0,0 +1,13 @@ +// +// DEMO.RC2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED + #error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... + +///////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/Res/demoDoc.ico b/SlnkDWFImpl/CxImage/demo/Res/demoDoc.ico new file mode 100644 index 0000000..fe2d3ba Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/demoDoc.ico differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/gray.ico b/SlnkDWFImpl/CxImage/demo/Res/gray.ico new file mode 100644 index 0000000..5ebc9d6 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/gray.ico differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/ico2.bin b/SlnkDWFImpl/CxImage/demo/Res/ico2.bin new file mode 100644 index 0000000..57e9dfd Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/ico2.bin differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/no1.ico b/SlnkDWFImpl/CxImage/demo/Res/no1.ico new file mode 100644 index 0000000..1309b13 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/no1.ico differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/ok.ico b/SlnkDWFImpl/CxImage/demo/Res/ok.ico new file mode 100644 index 0000000..cca7dbc Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/ok.ico differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/r1.ico b/SlnkDWFImpl/CxImage/demo/Res/r1.ico new file mode 100644 index 0000000..a1417ef Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/r1.ico differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/toolbar1.bmp b/SlnkDWFImpl/CxImage/demo/Res/toolbar1.bmp new file mode 100644 index 0000000..7d916a5 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/toolbar1.bmp differ diff --git a/SlnkDWFImpl/CxImage/demo/Res/us.png b/SlnkDWFImpl/CxImage/demo/Res/us.png new file mode 100644 index 0000000..45027b5 Binary files /dev/null and b/SlnkDWFImpl/CxImage/demo/Res/us.png differ diff --git a/SlnkDWFImpl/CxImage/demo/StdAfx.cpp b/SlnkDWFImpl/CxImage/demo/StdAfx.cpp new file mode 100644 index 0000000..b94a4d1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/StdAfx.cpp @@ -0,0 +1,6 @@ +// stdafx.cpp : source file that includes just the standard includes +// demo.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + diff --git a/SlnkDWFImpl/CxImage/demo/StdAfx.h b/SlnkDWFImpl/CxImage/demo/StdAfx.h new file mode 100644 index 0000000..fb8881f --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/StdAfx.h @@ -0,0 +1,22 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#ifndef WINVER +#define WINVER 0x0400 +#endif + +#include // MFC core and standard components +#include // MFC extensions +#include // MFC Automation classes +//#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows 95 Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + + + + diff --git a/SlnkDWFImpl/CxImage/demo/TwainCpp.cpp b/SlnkDWFImpl/CxImage/demo/TwainCpp.cpp new file mode 100644 index 0000000..b393be7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/TwainCpp.cpp @@ -0,0 +1,584 @@ +#include "stdafx.h" +#include "twaincpp.h" + +/* +Constructor: + Parameters : HWND + Window to subclass + +*/ +CTwain::CTwain(HWND hWnd) +{ + m_hTwainDLL = NULL; + m_pDSMProc = NULL; + m_bSourceSelected = FALSE; + m_bDSOpen = m_bDSMOpen = FALSE; + m_bSourceEnabled = FALSE; + m_bModalUI = TRUE; + m_nImageCount = TWCPP_ANYCOUNT; + if(hWnd) + { + InitTwain(hWnd); + } +} + +CTwain::~CTwain() +{ + ReleaseTwain(); +} + +/* +Initializes TWAIN interface . Is already called from the constructor. +It should be called again if ReleaseTwain is called. + + hWnd is the window which has to subclassed in order to recieve + Twain messaged. Normally - this would be your main application window. + +*/ +BOOL CTwain::InitTwain(HWND hWnd) +{ +char libName[512]; + if(IsValidDriver()) + { + return TRUE; + } + memset(&m_AppId,0,sizeof(m_AppId)); + if(!IsWindow(hWnd)) + { + return FALSE; + } + m_hMessageWnd = hWnd; + strcpy(libName,"TWAIN_32.DLL"); + + m_hTwainDLL = LoadLibrary(libName); + if(m_hTwainDLL != NULL) + { + if(!(m_pDSMProc = (DSMENTRYPROC)GetProcAddress(m_hTwainDLL,MAKEINTRESOURCE(1)))) + { + FreeLibrary(m_hTwainDLL); + m_hTwainDLL = NULL; + } + } + if(IsValidDriver()) + { + GetIdentity(); + m_bDSMOpen= CallTwainProc(&m_AppId,NULL,DG_CONTROL,DAT_PARENT,MSG_OPENDSM,(TW_MEMREF)&m_hMessageWnd); + return TRUE; + } + else + { + return FALSE; + } +} + +/* +Releases the twain interface . Need not be called unless you +want to specifically shut it down. +*/ +void CTwain::ReleaseTwain() +{ + if(IsValidDriver()) + { + CloseDSM(); + FreeLibrary(m_hTwainDLL); + m_hTwainDLL = NULL; + m_pDSMProc = NULL; + } +} + +/* +Returns true if a valid driver has been loaded +*/ +BOOL CTwain::IsValidDriver() const +{ + return (m_hTwainDLL && m_pDSMProc); +} +/* +* Fucntion: CallDSMEntry +* Author: Nancy Letourneau / J.F.L. Peripherals Inc. +* Input: +* Function - +* pApp - +* pSrc - +* DG - +* DAT - +* MSG - +* pData - +* Output: +* TW_UINT16 - Value of Item field of container. +* Comments: +* +*/ +TW_UINT16 CTwain::CallDSMEntry(pTW_IDENTITY pApp, pTW_IDENTITY pSrc, + TW_UINT32 DG, TW_UINT16 DAT, TW_UINT16 MSG, TW_MEMREF pData) +{ + TW_UINT16 twRC = (*m_pDSMProc)(pApp, pSrc, DG, DAT, MSG, pData); + + if((twRC != TWRC_SUCCESS)&&(DAT!=DAT_EVENT)) + { + VERIFY((*m_pDSMProc)(pApp, pSrc, DG_CONTROL, DAT_STATUS, MSG_GET, + (TW_MEMREF)&m_Status) == TWRC_SUCCESS); + TRACE("CallDSMEntry function: call failed with RC = %d, CC = %d.\n", + twRC, m_Status); + } + return twRC; +} +/* +Entry point into Twain. For a complete description of this +routine please refer to the Twain specification 1.8 +*/ +BOOL CTwain::CallTwainProc(pTW_IDENTITY pOrigin,pTW_IDENTITY pDest, + TW_UINT32 DG,TW_UINT16 DAT,TW_UINT16 MSG, + TW_MEMREF pData) +{ + if(IsValidDriver()) + { + USHORT ret_val; + ret_val = (*m_pDSMProc)(pOrigin,pDest,DG,DAT,MSG,pData); + m_returnCode = ret_val; + if(ret_val != TWRC_SUCCESS) + { + (*m_pDSMProc)(pOrigin,pDest,DG_CONTROL,DAT_STATUS,MSG_GET,&m_Status); + } + return (ret_val == TWRC_SUCCESS); + } + else + { + m_returnCode = TWRC_FAILURE; + return FALSE; + } +} + +/* +This function should ideally be overridden in the derived class . If only a +few fields need to be updated , call CTawin::GetIdentity first in your +derived class +*/ +void CTwain::GetIdentity() +{ + // Expects all the fields in m_AppId to be set except for the id field. + m_AppId.Id = 0; // Initialize to 0 (Source Manager + // will assign real value) + m_AppId.Version.MajorNum = 3; //Your app's version number + m_AppId.Version.MinorNum = 5; + m_AppId.Version.Language = TWLG_USA; + m_AppId.Version.Country = TWCY_USA; + strcpy (m_AppId.Version.Info, "3.5"); + m_AppId.ProtocolMajor = TWON_PROTOCOLMAJOR; + m_AppId.ProtocolMinor = TWON_PROTOCOLMINOR; + m_AppId.SupportedGroups = DG_IMAGE | DG_CONTROL; + strcpy (m_AppId.Manufacturer, "MICSS"); + strcpy (m_AppId.ProductFamily, "Generic"); + strcpy (m_AppId.ProductName, "Twain Test"); + +} + + +/* +Called to display a dialog box to select the Twain source to use. +This can be overridden if a list of all sources is available +to the application. These sources can be enumerated by Twain. +it is not yet supportted by CTwain. +*/ +BOOL CTwain::SelectSource() +{ + memset(&m_Source,0,sizeof(m_Source)); + if(!SourceSelected()) + { + SelectDefaultSource(); + } + if(CallTwainProc(&m_AppId,NULL,DG_CONTROL,DAT_IDENTITY,MSG_USERSELECT,&m_Source)) + { + m_bSourceSelected = TRUE; + } + return m_bSourceSelected; +} + +/* +Called to select the default source +*/ +BOOL CTwain::SelectDefaultSource() +{ + m_bSourceSelected = CallTwainProc(&m_AppId,NULL,DG_CONTROL,DAT_IDENTITY,MSG_GETDEFAULT,&m_Source); + return m_bSourceSelected; +} + +/* +Closes the Data Source +*/ +void CTwain::CloseDS() +{ + if(DSOpen()) + { + DisableSource(); + CallTwainProc(&m_AppId,NULL,DG_CONTROL,DAT_IDENTITY,MSG_CLOSEDS,(TW_MEMREF)&m_Source); + m_bDSOpen = FALSE; + } +} + +/* +Closes the Data Source Manager +*/ +void CTwain::CloseDSM() +{ + if(DSMOpen()) + { + CloseDS(); + CallTwainProc(&m_AppId,NULL,DG_CONTROL,DAT_PARENT,MSG_CLOSEDSM,(TW_MEMREF)&m_hMessageWnd); + m_bDSMOpen = FALSE; + } +} + +/* +Returns true if the Data Source Manager is Open +*/ +BOOL CTwain::DSMOpen() const +{ + return IsValidDriver() && m_bDSMOpen; +} + +/* +Returns true if the Data Source is Open +*/ +BOOL CTwain::DSOpen() const +{ + return IsValidDriver() && DSMOpen() && m_bDSOpen; +} + +/* +Opens a Data Source supplied as the input parameter +*/ +BOOL CTwain::OpenSource(TW_IDENTITY *pSource) +{ + if(pSource) + { + m_Source = *pSource; + } + if(DSMOpen()) + { + if(!SourceSelected()) + { + SelectDefaultSource(); + } + m_bDSOpen = CallTwainProc(&m_AppId,NULL,DG_CONTROL,DAT_IDENTITY,MSG_OPENDS,(TW_MEMREF)&m_Source); + } + return DSOpen(); +} + +/* +Should be called from the main message loop of the application. Can always be called, +it will not process the message unless a scan is in progress. +*/ +BOOL CTwain::ProcessMessage(MSG msg) +{ + if(SourceEnabled()){ + + TW_UINT16 twRC = TWRC_NOTDSEVENT; + TW_EVENT twEvent; + + memset(&twEvent, 0, sizeof(TW_EVENT)); + // twEvent.TWMessage = MSG_NULL; + + twEvent.pEvent = (TW_MEMREF)&msg; + + twRC = CallDSMEntry(&m_AppId,&m_Source,DG_CONTROL,DAT_EVENT,MSG_PROCESSEVENT,(TW_MEMREF)&twEvent); + + // CallTwainProc(&m_AppId,&m_Source,DG_CONTROL,DAT_EVENT,MSG_PROCESSEVENT,(TW_MEMREF)&twEvent); + // if(GetRC() != TWRC_NOTDSEVENT) + // { + TranslateMessage(twEvent); + // } + + // tell the caller what happened + return (twRC==TWRC_DSEVENT); // returns TRUE or FALSE + } + return FALSE; +} + +/* +Queries the capability of the Twain Data Source +*/ +BOOL CTwain::GetCapability(TW_CAPABILITY& twCap,TW_UINT16 cap,TW_UINT16 conType) +{ + if(DSOpen()) + { + twCap.Cap = cap; + twCap.ConType = conType; + twCap.hContainer = NULL; + + if(CallTwainProc(&m_AppId,&m_Source,DG_CONTROL,DAT_CAPABILITY,MSG_GET,(TW_MEMREF)&twCap)) + { + return TRUE; + } + } + return FALSE; +} + +/* +Queries the capability of the Twain Data Source +*/ +BOOL CTwain::GetCapability(TW_UINT16 cap,TW_UINT32& value) +{ +TW_CAPABILITY twCap; + if(GetCapability(twCap,cap)) + { + pTW_ONEVALUE pVal; + pVal = (pTW_ONEVALUE )GlobalLock(twCap.hContainer); + if(pVal) + { + value = pVal->Item; + GlobalUnlock(pVal); + GlobalFree(twCap.hContainer); + return TRUE; + } + } + return FALSE; +} + + +/* +Sets the capability of the Twain Data Source +*/ +BOOL CTwain::SetCapability(TW_UINT16 cap,TW_UINT16 value,BOOL sign) +{ + if(DSOpen()) + { + TW_CAPABILITY twCap; + pTW_ONEVALUE pVal; + BOOL ret_value = FALSE; + + twCap.Cap = cap; + twCap.ConType = TWON_ONEVALUE; + + twCap.hContainer = GlobalAlloc(GHND,sizeof(TW_ONEVALUE)); + if(twCap.hContainer) + { + pVal = (pTW_ONEVALUE)GlobalLock(twCap.hContainer); + pVal->ItemType = sign ? TWTY_INT16 : TWTY_UINT16; + pVal->Item = (TW_UINT32)value; + GlobalUnlock(twCap.hContainer); + ret_value = SetCapability(twCap); + GlobalFree(twCap.hContainer); + } + return ret_value; + } + return FALSE; +} + +/* +Sets the capability of the Twain Data Source +*/ +BOOL CTwain::SetCapability(TW_CAPABILITY& cap) +{ + if(DSOpen()) + { + return CallTwainProc(&m_AppId,&m_Source,DG_CONTROL,DAT_CAPABILITY,MSG_SET,(TW_MEMREF)&cap); + } + return FALSE; +} + +/* +Sets the number of images which can be accpeted by the application at one time +*/ +BOOL CTwain::SetImageCount(TW_INT16 nCount) +{ + if(SetCapability(CAP_XFERCOUNT,(TW_UINT16)nCount,TRUE)) + { + m_nImageCount = nCount; + return TRUE; + } + else + { + if(GetRC() == TWRC_CHECKSTATUS) + { + TW_UINT32 count; + if(GetCapability(CAP_XFERCOUNT,count)) + { + nCount = (TW_INT16)count; + if(SetCapability(CAP_XFERCOUNT,nCount)) + { + m_nImageCount = nCount; + return TRUE; + } + } + } + } + return FALSE; +} + +/* +Called to enable the Twain Acquire Dialog. This too can be +overridden but is a helluva job . +*/ +BOOL CTwain::EnableSource(BOOL showUI) +{ + if(DSOpen() && !SourceEnabled()) + { + TW_USERINTERFACE twUI; + twUI.ShowUI = showUI; + twUI.hParent = (TW_HANDLE)m_hMessageWnd; + if(CallTwainProc(&m_AppId,&m_Source,DG_CONTROL,DAT_USERINTERFACE,MSG_ENABLEDS,(TW_MEMREF)&twUI)) + { + m_bSourceEnabled = TRUE; + m_bModalUI = twUI.ModalUI; + } + else + { + m_bSourceEnabled = FALSE; + m_bModalUI = TRUE; + } + return m_bSourceEnabled; + } + return FALSE; +} + +/* +Called to acquire images from the source. parameter numImages i the +numberof images that you an handle concurrently +*/ +BOOL CTwain::Acquire(int numImages) +{ + if(DSOpen() || OpenSource()) + { + if(SetImageCount(numImages)) + { + if(EnableSource()) + { + return TRUE; + } + } + } + return FALSE; +} + +/* + Called to disable the source. +*/ +BOOL CTwain::DisableSource() +{ + if(SourceEnabled()) + { + TW_USERINTERFACE twUI; + if(CallTwainProc(&m_AppId,&m_Source,DG_CONTROL,DAT_USERINTERFACE,MSG_DISABLEDS,&twUI)) + { + m_bSourceEnabled = FALSE; + return TRUE; + } + } + return FALSE; +} + +/* +Called by ProcessMessage to Translate a TWAIN message +*/ +void CTwain::TranslateMessage(TW_EVENT& twEvent) +{ + switch(twEvent.TWMessage) + { + case MSG_XFERREADY: + TransferImage(); + break; + case MSG_CLOSEDSREQ: + if(CanClose()) + { + CloseDS(); + } + break; + + // No message from the Source to the App break; + // possible new message + case MSG_NULL: + default: + break; + } +} + +/* +Gets Imageinfo for an image which is about to be transferred. +*/ +BOOL CTwain::GetImageInfo(TW_IMAGEINFO& info) +{ + if(SourceEnabled()) + { + return CallTwainProc(&m_AppId,&m_Source,DG_IMAGE,DAT_IMAGEINFO,MSG_GET,(TW_MEMREF)&info); + } + return FALSE; +} + +/* +Trasnfers the image or cancels the transfer depending on the state of the +TWAIN system +*/ +void CTwain::TransferImage() +{ +TW_IMAGEINFO info; +BOOL bContinue=TRUE; + while(bContinue) + { + if(GetImageInfo(info)) + { + int permission; + permission = ShouldTransfer(info); + switch(permission) + { + case TWCPP_CANCELTHIS: + bContinue=EndTransfer(); + break; + case TWCPP_CANCELALL: + CancelTransfer(); + bContinue=FALSE; + break; + case TWCPP_DOTRANSFER: + bContinue=GetImage(info); + break; + } + } + } +} + +/* +Ends the current transfer. +Returns TRUE if the more images are pending +*/ +BOOL CTwain::EndTransfer() +{ +TW_PENDINGXFERS twPend; + if(CallTwainProc(&m_AppId,&m_Source,DG_CONTROL,DAT_PENDINGXFERS,MSG_ENDXFER,(TW_MEMREF)&twPend)) + { + return twPend.Count != 0; + } + return FALSE; +} + +/* +Aborts all transfers +*/ +void CTwain::CancelTransfer() +{ +TW_PENDINGXFERS twPend; + CallTwainProc(&m_AppId,&m_Source,DG_CONTROL,DAT_PENDINGXFERS,MSG_RESET,(TW_MEMREF)&twPend); +} + +/* +Calls TWAIN to actually get the image +*/ +BOOL CTwain::GetImage(TW_IMAGEINFO& info) +{ +HANDLE hBitmap; + CallTwainProc(&m_AppId,&m_Source,DG_IMAGE,DAT_IMAGENATIVEXFER,MSG_GET,&hBitmap); + switch(m_returnCode) + { + case TWRC_XFERDONE: + SetImage(hBitmap,info); + break; + case TWRC_CANCEL: + break; + case TWRC_FAILURE: + CancelTransfer(); + return FALSE; + + } + GlobalFree(hBitmap); + return EndTransfer(); +} + diff --git a/SlnkDWFImpl/CxImage/demo/TwainCpp.h b/SlnkDWFImpl/CxImage/demo/TwainCpp.h new file mode 100644 index 0000000..9db366a --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/TwainCpp.h @@ -0,0 +1,102 @@ +#ifndef __TWAINCPP_ +#define __TWAINCPP_ + +#include "Twain.h" + + +#define TWCPP_ANYCOUNT (-1) +#define TWCPP_CANCELTHIS (1) +#define TWCPP_CANCELALL (2) +#define TWCPP_DOTRANSFER (0) + +class CTwain +{ +public: + + + CTwain(HWND hWnd = NULL); + virtual ~CTwain(); + BOOL InitTwain(HWND hWnd); + void ReleaseTwain(); + + + /* + This routine must be implemented by the dervied class + After setting the required values in the m_AppId structure, + the derived class should call the parent class implementation + Refer Pg: 51 of the Twain Specification version 1.8 + */ + virtual void GetIdentity(); + virtual BOOL SelectSource(); + virtual BOOL OpenSource(TW_IDENTITY *pSource=NULL); + virtual int ShouldTransfer(TW_IMAGEINFO& info) { return TWCPP_DOTRANSFER;}; + + BOOL ProcessMessage(MSG msg); + + BOOL SelectDefaultSource(); + BOOL IsValidDriver() const; + BOOL SourceSelected() const {return m_bSourceSelected;} ; + BOOL DSMOpen() const; + BOOL DSOpen() const; + BOOL SourceEnabled() const { return m_bSourceEnabled;}; + BOOL ModalUI() const { return m_bModalUI; }; + + TW_INT16 GetRC() const { return m_returnCode; }; + TW_STATUS GetStatus() const { return m_Status; }; + + BOOL SetImageCount(TW_INT16 nCount = 1); + BOOL Acquire(int numImages=1); + +protected: + BOOL CallTwainProc(pTW_IDENTITY pOrigin,pTW_IDENTITY pDest, + TW_UINT32 DG,TW_UINT16 DAT,TW_UINT16 MSG, + TW_MEMREF pData); + TW_UINT16 CallDSMEntry(pTW_IDENTITY pApp, pTW_IDENTITY pSrc, + TW_UINT32 DG, TW_UINT16 DAT, TW_UINT16 MSG, + TW_MEMREF pData); + + void CloseDSM(); + void CloseDS(); + + BOOL GetCapability(TW_CAPABILITY& twCap,TW_UINT16 cap,TW_UINT16 conType=TWON_DONTCARE16); + BOOL GetCapability(TW_UINT16 cap,TW_UINT32& value); + BOOL SetCapability(TW_UINT16 cap,TW_UINT16 value,BOOL sign=FALSE); + BOOL SetCapability(TW_CAPABILITY& twCap); + BOOL EnableSource(BOOL showUI = TRUE); + + BOOL GetImageInfo(TW_IMAGEINFO& info); + + virtual BOOL DisableSource(); + virtual BOOL CanClose() { return TRUE; }; + + void TranslateMessage(TW_EVENT& twEvent); + void TransferImage(); + BOOL EndTransfer(); + void CancelTransfer(); + BOOL ShouldContinue(); + BOOL GetImage(TW_IMAGEINFO& info); + + virtual void SetImage(HANDLE hBitmap,TW_IMAGEINFO& info)=0; +// virtual void CopyImage(HANDLE hBitmap,TW_IMAGEINFO& info); + +protected: + HINSTANCE m_hTwainDLL; + DSMENTRYPROC m_pDSMProc; + + TW_IDENTITY m_AppId; + TW_IDENTITY m_Source; + TW_STATUS m_Status; + TW_INT16 m_returnCode; + HWND m_hMessageWnd; + + BOOL m_bSourceSelected; + BOOL m_bDSMOpen; + BOOL m_bDSOpen; + BOOL m_bSourceEnabled; + BOOL m_bModalUI; + + int m_nImageCount; +}; + + +#endif \ No newline at end of file diff --git a/SlnkDWFImpl/CxImage/demo/demo.clw b/SlnkDWFImpl/CxImage/demo/demo.clw new file mode 100644 index 0000000..82774ce --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.clw @@ -0,0 +1,1129 @@ +; CLW file contains information for the MFC ClassWizard + +[General Info] +Version=1 +LastClass=DlgOptions +LastTemplate=CDialog +NewFileInclude1=#include "stdafx.h" +NewFileInclude2=#include "demo.h" +LastPage=0 + +ClassCount=27 +Class1=CDemoApp +Class2=CDemoDoc +Class3=CDemoView +Class4=CMainFrame + +ResourceCount=31 +Resource1=IDD_ABOUTBOX +Resource2=IDR_MAINFRAME +Resource3=IDR_DEMOTYPE +Class5=CAboutDlg +Class6=CChildFrame +Resource4=IDR_MAINFRAME (Neutral) +Resource5=IDD_REPAIR (Neutral) +Resource6=IDD_THRESHOLD (Neutral) +Class7=DlgRotate +Resource7=IDD_OPACITY (Neutral) +Class8=DlgCapture +Resource8=IDD_ABOUTBOX (Neutral) +Resource9=IDD_INCBPP (Neutral) +Class9=DlgResample +Resource10=IDD_OPTIONS (Neutral) +Resource11=IDD_PALETTE (Neutral) +Class10=DlgDecBpp +Class11=DlgIncBpp +Resource12=IDD_ROTATE (Neutral) +Class12=DlgOptions +Resource13=IDD_HISTO (Neutral) +Class13=DlgDither +Resource14=IDD_SKEW (Neutral) +Class14=DlgThreshold +Resource15=IDM_CXIMAGE1 +Class15=DlgColorize +Resource16=IDD_CAPTURE (Neutral) +Resource17=IDD_FFT (Neutral) +Class16=DlgOpacity +Resource18=IDD_COMBINE (Neutral) +Class17=DlgURL +Resource19=IDD_DITHER (Neutral) +Class18=DlgGamma +Resource20=IDD_COLORIZE (Neutral) +Class19=DlgHisto +Resource21=IDR_TOOLBAR1 +Class20=DlgPalette +Resource22=IDD_MIX (Neutral) +Class21=DlgCombine +Resource23=IDD_TEXT (Neutral) +Resource24=IDR_TOOLBAR1 (Neutral) +Resource25=IDD_DECBPP (Neutral) +Class22=DlgFFT +Resource26=IDD_RESAMPLE (Neutral) +Class23=DlgRepair +Resource27=IDD_GAMMA (Neutral) +Class24=DlgText +Resource28=IDD_DWNURL (Neutral) +Class25=DlgMix +Resource29=IDR_DEMOTYPE (Neutral) +Class26=DlgSkew +Resource30=IDM_CXIMAGE1 (Neutral) +Class27=DlgJpeg +Resource31=IDD_JPEG (Neutral) + +[CLS:CDemoApp] +Type=0 +HeaderFile=demo.h +ImplementationFile=demo.cpp +Filter=W +LastObject=ID_CXIMAGE_HISTOGRAM_STRETCH +BaseClass=CWinApp +VirtualFilter=AC + +[CLS:CDemoDoc] +Type=0 +HeaderFile=demoDoc.h +ImplementationFile=demoDoc.cpp +Filter=N +LastObject=ID_CXIMAGE_CROP +BaseClass=CDocument +VirtualFilter=DC + +[CLS:CDemoView] +Type=0 +HeaderFile=demoView.h +ImplementationFile=demoView.cpp +Filter=C +LastObject=ID_STRETCH_MODE +BaseClass=CScrollView +VirtualFilter=VWC + +[CLS:CMainFrame] +Type=0 +HeaderFile=MainFrm.h +ImplementationFile=MainFrm.cpp +Filter=W +BaseClass=CMDIFrameWnd +VirtualFilter=fWC +LastObject=ID_CXIMAGE_DEMOCREATEFROMARRAY + + +[CLS:CChildFrame] +Type=0 +HeaderFile=ChildFrm.h +ImplementationFile=ChildFrm.cpp +Filter=M +LastObject=CChildFrame +BaseClass=CMDIChildWnd +VirtualFilter=mfWC + +[CLS:CAboutDlg] +Type=0 +HeaderFile=demo.cpp +ImplementationFile=demo.cpp +Filter=D +BaseClass=CDialog +VirtualFilter=dWC +LastObject=IDOK + +[DLG:IDD_ABOUTBOX] +Type=1 +ControlCount=4 +Control1=IDC_STATIC,static,1342177283 +Control2=IDC_STATIC,static,1342308352 +Control3=IDC_STATIC,static,1342308352 +Control4=IDOK,button,1342373889 +Class=CAboutDlg + +[MNU:IDR_MAINFRAME] +Type=1 +Class=CMainFrame +Command1=ID_FILE_NEW +Command2=ID_FILE_OPEN +Command3=ID_FILE_PRINT_SETUP +Command4=ID_FILE_MRU_FILE1 +Command5=ID_APP_EXIT +Command6=ID_VIEW_TOOLBAR +Command7=ID_VIEW_STATUS_BAR +CommandCount=8 +Command8=ID_APP_ABOUT + +[TB:IDR_MAINFRAME] +Type=1 +Class=CMainFrame +Command1=ID_FILE_NEW +Command2=ID_FILE_OPEN +Command3=ID_FILE_SAVE +Command4=ID_EDIT_CUT +Command5=ID_EDIT_COPY +Command6=ID_EDIT_PASTE +Command7=ID_FILE_PRINT +CommandCount=8 +Command8=ID_APP_ABOUT + +[MNU:IDR_DEMOTYPE] +Type=1 +Class=CDemoView +Command1=ID_FILE_NEW +Command2=ID_FILE_OPEN +Command3=ID_FILE_CLOSE +Command4=ID_FILE_SAVE +Command5=ID_FILE_SAVE_AS +Command6=ID_FILE_PRINT +Command7=ID_FILE_PRINT_PREVIEW +Command8=ID_FILE_PRINT_SETUP +Command9=ID_FILE_MRU_FILE1 +Command10=ID_APP_EXIT +Command11=ID_EDIT_UNDO +Command12=ID_EDIT_CUT +Command13=ID_EDIT_COPY +Command14=ID_EDIT_PASTE +CommandCount=21 +Command15=ID_VIEW_TOOLBAR +Command16=ID_VIEW_STATUS_BAR +Command17=ID_WINDOW_NEW +Command18=ID_WINDOW_CASCADE +Command19=ID_WINDOW_TILE_HORZ +Command20=ID_WINDOW_ARRANGE +Command21=ID_APP_ABOUT + +[ACL:IDR_MAINFRAME] +Type=1 +Class=CMainFrame +Command1=ID_FILE_NEW +Command2=ID_FILE_OPEN +Command3=ID_FILE_SAVE +Command4=ID_FILE_PRINT +Command5=ID_EDIT_UNDO +Command6=ID_EDIT_CUT +Command7=ID_EDIT_COPY +Command8=ID_EDIT_PASTE +Command9=ID_EDIT_UNDO +Command10=ID_EDIT_CUT +Command11=ID_EDIT_COPY +Command12=ID_EDIT_PASTE +CommandCount=14 +Command13=ID_NEXT_PANE +Command14=ID_PREV_PANE + + +[CLS:DlgRotate] +Type=0 +HeaderFile=DlgRotate.h +ImplementationFile=DlgRotate.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=IDC_CHECK1 + +[CLS:DlgCapture] +Type=0 +HeaderFile=dlgcapture.h +ImplementationFile=dlgcapture.cpp +BaseClass=CDialog +LastObject=DlgCapture +Filter=D +VirtualFilter=dWC + +[DLG:IDD_ABOUTBOX (Neutral)] +Type=1 +Class=CAboutDlg +ControlCount=19 +Control1=IDC_STATIC,static,1342177283 +Control2=IDC_STATIC,static,1342308480 +Control3=IDOK,button,1342242817 +Control4=IDC_STATIC,static,1342308481 +Control5=IDC_STATIC,static,1342308352 +Control6=IDC_STATIC,static,1342308352 +Control7=IDC_STATIC,static,1342308352 +Control8=IDC_STATIC,static,1342308352 +Control9=IDC_STATIC,static,1342308352 +Control10=IDC_STATIC,static,1342308352 +Control11=IDC_STATIC,static,1342308352 +Control12=IDC_STATIC,static,1342308352 +Control13=IDC_STATIC,static,1342308352 +Control14=IDC_STATIC,static,1342308352 +Control15=IDC_STATIC,static,1342308352 +Control16=IDC_STATIC,static,1342308352 +Control17=IDC_STATIC,static,1342308352 +Control18=IDC_STATIC,static,1342308352 +Control19=IDC_STATIC,static,1342308352 + +[MNU:IDR_DEMOTYPE (Neutral)] +Type=1 +Class=CDemoView +Command1=ID_FILE_NEW +Command2=ID_FILE_OPEN +Command3=ID_FILE_CLOSE +Command4=ID_FILE_SAVE +Command5=ID_FILE_SAVE_AS +Command6=ID_FILE_SELECTSOURCE +Command7=ID_FILE_ACQUIRE +Command8=ID_FILE_CAPTURE +Command9=ID_FILE_PRINT +Command10=ID_FILE_PRINT_PREVIEW +Command11=ID_FILE_PRINT_SETUP +Command12=ID_FILE_MRU_FILE1 +Command13=ID_APP_EXIT +Command14=ID_EDIT_UNDO +Command15=ID_EDIT_REDO +Command16=ID_EDIT_CUT +Command17=ID_EDIT_COPY +Command18=ID_EDIT_PASTE +Command19=ID_VIEW_TOOLBAR +Command20=ID_VIEW_STATUS_BAR +Command21=ID_VIEW_HISTOGRAM +Command22=ID_VIEW_PALETTE +Command23=ID_VIEW_TOOLS_MOVE +Command24=ID_VIEW_TOOLS_SELECT +Command25=ID_VIEW_TOOLS_ZOOM +Command26=ID_VIEW_TOOLS_TEXT +Command27=ID_VIEW_TOOLS_TRACKER +Command28=ID_VIEW_MENUSTYLE_NORMAL +Command29=ID_VIEW_MENUSTYLE_XP +Command30=ID_STRETCH_MODE +Command31=ID_VIEW_SMOOTH +Command32=ID_VIEW_FULLSCREEN +Command33=ID_VIEW_ZOOMIN +Command34=ID_VIEW_ZOOMOUT +Command35=ID_VIEW_NORMALVIEWING11 +Command36=ID_IMAGE_FROM_BITMAP +Command37=ID_CXIMAGE_LOADJPEGRESOURCE +Command38=ID_CXIMAGE_LOADICONRESOURCE +Command39=ID_CXIMAGE_LOADPNGRESOURCE +Command40=ID_CXIMAGE_LOADGIFRESOURCE +Command41=ID_CXIMAGE_LOADTIFRESOURCE +Command42=ID_TRANSFORM_ELLIPSE +Command43=ID_CXIMAGE_DEMOSAVEMULTIPAGETIFF +Command44=ID_CXIMAGE_DEMOSAVEANIMATEDGIF +Command45=ID_CXIMAGE_DOWNLOADFROMURL +Command46=ID_CXIMAGE_DEMOCREATEFROMARRAY +Command47=ID_CXIMAGE_MIRROR +Command48=ID_CXIMAGE_FLIP +Command49=ID_CXIMAGE_NEGATIVE +Command50=ID_CXIMAGE_ROTATEL +Command51=ID_CXIMAGE_ROTATER +Command52=ID_CXIMAGE_ROTATE +Command53=ID_CXIMAGE_RESAMPLE +Command54=ID_CXIMAGE_SKEW +Command55=ID_CXIMAGE_CROP +Command56=ID_CXIMAGE_SETTRANSPARENCY +Command57=ID_CXIMAGE_REMOVETRANSPARENCY +Command58=ID_CXIMAGE_OPACITY +Command59=ID_CXIMAGE_REMOVEALPHACHANNEL +Command60=ID_CXIMAGE_ALPHACHANNEL_SPLIT +Command61=ID_CXIMAGE_ALPHASTRIP +Command62=ID_CXIMAGE_INVETALPHA +Command63=ID_CXIMAGE_ALPHAPALETTETOGGLE +Command64=ID_CXIMAGE_ALPHACREATE +Command65=ID_CXIMAGE_GRAYSCALE +Command66=ID_CXIMAGE_DITHER +Command67=ID_CXIMAGE_DECREASEBPP +Command68=ID_CXIMAGE_INCREASEBPP +Command69=ID_CXIMAGE_HISTOGRAM_STRETCH +Command70=ID_CXIMAGE_HISTOGRAM_STRETCH1 +Command71=ID_CXIMAGE_HISTOGRAM_STRETCH2 +Command72=ID_CXIMAGE_HISTOGRAM_EQUALIZE +Command73=ID_CXIMAGE_HISTOGRAM_NORMALIZE +Command74=ID_CXIMAGE_HISTOGRAM_LOG +Command75=ID_CXIMAGE_HISTOGRAM_ROOT +Command76=ID_CXIMAGE_OPTIONS +Command77=ID_CXIMAGE_THRESHOLD +Command78=ID_CXIMAGE_COLORIZE +Command79=ID_CXIMAGE_GAMMA +Command80=ID_CXIMAGE_LIGHTEN +Command81=ID_CXIMAGE_DARKEN +Command82=ID_CXIMAGE_CONTRAST +Command83=ID_CXIMAGE_LESSCONTRAST +Command84=ID_CXIMAGE_BLUR +Command85=ID_CXIMAGE_SOFTEN +Command86=ID_CXIMAGE_GAUSSIAN3X3 +Command87=ID_CXIMAGE_GAUSSIAN5X5 +Command88=ID_CXIMAGE_SHARPEN +Command89=ID_CXIMAGE_EDGE +Command90=ID_CXIMAGE_EMBOSS +Command91=ID_CXIMAGE_ADDNOISE +Command92=ID_CXIMAGE_MEDIAN +Command93=ID_CXIMAGE_ERODE +Command94=ID_CXIMAGE_DILATE +Command95=ID_CXIMAGE_CONTOUR +Command96=ID_FILTERS_NONLINEAR_EDGE +Command97=ID_CXIMAGE_JITTER +Command98=ID_CXIMAGE_CIRCLETRANSFORM_PINCH +Command99=ID_CXIMAGE_CIRCLETRANSFORM_PUNCH +Command100=ID_CXIMAGE_CIRCLETRANSFORM_SWIRL +Command101=ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER +Command102=ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM +Command103=ID_CXIMAGE_PSEUDOCOLORS +Command104=ID_CXIMAGE_SPLITRGB +Command105=ID_CXIMAGE_SPLITHSL +Command106=ID_CXIMAGE_SPLITYUV +Command107=ID_CXIMAGE_SPLITYIQ +Command108=ID_CXIMAGE_SPLITXYZ +Command109=ID_CXIMAGE_SPLITCMYK +Command110=ID_CXIMAGE_COMBINE +Command111=ID_CXIMAGE_FFT +Command112=ID_CXIMAGE_REPAIR +Command113=ID_FILTERS_MIX +Command114=ID_FILTERS_JPEGCOMPRESSION +Command115=ID_WINDOW_NEW +Command116=ID_WINDOW_CASCADE +Command117=ID_WINDOW_TILE_HORZ +Command118=ID_WINDOW_ARRANGE +Command119=ID_WINDOW_CLOSEALL +Command120=ID_WINDOW_DUPLICATE +Command121=ID_APP_ABOUT +CommandCount=121 + +[TB:IDR_MAINFRAME (Neutral)] +Type=1 +Class=? +Command1=ID_FILE_NEW +Command2=ID_FILE_OPEN +Command3=ID_FILE_SAVE +Command4=ID_FILE_PRINT +Command5=ID_FILE_ACQUIRE +Command6=ID_EDIT_CUT +Command7=ID_EDIT_COPY +Command8=ID_EDIT_PASTE +Command9=ID_EDIT_UNDO +Command10=ID_EDIT_REDO +Command11=ID_VIEW_ZOOMIN +Command12=ID_VIEW_NORMALVIEWING11 +Command13=ID_VIEW_ZOOMOUT +Command14=ID_VIEW_TOOLS_MOVE +Command15=ID_VIEW_TOOLS_SELECT +Command16=ID_VIEW_TOOLS_TRACKER +Command17=ID_VIEW_TOOLS_ZOOM +Command18=ID_VIEW_TOOLS_TEXT +Command19=ID_VIEW_HISTOGRAM +Command20=ID_VIEW_PALETTE +Command21=ID_CXIMAGE_OPTIONS +Command22=ID_APP_ABOUT +CommandCount=22 + +[MNU:IDR_MAINFRAME (Neutral)] +Type=1 +Class=CMainFrame +Command1=ID_FILE_NEW +Command2=ID_FILE_OPEN +Command3=ID_FILE_SELECTSOURCE +Command4=ID_FILE_ACQUIRE +Command5=ID_FILE_CAPTURE +Command6=ID_FILE_PRINT_SETUP +Command7=ID_FILE_MRU_FILE1 +Command8=ID_APP_EXIT +Command9=ID_EDIT_PASTE +Command10=ID_VIEW_TOOLBAR +Command11=ID_VIEW_STATUS_BAR +Command12=ID_VIEW_HISTOGRAM +Command13=ID_VIEW_MENUSTYLE_NORMAL +Command14=ID_VIEW_MENUSTYLE_XP +Command15=ID_VIEW_FULLSCREEN +Command16=ID_IMAGE_FROM_BITMAP +Command17=ID_CXIMAGE_LOADJPEGRESOURCE +Command18=ID_CXIMAGE_LOADICONRESOURCE +Command19=ID_CXIMAGE_LOADPNGRESOURCE +Command20=ID_CXIMAGE_LOADGIFRESOURCE +Command21=ID_CXIMAGE_LOADTIFRESOURCE +Command22=ID_CXIMAGE_DEMOSAVEMULTIPAGETIFF +Command23=ID_CXIMAGE_DEMOSAVEANIMATEDGIF +Command24=ID_CXIMAGE_DOWNLOADFROMURL +Command25=ID_CXIMAGE_DEMOCREATEFROMARRAY +Command26=ID_APP_ABOUT +CommandCount=26 + +[ACL:IDR_MAINFRAME (Neutral)] +Type=1 +Class=? +Command1=ID_EDIT_COPY +Command2=ID_WINDOW_DUPLICATE +Command3=ID_FILE_NEW +Command4=ID_FILE_OPEN +Command5=ID_FILE_PRINT +Command6=ID_FILE_SAVE +Command7=ID_EDIT_PASTE +Command8=ID_VIEW_ZOOMIN +Command9=ID_EDIT_UNDO +Command10=ID_EDIT_CUT +Command11=ID_VIEW_NORMALVIEWING11 +Command12=ID_NEXT_PANE +Command13=ID_PREV_PANE +Command14=ID_EDIT_COPY +Command15=ID_EDIT_PASTE +Command16=ID_VIEW_ZOOMOUT +Command17=ID_EDIT_CUT +Command18=ID_EDIT_REDO +Command19=ID_EDIT_UNDO +CommandCount=19 + +[DLG:IDD_ROTATE (Neutral)] +Type=1 +Class=DlgRotate +ControlCount=9 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_EDIT1,edit,1350631552 +Control4=IDC_STATIC,static,1342308352 +Control5=IDC_STATIC,static,1342308352 +Control6=IDC_COMBO_IM,combobox,1344339971 +Control7=IDC_STATIC,static,1342308352 +Control8=IDC_COMBO_OM,combobox,1344339971 +Control9=IDC_CHECK1,button,1342242819 + +[DLG:IDD_CAPTURE (Neutral)] +Type=1 +Class=DlgCapture +ControlCount=3 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_LIST1,listbox,1352728835 + +[MNU:IDM_CXIMAGE1] +Type=1 +Class=? +Command1=ID_EDIT_UNDO +Command2=ID_EDIT_REDO +Command3=ID_EDIT_COPY +Command4=ID_EDIT_PASTE +Command5=ID_CXIMAGE_MIRROR +Command6=ID_CXIMAGE_FLIP +Command7=ID_CXIMAGE_NEGATIVE +Command8=ID_CXIMAGE_THRESHOLD +Command9=ID_CXIMAGE_COLORIZE +Command10=ID_CXIMAGE_GAMMA +Command11=ID_CXIMAGE_LIGHTEN +Command12=ID_CXIMAGE_DARKEN +Command13=ID_CXIMAGE_CONTRAST +Command14=ID_CXIMAGE_ADDNOISE +Command15=ID_CXIMAGE_MEDIAN +Command16=ID_CXIMAGE_ERODE +Command17=ID_CXIMAGE_DILATE +Command18=ID_CXIMAGE_BLUR +Command19=ID_CXIMAGE_SOFTEN +Command20=ID_CXIMAGE_SHARPEN +Command21=ID_CXIMAGE_EDGE +Command22=ID_CXIMAGE_EMBOSS +Command23=ID_CXIMAGE_ROTATEL +Command24=ID_CXIMAGE_ROTATER +Command25=ID_CXIMAGE_ROTATE +Command26=ID_CXIMAGE_RESAMPLE +Command27=ID_CXIMAGE_CROP +Command28=ID_CXIMAGE_SETTRANSPARENCY +Command29=ID_CXIMAGE_REMOVETRANSPARENCY +Command30=ID_CXIMAGE_OPACITY +Command31=ID_CXIMAGE_REMOVEALPHACHANNEL +Command32=ID_CXIMAGE_ALPHASTRIP +Command33=ID_CXIMAGE_INVETALPHA +Command34=ID_CXIMAGE_ALPHAPALETTETOGGLE +Command35=ID_CXIMAGE_GRAYSCALE +Command36=ID_CXIMAGE_DITHER +Command37=ID_CXIMAGE_DECREASEBPP +Command38=ID_CXIMAGE_INCREASEBPP +Command39=ID_CXIMAGE_SPLITRGB +Command40=ID_CXIMAGE_SPLITYUV +Command41=ID_CXIMAGE_SPLITHSL +Command42=ID_CXIMAGE_PSEUDOCOLORS +Command43=ID_CXIMAGE_COMBINE +Command44=ID_CXIMAGE_OPTIONS +CommandCount=44 + +[DLG:IDD_RESAMPLE (Neutral)] +Type=1 +Class=DlgResample +ControlCount=13 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_EDIT1,edit,1350631552 +Control4=IDC_STATIC,static,1342308352 +Control5=IDC_COMBO_IM,combobox,1344339971 +Control6=IDC_STATIC,button,1342177287 +Control7=IDC_STATIC,button,1342177287 +Control8=IDC_EDIT2,edit,1350631552 +Control9=IDC_EDIT3,edit,1350631552 +Control10=IDC_STATIC,static,1342308352 +Control11=IDC_RADIO1,button,1342308361 +Control12=IDC_RADIO2,button,1342177289 +Control13=IDC_CHECK2,button,1342242819 + +[CLS:DlgResample] +Type=0 +HeaderFile=DlgResample.h +ImplementationFile=DlgResample.cpp +BaseClass=CDialog +Filter=D +LastObject=IDC_EDIT1 +VirtualFilter=dWC + +[CLS:DlgDecBpp] +Type=0 +HeaderFile=DlgDecBpp.h +ImplementationFile=DlgDecBpp.cpp +BaseClass=CDialog +Filter=D +LastObject=DlgDecBpp +VirtualFilter=dWC + +[CLS:DlgIncBpp] +Type=0 +HeaderFile=DlgIncBpp.h +ImplementationFile=DlgIncBpp.cpp +BaseClass=CDialog +Filter=D +LastObject=65535 +VirtualFilter=dWC + +[CLS:DlgOptions] +Type=0 +HeaderFile=DlgOptions.h +ImplementationFile=DlgOptions.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=DlgOptions + +[CLS:DlgDither] +Type=0 +HeaderFile=DlgDither.h +ImplementationFile=DlgDither.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=IDC_RADIO8 + +[DLG:IDD_THRESHOLD (Neutral)] +Type=1 +Class=DlgThreshold +ControlCount=4 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_EDIT1,edit,1350631552 +Control4=IDC_STATIC,static,1342308352 + +[CLS:DlgThreshold] +Type=0 +HeaderFile=DlgThreshold.h +ImplementationFile=DlgThreshold.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=DlgThreshold + +[DLG:IDD_DECBPP (Neutral)] +Type=1 +Class=DlgDecBpp +ControlCount=12 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_RADIO1,button,1342308361 +Control4=IDC_STATIC,button,1342177287 +Control5=IDC_RADIO2,button,1342177289 +Control6=IDC_RADIO3,button,1342177289 +Control7=IDC_STATIC,button,1342177287 +Control8=IDC_RADIO4,button,1342308361 +Control9=IDC_RADIO5,button,1342177289 +Control10=IDC_CHECK1,button,1342242819 +Control11=IDC_CHECK2,button,1342242819 +Control12=IDC_EDIT1,edit,1350631552 + +[DLG:IDD_INCBPP (Neutral)] +Type=1 +Class=DlgIncBpp +ControlCount=6 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_RADIO1,button,1342308361 +Control4=65535,button,1342177287 +Control5=IDC_RADIO2,button,1342177289 +Control6=IDC_RADIO3,button,1342177289 + +[DLG:IDD_OPTIONS (Neutral)] +Type=1 +Class=DlgOptions +ControlCount=28 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_STATIC,static,1342308352 +Control4=IDC_EDIT1,edit,1350631552 +Control5=IDC_STATIC,static,1342308352 +Control6=IDC_EDIT2,edit,1350631552 +Control7=IDC_STATIC,static,1342308352 +Control8=IDC_EDIT3,edit,1350631552 +Control9=IDC_STATIC,button,1342177287 +Control10=IDC_RADIO1,button,1342308361 +Control11=IDC_RADIO2,button,1342177289 +Control12=IDC_RADIO3,button,1342177289 +Control13=IDC_RADIO4,button,1342177289 +Control14=IDC_RADIO5,button,1342177289 +Control15=IDC_RADIO6,button,1342177289 +Control16=IDC_RADIO7,button,1342177289 +Control17=IDEXIF,button,1342242816 +Control18=IDC_STATIC,button,1342177287 +Control19=IDC_RADIO8,button,1342308361 +Control20=IDC_RADIO9,button,1342177289 +Control21=IDC_RADIO10,button,1342177289 +Control22=IDC_RADIO11,button,1342308361 +Control23=IDC_RADIO12,button,1342177289 +Control24=IDC_STATIC,button,1342177287 +Control25=IDC_RADIO13,button,1342308361 +Control26=IDC_RADIO14,button,1342177289 +Control27=IDC_STATIC,button,1342177287 +Control28=IDC_CHECK5,button,1342242819 + +[DLG:IDD_DITHER (Neutral)] +Type=1 +Class=DlgDither +ControlCount=10 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_RADIO1,button,1342308361 +Control4=IDC_RADIO2,button,1342177289 +Control5=IDC_RADIO3,button,1342177289 +Control6=IDC_RADIO4,button,1342177289 +Control7=IDC_RADIO5,button,1342177289 +Control8=IDC_RADIO6,button,1342177289 +Control9=IDC_RADIO7,button,1342177289 +Control10=IDC_RADIO8,button,1342177289 + +[DLG:IDD_COLORIZE (Neutral)] +Type=1 +Class=DlgColorize +ControlCount=17 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_EDIT1,edit,1350631552 +Control4=IDC_STATIC,static,1342308352 +Control5=IDC_EDIT2,edit,1350631552 +Control6=IDC_STATIC,static,1342308352 +Control7=IDC_EDIT3,edit,1350631552 +Control8=IDC_STATIC,static,1342308352 +Control9=IDC_EDIT4,edit,1350631552 +Control10=IDC_STATIC,static,1342308352 +Control11=IDC_EDIT5,edit,1350631552 +Control12=IDC_STATIC,static,1342308352 +Control13=IDC_RADIO3,button,1342308361 +Control14=IDC_RADIO4,button,1342177289 +Control15=IDC_EDIT8,edit,1350631552 +Control16=IDC_STATIC,static,1342308352 +Control17=IDCOLORS,button,1342242816 + +[CLS:DlgColorize] +Type=0 +HeaderFile=DlgColorize.h +ImplementationFile=DlgColorize.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=IDC_EDIT1 + +[TB:IDR_TOOLBAR1] +Type=1 +Class=? +Command1=ID_VIEW_NORMALVIEWING11 +Command2=ID_CXIMAGE_OPTIONS +Command3=ID_APP_EXIT +Command4=ID_VIEW_ZOOMIN +Command5=ID_VIEW_ZOOMOUT +Command6=ID_CXIMAGE_ROTATE +Command7=ID_CXIMAGE_FLIP +Command8=ID_CXIMAGE_MIRROR +Command9=ID_CXIMAGE_RESAMPLE +Command10=ID_CXIMAGE_CROP +Command11=ID_CXIMAGE_GRAYSCALE +Command12=ID_CXIMAGE_NEGATIVE +Command13=ID_CXIMAGE_DECREASEBPP +Command14=ID_CXIMAGE_INCREASEBPP +Command15=ID_CXIMAGE_SPLITCHANNELS +Command16=ID_BUTTON32842 +Command17=ID_CXIMAGE_SETTRANSPARENCY +Command18=ID_CXIMAGE_REMOVETRANSPARENCY +Command19=ID_VIEW_PALETTE +CommandCount=19 + +[DLG:IDD_OPACITY (Neutral)] +Type=1 +Class=DlgOpacity +ControlCount=4 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_EDIT1,edit,1350631552 +Control4=IDC_STATIC,static,1342308352 + +[CLS:DlgOpacity] +Type=0 +HeaderFile=DlgOpacity.h +ImplementationFile=DlgOpacity.cpp +BaseClass=CDialog +Filter=D +LastObject=IDCANCEL +VirtualFilter=dWC + +[CLS:DlgURL] +Type=0 +HeaderFile=DlgURL.h +ImplementationFile=DlgURL.cpp +BaseClass=CDialog +Filter=D +LastObject=DlgURL +VirtualFilter=dWC + +[DLG:IDD_DWNURL (Neutral)] +Type=1 +Class=DlgURL +ControlCount=6 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_STATIC,static,1342308352 +Control4=IDC_STATIC,static,1342308352 +Control5=IDC_STATUS,static,1342308352 +Control6=IDC_URL,edit,1350631552 + +[DLG:IDD_GAMMA (Neutral)] +Type=1 +Class=DlgGamma +ControlCount=4 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_EDIT1,edit,1350631552 +Control4=IDC_STATIC,static,1342308352 + +[CLS:DlgGamma] +Type=0 +HeaderFile=DlgGamma.h +ImplementationFile=DlgGamma.cpp +BaseClass=CDialog +Filter=D +LastObject=DlgGamma +VirtualFilter=dWC + +[DLG:IDD_HISTO (Neutral)] +Type=1 +Class=DlgHisto +ControlCount=1 +Control1=IDC_LOG,button,1342242819 + +[CLS:DlgHisto] +Type=0 +HeaderFile=DlgHisto.h +ImplementationFile=DlgHisto.cpp +BaseClass=CDialogBar +Filter=C +LastObject=DlgHisto +VirtualFilter=dWC + +[DLG:IDD_PALETTE (Neutral)] +Type=1 +Class=DlgPalette +ControlCount=11 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_STATIC,static,1342177298 +Control4=IDC_LOAD,button,1342242816 +Control5=IDC_SAVE,button,1342242816 +Control6=IDC_STATIC,button,1342177287 +Control7=IDC_RADIO1,button,1342308361 +Control8=IDC_RADIO2,button,1342177289 +Control9=IDC_RADIO3,button,1342177289 +Control10=IDC_CHECK2,button,1342242819 +Control11=IDC_BAR,static,1342312448 + +[CLS:DlgPalette] +Type=0 +HeaderFile=DlgPalette.h +ImplementationFile=DlgPalette.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=IDOK + +[DLG:IDD_COMBINE (Neutral)] +Type=1 +Class=DlgCombine +ControlCount=16 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_COMBO1,combobox,1344339971 +Control4=IDC_STATIC,static,1342308352 +Control5=IDC_STATIC,static,1342308352 +Control6=IDC_STATIC,static,1342308352 +Control7=IDC_COMBO2,combobox,1344339971 +Control8=IDC_COMBO3,combobox,1344339971 +Control9=IDC_STATIC,static,1342308352 +Control10=IDC_COMBO4,combobox,1344339971 +Control11=IDC_COMBO5,combobox,1344339971 +Control12=IDC_COMBO6,combobox,1344339971 +Control13=IDC_COMBO7,combobox,1344339971 +Control14=IDC_COMBO8,combobox,1344339971 +Control15=IDC_COMBO9,combobox,1344339971 +Control16=IDC_STATIC,static,1342308352 + +[CLS:DlgCombine] +Type=0 +HeaderFile=DlgCombine.h +ImplementationFile=DlgCombine.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=DlgCombine + +[TB:IDR_TOOLBAR1 (Neutral)] +Type=1 +Class=? +Command1=ID_VIEW_NORMALVIEWING11 +Command2=ID_CXIMAGE_OPTIONS +Command3=ID_APP_EXIT +Command4=ID_VIEW_ZOOMIN +Command5=ID_VIEW_ZOOMOUT +Command6=ID_CXIMAGE_ROTATE +Command7=ID_CXIMAGE_FLIP +Command8=ID_CXIMAGE_MIRROR +Command9=ID_CXIMAGE_RESAMPLE +Command10=ID_CXIMAGE_CROP +Command11=ID_CXIMAGE_GRAYSCALE +Command12=ID_CXIMAGE_NEGATIVE +Command13=ID_CXIMAGE_DECREASEBPP +Command14=ID_CXIMAGE_INCREASEBPP +Command15=ID_CXIMAGE_SPLITCHANNELS +Command16=ID_BUTTON32842 +Command17=ID_CXIMAGE_SETTRANSPARENCY +Command18=ID_CXIMAGE_REMOVETRANSPARENCY +Command19=ID_VIEW_PALETTE +CommandCount=19 + +[MNU:IDM_CXIMAGE1 (Neutral)] +Type=1 +Class=? +Command1=ID_EDIT_UNDO +Command2=ID_EDIT_REDO +Command3=ID_EDIT_COPY +Command4=ID_EDIT_PASTE +Command5=ID_CXIMAGE_MIRROR +Command6=ID_CXIMAGE_FLIP +Command7=ID_CXIMAGE_NEGATIVE +Command8=ID_CXIMAGE_THRESHOLD +Command9=ID_CXIMAGE_COLORIZE +Command10=ID_CXIMAGE_GAMMA +Command11=ID_CXIMAGE_LIGHTEN +Command12=ID_CXIMAGE_DARKEN +Command13=ID_CXIMAGE_CONTRAST +Command14=ID_CXIMAGE_LESSCONTRAST +Command15=ID_CXIMAGE_PSEUDOCOLORS +Command16=ID_CXIMAGE_SPLITRGB +Command17=ID_CXIMAGE_SPLITHSL +Command18=ID_CXIMAGE_SPLITYUV +Command19=ID_CXIMAGE_SPLITYIQ +Command20=ID_CXIMAGE_SPLITXYZ +Command21=ID_CXIMAGE_SPLITCMYK +Command22=ID_CXIMAGE_COMBINE +Command23=ID_CXIMAGE_FFT +Command24=ID_CXIMAGE_REPAIR +Command25=ID_FILTERS_MIX +Command26=ID_CXIMAGE_BLUR +Command27=ID_CXIMAGE_SOFTEN +Command28=ID_CXIMAGE_GAUSSIAN3X3 +Command29=ID_CXIMAGE_GAUSSIAN5X5 +Command30=ID_CXIMAGE_SHARPEN +Command31=ID_CXIMAGE_EDGE +Command32=ID_CXIMAGE_EMBOSS +Command33=ID_CXIMAGE_ADDNOISE +Command34=ID_CXIMAGE_MEDIAN +Command35=ID_CXIMAGE_ERODE +Command36=ID_CXIMAGE_DILATE +Command37=ID_CXIMAGE_CONTOUR +Command38=ID_FILTERS_NONLINEAR_EDGE +Command39=ID_CXIMAGE_JITTER +Command40=ID_CXIMAGE_CIRCLETRANSFORM_PINCH +Command41=ID_CXIMAGE_CIRCLETRANSFORM_PUNCH +Command42=ID_CXIMAGE_CIRCLETRANSFORM_SWIRL +Command43=ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER +Command44=ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM +Command45=ID_CXIMAGE_ROTATEL +Command46=ID_CXIMAGE_ROTATER +Command47=ID_CXIMAGE_ROTATE +Command48=ID_CXIMAGE_RESAMPLE +Command49=ID_CXIMAGE_SKEW +Command50=ID_CXIMAGE_CROP +Command51=ID_CXIMAGE_SETTRANSPARENCY +Command52=ID_CXIMAGE_REMOVETRANSPARENCY +Command53=ID_CXIMAGE_OPACITY +Command54=ID_CXIMAGE_REMOVEALPHACHANNEL +Command55=ID_CXIMAGE_ALPHACHANNEL_SPLIT +Command56=ID_CXIMAGE_ALPHASTRIP +Command57=ID_CXIMAGE_INVETALPHA +Command58=ID_CXIMAGE_ALPHAPALETTETOGGLE +Command59=ID_CXIMAGE_ALPHACREATE +Command60=ID_CXIMAGE_GRAYSCALE +Command61=ID_CXIMAGE_DITHER +Command62=ID_CXIMAGE_DECREASEBPP +Command63=ID_CXIMAGE_INCREASEBPP +Command64=ID_CXIMAGE_HISTOGRAM_STRETCH +Command65=ID_CXIMAGE_HISTOGRAM_STRETCH1 +Command66=ID_CXIMAGE_HISTOGRAM_STRETCH2 +Command67=ID_CXIMAGE_HISTOGRAM_EQUALIZE +Command68=ID_CXIMAGE_HISTOGRAM_NORMALIZE +Command69=ID_CXIMAGE_HISTOGRAM_LOG +Command70=ID_CXIMAGE_HISTOGRAM_ROOT +Command71=ID_CXIMAGE_OPTIONS +CommandCount=71 + +[DLG:IDD_FFT (Neutral)] +Type=1 +Class=DlgFFT +ControlCount=9 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_REAL,combobox,1344339971 +Control4=IDC_IMAG,combobox,1344339971 +Control5=IDC_STATIC,static,1342308352 +Control6=IDC_STATIC,static,1342308352 +Control7=IDC_CHECK1,button,1342242819 +Control8=IDC_CHECK3,button,1342242819 +Control9=IDC_CHECK4,button,1342242819 + +[CLS:DlgFFT] +Type=0 +HeaderFile=DlgFFT.h +ImplementationFile=DlgFFT.cpp +BaseClass=CDialog +Filter=D +LastObject=IDC_CHECK1 +VirtualFilter=dWC + +[DLG:IDD_REPAIR (Neutral)] +Type=1 +Class=DlgRepair +ControlCount=8 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_STATIC,static,1342308352 +Control4=IDC_EDIT2,edit,1350631552 +Control5=IDC_STATIC,static,1342308352 +Control6=IDC_EDIT3,edit,1350631552 +Control7=IDC_STATIC,static,1342308352 +Control8=IDC_COMBO9,combobox,1344339971 + +[CLS:DlgRepair] +Type=0 +HeaderFile=DlgRepair.h +ImplementationFile=DlgRepair.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=DlgRepair + +[DLG:IDD_TEXT (Neutral)] +Type=1 +Class=DlgText +ControlCount=19 +Control1=IDOK,button,1342242816 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_EDIT1,edit,1350635716 +Control4=IDC_STATIC,static,1342308352 +Control5=ID_FONT,button,1342242816 +Control6=IDC_BTN_TXTCOLOR,button,1342242816 +Control7=IDC_BTN_BCKCOLOR,button,1342242816 +Control8=IDC_CHECK1,button,1342242819 +Control9=IDC_STATIC,button,1342177287 +Control10=IDC_SLIDER_OPACITY,msctls_trackbar32,1342242821 +Control11=IDC_SLIDER_RADIUS,msctls_trackbar32,1342242821 +Control12=IDC_STATIC,static,1342308352 +Control13=IDC_STATIC,static,1342308352 +Control14=IDC_STATIC_OP,static,1342308352 +Control15=IDC_STATIC_RADIUS,static,1342308352 +Control16=IDC_STATIC,button,1342177287 +Control17=IDC_RADIO1,button,1342177289 +Control18=IDC_RADIO2,button,1342177289 +Control19=IDC_RADIO3,button,1342177289 + +[CLS:DlgText] +Type=0 +HeaderFile=DlgText.h +ImplementationFile=DlgText.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=DlgText + +[DLG:IDD_MIX (Neutral)] +Type=1 +Class=DlgMix +ControlCount=16 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_DST,combobox,1344339971 +Control4=IDC_STATIC,static,1342308352 +Control5=IDC_STATIC,static,1342308352 +Control6=IDC_SRC,combobox,1344339971 +Control7=IDC_OP,combobox,1344339971 +Control8=IDC_STATIC,static,1342308352 +Control9=IDC_PICTURE,static,1342181390 +Control10=IDC_BUTTON1,button,1342242816 +Control11=IDC_EDIT1,edit,1350631552 +Control12=IDC_STATIC,static,1342308352 +Control13=IDC_STATIC,static,1342308352 +Control14=IDC_EDIT2,edit,1350631552 +Control15=IDC_CHECK1,button,1342251011 +Control16=IDC_STATIC,button,1342177287 + +[CLS:DlgMix] +Type=0 +HeaderFile=DlgMix.h +ImplementationFile=DlgMix.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=IDC_CHECK1 + +[DLG:IDD_SKEW (Neutral)] +Type=1 +Class=DlgSkew +ControlCount=19 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_CHECK1,button,1342242819 +Control4=IDC_STATIC,button,1342177287 +Control5=IDC_STATIC,static,1342308352 +Control6=IDC_STATIC,static,1342308352 +Control7=IDC_STATIC,button,1342177287 +Control8=IDC_STATIC,static,1342308352 +Control9=IDC_STATIC,static,1342308352 +Control10=IDC_EDIT1,edit,1350631552 +Control11=IDC_EDIT2,edit,1350631552 +Control12=IDC_EDIT4,edit,1350631552 +Control13=IDC_EDIT5,edit,1350631552 +Control14=IDC_STATIC,static,1342308352 +Control15=IDC_STATIC,static,1342308352 +Control16=IDC_EDIT6,edit,1342244864 +Control17=IDC_EDIT7,edit,1342244864 +Control18=IDC_EDIT8,edit,1342244864 +Control19=IDC_EDIT9,edit,1342244864 + +[CLS:DlgSkew] +Type=0 +HeaderFile=DlgSkew.h +ImplementationFile=DlgSkew.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=IDC_EDIT4 + +[DLG:IDD_JPEG (Neutral)] +Type=1 +Class=DlgJpeg +ControlCount=7 +Control1=IDOK,button,1342242817 +Control2=IDCANCEL,button,1342242816 +Control3=IDC_EDIT1,edit,1350631552 +Control4=IDC_STATIC,static,1342308352 +Control5=IDC_STATIC,button,1342177287 +Control6=IDC_RADIO1,button,1342308361 +Control7=IDC_RADIO2,button,1342177289 + +[CLS:DlgJpeg] +Type=0 +HeaderFile=DlgJpeg.h +ImplementationFile=DlgJpeg.cpp +BaseClass=CDialog +Filter=D +VirtualFilter=dWC +LastObject=IDC_EDIT1 + diff --git a/SlnkDWFImpl/CxImage/demo/demo.cpp b/SlnkDWFImpl/CxImage/demo/demo.cpp new file mode 100644 index 0000000..cccbf85 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.cpp @@ -0,0 +1,766 @@ +// demo.cpp : Defines the class behaviors for the application. + +#include "stdafx.h" +#include "demo.h" + +#include "MainFrm.h" +#include "ChildFrm.h" +#include "demoDoc.h" +#include "demoView.h" +#include "xTargetButton.h" +#include "DlgURL.h" + +#include "ximage.h" +#include "ximagif.h" +#include "ximatif.h" +#include "xfile.h" + +#ifdef _DEBUG +#define _CRTDBG_MAP_ALLOC +#include +#include +#undef THIS_FILE +static char BASED_CODE THIS_FILE[] = __FILE__; +#endif + +DocType doctypes[CMAX_IMAGE_FORMATS] = +{ + { -1, TRUE, TRUE, "Supported files", "*.bmp;*.gif;*.jpg;*.jpeg;*.png;*.ico;*.tif;*.tiff;*.tga;*.pcx;*.wbmp;*.wmf;*.emf;*.j2k;*.jp2;*.jbg;*.j2c;*.jpc;*.pgx;*.pnm;*.pgm;*.ppm;*.ras" }, +#if CXIMAGE_SUPPORT_BMP + { CXIMAGE_FORMAT_BMP, TRUE, TRUE, "BMP files", "*.bmp" }, +#endif +#if CXIMAGE_SUPPORT_GIF + { CXIMAGE_FORMAT_GIF, TRUE, TRUE, "GIF files", "*.gif" }, +#endif +#if CXIMAGE_SUPPORT_JPG + { CXIMAGE_FORMAT_JPG, TRUE, TRUE, "JPG files", "*.jpg;*.jpeg" }, +#endif +#if CXIMAGE_SUPPORT_PNG + { CXIMAGE_FORMAT_PNG, TRUE, TRUE, "PNG files", "*.png" }, +#endif +#if CXIMAGE_SUPPORT_MNG + { CXIMAGE_FORMAT_MNG, TRUE, TRUE, "MNG files", "*.mng;*.jng;*.png" }, +#endif +#if CXIMAGE_SUPPORT_ICO + { CXIMAGE_FORMAT_ICO, TRUE, TRUE, "ICO CUR files", "*.ico;*.cur" }, +#endif +#if CXIMAGE_SUPPORT_TIF + { CXIMAGE_FORMAT_TIF, TRUE, TRUE, "TIF files", "*.tif;*.tiff" }, +#endif +#if CXIMAGE_SUPPORT_TGA + { CXIMAGE_FORMAT_TGA, TRUE, TRUE, "TGA files", "*.tga" }, +#endif +#if CXIMAGE_SUPPORT_PCX + { CXIMAGE_FORMAT_PCX, TRUE, TRUE, "PCX files", "*.pcx" }, +#endif +#if CXIMAGE_SUPPORT_WBMP + { CXIMAGE_FORMAT_WBMP, TRUE, TRUE, "WBMP files", "*.wbmp" }, +#endif +#if CXIMAGE_SUPPORT_WMF + { CXIMAGE_FORMAT_WMF, TRUE, FALSE, "WMF EMF files", "*.wmf;*.emf" }, +#endif +#if CXIMAGE_SUPPORT_J2K + { CXIMAGE_FORMAT_J2K, TRUE, TRUE, "J2K files", "*.j2k;*.jp2" }, +#endif +#if CXIMAGE_SUPPORT_JBG + { CXIMAGE_FORMAT_JBG, TRUE, TRUE, "JBG files", "*.jbg" }, +#endif +#if CXIMAGE_SUPPORT_JP2 + { CXIMAGE_FORMAT_JP2, TRUE, TRUE, "JP2 files", "*.j2k;*.jp2" }, +#endif +#if CXIMAGE_SUPPORT_JPC + { CXIMAGE_FORMAT_JPC, TRUE, TRUE, "JPC files", "*.j2c;*.jpc" }, +#endif +#if CXIMAGE_SUPPORT_PGX + { CXIMAGE_FORMAT_PGX, TRUE, TRUE, "PGX files", "*.pgx" }, +#endif +#if CXIMAGE_SUPPORT_RAS + { CXIMAGE_FORMAT_RAS, TRUE, TRUE, "RAS files", "*.ras" }, +#endif +#if CXIMAGE_SUPPORT_PNM + { CXIMAGE_FORMAT_PNM, TRUE, TRUE, "PNM files", "*.pnm;*.pgm;*.ppm" } +#endif +}; + +////////////////////////////////////////////////////////////////////////////// +// CDemoApp +BEGIN_MESSAGE_MAP(CDemoApp, CWinApp) + //{{AFX_MSG_MAP(CDemoApp) + ON_COMMAND(ID_APP_ABOUT, OnAppAbout) + ON_COMMAND(ID_IMAGE_FROM_BITMAP, OnImageFromBitmap) + ON_COMMAND(ID_CXIMAGE_LOADJPEGRESOURCE, OnCximageLoadjpegresource) + ON_COMMAND(ID_CXIMAGE_LOADICONRESOURCE, OnCximageLoadiconresource) + ON_COMMAND(ID_CXIMAGE_LOADGIFRESOURCE, OnCximageLoadgifresource) + ON_COMMAND(ID_CXIMAGE_LOADPNGRESOURCE, OnCximageLoadpngresource) + ON_COMMAND(ID_CXIMAGE_LOADTIFRESOURCE, OnCximageLoadtifresource) + ON_COMMAND(ID_WINDOW_CLOSEALL, OnWindowCloseall) + ON_COMMAND(ID_CXIMAGE_DEMOSAVEMULTIPAGETIFF, OnCximageDemosavemultipagetiff) + ON_COMMAND(ID_CXIMAGE_DEMOSAVEANIMATEDGIF, OnCximageDemosaveanimatedgif) + ON_COMMAND(ID_CXIMAGE_DOWNLOADFROMURL, OnCximageDownloadfromurl) + ON_COMMAND(ID_CXIMAGE_DEMOCREATEFROMARRAY, OnCximageDemocreatefromarray) + //}}AFX_MSG_MAP + // Standard file based document commands + ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) + ON_COMMAND(ID_FILE_OPEN, CDemoApp::OnFileOpen) + // Standard print setup command + ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup) +END_MESSAGE_MAP() + +////////////////////////////////////////////////////////////////////////////// +// CDemoApp construction +CDemoApp::CDemoApp() +{ + m_nDocCount=1; //counter for documents + +} +////////////////////////////////////////////////////////////////////////////// +// The one and only CDemoApp object +CDemoApp theApp; + +////////////////////////////////////////////////////////////////////////////// +// CDemoApp initialization +BOOL CDemoApp::InitInstance() +{ + // dump memory leaks +#ifdef _DEBUG + _CrtDumpMemoryLeaks(); + _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); +#endif + // Standard initialization +#ifdef _AFXDLL + Enable3dControls(); // Call this when using MFC in a shared DLL +#else + Enable3dControlsStatic(); // Call this when linking to MFC statically +#endif + + LoadStdProfileSettings(9); // Load standard INI file options (including MRU) + + // Register the application's document templates. Document templates + // serve as the connection between documents, frame windows and views. + CMultiDocTemplate* pDocTemplate; + pDocTemplate = new CMultiDocTemplate( + IDR_DEMOTYPE, + RUNTIME_CLASS(CDemoDoc), + RUNTIME_CLASS(CChildFrame), // custom MDI child frame + RUNTIME_CLASS(CDemoView)); + demoTemplate = pDocTemplate; + AddDocTemplate(pDocTemplate); + + // create main MDI Frame window + CMainFrame* pMainFrame = new CMainFrame; + if (!pMainFrame->LoadFrame(IDR_MAINFRAME)) return FALSE; + m_pMainWnd = pMainFrame; + + // This code replaces the MFC created menus with + // the Ownerdrawn versions + pDocTemplate->m_hMenuShared=pMainFrame->NewMenu(); + pMainFrame->m_hMenuDefault=pMainFrame->NewDefaultMenu(); + // This simulates a window being opened if you don't have + // a default window displayed at startup + pMainFrame->OnUpdateFrameMenu(pMainFrame->m_hMenuDefault); + + // Parse command line for standard shell commands, DDE, file open + CCommandLineInfo cmdInfo; + // Alter behaviour to not open window immediately + cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing; + ParseCommandLine(cmdInfo); + + // Dispatch commands specified on the command line + if (!ProcessShellCommand(cmdInfo)) return FALSE; + +#ifdef VATI_EXTENSIONS + // init m_text by a temporary CxImage + CxImage *ima = new CxImage; + ima->InitTextInfo( &m_text ); + delete ima; + + //recall last used font data for Text tool + sprintf( m_text.lfont.lfFaceName, GetProfileString ( "TextTool", "lfFaceName", "Arial") ); + m_text.lfont.lfCharSet = GetProfileInt ( "TextTool", "lfCharSet", EASTEUROPE_CHARSET ) ; + m_text.lfont.lfWeight = GetProfileInt ( "TextTool", "lfWeight", 0 ); + m_text.lfont.lfItalic = GetProfileInt ( "TextTool", "lfItalic", 0 ); + m_text.lfont.lfUnderline = GetProfileInt ( "TextTool", "lfUnderline", 0 ); + m_text.fcolor = GetProfileInt ( "TextTool", "fcolor", RGB( 255,255,160 )); + m_text.bcolor = GetProfileInt ( "TextTool", "bcolor", RGB( 32, 96, 0 )); + m_text.opaque = GetProfileInt ( "TextTool", "opaque", 1); + m_text.b_opacity = (float)(GetProfileInt( "TextTool", "opacity", 0 ))/(float)100.; + m_text.b_round = GetProfileInt ( "TextTool", "roundradius", 25 ); + + m_optJpegQuality = GetProfileInt("Options","JpegQuality",90); + + // recall if main window was maximized on last exit + if ( GetProfileInt ( "Screen", "maximized", 0 )) + m_nCmdShow|=SW_MAXIMIZE; +#endif; + + // The main window has been initialized, so show and update it. + pMainFrame -> ShowWindow ( m_nCmdShow ) ; + pMainFrame->UpdateWindow(); + + // Enable drag/drop open + m_pMainWnd->DragAcceptFiles(); + + // Enable open from command line + if (*m_lpCmdLine != 0) + OpenDocumentFile(m_lpCmdLine); + + return TRUE; +} + +////////////////////////////////////////////////////////////////////////////// +// CAboutDlg dialog used for App About +class CAboutDlg : public CDialog +{ +public: + CAboutDlg(); +// Dialog Data + //{{AFX_DATA(CAboutDlg) + enum { IDD = IDD_ABOUTBOX }; + CxTargetButton m_ok; + //}}AFX_DATA + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CAboutDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL +// Implementation +protected: + //{{AFX_MSG(CAboutDlg) + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; +////////////////////////////////////////////////////////////////////////////// +CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) +{ +} +////////////////////////////////////////////////////////////////////////////// +void CAboutDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgCapture) + DDX_Control(pDX, IDOK, m_ok); + //}}AFX_DATA_MAP +} +////////////////////////////////////////////////////////////////////////////// +BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) + //{{AFX_MSG_MAP(CAboutDlg) + // No message handlers + //}}AFX_MSG_MAP +END_MESSAGE_MAP() +////////////////////////////////////////////////////////////////////////////// +BOOL CAboutDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + m_ok.SetIcon(IDI_G,BS_LEFT); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} +////////////////////////////////////////////////////////////////////////////// +// App command to run the dialog +void CDemoApp::OnAppAbout() +{ + CAboutDlg aboutDlg; + aboutDlg.DoModal(); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnFileOpen() +{ + // prompt the user (with all document templates) + CString newName; + int nDocType = -1; + if (!PromptForFileName(newName, AFX_IDS_OPENFILE, + OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, TRUE, &nDocType)) + return; // open cancelled + + OpenDocumentFile(newName); + +} +////////////////////////////////////////////////////////////////////////////// +// prompt for file name - used for open and save as +// static function called from app +BOOL CDemoApp::PromptForFileName(CString& fileName, UINT nIDSTitle, + DWORD dwFlags, BOOL bOpenFileDialog, int* pType) +{ + CFileDialog dlgFile(bOpenFileDialog); + CString title; + if (bOpenFileDialog) title="Open image file"; else title="Save image file"; + + dlgFile.m_ofn.Flags |= dwFlags; + + int nDocType = (pType != NULL) ? *pType : CXIMAGE_FORMAT_BMP; + if (nDocType==0) nDocType=1; + + int nIndex = GetIndexFromType(nDocType, bOpenFileDialog); + if (nIndex == -1) nIndex = 0; + + dlgFile.m_ofn.nFilterIndex = nIndex +1; + // strDefExt is necessary to hold onto the memory from GetExtFromType + CString strDefExt = GetExtFromType(nDocType).Mid(2,3); + dlgFile.m_ofn.lpstrDefExt = strDefExt; + + CString strFilter = GetFileTypes(bOpenFileDialog); + dlgFile.m_ofn.lpstrFilter = strFilter; + dlgFile.m_ofn.lpstrTitle = title; + dlgFile.m_ofn.lpstrFile = fileName.GetBuffer(_MAX_PATH); + + BOOL bRet = (dlgFile.DoModal() == IDOK) ? TRUE : FALSE; + fileName.ReleaseBuffer(); + if (bRet){ + if (pType != NULL){ + int nIndex = (int)dlgFile.m_ofn.nFilterIndex - 1; + ASSERT(nIndex >= 0); + *pType = GetTypeFromIndex(nIndex, bOpenFileDialog); + } + } + return bRet; +} +////////////////////////////////////////////////////////////////////////////// +int CDemoApp::GetIndexFromType(int nDocType, BOOL bOpenFileDialog) +{ + int nCnt = 0; + for (int i=0;iLoadResource(FindResource(NULL,MAKEINTRESOURCE(IDB_BITMAP1),RT_BITMAP),CXIMAGE_FORMAT_BMP)){ + AfxMessageBox(newImage->GetLastError()); + delete newImage; + newImage =NULL; + return; + } + + CDemoDoc *doc = (CDemoDoc *)demoTemplate->OpenDocumentFile(NULL); + if (doc){ + doc->image = newImage; + CString s; + s.Format("BITMAP Resource Image %d",m_nDocCount++); + doc->SetTitle(s); + doc->UpdateAllViews(0); + doc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageLoadjpegresource() +{ + CxImage* newImage = new CxImage(); + if (!newImage->LoadResource(FindResource(NULL,"IDR_JPG2","JPG"),CXIMAGE_FORMAT_JPG)){ + AfxMessageBox(newImage->GetLastError()); + delete newImage; + newImage =NULL; + return; + } + CDemoDoc *doc = (CDemoDoc *)demoTemplate->OpenDocumentFile(NULL); + if (doc){ + doc->image = newImage; + CString s; + s.Format("JPEG Resource Image %d",m_nDocCount++); + doc->SetTitle(s); + doc->UpdateAllViews(0); + doc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageLoadiconresource() +{ + CxImage* newImage = new CxImage(); + if (!newImage->LoadResource(FindResource(NULL,MAKEINTRESOURCE(IDR_ICO1),"ICO"),CXIMAGE_FORMAT_ICO)){ + AfxMessageBox(newImage->GetLastError()); + delete newImage; + newImage =NULL; + return; + } + +// HICON my_Icon = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_G),IMAGE_ICON,0, 0, 0); +// CxImage my_image; +// my_image.CreateFromHICON(my_Icon); +// DestroyIcon(my_Icon); + + CDemoDoc *doc = (CDemoDoc *)demoTemplate->OpenDocumentFile(NULL); + if (doc){ + doc->image = newImage; + CString s; + s.Format("Icon Resource Image %d",m_nDocCount++); + doc->SetTitle(s); + doc->UpdateAllViews(0); + doc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageLoadgifresource() +{ + CxImage* newImage = new CxImage(); + if (!newImage->LoadResource(FindResource(NULL,MAKEINTRESOURCE(IDR_GIF1),"GIF"),CXIMAGE_FORMAT_GIF)){ + AfxMessageBox(newImage->GetLastError()); + delete newImage; + newImage =NULL; + return; + } + CDemoDoc *doc = (CDemoDoc *)demoTemplate->OpenDocumentFile(NULL); + if (doc){ + doc->image = newImage; + + CString s; + s.Format("GIF Resource Image %d",m_nDocCount++); + doc->SetTitle(s); + doc->UpdateAllViews(0); + doc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageLoadpngresource() +{ + CxImage* newImage = new CxImage(); + if (!newImage->LoadResource(FindResource(NULL,MAKEINTRESOURCE(IDR_PNG1),"PNG"),CXIMAGE_FORMAT_PNG)){ + AfxMessageBox(newImage->GetLastError()); + delete newImage; + newImage =NULL; + return; + } + + CDemoDoc *doc = (CDemoDoc *)demoTemplate->OpenDocumentFile(NULL); + if (doc){ + doc->image = newImage; + + CString s; + s.Format("PNG Resource Image %d",m_nDocCount++); + doc->SetTitle(s); + doc->UpdateAllViews(0); + doc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageLoadtifresource() +{ + CxImage* newImage = new CxImage(); + if (!newImage->LoadResource(FindResource(NULL,MAKEINTRESOURCE(IDR_TIF1),"TIF"),CXIMAGE_FORMAT_TIF)){ + AfxMessageBox(newImage->GetLastError()); + delete newImage; + newImage =NULL; + return; + } + CDemoDoc *doc = (CDemoDoc *)demoTemplate->OpenDocumentFile(NULL); + if (doc){ + doc->image = newImage; + + CString s; + s.Format("TIF Resource Image %d",m_nDocCount++); + doc->SetTitle(s); + doc->UpdateAllViews(0); + doc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnWindowCloseall() +{ + POSITION pos = AfxGetApp()->GetFirstDocTemplatePosition(); + while(pos) { + CDocTemplate* pTemplate = AfxGetApp()->GetNextDocTemplate(pos); + POSITION pos2 = pTemplate->GetFirstDocPosition(); + while(pos2) { + CDocument* pDocument; + if ((pDocument=pTemplate->GetNextDoc(pos2)) != NULL) + pDocument->OnCloseDocument(); + } + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageDemosavemultipagetiff() +{ + CxImage* newImage1 = new CxImage(); + if (!newImage1->LoadResource(FindResource(NULL,MAKEINTRESOURCE(IDR_TIF1),"TIF"),CXIMAGE_FORMAT_TIF)){ + AfxMessageBox(newImage1->GetLastError()); + delete newImage1; + newImage1 =NULL; + } + CxImage* newImage2 = new CxImage(); + if (!newImage2->LoadResource(FindResource(NULL,MAKEINTRESOURCE(IDR_GIF1),"GIF"),CXIMAGE_FORMAT_GIF)){ + AfxMessageBox(newImage2->GetLastError()); + delete newImage2; + newImage2 =NULL; + } + CxImage* newImage3 = new CxImage(); + if (!newImage3->LoadResource(FindResource(NULL,"IDR_JPG2","JPG"),CXIMAGE_FORMAT_JPG)){ + AfxMessageBox(newImage3->GetLastError()); + delete newImage3; + newImage3 =NULL; + } + newImage3->DecreaseBpp(8,true); + + CxImage *pimage[3]; + pimage[0]=newImage1; + pimage[1]=newImage2; + pimage[2]=newImage3; + + FILE* hFile; + hFile = fopen("multipage.tif","w+b"); + + CxImage multiimage; + multiimage.Encode(hFile,pimage,3,CXIMAGE_FORMAT_TIF); + + fclose(hFile); + + delete newImage1; + delete newImage2; + delete newImage3; + + /*{ + FILE* hFile; + hFile = fopen("c:\\multi.tif","w+b"); + + CxImageTIF image; + image.Load("c:\\1.tif",CXIMAGE_FORMAT_TIF); + image.Encode(hFile,true); + image.Load("c:\\2.bmp",CXIMAGE_FORMAT_BMP); + image.Encode(hFile,true); + image.Load("c:\\3.png",CXIMAGE_FORMAT_PNG); + image.Encode(hFile); + + fclose(hFile); + }*/ + + AfxMessageBox("file ""mulipage.tif"" saved to disk",MB_OK); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageDemosaveanimatedgif() +{ + CxImage* newImage = new CxImage(); + if (!newImage->LoadResource(FindResource(NULL,MAKEINTRESOURCE(IDR_GIF1),"GIF"),CXIMAGE_FORMAT_GIF)){ + AfxMessageBox(newImage->GetLastError()); + delete newImage; + newImage =NULL; + } + + newImage->IncreaseBpp(24); + + CxImage ima1,ima2,ima3; + ima1.Copy(*newImage); + ima1.Light(22); + ima2.Copy(*newImage); + ima2.Light(44); + ima3.Copy(*newImage); + ima3.Light(66); + + newImage->DecreaseBpp(8,0,0); + ima1.DecreaseBpp(8,0,0); + ima2.DecreaseBpp(8,0,0); + ima3.DecreaseBpp(8,0,0); + + newImage->SetTransIndex(newImage->GetPixelIndex(0,0)); + ima1.SetTransIndex(ima1.GetPixelIndex(0,0)); + ima2.SetTransIndex(ima2.GetPixelIndex(0,0)); + ima3.SetTransIndex(ima3.GetPixelIndex(0,0)); + + newImage->SetFrameDelay(22); + ima1.SetFrameDelay(22); + ima2.SetFrameDelay(22); + ima3.SetFrameDelay(44); + + CxImage *pimage[7]; + pimage[0]=newImage; + pimage[1]=&ima1; + pimage[2]=&ima2; + pimage[3]=&ima3; + pimage[4]=&ima2; + pimage[5]=&ima1; + pimage[6]=newImage; + + FILE* hFile; + hFile = fopen("ani.gif","wb"); + + CxImageGIF multiimage; + multiimage.SetComment("CxImage demo"); + multiimage.SetLoops(3); + multiimage.SetDisposalMethod(2); + multiimage.Encode(hFile,pimage,7); + + fclose(hFile); + + delete newImage; + + AfxMessageBox("file ""ani.gif"" saved to disk",MB_OK); + +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageDownloadfromurl() +{ + DlgURL dlg; + if (dlg.DoModal()==IDOK){ + long size = dlg.m_size; + if (size){ + CxMemFile memfile((BYTE*)dlg.m_data.GetBuffer(0),size); + + CDemoDoc *doc = (CDemoDoc *)demoTemplate->OpenDocumentFile(NULL); + if (doc){ + CString ext(doc->FindExtension(dlg.m_url)); + ext.MakeLower(); + if (ext == "") return; + + int type = doc->FindType(ext); + + CxImage* ima = new CxImage(); + ima->Decode(&memfile,type); + + doc->image = ima; + doc->SetTitle(dlg.m_url); + doc->UpdateAllViews(0); + doc->UpdateStatusBar(); + + + + + if (ima->GetNumFrames()>1){ + CString s; + s.Format("File with %d images. Read all?",ima->GetNumFrames()); + if (AfxMessageBox(s,MB_OKCANCEL)==IDOK){ + + int j; // points to the document name + for(j=strlen(dlg.m_url)-1;j>=0;j--){ + if (dlg.m_url[j]=='\\'){ j++; break; } + } + // create the documents for the other images + for(int i=1;iGetNumFrames();i++){ + CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDoc) { + CxImage *newImage = new CxImage(); + newImage->SetFrame(i); + memfile.Seek(0,SEEK_SET); + newImage->Decode(&memfile,type); + NewDoc->image = newImage; + CString s; + s.Format("%s (%d)",dlg.m_url.Mid(j),i+1); + NewDoc->SetTitle(s); + NewDoc->UpdateAllViews(NULL,WM_USER_NEWIMAGE); + } + } + } + } + } + } + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoApp::OnCximageDemocreatefromarray() +{ + CxImage* newImage = new CxImage(); + + long w = 256; + long h = 256; + BYTE c = 4; + + BYTE* pArray = (BYTE*)malloc(w*h*c); + + int n,d,e; + int a=w/2; + for(int i = 0; i < h; i++) { + for(int j = 0; j < w; j++) { + n=c*(j+w*i); + d=(BYTE)((a*i)/h+(a*(w-j))/w); + e=(BYTE)((a*(h-i))/h+(a*(w-j))/w); + if (c==4) pArray[n+3]=(BYTE)(d); + pArray[n+2]=(BYTE)(e); + pArray[n+1]=(BYTE)(255-d); + pArray[n]=(BYTE)(255-e); + } + } + + newImage->CreateFromArray(pArray,w,h,8*c,c*w,0); + free(pArray); + + if (!newImage->IsValid()){ + AfxMessageBox(newImage->GetLastError()); + delete newImage; + newImage =NULL; + return; + } + + CDemoDoc *doc = (CDemoDoc *)demoTemplate->OpenDocumentFile(NULL); + if (doc){ + doc->image = newImage; + + CString s; + s.Format("CreateFromArray Image %d",m_nDocCount++); + doc->SetTitle(s); + doc->UpdateAllViews(0); + doc->UpdateStatusBar(); + } +} +////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/demo.dsp b/SlnkDWFImpl/CxImage/demo/demo.dsp new file mode 100644 index 0000000..93a95d8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.dsp @@ -0,0 +1,450 @@ +# Microsoft Developer Studio Project File - Name="demo" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Application" 0x0101 + +CFG=demo - Win32 Release +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "demo.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "demo.mak" CFG="demo - Win32 Release" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "demo - Win32 Release" (based on "Win32 (x86) Application") +!MESSAGE "demo - Win32 Debug" (based on "Win32 (x86) Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "demo - Win32 Release" + +# PROP BASE Use_MFC 6 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir ".\Release" +# PROP BASE Intermediate_Dir ".\Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 6 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\cximage" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /D "VATI_EXTENSIONS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE MTL /nologo /D "NDEBUG" /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "NDEBUG" /d "_AFXDLL" +# ADD RSC /l 0x809 /d "NDEBUG" /d "_AFXDLL" /d "VATI_EXTENSIONS" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 /nologo /subsystem:windows /machine:I386 +# ADD LINK32 wininet.lib ../png/Release/png.lib ../jpeg/Release/jpeg.lib ../zlib/Release/zlib.lib ../tiff/Release/tiff.lib ../j2k/Release/j2k.lib ../jbig/Release/jbig.lib ../jasper/Release/jasper.lib ../cximage/Release/cximage.lib /nologo /subsystem:windows /machine:I386 /out:"../bin/demo.exe" + +!ELSEIF "$(CFG)" == "demo - Win32 Debug" + +# PROP BASE Use_MFC 6 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir ".\Debug" +# PROP BASE Intermediate_Dir ".\Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 6 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c +# ADD CPP /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /I "..\cximage" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /D "VATI_EXTENSIONS" /FD /c +# SUBTRACT CPP /Fr /YX /Yc /Yu +# ADD BASE MTL /nologo /D "_DEBUG" /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "_DEBUG" /d "_AFXDLL" +# ADD RSC /l 0x809 /d "_DEBUG" /d "_AFXDLL" /d "VATI_EXTENSIONS" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 /nologo /subsystem:windows /debug /machine:I386 +# ADD LINK32 wininet.lib ../png/Debug/png.lib ../jpeg/Debug/jpeg.lib ../zlib/Debug/zlib.lib ../tiff/Debug/tiff.lib ../j2k/Debug/j2k.lib ../jbig/Debug/jbig.lib ../jasper/Debug/jasper.lib ../cximage/Debug/cximage.lib /nologo /subsystem:windows /debug /machine:I386 /out:"../bin/demod.exe" + +!ENDIF + +# Begin Target + +# Name "demo - Win32 Release" +# Name "demo - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90" +# Begin Source File + +SOURCE=.\BCMenu.cpp +# End Source File +# Begin Source File + +SOURCE=.\ChildFrm.cpp +# End Source File +# Begin Source File + +SOURCE=.\demo.cpp +# End Source File +# Begin Source File + +SOURCE=.\demo.rc +# End Source File +# Begin Source File + +SOURCE=.\demoDoc.cpp +# End Source File +# Begin Source File + +SOURCE=.\demoView.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgCapture.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgColorize.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgCombine.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgDecBpp.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgDither.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgFFT.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgGamma.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgHisto.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgIncBpp.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgJpeg.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgMix.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgOpacity.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgOptions.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgPalette.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgRepair.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgResample.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgRotate.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgSkew.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgText.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgThreshold.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgURL.cpp +# End Source File +# Begin Source File + +SOURCE=.\logomdi.cpp +# End Source File +# Begin Source File + +SOURCE=.\MainFrm.cpp +# End Source File +# Begin Source File + +SOURCE=.\Quantize.cpp +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.cpp +# ADD CPP /Yc"stdafx.h" +# End Source File +# Begin Source File + +SOURCE=.\TwainCpp.cpp +# End Source File +# Begin Source File + +SOURCE=.\xTargetButton.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" +# Begin Source File + +SOURCE=.\BCMenu.h +# End Source File +# Begin Source File + +SOURCE=.\ChildFrm.h +# End Source File +# Begin Source File + +SOURCE=.\demo.h +# End Source File +# Begin Source File + +SOURCE=.\demoDoc.h +# End Source File +# Begin Source File + +SOURCE=.\demoView.h +# End Source File +# Begin Source File + +SOURCE=.\DlgCapture.h +# End Source File +# Begin Source File + +SOURCE=.\DlgColorize.h +# End Source File +# Begin Source File + +SOURCE=.\DlgCombine.h +# End Source File +# Begin Source File + +SOURCE=.\DlgDecBpp.h +# End Source File +# Begin Source File + +SOURCE=.\DlgDither.h +# End Source File +# Begin Source File + +SOURCE=.\DlgFFT.h +# End Source File +# Begin Source File + +SOURCE=.\DlgGamma.h +# End Source File +# Begin Source File + +SOURCE=.\DlgHisto.h +# End Source File +# Begin Source File + +SOURCE=.\DlgIncBpp.h +# End Source File +# Begin Source File + +SOURCE=.\DlgJpeg.h +# End Source File +# Begin Source File + +SOURCE=.\DlgMix.h +# End Source File +# Begin Source File + +SOURCE=.\DlgOpacity.h +# End Source File +# Begin Source File + +SOURCE=.\DlgOptions.h +# End Source File +# Begin Source File + +SOURCE=.\DlgPalette.h +# End Source File +# Begin Source File + +SOURCE=.\DlgRepair.h +# End Source File +# Begin Source File + +SOURCE=.\DlgResample.h +# End Source File +# Begin Source File + +SOURCE=.\DlgRotate.h +# End Source File +# Begin Source File + +SOURCE=.\DlgSkew.h +# End Source File +# Begin Source File + +SOURCE=.\DlgText.h +# End Source File +# Begin Source File + +SOURCE=.\DlgThreshold.h +# End Source File +# Begin Source File + +SOURCE=.\DlgURL.h +# End Source File +# Begin Source File + +SOURCE=.\logomdi.h +# End Source File +# Begin Source File + +SOURCE=.\MainFrm.h +# End Source File +# Begin Source File + +SOURCE=.\Quantize.h +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.h +# End Source File +# Begin Source File + +SOURCE=.\TwainCpp.h +# End Source File +# Begin Source File + +SOURCE=.\xTargetButton.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" +# Begin Source File + +SOURCE=.\res\b1.ico +# End Source File +# Begin Source File + +SOURCE=.\res\bg.BMP +# End Source File +# Begin Source File + +SOURCE=.\res\bg.gif +# End Source File +# Begin Source File + +SOURCE=.\res\bg.jpg +# End Source File +# Begin Source File + +SOURCE=.\res\bg2.jpg +# End Source File +# Begin Source File + +SOURCE=.\res\canc.ico +# End Source File +# Begin Source File + +SOURCE=.\res\demo.ico +# End Source File +# Begin Source File + +SOURCE=.\res\demo.rc2 +# End Source File +# Begin Source File + +SOURCE=.\res\demoDoc.ico +# End Source File +# Begin Source File + +SOURCE=.\res\Explorer.ico +# End Source File +# Begin Source File + +SOURCE=.\res\gray.ico +# End Source File +# Begin Source File + +SOURCE=.\res\ico2.bin +# End Source File +# Begin Source File + +SOURCE=.\res\icon1.ico +# End Source File +# Begin Source File + +SOURCE=.\res\no1.ico +# End Source File +# Begin Source File + +SOURCE=.\res\ok.ico +# End Source File +# Begin Source File + +SOURCE=.\res\r1.ico +# End Source File +# Begin Source File + +SOURCE=.\res\testbmp.bmp +# End Source File +# Begin Source File + +SOURCE=.\res\Toolbar.bmp +# End Source File +# Begin Source File + +SOURCE=.\res\toolbar1.bmp +# End Source File +# End Group +# Begin Source File + +SOURCE=.\res\bg.tif +# End Source File +# Begin Source File + +SOURCE=.\res\us.png +# End Source File +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/demo/demo.dsw b/SlnkDWFImpl/CxImage/demo/demo.dsw new file mode 100644 index 0000000..c5bdf4a --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "demo"=.\demo.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/demo/demo.h b/SlnkDWFImpl/CxImage/demo/demo.h new file mode 100644 index 0000000..1117c60 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.h @@ -0,0 +1,83 @@ +// demo.h : main header file for the DEMO application +// + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +// just for including CXTEXTINFO type declaration: +#include "ximage.h" + +///////////////////////////////////////////////////////////////////////////// +// CDemoApp: +// See demo.cpp for the implementation of this class +// + +class CDemoApp : public CWinApp +{ +public: + CDemoApp(); + + // Attributes + int m_nDocCount; //number of documents + CMultiDocTemplate *demoTemplate; + +#ifdef VATI_EXTENSIONS + int m_optJpegQuality; + // for text placement + CxImage::CXTEXTINFO m_text; +#endif + + // Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CDemoApp) + public: + virtual BOOL InitInstance(); + //}}AFX_VIRTUAL + +// Operations + BOOL PromptForFileName(CString& fileName, UINT nIDSTitle, + DWORD dwFlags, BOOL bOpenFileDialog, int* pType=NULL); + int GetIndexFromType(int nDocType, BOOL bOpenFileDialog); + int GetTypeFromIndex(int nIndex, BOOL bOpenFileDialog); + CString GetExtFromType(int nDocType); + CString GetDescFromType(int nDocType); + CString GetFileTypes(BOOL bOpenFileDialog); + BOOL GetWritableType(int nDocType); + +// Implementation + + //{{AFX_MSG(CDemoApp) + afx_msg void OnAppAbout(); + afx_msg void OnFileOpen(); + afx_msg void OnImageFromBitmap(); + afx_msg void OnCximageLoadjpegresource(); + afx_msg void OnCximageLoadiconresource(); + afx_msg void OnCximageLoadgifresource(); + afx_msg void OnCximageLoadpngresource(); + afx_msg void OnCximageLoadtifresource(); + afx_msg void OnWindowCloseall(); + afx_msg void OnCximageDemosavemultipagetiff(); + afx_msg void OnCximageDemosaveanimatedgif(); + afx_msg void OnCximageDownloadfromurl(); + afx_msg void OnCximageDemocreatefromarray(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +extern CDemoApp theApp; + +struct DocType +{ +public: + int nID; + BOOL bRead; + BOOL bWrite; + const char* description; + const char* ext; +}; + + +///////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/demo.mak b/SlnkDWFImpl/CxImage/demo/demo.mak new file mode 100644 index 0000000..fbfe3c8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.mak @@ -0,0 +1,434 @@ +# Microsoft Developer Studio Generated NMAKE File, Format Version 4.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Application" 0x0101 + +!IF "$(CFG)" == "" +CFG=demo - Win32 Debug +!MESSAGE No configuration specified. Defaulting to demo - Win32 Debug. +!ENDIF + +!IF "$(CFG)" != "demo - Win32 Release" && "$(CFG)" != "demo - Win32 Debug" +!MESSAGE Invalid configuration "$(CFG)" specified. +!MESSAGE You can specify a configuration when running NMAKE on this makefile +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "demo.mak" CFG="demo - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "demo - Win32 Release" (based on "Win32 (x86) Application") +!MESSAGE "demo - Win32 Debug" (based on "Win32 (x86) Application") +!MESSAGE +!ERROR An invalid configuration is specified. +!ENDIF + +!IF "$(OS)" == "Windows_NT" +NULL= +!ELSE +NULL=nul +!ENDIF +################################################################################ +# Begin Project +# PROP Target_Last_Scanned "demo - Win32 Debug" +CPP=cl.exe +RSC=rc.exe +MTL=mktyplib.exe + +!IF "$(CFG)" == "demo - Win32 Release" + +# PROP BASE Use_MFC 6 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 6 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +OUTDIR=.\Release +INTDIR=.\Release + +ALL : "$(OUTDIR)\demo.exe" + +CLEAN : + -@erase ".\Release\demo.exe" + -@erase ".\Release\ChildFrm.obj" + -@erase ".\Release\demo.pch" + -@erase ".\Release\demoView.obj" + -@erase ".\Release\StdAfx.obj" + -@erase ".\Release\demoDoc.obj" + -@erase ".\Release\MainFrm.obj" + -@erase ".\Release\demo.obj" + -@erase ".\Release\demo.res" + +"$(OUTDIR)" : + if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" + +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\cimage" /I "..\jpeg" /I "..\zlib" /I "..\png" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c +CPP_PROJ=/nologo /MD /W3 /GX /O2 /I "..\cimage" /I "..\jpeg" /I "..\zlib" /I\ + "..\png" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS"\ + /Fp"$(INTDIR)/demo.pch" /Yu"stdafx.h" /Fo"$(INTDIR)/" /c +CPP_OBJS=.\Release/ +CPP_SBRS= +# ADD BASE MTL /nologo /D "NDEBUG" /win32 +# ADD MTL /nologo /D "NDEBUG" /win32 +MTL_PROJ=/nologo /D "NDEBUG" /win32 +# ADD BASE RSC /l 0x809 /d "NDEBUG" /d "_AFXDLL" +# ADD RSC /l 0x809 /d "NDEBUG" /d "_AFXDLL" +RSC_PROJ=/l 0x809 /fo"$(INTDIR)/demo.res" /d "NDEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +BSC32_FLAGS=/nologo /o"$(OUTDIR)/demo.bsc" +BSC32_SBRS= +LINK32=link.exe +# ADD BASE LINK32 /nologo /subsystem:windows /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib winmm.lib ../png/Release/png.lib ../jpeg/Release/jpeg.lib ../zlib/Release/zlib.lib ../cimage/Release/cimage.lib /nologo /subsystem:windows /machine:I386 +LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib\ + advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib winmm.lib\ + ../png/Release/png.lib ../jpeg/Release/jpeg.lib ../zlib/Release/zlib.lib\ + ../cimage/Release/cimage.lib /nologo /subsystem:windows /incremental:no\ + /pdb:"$(OUTDIR)/demo.pdb" /machine:I386 /out:"$(OUTDIR)/demo.exe" +LINK32_OBJS= \ + "$(INTDIR)/ChildFrm.obj" \ + "$(INTDIR)/demoView.obj" \ + "$(INTDIR)/StdAfx.obj" \ + "$(INTDIR)/demoDoc.obj" \ + "$(INTDIR)/MainFrm.obj" \ + "$(INTDIR)/demo.obj" \ + "$(INTDIR)/demo.res" + +"$(OUTDIR)\demo.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) + $(LINK32) @<< + $(LINK32_FLAGS) $(LINK32_OBJS) +<< + +!ELSEIF "$(CFG)" == "demo - Win32 Debug" + +# PROP BASE Use_MFC 6 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 6 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +OUTDIR=.\Debug +INTDIR=.\Debug + +ALL : "$(OUTDIR)\demo.exe" + +CLEAN : + -@erase ".\Debug\vc40.pdb" + -@erase ".\Debug\demo.pch" + -@erase ".\Debug\vc40.idb" + -@erase ".\Debug\demo.exe" + -@erase ".\Debug\ChildFrm.obj" + -@erase ".\Debug\MainFrm.obj" + -@erase ".\Debug\demo.obj" + -@erase ".\Debug\demoDoc.obj" + -@erase ".\Debug\demoView.obj" + -@erase ".\Debug\StdAfx.obj" + -@erase ".\Debug\demo.res" + -@erase ".\Debug\demo.ilk" + -@erase ".\Debug\demo.pdb" + +"$(OUTDIR)" : + if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" + +# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\cimage" /I "..\jpeg" /I "..\zlib" /I "..\png" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c +CPP_PROJ=/nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\cimage" /I "..\jpeg" /I\ + "..\zlib" /I "..\png" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D\ + "_MBCS" /Fp"$(INTDIR)/demo.pch" /Yu"stdafx.h" /Fo"$(INTDIR)/" /Fd"$(INTDIR)/"\ + /c +CPP_OBJS=.\Debug/ +CPP_SBRS= +# ADD BASE MTL /nologo /D "_DEBUG" /win32 +# ADD MTL /nologo /D "_DEBUG" /win32 +MTL_PROJ=/nologo /D "_DEBUG" /win32 +# ADD BASE RSC /l 0x809 /d "_DEBUG" /d "_AFXDLL" +# ADD RSC /l 0x809 /d "_DEBUG" /d "_AFXDLL" +RSC_PROJ=/l 0x809 /fo"$(INTDIR)/demo.res" /d "_DEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +BSC32_FLAGS=/nologo /o"$(OUTDIR)/demo.bsc" +BSC32_SBRS= +LINK32=link.exe +# ADD BASE LINK32 /nologo /subsystem:windows /debug /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib winmm.lib ../png/Debug/png.lib ../jpeg/Debug/jpeg.lib ../zlib/Debug/zlib.lib ../cimage/Debug/cimage.lib /nologo /subsystem:windows /debug /machine:I386 +LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib\ + advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib winmm.lib\ + ../png/Debug/png.lib ../jpeg/Debug/jpeg.lib ../zlib/Debug/zlib.lib\ + ../cimage/Debug/cimage.lib /nologo /subsystem:windows /incremental:yes\ + /pdb:"$(OUTDIR)/demo.pdb" /debug /machine:I386 /out:"$(OUTDIR)/demo.exe" +LINK32_OBJS= \ + "$(INTDIR)/ChildFrm.obj" \ + "$(INTDIR)/MainFrm.obj" \ + "$(INTDIR)/demo.obj" \ + "$(INTDIR)/demoDoc.obj" \ + "$(INTDIR)/demoView.obj" \ + "$(INTDIR)/StdAfx.obj" \ + "$(INTDIR)/demo.res" + +"$(OUTDIR)\demo.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) + $(LINK32) @<< + $(LINK32_FLAGS) $(LINK32_OBJS) +<< + +!ENDIF + +.c{$(CPP_OBJS)}.obj: + $(CPP) $(CPP_PROJ) $< + +.cpp{$(CPP_OBJS)}.obj: + $(CPP) $(CPP_PROJ) $< + +.cxx{$(CPP_OBJS)}.obj: + $(CPP) $(CPP_PROJ) $< + +.c{$(CPP_SBRS)}.sbr: + $(CPP) $(CPP_PROJ) $< + +.cpp{$(CPP_SBRS)}.sbr: + $(CPP) $(CPP_PROJ) $< + +.cxx{$(CPP_SBRS)}.sbr: + $(CPP) $(CPP_PROJ) $< + +################################################################################ +# Begin Target + +# Name "demo - Win32 Release" +# Name "demo - Win32 Debug" + +!IF "$(CFG)" == "demo - Win32 Release" + +!ELSEIF "$(CFG)" == "demo - Win32 Debug" + +!ENDIF + +################################################################################ +# Begin Source File + +SOURCE=.\ReadMe.txt + +!IF "$(CFG)" == "demo - Win32 Release" + +!ELSEIF "$(CFG)" == "demo - Win32 Debug" + +!ENDIF + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\demo.cpp + +!IF "$(CFG)" == "demo - Win32 Release" + +DEP_CPP_DEMO_=\ + ".\StdAfx.h"\ + ".\demo.h"\ + ".\MainFrm.h"\ + ".\ChildFrm.h"\ + ".\demoDoc.h"\ + ".\demoView.h"\ + ".\..\cimage\cimage.h"\ + ".\..\cimage\cimageb.h"\ + ".\..\cimage\stdafx.h"\ + ".\..\cimage\cmap.h"\ + +NODEP_CPP_DEMO_=\ + ".\nIndex"\ + + +"$(INTDIR)\demo.obj" : $(SOURCE) $(DEP_CPP_DEMO_) "$(INTDIR)"\ + "$(INTDIR)\demo.pch" + + +!ELSEIF "$(CFG)" == "demo - Win32 Debug" + +DEP_CPP_DEMO_=\ + ".\StdAfx.h"\ + ".\demo.h"\ + ".\MainFrm.h"\ + ".\ChildFrm.h"\ + ".\demoDoc.h"\ + ".\demoView.h"\ + ".\..\cimage\cimage.h"\ + ".\..\cimage\cimageb.h"\ + ".\..\cimage\stdafx.h"\ + ".\..\cimage\cmap.h"\ + + +"$(INTDIR)\demo.obj" : $(SOURCE) $(DEP_CPP_DEMO_) "$(INTDIR)"\ + "$(INTDIR)\demo.pch" + + +!ENDIF + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\StdAfx.cpp +DEP_CPP_STDAF=\ + ".\StdAfx.h"\ + + +!IF "$(CFG)" == "demo - Win32 Release" + +# ADD CPP /Yc"stdafx.h" + +BuildCmds= \ + $(CPP) /nologo /MD /W3 /GX /O2 /I "..\cimage" /I "..\jpeg" /I "..\zlib" /I\ + "..\png" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS"\ + /Fp"$(INTDIR)/demo.pch" /Yc"stdafx.h" /Fo"$(INTDIR)/" /c $(SOURCE) \ + + +"$(INTDIR)\StdAfx.obj" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" + $(BuildCmds) + +"$(INTDIR)\demo.pch" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" + $(BuildCmds) + +!ELSEIF "$(CFG)" == "demo - Win32 Debug" + +# ADD CPP /Yc"stdafx.h" + +BuildCmds= \ + $(CPP) /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\cimage" /I "..\jpeg" /I\ + "..\zlib" /I "..\png" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D\ + "_MBCS" /Fp"$(INTDIR)/demo.pch" /Yc"stdafx.h" /Fo"$(INTDIR)/" /Fd"$(INTDIR)/"\ + /c $(SOURCE) \ + + +"$(INTDIR)\StdAfx.obj" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" + $(BuildCmds) + +"$(INTDIR)\demo.pch" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" + $(BuildCmds) + +!ENDIF + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\MainFrm.cpp +DEP_CPP_MAINF=\ + ".\StdAfx.h"\ + ".\demo.h"\ + ".\MainFrm.h"\ + + +"$(INTDIR)\MainFrm.obj" : $(SOURCE) $(DEP_CPP_MAINF) "$(INTDIR)"\ + "$(INTDIR)\demo.pch" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\ChildFrm.cpp +DEP_CPP_CHILD=\ + ".\StdAfx.h"\ + ".\demo.h"\ + ".\ChildFrm.h"\ + + +"$(INTDIR)\ChildFrm.obj" : $(SOURCE) $(DEP_CPP_CHILD) "$(INTDIR)"\ + "$(INTDIR)\demo.pch" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\demoDoc.cpp + +!IF "$(CFG)" == "demo - Win32 Release" + +DEP_CPP_DEMOD=\ + ".\StdAfx.h"\ + ".\demo.h"\ + ".\demoDoc.h"\ + ".\..\cimage\cimage.h"\ + ".\..\cimage\cimageb.h"\ + ".\..\cimage\stdafx.h"\ + ".\..\cimage\cmap.h"\ + +NODEP_CPP_DEMOD=\ + ".\return"\ + + +"$(INTDIR)\demoDoc.obj" : $(SOURCE) $(DEP_CPP_DEMOD) "$(INTDIR)"\ + "$(INTDIR)\demo.pch" + + +!ELSEIF "$(CFG)" == "demo - Win32 Debug" + +DEP_CPP_DEMOD=\ + ".\StdAfx.h"\ + ".\demo.h"\ + ".\demoDoc.h"\ + ".\..\cimage\cimage.h"\ + ".\..\cimage\cimageb.h"\ + ".\..\cimage\stdafx.h"\ + ".\..\cimage\cmap.h"\ + + +"$(INTDIR)\demoDoc.obj" : $(SOURCE) $(DEP_CPP_DEMOD) "$(INTDIR)"\ + "$(INTDIR)\demo.pch" + + +!ENDIF + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\demoView.cpp +DEP_CPP_DEMOV=\ + ".\StdAfx.h"\ + ".\..\cimage\cimage.h"\ + ".\MainFrm.h"\ + ".\demo.h"\ + ".\demoDoc.h"\ + ".\demoView.h"\ + ".\..\cimage\cimageb.h"\ + ".\..\cimage\stdafx.h"\ + ".\..\cimage\cmap.h"\ + + +"$(INTDIR)\demoView.obj" : $(SOURCE) $(DEP_CPP_DEMOV) "$(INTDIR)"\ + "$(INTDIR)\demo.pch" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\demo.rc +DEP_RSC_DEMO_R=\ + ".\res\demo.ico"\ + ".\res\demoDoc.ico"\ + ".\res\Toolbar.bmp"\ + ".\res\demo.rc2"\ + + +"$(INTDIR)\demo.res" : $(SOURCE) $(DEP_RSC_DEMO_R) "$(INTDIR)" + $(RSC) $(RSC_PROJ) $(SOURCE) + + +# End Source File +# End Target +# End Project +################################################################################ diff --git a/SlnkDWFImpl/CxImage/demo/demo.rc b/SlnkDWFImpl/CxImage/demo/demo.rc new file mode 100644 index 0000000..51e7e73 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.rc @@ -0,0 +1,1796 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Neutral resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) +#ifdef _WIN32 +LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON DISCARDABLE "res\\demo.ico" +IDR_DEMOTYPE ICON DISCARDABLE "res\\demoDoc.ico" +IDI_OK ICON DISCARDABLE "res\\ok.ico" +IDI_CANC ICON DISCARDABLE "res\\canc.ico" +IDI_R ICON DISCARDABLE "res\\no1.ico" +IDI_G ICON DISCARDABLE "res\\r1.ico" +IDI_B ICON DISCARDABLE "res\\b1.ico" +IDI_GRAY ICON DISCARDABLE "res\\gray.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDR_MAINFRAME BITMAP MOVEABLE PURE "res\\Toolbar.bmp" +IDB_BITMAP1 BITMAP DISCARDABLE "res\\bg.BMP" +IDR_TOOLBAR1 BITMAP DISCARDABLE "res\\toolbar1.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// Toolbar +// + +IDR_MAINFRAME TOOLBAR DISCARDABLE 16, 15 +BEGIN + BUTTON ID_FILE_NEW + BUTTON ID_FILE_OPEN + BUTTON ID_FILE_SAVE + BUTTON ID_FILE_PRINT + BUTTON ID_FILE_ACQUIRE + SEPARATOR + BUTTON ID_EDIT_CUT + BUTTON ID_EDIT_COPY + BUTTON ID_EDIT_PASTE + SEPARATOR + BUTTON ID_EDIT_UNDO + BUTTON ID_EDIT_REDO + SEPARATOR + BUTTON ID_VIEW_ZOOMIN + BUTTON ID_VIEW_NORMALVIEWING11 + BUTTON ID_VIEW_ZOOMOUT + SEPARATOR + BUTTON ID_VIEW_TOOLS_MOVE + BUTTON ID_VIEW_TOOLS_SELECT + BUTTON ID_VIEW_TOOLS_TRACKER + BUTTON ID_VIEW_TOOLS_ZOOM + BUTTON ID_VIEW_TOOLS_TEXT + SEPARATOR + BUTTON ID_VIEW_HISTOGRAM + BUTTON ID_VIEW_PALETTE + BUTTON ID_CXIMAGE_OPTIONS + SEPARATOR + BUTTON ID_APP_ABOUT +END + +IDR_TOOLBAR1 TOOLBAR DISCARDABLE 16, 15 +BEGIN + BUTTON ID_VIEW_NORMALVIEWING11 + BUTTON ID_CXIMAGE_OPTIONS + BUTTON ID_APP_EXIT + BUTTON ID_VIEW_ZOOMIN + BUTTON ID_VIEW_ZOOMOUT + BUTTON ID_CXIMAGE_ROTATE + BUTTON ID_CXIMAGE_FLIP + BUTTON ID_CXIMAGE_MIRROR + BUTTON ID_CXIMAGE_RESAMPLE + BUTTON ID_CXIMAGE_CROP + BUTTON ID_CXIMAGE_GRAYSCALE + BUTTON ID_CXIMAGE_NEGATIVE + BUTTON ID_CXIMAGE_DECREASEBPP + BUTTON ID_CXIMAGE_INCREASEBPP + BUTTON ID_CXIMAGE_SPLITCHANNELS + BUTTON ID_BUTTON32842 + BUTTON ID_CXIMAGE_SETTRANSPARENCY + BUTTON ID_CXIMAGE_REMOVETRANSPARENCY + BUTTON ID_VIEW_PALETTE +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDR_MAINFRAME MENU PRELOAD DISCARDABLE +BEGIN + POPUP "&File" + BEGIN + MENUITEM "&New\tCtrl+N", ID_FILE_NEW + MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN + MENUITEM SEPARATOR + MENUITEM "Select Source...", ID_FILE_SELECTSOURCE + MENUITEM "Acquire...", ID_FILE_ACQUIRE + MENUITEM SEPARATOR + MENUITEM "Capture...", ID_FILE_CAPTURE + MENUITEM SEPARATOR + MENUITEM "P&rint Setup...", ID_FILE_PRINT_SETUP + MENUITEM SEPARATOR + MENUITEM "Recent File", ID_FILE_MRU_FILE1, GRAYED + MENUITEM SEPARATOR + MENUITEM "E&xit", ID_APP_EXIT + END + POPUP "&Edit" + BEGIN + MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE + END + POPUP "&View" + BEGIN + MENUITEM "&Toolbar", ID_VIEW_TOOLBAR + MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR + MENUITEM "Histogram", ID_VIEW_HISTOGRAM + POPUP "Menu Style" + BEGIN + MENUITEM "Default", ID_VIEW_MENUSTYLE_NORMAL + MENUITEM "XP", ID_VIEW_MENUSTYLE_XP + END + MENUITEM SEPARATOR + MENUITEM "Full Screen", ID_VIEW_FULLSCREEN + END + POPUP "CxImage" + BEGIN + MENUITEM "Load Bitmap Resource", ID_IMAGE_FROM_BITMAP + MENUITEM "Load Jpeg Resource", ID_CXIMAGE_LOADJPEGRESOURCE + MENUITEM "Load Icon Resource", ID_CXIMAGE_LOADICONRESOURCE + MENUITEM "Load Png Resource", ID_CXIMAGE_LOADPNGRESOURCE + MENUITEM "Load Gif Resource", ID_CXIMAGE_LOADGIFRESOURCE + MENUITEM "Load Tif Resource", ID_CXIMAGE_LOADTIFRESOURCE + MENUITEM SEPARATOR + MENUITEM "Demo Save MultiPageTIFF", ID_CXIMAGE_DEMOSAVEMULTIPAGETIFF + + MENUITEM "Demo Save Animated GIF", ID_CXIMAGE_DEMOSAVEANIMATEDGIF + + MENUITEM "Download from URL ...", ID_CXIMAGE_DOWNLOADFROMURL + MENUITEM "Demo CreateFromArray", ID_CXIMAGE_DEMOCREATEFROMARRAY + + END + POPUP "&Help" + BEGIN + MENUITEM "&About demo...", ID_APP_ABOUT + END +END + +IDR_DEMOTYPE MENU PRELOAD DISCARDABLE +BEGIN + POPUP "&File" + BEGIN + MENUITEM "&New\tCtrl+N", ID_FILE_NEW + MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN + MENUITEM "&Close", ID_FILE_CLOSE + MENUITEM "&Save\tCtrl+S", ID_FILE_SAVE + MENUITEM "Save &As...", ID_FILE_SAVE_AS + MENUITEM SEPARATOR + MENUITEM "Select Source...", ID_FILE_SELECTSOURCE + MENUITEM "Acquire...", ID_FILE_ACQUIRE + MENUITEM SEPARATOR + MENUITEM "Capture...", ID_FILE_CAPTURE + MENUITEM SEPARATOR + MENUITEM "&Print...\tCtrl+P", ID_FILE_PRINT + MENUITEM "Print Pre&view", ID_FILE_PRINT_PREVIEW + MENUITEM "P&rint Setup...", ID_FILE_PRINT_SETUP + MENUITEM SEPARATOR + MENUITEM "Recent File", ID_FILE_MRU_FILE1, GRAYED + MENUITEM SEPARATOR + MENUITEM "E&xit", ID_APP_EXIT + END + POPUP "&Edit" + BEGIN + MENUITEM "&Undo\tCtrl+Z", ID_EDIT_UNDO + MENUITEM "Redo\tCtrl+Y", ID_EDIT_REDO + MENUITEM SEPARATOR + MENUITEM "Cu&t\tCtrl+X", ID_EDIT_CUT + MENUITEM "&Copy\tCtrl+C", ID_EDIT_COPY + MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE + END + POPUP "&View" + BEGIN + MENUITEM "&Toolbar", ID_VIEW_TOOLBAR + MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR + MENUITEM "Histogram", ID_VIEW_HISTOGRAM + MENUITEM "Palette", ID_VIEW_PALETTE + POPUP "Tools" + BEGIN + MENUITEM "Move", ID_VIEW_TOOLS_MOVE + MENUITEM "Select", ID_VIEW_TOOLS_SELECT + MENUITEM "Zoom", ID_VIEW_TOOLS_ZOOM + MENUITEM "Text", ID_VIEW_TOOLS_TEXT + MENUITEM "Tracker", ID_VIEW_TOOLS_TRACKER + END + POPUP "Menu Style" + BEGIN + MENUITEM "Default", ID_VIEW_MENUSTYLE_NORMAL + MENUITEM "XP", ID_VIEW_MENUSTYLE_XP + END + MENUITEM SEPARATOR + MENUITEM "Str&etch mode", ID_STRETCH_MODE + MENUITEM "Smooth", ID_VIEW_SMOOTH + MENUITEM "Full Screen", ID_VIEW_FULLSCREEN + MENUITEM SEPARATOR + MENUITEM "Zoom In\t+", ID_VIEW_ZOOMIN + MENUITEM "Zoom Out\t-", ID_VIEW_ZOOMOUT + MENUITEM "Normal Viewing (1:1)\t/", ID_VIEW_NORMALVIEWING11 + END + POPUP "CxImage" + BEGIN + POPUP "Resources" + BEGIN + MENUITEM "Load Bitmap Resource", ID_IMAGE_FROM_BITMAP + MENUITEM "Load Jpeg Resource", ID_CXIMAGE_LOADJPEGRESOURCE + + MENUITEM "Load Icon Resource", ID_CXIMAGE_LOADICONRESOURCE + + MENUITEM "Load Png Resource", ID_CXIMAGE_LOADPNGRESOURCE + + MENUITEM "Load Gif Resource", ID_CXIMAGE_LOADGIFRESOURCE + + MENUITEM "Load Tif Resource", ID_CXIMAGE_LOADTIFRESOURCE + + END + MENUITEM SEPARATOR + POPUP "Demo" + BEGIN + MENUITEM "&Ellipse transform", ID_TRANSFORM_ELLIPSE + MENUITEM "Save MultiPageTIFF", ID_CXIMAGE_DEMOSAVEMULTIPAGETIFF + + MENUITEM "Save Animated GIF", ID_CXIMAGE_DEMOSAVEANIMATEDGIF + + MENUITEM "Download from URL ...", ID_CXIMAGE_DOWNLOADFROMURL + + MENUITEM "Demo CreateFromArray", ID_CXIMAGE_DEMOCREATEFROMARRAY + + END + MENUITEM SEPARATOR + MENUITEM "Mirror", ID_CXIMAGE_MIRROR + MENUITEM "Flip", ID_CXIMAGE_FLIP + MENUITEM "Negative", ID_CXIMAGE_NEGATIVE + MENUITEM SEPARATOR + MENUITEM "Rotate Left", ID_CXIMAGE_ROTATEL + MENUITEM "Rotate Right", ID_CXIMAGE_ROTATER + MENUITEM "Rotate...", ID_CXIMAGE_ROTATE + MENUITEM "Resample...", ID_CXIMAGE_RESAMPLE + MENUITEM "Skew...", ID_CXIMAGE_SKEW + MENUITEM "Crop", ID_CXIMAGE_CROP + MENUITEM SEPARATOR + MENUITEM "Set Transparency... (click)", ID_CXIMAGE_SETTRANSPARENCY + MENUITEM "Remove Transparency", ID_CXIMAGE_REMOVETRANSPARENCY + + POPUP "Alpha Channel" + BEGIN + MENUITEM "Opacity...", ID_CXIMAGE_OPACITY + MENUITEM "Remove", ID_CXIMAGE_REMOVEALPHACHANNEL + + MENUITEM "Split", ID_CXIMAGE_ALPHACHANNEL_SPLIT + + MENUITEM "Strip", ID_CXIMAGE_ALPHASTRIP + MENUITEM "Invert", ID_CXIMAGE_INVETALPHA + MENUITEM "Toggle Alpha Palette ", ID_CXIMAGE_ALPHAPALETTETOGGLE + + MENUITEM "Create from lightness", ID_CXIMAGE_ALPHACREATE + END + MENUITEM SEPARATOR + MENUITEM "Gray Scale", ID_CXIMAGE_GRAYSCALE + MENUITEM "Dither...", ID_CXIMAGE_DITHER + MENUITEM "Decrease Bpp...", ID_CXIMAGE_DECREASEBPP + MENUITEM "Increase Bpp...", ID_CXIMAGE_INCREASEBPP + POPUP "Histogram" + BEGIN + MENUITEM "Stretch", ID_CXIMAGE_HISTOGRAM_STRETCH + + MENUITEM "Stretch1", ID_CXIMAGE_HISTOGRAM_STRETCH1 + + MENUITEM "Stretch2", ID_CXIMAGE_HISTOGRAM_STRETCH2 + + MENUITEM SEPARATOR + MENUITEM "Equalize", ID_CXIMAGE_HISTOGRAM_EQUALIZE + + MENUITEM "Normalize", ID_CXIMAGE_HISTOGRAM_NORMALIZE + + MENUITEM SEPARATOR + MENUITEM "Log", ID_CXIMAGE_HISTOGRAM_LOG + MENUITEM "Root", ID_CXIMAGE_HISTOGRAM_ROOT + + END + MENUITEM SEPARATOR + MENUITEM "Options...", ID_CXIMAGE_OPTIONS + END + POPUP "Filters" + BEGIN + MENUITEM "Threshold...", ID_CXIMAGE_THRESHOLD + MENUITEM "Colorize...", ID_CXIMAGE_COLORIZE + MENUITEM "Gamma...", ID_CXIMAGE_GAMMA + MENUITEM SEPARATOR + MENUITEM "Lighten", ID_CXIMAGE_LIGHTEN + MENUITEM "Darken", ID_CXIMAGE_DARKEN + MENUITEM "More Contrast", ID_CXIMAGE_CONTRAST + MENUITEM "Less Contrast", ID_CXIMAGE_LESSCONTRAST + MENUITEM SEPARATOR + POPUP "Linear" + BEGIN + MENUITEM "Blur", ID_CXIMAGE_BLUR + MENUITEM "Soften", ID_CXIMAGE_SOFTEN + MENUITEM "Gaussian 3x3", ID_CXIMAGE_GAUSSIAN3X3 + MENUITEM "Gaussian 5x5", ID_CXIMAGE_GAUSSIAN5X5 + MENUITEM "Sharpen", ID_CXIMAGE_SHARPEN + MENUITEM "Edge", ID_CXIMAGE_EDGE + MENUITEM "Emboss", ID_CXIMAGE_EMBOSS + END + POPUP "Non Linear" + BEGIN + MENUITEM "Add Noise", ID_CXIMAGE_ADDNOISE + MENUITEM "Median", ID_CXIMAGE_MEDIAN + MENUITEM "Erode", ID_CXIMAGE_ERODE + MENUITEM "Dilate", ID_CXIMAGE_DILATE + MENUITEM "Contour", ID_CXIMAGE_CONTOUR + MENUITEM "Edge", ID_FILTERS_NONLINEAR_EDGE + + MENUITEM "Jitter", ID_CXIMAGE_JITTER + END + POPUP "CircleTransform " + BEGIN + MENUITEM "Pinch", ID_CXIMAGE_CIRCLETRANSFORM_PINCH + + MENUITEM "Punch", ID_CXIMAGE_CIRCLETRANSFORM_PUNCH + + MENUITEM "Twirl", ID_CXIMAGE_CIRCLETRANSFORM_SWIRL + + MENUITEM "Cylinder", ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER + + MENUITEM "Bathroom", ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM + + END + MENUITEM SEPARATOR + MENUITEM "Pseudo Colors", ID_CXIMAGE_PSEUDOCOLORS + POPUP "Split" + BEGIN + MENUITEM "Split to RGB", ID_CXIMAGE_SPLITRGB + MENUITEM "Split to HSL", ID_CXIMAGE_SPLITHSL + MENUITEM "Split to YUV", ID_CXIMAGE_SPLITYUV + MENUITEM "Split to YIQ", ID_CXIMAGE_SPLITYIQ + MENUITEM "Split to XYZ", ID_CXIMAGE_SPLITXYZ + MENUITEM "Split to CMYK", ID_CXIMAGE_SPLITCMYK + END + MENUITEM "Combine ...", ID_CXIMAGE_COMBINE + MENUITEM "FFT...", ID_CXIMAGE_FFT + MENUITEM "Repair...", ID_CXIMAGE_REPAIR + MENUITEM "Mix ...", ID_FILTERS_MIX + MENUITEM "JPEG compression ...", ID_FILTERS_JPEGCOMPRESSION + END + POPUP "&Window" + BEGIN + MENUITEM "&New Window", ID_WINDOW_NEW + MENUITEM "&Cascade", ID_WINDOW_CASCADE + MENUITEM "&Tile", ID_WINDOW_TILE_HORZ + MENUITEM "&Arrange Icons", ID_WINDOW_ARRANGE + MENUITEM SEPARATOR + MENUITEM "Close All", ID_WINDOW_CLOSEALL + MENUITEM SEPARATOR + MENUITEM "Duplicate\tCtrl+D", ID_WINDOW_DUPLICATE + END + POPUP "&Help" + BEGIN + MENUITEM "&About demo...", ID_APP_ABOUT + END +END + +IDM_CXIMAGE1 MENU DISCARDABLE +BEGIN + POPUP "CxImage" + BEGIN + MENUITEM "&Undo\tCtrl+Z", ID_EDIT_UNDO + MENUITEM "Redo\tCtrl+Y", ID_EDIT_REDO + MENUITEM SEPARATOR + MENUITEM "&Copy\tCtrl+C", ID_EDIT_COPY + MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE + MENUITEM SEPARATOR + MENUITEM "Mirror", ID_CXIMAGE_MIRROR + MENUITEM "Flip", ID_CXIMAGE_FLIP + MENUITEM "Negative", ID_CXIMAGE_NEGATIVE + POPUP "Filters" + BEGIN + MENUITEM "Threshold...", ID_CXIMAGE_THRESHOLD + MENUITEM "Colorize...", ID_CXIMAGE_COLORIZE + MENUITEM "Gamma...", ID_CXIMAGE_GAMMA + MENUITEM SEPARATOR + MENUITEM "Lighten", ID_CXIMAGE_LIGHTEN + MENUITEM "Darken", ID_CXIMAGE_DARKEN + MENUITEM "More Contrast", ID_CXIMAGE_CONTRAST + MENUITEM "Less Contrast", ID_CXIMAGE_LESSCONTRAST + MENUITEM SEPARATOR + MENUITEM "Pseudo Colors", ID_CXIMAGE_PSEUDOCOLORS + POPUP "Split" + BEGIN + MENUITEM "Split to RGB", ID_CXIMAGE_SPLITRGB + MENUITEM "Split to HSL", ID_CXIMAGE_SPLITHSL + MENUITEM "Split to YUV", ID_CXIMAGE_SPLITYUV + MENUITEM "Split to YIQ", ID_CXIMAGE_SPLITYIQ + MENUITEM "Split to XYZ", ID_CXIMAGE_SPLITXYZ + MENUITEM "Split to CMYK", ID_CXIMAGE_SPLITCMYK + END + MENUITEM "Combine...", ID_CXIMAGE_COMBINE + MENUITEM "FFT...", ID_CXIMAGE_FFT + MENUITEM "Repair...", ID_CXIMAGE_REPAIR + MENUITEM "Mix ...", ID_FILTERS_MIX + END + POPUP "Linear" + BEGIN + MENUITEM "Blur", ID_CXIMAGE_BLUR + MENUITEM "Soften", ID_CXIMAGE_SOFTEN + MENUITEM "Gaussian 3x3", ID_CXIMAGE_GAUSSIAN3X3 + MENUITEM "Gaussian 5x5", ID_CXIMAGE_GAUSSIAN5X5 + MENUITEM "Sharpen", ID_CXIMAGE_SHARPEN + MENUITEM "Edge", ID_CXIMAGE_EDGE + MENUITEM "Emboss", ID_CXIMAGE_EMBOSS + END + POPUP "Non Linear" + BEGIN + MENUITEM "Add Noise", ID_CXIMAGE_ADDNOISE + MENUITEM "Median", ID_CXIMAGE_MEDIAN + MENUITEM "Erode", ID_CXIMAGE_ERODE + MENUITEM "Dilate", ID_CXIMAGE_DILATE + MENUITEM "Contour", ID_CXIMAGE_CONTOUR + MENUITEM "Edge", ID_FILTERS_NONLINEAR_EDGE + + MENUITEM "Jitter", ID_CXIMAGE_JITTER + END + POPUP "CircleTransform " + BEGIN + MENUITEM "Pinch", ID_CXIMAGE_CIRCLETRANSFORM_PINCH + + MENUITEM "Punch", ID_CXIMAGE_CIRCLETRANSFORM_PUNCH + + MENUITEM "Twirl", ID_CXIMAGE_CIRCLETRANSFORM_SWIRL + + MENUITEM "Cylinder", ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER + + MENUITEM "Bathroom", ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM + + END + MENUITEM SEPARATOR + MENUITEM "Rotate Left", ID_CXIMAGE_ROTATEL + MENUITEM "Rotate Right", ID_CXIMAGE_ROTATER + MENUITEM "Rotate...", ID_CXIMAGE_ROTATE + MENUITEM "Resample...", ID_CXIMAGE_RESAMPLE + MENUITEM "Skew...", ID_CXIMAGE_SKEW + MENUITEM "Crop", ID_CXIMAGE_CROP + MENUITEM SEPARATOR + MENUITEM "Set Transparency... (click)", ID_CXIMAGE_SETTRANSPARENCY + MENUITEM "Remove Transparency", ID_CXIMAGE_REMOVETRANSPARENCY + + POPUP "Alpha Channel" + BEGIN + MENUITEM "Opacity...", ID_CXIMAGE_OPACITY + MENUITEM "Remove", ID_CXIMAGE_REMOVEALPHACHANNEL + + MENUITEM "Split", ID_CXIMAGE_ALPHACHANNEL_SPLIT + + MENUITEM "Strip", ID_CXIMAGE_ALPHASTRIP + MENUITEM "Invert", ID_CXIMAGE_INVETALPHA + MENUITEM "Toggle Alpha Palette ", ID_CXIMAGE_ALPHAPALETTETOGGLE + + MENUITEM "Create from lightness", ID_CXIMAGE_ALPHACREATE + END + MENUITEM SEPARATOR + MENUITEM "Gray Scale", ID_CXIMAGE_GRAYSCALE + MENUITEM "Dither...", ID_CXIMAGE_DITHER + MENUITEM "Decrease Bpp...", ID_CXIMAGE_DECREASEBPP + MENUITEM "Increase Bpp...", ID_CXIMAGE_INCREASEBPP + POPUP "Histogram" + BEGIN + MENUITEM "Stretch", ID_CXIMAGE_HISTOGRAM_STRETCH + + MENUITEM "Stretch1", ID_CXIMAGE_HISTOGRAM_STRETCH1 + + MENUITEM "Stretch2", ID_CXIMAGE_HISTOGRAM_STRETCH2 + + MENUITEM SEPARATOR + MENUITEM "Equalize", ID_CXIMAGE_HISTOGRAM_EQUALIZE + + MENUITEM "Normalize", ID_CXIMAGE_HISTOGRAM_NORMALIZE + + MENUITEM SEPARATOR + MENUITEM "Log", ID_CXIMAGE_HISTOGRAM_LOG + MENUITEM "Root", ID_CXIMAGE_HISTOGRAM_ROOT + + END + MENUITEM SEPARATOR + MENUITEM "Options...", ID_CXIMAGE_OPTIONS + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Accelerator +// + +IDR_MAINFRAME ACCELERATORS PRELOAD MOVEABLE PURE +BEGIN + "C", ID_EDIT_COPY, VIRTKEY, CONTROL, NOINVERT + "D", ID_WINDOW_DUPLICATE, VIRTKEY, CONTROL, NOINVERT + "N", ID_FILE_NEW, VIRTKEY, CONTROL, NOINVERT + "O", ID_FILE_OPEN, VIRTKEY, CONTROL, NOINVERT + "P", ID_FILE_PRINT, VIRTKEY, CONTROL, NOINVERT + "S", ID_FILE_SAVE, VIRTKEY, CONTROL, NOINVERT + "V", ID_EDIT_PASTE, VIRTKEY, CONTROL, NOINVERT + VK_ADD, ID_VIEW_ZOOMIN, VIRTKEY, NOINVERT + VK_BACK, ID_EDIT_UNDO, VIRTKEY, ALT, NOINVERT + VK_DELETE, ID_EDIT_CUT, VIRTKEY, SHIFT, NOINVERT + VK_DIVIDE, ID_VIEW_NORMALVIEWING11, VIRTKEY, NOINVERT + VK_F6, ID_NEXT_PANE, VIRTKEY, NOINVERT + VK_F6, ID_PREV_PANE, VIRTKEY, SHIFT, NOINVERT + VK_INSERT, ID_EDIT_COPY, VIRTKEY, CONTROL, NOINVERT + VK_INSERT, ID_EDIT_PASTE, VIRTKEY, SHIFT, NOINVERT + VK_SUBTRACT, ID_VIEW_ZOOMOUT, VIRTKEY, NOINVERT + "X", ID_EDIT_CUT, VIRTKEY, CONTROL, NOINVERT + "Y", ID_EDIT_REDO, VIRTKEY, CONTROL, NOINVERT + "Z", ID_EDIT_UNDO, VIRTKEY, CONTROL, NOINVERT +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOGEX 0, 0, 245, 254 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "About demo" +FONT 8, "MS Sans Serif" +BEGIN + ICON IDR_MAINFRAME,IDC_STATIC,7,7,20,20 + LTEXT "CImage Demo Version 1.0 © Julian Smart et al, 1997", + IDC_STATIC,7,54,231,11,SS_NOPREFIX,WS_EX_STATICEDGE + DEFPUSHBUTTON "OK",IDOK,188,7,50,16 + CTEXT "CxImage Demo Version 5.99c\n© Davide Pizzolato, 2001 - 2004\nwww.xdp.it", + IDC_STATIC,38,7,143,28,SS_NOPREFIX,WS_EX_STATICEDGE + LTEXT "CImage © Alejandro Aguilar Sierra, 1995 - 1998", + IDC_STATIC,7,41,231,11,0,WS_EX_STATICEDGE + LTEXT "BCMenu Version 3.033 © Brent Corkum, 2002",IDC_STATIC,7, + 106,231,11,0,WS_EX_STATICEDGE + LTEXT "CQuantizer © Jeff Prosise, 1997",IDC_STATIC,7,67,231,11, + 0,WS_EX_STATICEDGE + LTEXT "CTwain © Rajiv Ramachandran, 2000",IDC_STATIC,7,80,231, + 11,0,WS_EX_STATICEDGE + LTEXT "CxTargetButton Version 1.00 © Davide Pizzolato, 2002", + IDC_STATIC,7,93,231,11,0,WS_EX_STATICEDGE + LTEXT "IJG JPEG library © Thomas G. Lane, 1994 - 1998", + IDC_STATIC,7,119,231,11,0,WS_EX_STATICEDGE + LTEXT "LibPNG version 1.2.7 © Glenn Randers-Pehrson, 1998 - 2004", + IDC_STATIC,7,131,231,11,0,WS_EX_STATICEDGE + LTEXT "LibTIFF version 3.5.7 © Sam Leffler, 1988 - 1997", + IDC_STATIC,7,144,231,11,0,WS_EX_STATICEDGE + LTEXT "GIF © CompuServe Incorporated",IDC_STATIC,7,157,231,11, + 0,WS_EX_STATICEDGE + LTEXT "Gif-RLE © Hutchison Avenue Software Corporation, 1998", + IDC_STATIC,7,170,231,11,0,WS_EX_STATICEDGE + LTEXT "LIBMNG version 1.0.2 © Gerard Juyn, 2000 - 2001", + IDC_STATIC,7,183,231,11,0,WS_EX_STATICEDGE + LTEXT "LibJ2k © David Janssens, 2001 - 2002",IDC_STATIC,7,195, + 231,11,0,WS_EX_STATICEDGE + LTEXT "LIBJBG © Markus Kuhn, 2002",IDC_STATIC,7,208,231,11,0, + WS_EX_STATICEDGE + LTEXT "JasPer © Image Power, UBC, Michael David Adams, 2001 - 2004 ", + IDC_STATIC,7,220,231,11,0,WS_EX_STATICEDGE + LTEXT "zlib version 1.2.1 © Jean-loup Gailly and Mark Adler, 1995 - 2003", + IDC_STATIC,7,233,231,11,0,WS_EX_STATICEDGE +END + +IDD_ROTATE DIALOG DISCARDABLE 0, 0, 143, 114 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Rotate" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,86,6,50,16 + PUSHBUTTON "Cancel",IDCANCEL,86,23,50,16 + EDITTEXT IDC_EDIT1,10,25,51,12,ES_AUTOHSCROLL + LTEXT "Angle [degrees]",IDC_STATIC,10,10,50,8 + LTEXT "Interpolation method",IDC_STATIC,10,41,65,8 + COMBOBOX IDC_COMBO_IM,10,49,126,95,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + LTEXT "Overflow method",IDC_STATIC,10,68,54,8 + COMBOBOX IDC_COMBO_OM,10,78,126,72,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + CONTROL "Keep original size",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,11,97,71,10 +END + +IDD_CAPTURE DIALOG DISCARDABLE 0, 0, 297, 81 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Capture" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,5,58,50,16 + PUSHBUTTON "Cancel",IDCANCEL,60,58,50,16 + LISTBOX IDC_LIST1,5,5,285,45,LBS_SORT | LBS_NOINTEGRALHEIGHT | + WS_VSCROLL | WS_TABSTOP +END + +IDD_RESAMPLE DIALOG DISCARDABLE 0, 0, 152, 108 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Resample" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,95,6,50,16 + PUSHBUTTON "Cancel",IDCANCEL,95,23,50,16 + EDITTEXT IDC_EDIT1,17,18,51,12,ES_AUTOHSCROLL + LTEXT "Interpolation:",IDC_STATIC,7,91,42,8 + COMBOBOX IDC_COMBO_IM,56,89,89,118,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + GROUPBOX "",IDC_STATIC,7,40,138,43 + GROUPBOX "",IDC_STATIC,7,6,80,31 + EDITTEXT IDC_EDIT2,17,52,51,12,ES_AUTOHSCROLL + EDITTEXT IDC_EDIT3,84,52,51,12,ES_AUTOHSCROLL + LTEXT "x",IDC_STATIC,74,54,8,8 + CONTROL "Size factor",IDC_RADIO1,"Button",BS_AUTORADIOBUTTON | + WS_GROUP,13,6,49,10 + CONTROL "Pixel Width x Height",IDC_RADIO2,"Button", + BS_AUTORADIOBUTTON,13,40,79,10 + CONTROL "Maintain original aspect ratio",IDC_CHECK2,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,18,68,105,10 +END + +IDD_DECBPP DIALOG DISCARDABLE 0, 0, 131, 106 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Decrease Bpp" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,74,7,50,16 + PUSHBUTTON "Cancel",IDCANCEL,74,24,50,16 + CONTROL "1",IDC_RADIO1,"Button",BS_AUTORADIOBUTTON | WS_GROUP,15, + 85,25,10 + GROUPBOX "Bpp",IDC_STATIC,7,70,118,30 + CONTROL "4",IDC_RADIO2,"Button",BS_AUTORADIOBUTTON,50,85,25,10 + CONTROL "8",IDC_RADIO3,"Button",BS_AUTORADIOBUTTON,85,85,25,10 + GROUPBOX "Palette",IDC_STATIC,7,5,63,35 + CONTROL "Standard",IDC_RADIO4,"Button",BS_AUTORADIOBUTTON | + WS_GROUP,15,15,45,10 + CONTROL "Optimized",IDC_RADIO5,"Button",BS_AUTORADIOBUTTON,15,25, + 45,10 + CONTROL " Error Diffusion",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,7,43,110,10 + CONTROL "Limit max colors:",IDC_CHECK2,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,7,55,67,10 + EDITTEXT IDC_EDIT1,87,54,22,12,ES_AUTOHSCROLL +END + +IDD_INCBPP DIALOG DISCARDABLE 0, 0, 132, 71 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Increase Bpp" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,75,5,50,16 + PUSHBUTTON "Cancel",IDCANCEL,75,22,50,16 + CONTROL "4",IDC_RADIO1,"Button",BS_AUTORADIOBUTTON | WS_GROUP,15, + 20,25,10 + GROUPBOX "Bpp",-1,5,5,60,60 + CONTROL "8",IDC_RADIO2,"Button",BS_AUTORADIOBUTTON,15,35,25,10 + CONTROL "24",IDC_RADIO3,"Button",BS_AUTORADIOBUTTON,15,50,25,10 +END + +IDD_OPTIONS DIALOG DISCARDABLE 0, 0, 193, 204 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Options" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,136,7,50,16 + PUSHBUTTON "Cancel",IDCANCEL,136,23,50,16 + LTEXT "JPEG quality [0 ... 100]",IDC_STATIC,10,12,73,8 + EDITTEXT IDC_EDIT1,96,10,32,12,ES_AUTOHSCROLL + LTEXT "X resolution [DPI]",IDC_STATIC,10,27,56,8 + EDITTEXT IDC_EDIT2,96,25,32,12,ES_AUTOHSCROLL + LTEXT "Y resolution [DPI]",IDC_STATIC,10,42,56,8 + EDITTEXT IDC_EDIT3,96,40,32,12,ES_AUTOHSCROLL + GROUPBOX "TIFF",IDC_STATIC,7,57,75,92 + CONTROL "Default : auto",IDC_RADIO1,"Button",BS_AUTORADIOBUTTON | + WS_GROUP,11,69,61,10 + CONTROL "none",IDC_RADIO2,"Button",BS_AUTORADIOBUTTON,11,80,32, + 10 + CONTROL "RLE",IDC_RADIO3,"Button",BS_AUTORADIOBUTTON,11,91,30,10 + CONTROL "Fax",IDC_RADIO4,"Button",BS_AUTORADIOBUTTON,11,102,48, + 10 + CONTROL "Packbits",IDC_RADIO5,"Button",BS_AUTORADIOBUTTON,11,113, + 43,10 + CONTROL "Jpeg",IDC_RADIO6,"Button",BS_AUTORADIOBUTTON,11,124,31, + 10 + CONTROL "LZW",IDC_RADIO7,"Button",BS_AUTORADIOBUTTON,11,136,32, + 10 + PUSHBUTTON "Exif",IDEXIF,136,39,50,16 + GROUPBOX "GIF",IDC_STATIC,88,96,98,46 + CONTROL "Default : LZW",IDC_RADIO8,"Button",BS_AUTORADIOBUTTON | + WS_GROUP,94,106,61,10 + CONTROL "None",IDC_RADIO9,"Button",BS_AUTORADIOBUTTON,94,118,33, + 10 + CONTROL "RLE",IDC_RADIO10,"Button",BS_AUTORADIOBUTTON,94,129,30, + 10 + CONTROL "Default : not interlaced",IDC_RADIO11,"Button", + BS_AUTORADIOBUTTON | WS_GROUP,94,69,87,10 + CONTROL "interlaced",IDC_RADIO12,"Button",BS_AUTORADIOBUTTON,94, + 80,47,10 + GROUPBOX "PNG",IDC_STATIC,88,58,98,37 + CONTROL "Default : baseline",IDC_RADIO13,"Button", + BS_AUTORADIOBUTTON | WS_GROUP,94,157,71,10 + CONTROL "progressive",IDC_RADIO14,"Button",BS_AUTORADIOBUTTON,94, + 168,52,10 + GROUPBOX "JPEG",IDC_STATIC,89,144,97,53 + CONTROL "Optimize",IDC_CHECK5,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,94,181,43,10 +END + +IDD_DITHER DIALOG DISCARDABLE 0, 0, 149, 122 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Dither" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,92,7,50,16 + PUSHBUTTON "Cancel",IDCANCEL,92,23,50,16 + CONTROL "Floyd-Steinberg",IDC_RADIO1,"Button",BS_AUTORADIOBUTTON | + WS_GROUP,7,7,65,10 + CONTROL "Ordered dither",IDC_RADIO2,"Button",BS_AUTORADIOBUTTON, + 7,21,61,10 + CONTROL "Burkes",IDC_RADIO3,"Button",BS_AUTORADIOBUTTON,7,35,38, + 10 + CONTROL "Stucki",IDC_RADIO4,"Button",BS_AUTORADIOBUTTON,7,49,36, + 10 + CONTROL "Jarvis-Judice-Ninke",IDC_RADIO5,"Button", + BS_AUTORADIOBUTTON,7,63,77,10 + CONTROL "Sierra",IDC_RADIO6,"Button",BS_AUTORADIOBUTTON,7,77,34, + 10 + CONTROL "Stevenson-Arce",IDC_RADIO7,"Button",BS_AUTORADIOBUTTON, + 7,91,67,10 + CONTROL "Bayer matrix (4x4 ordered dither)",IDC_RADIO8,"Button", + BS_AUTORADIOBUTTON,7,105,117,10 +END + +IDD_THRESHOLD DIALOG DISCARDABLE 0, 0, 143, 46 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Threshold" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,86,6,50,16 + PUSHBUTTON "Cancel",IDCANCEL,86,23,50,16 + EDITTEXT IDC_EDIT1,10,25,51,12,ES_AUTOHSCROLL + LTEXT "Level [0 ... 255]",IDC_STATIC,10,10,50,8 +END + +IDD_COLORIZE DIALOG DISCARDABLE 0, 0, 166, 127 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Colorize" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,109,6,50,16 + PUSHBUTTON "Cancel",IDCANCEL,109,23,50,16 + EDITTEXT IDC_EDIT1,75,17,25,12,ES_AUTOHSCROLL + LTEXT "Hue: [0 : 255]",IDC_STATIC,7,19,44,8 + EDITTEXT IDC_EDIT2,75,32,25,12,ES_AUTOHSCROLL + LTEXT "Saturation: [0 : 255]",IDC_STATIC,7,33,63,8 + EDITTEXT IDC_EDIT3,75,76,25,12,ES_AUTOHSCROLL + LTEXT "Red: [-255 : 255]",IDC_STATIC,7,78,60,8 + EDITTEXT IDC_EDIT4,75,93,25,12,ES_AUTOHSCROLL + LTEXT "Green: [-255 : 255]",IDC_STATIC,7,95,60,8 + EDITTEXT IDC_EDIT5,75,109,25,12,ES_AUTOHSCROLL + LTEXT "Blue: [-255 : 255]",IDC_STATIC,7,111,61,8 + CONTROL "HSL",IDC_RADIO3,"Button",BS_AUTORADIOBUTTON | WS_GROUP, + 7,6,30,10 + CONTROL "RGB",IDC_RADIO4,"Button",BS_AUTORADIOBUTTON,7,64,31,10 + EDITTEXT IDC_EDIT8,75,47,25,12,ES_AUTOHSCROLL + LTEXT "Blend: [%]",IDC_STATIC,7,48,32,8 + PUSHBUTTON "Colors...",IDCOLORS,109,40,50,16 +END + +IDD_OPACITY DIALOG DISCARDABLE 0, 0, 143, 46 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Opacity" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,86,6,50,16 + PUSHBUTTON "Cancel",IDCANCEL,86,23,50,16 + EDITTEXT IDC_EDIT1,10,25,51,12,ES_AUTOHSCROLL + LTEXT "Level [0 ... 255]",IDC_STATIC,10,10,50,8 +END + +IDD_DWNURL DIALOGEX 0, 0, 287, 46 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Download from URL" +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + DEFPUSHBUTTON "Download",IDOK,230,7,50,16 + PUSHBUTTON "Cancel",IDCANCEL,230,23,50,16 + LTEXT "URL",IDC_STATIC,7,10,16,8 + LTEXT "Status",IDC_STATIC,7,26,21,8 + LTEXT "",IDC_STATUS,38,25,183,11,0,WS_EX_STATICEDGE + EDITTEXT IDC_URL,38,7,183,14,ES_AUTOHSCROLL +END + +IDD_GAMMA DIALOG DISCARDABLE 0, 0, 143, 46 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Gamma" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,86,6,50,16 + PUSHBUTTON "Cancel",IDCANCEL,86,23,50,16 + EDITTEXT IDC_EDIT1,10,25,51,12,ES_AUTOHSCROLL + LTEXT "Correction [0...5]",IDC_STATIC,10,10,53,8 +END + +IDD_HISTO DIALOGEX 0, 0, 186, 115 +STYLE WS_CHILD +EXSTYLE WS_EX_TOOLWINDOW +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + CONTROL "log",IDC_LOG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,148, + 7,30,15 +END + +IDD_PALETTE DIALOGEX 0, 0, 271, 135 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Palette" +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,159,7,50,16 + PUSHBUTTON "Cancel",IDCANCEL,214,7,50,16 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,7,7,132,122, + WS_EX_TRANSPARENT + PUSHBUTTON "Load ...",IDC_LOAD,159,29,50,16 + PUSHBUTTON "Save ...",IDC_SAVE,214,29,50,16 + GROUPBOX "Load Options",IDC_STATIC,159,52,105,48 + CONTROL "Maintain indexes",IDC_RADIO1,"Button", + BS_AUTORADIOBUTTON | WS_GROUP,168,64,69,10 + CONTROL "Nearest color matching",IDC_RADIO2,"Button", + BS_AUTORADIOBUTTON,168,75,89,10 + CONTROL "Error diffusion dithering",IDC_RADIO3,"Button", + BS_AUTORADIOBUTTON,168,87,87,10 + CONTROL "Edit alpha component",IDC_CHECK2,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,168,104,85,10 + LTEXT " I = 0, RGBA = (0,0,0,0)",IDC_BAR,143,117,121,12, + SS_SUNKEN +END + +IDD_COMBINE DIALOG DISCARDABLE 0, 0, 242, 119 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Combine" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,185,7,50,16 + PUSHBUTTON "Cancel",IDCANCEL,185,24,50,16 + COMBOBOX IDC_COMBO1,7,19,114,55,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + LTEXT "Red / H / Y / X channel source:",IDC_STATIC,7,7,97,8 + LTEXT "Green / S / U / I / Y channel source:",IDC_STATIC,7, + 35,97,8 + LTEXT "Blue / L / V / Q / Z channel source:",IDC_STATIC,7,63, + 97,8 + COMBOBOX IDC_COMBO2,7,47,114,55,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + COMBOBOX IDC_COMBO3,7,74,114,57,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + LTEXT "Alpha channel source:",IDC_STATIC,7,90,97,8 + COMBOBOX IDC_COMBO4,7,101,114,61,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + COMBOBOX IDC_COMBO5,125,19,48,55,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + COMBOBOX IDC_COMBO6,125,47,48,55,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + COMBOBOX IDC_COMBO7,125,74,48,55,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + COMBOBOX IDC_COMBO8,125,100,48,55,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + COMBOBOX IDC_COMBO9,185,60,50,79,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + LTEXT "Color Space",IDC_STATIC,188,50,40,8 +END + +IDD_FFT DIALOG DISCARDABLE 0, 0, 252, 79 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "FFT" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,195,39,50,16 + PUSHBUTTON "Cancel",IDCANCEL,195,56,50,16 + COMBOBOX IDC_REAL,7,20,114,114,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + COMBOBOX IDC_IMAG,131,20,114,126,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + LTEXT "Real",IDC_STATIC,7,7,16,8 + LTEXT "Imaginary",IDC_STATIC,131,7,31,8 + CONTROL "Inverse",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,7,41,39,10 + CONTROL "Compute magnitude",IDC_CHECK3,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,7,51,79,10 + CONTROL "Force FFT",IDC_CHECK4,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,7,61,49,10 +END + +IDD_REPAIR DIALOG DISCARDABLE 0, 0, 186, 61 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Repair" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,129,7,50,16 + PUSHBUTTON "Cancel",IDCANCEL,129,23,50,16 + LTEXT "Radius",IDC_STATIC,10,27,23,8 + EDITTEXT IDC_EDIT2,65,25,38,12,ES_AUTOHSCROLL + LTEXT "Iterations",IDC_STATIC,10,42,30,8 + EDITTEXT IDC_EDIT3,65,40,38,12,ES_AUTOHSCROLL + LTEXT "Color Space",IDC_STATIC,7,7,40,8 + COMBOBOX IDC_COMBO9,65,7,50,79,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP +END + +IDD_TEXT DIALOG DISCARDABLE 0, 0, 262, 167 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Place text to image" +FONT 8, "MS Sans Serif" +BEGIN + PUSHBUTTON "OK",IDOK,195,6,59,16 + PUSHBUTTON "Cancel",IDCANCEL,195,23,59,16 + EDITTEXT IDC_EDIT1,7,24,180,56,ES_MULTILINE | ES_AUTOVSCROLL | + ES_AUTOHSCROLL | ES_WANTRETURN + LTEXT "Text to place:",IDC_STATIC,10,10,177,8 + PUSHBUTTON "Font",ID_FONT,195,49,59,14 + PUSHBUTTON "Color...",IDC_BTN_TXTCOLOR,195,64,59,14 + PUSHBUTTON "Color...",IDC_BTN_BCKCOLOR,108,95,59,14 + CONTROL "Text has background",IDC_CHECK1,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,13,98,90,8 + GROUPBOX "Background",IDC_STATIC,7,85,174,75 + CONTROL "Slider1",IDC_SLIDER_OPACITY,"msctls_trackbar32", + TBS_AUTOTICKS | TBS_TOP | WS_TABSTOP,61,111,93,20 + CONTROL "Slider1",IDC_SLIDER_RADIUS,"msctls_trackbar32", + TBS_AUTOTICKS | TBS_TOP | WS_TABSTOP,61,131,93,21 + LTEXT "Opacity:",IDC_STATIC,14,116,48,12 + LTEXT "Round radius:",IDC_STATIC,14,137,48,12 + LTEXT "0%",IDC_STATIC_OP,160,117,17,13 + LTEXT "0%",IDC_STATIC_RADIUS,160,138,17,13 + GROUPBOX "Alignment",IDC_STATIC,184,85,70,75 + CONTROL "centered",IDC_RADIO1,"Button",BS_AUTORADIOBUTTON,195,97, + 48,11 + CONTROL "to left",IDC_RADIO2,"Button",BS_AUTORADIOBUTTON,195,111, + 50,11 + CONTROL "to right",IDC_RADIO3,"Button",BS_AUTORADIOBUTTON,195, + 125,50,11 +END + +IDD_MIX DIALOG DISCARDABLE 0, 0, 245, 178 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Mix" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,188,141,50,14 + PUSHBUTTON "Cancel",IDCANCEL,188,156,50,14 + COMBOBOX IDC_DST,38,7,200,108,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + LTEXT "Dst :",IDC_STATIC,7,11,16,8 + LTEXT "Src :",IDC_STATIC,7,25,16,8 + COMBOBOX IDC_SRC,37,23,200,92,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + COMBOBOX IDC_OP,190,39,48,64,CBS_DROPDOWNLIST | WS_VSCROLL | + WS_TABSTOP + LTEXT "OpType :",IDC_STATIC,158,41,30,8 + CONTROL "",IDC_PICTURE,"Static",SS_BITMAP | SS_SUNKEN,7,42,16,14 + PUSHBUTTON "Refresh Preview",IDC_BUTTON1,165,117,64,14 + EDITTEXT IDC_EDIT1,195,66,36,12,ES_AUTOHSCROLL + LTEXT "X offset :",IDC_STATIC,164,69,29,8 + LTEXT "Y offset :",IDC_STATIC,164,84,29,8 + EDITTEXT IDC_EDIT2,195,82,36,12,ES_AUTOHSCROLL + CONTROL "Mix alpha channel",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | + BS_MULTILINE | WS_TABSTOP,164,97,55,17 + GROUPBOX "Source options",IDC_STATIC,158,55,80,82 +END + +IDD_SKEW DIALOGEX 0, 0, 151, 122 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Skew" +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,94,7,50,16 + PUSHBUTTON "Cancel",IDCANCEL,94,23,50,16 + CONTROL "Enable interpolation",IDC_CHECK1,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,17,106,78,10 + GROUPBOX "Pivot",IDC_STATIC,7,7,72,44 + LTEXT "x :",IDC_STATIC,18,20,8,8 + LTEXT "y :",IDC_STATIC,18,33,9,8 + GROUPBOX "Skew",IDC_STATIC,7,56,137,46 + LTEXT "x :",IDC_STATIC,18,73,8,8 + LTEXT "y :",IDC_STATIC,18,86,9,8 + EDITTEXT IDC_EDIT1,33,19,30,12,ES_AUTOHSCROLL + EDITTEXT IDC_EDIT2,33,32,30,12,ES_AUTOHSCROLL + EDITTEXT IDC_EDIT4,33,72,30,12,ES_AUTOHSCROLL + EDITTEXT IDC_EDIT5,33,85,30,12,ES_AUTOHSCROLL + LTEXT "Angle",IDC_STATIC,74,62,19,8 + LTEXT "Slope",IDC_STATIC,108,62,19,8 + EDITTEXT IDC_EDIT6,69,72,30,12,ES_READONLY | NOT WS_BORDER, + WS_EX_STATICEDGE + EDITTEXT IDC_EDIT7,69,85,30,12,ES_READONLY | NOT WS_BORDER, + WS_EX_STATICEDGE + EDITTEXT IDC_EDIT8,106,72,30,12,ES_READONLY | NOT WS_BORDER, + WS_EX_STATICEDGE + EDITTEXT IDC_EDIT9,106,85,30,12,ES_READONLY | NOT WS_BORDER, + WS_EX_STATICEDGE +END + +IDD_JPEG DIALOG DISCARDABLE 0, 0, 143, 92 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "JPEG compression" +FONT 8, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "OK",IDOK,86,6,50,16 + PUSHBUTTON "Cancel",IDCANCEL,86,23,50,16 + EDITTEXT IDC_EDIT1,10,25,51,12,ES_AUTOHSCROLL + LTEXT "Level [0 ... 255]",IDC_STATIC,10,10,50,8 + GROUPBOX "Format",IDC_STATIC,7,42,129,43 + CONTROL "Jpeg standard (JPG)",IDC_RADIO1,"Button", + BS_AUTORADIOBUTTON | WS_GROUP,15,54,80,10 + CONTROL "Jpeg 2000 (JPC, JP2)",IDC_RADIO2,"Button", + BS_AUTORADIOBUTTON,15,67,84,10 +END + + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 5,9,9,3 + PRODUCTVERSION 5,9,9,3 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x29L +#else + FILEFLAGS 0x28L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", " \0" + VALUE "CompanyName", "www.xdp.it\0" + VALUE "FileDescription", "DEMO CxImage Application\0" + VALUE "FileVersion", "5, 9, 9, 3\0" + VALUE "InternalName", "DEMO\0" + VALUE "LegalCopyright", " © Davide Pizzolato 2001-2004\0" + VALUE "LegalTrademarks", "Freeware\0" + VALUE "OriginalFilename", "DEMO.EXE\0" + VALUE "PrivateBuild", "5\0" + VALUE "ProductName", "CxImage\0" + VALUE "ProductVersion", "5, 9, 9, 3\0" + VALUE "SpecialBuild", "0\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // !_MAC + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 238 + TOPMARGIN, 7 + BOTTOMMARGIN, 247 + END + + IDD_ROTATE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 136 + TOPMARGIN, 6 + BOTTOMMARGIN, 107 + END + + IDD_CAPTURE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 290 + TOPMARGIN, 7 + BOTTOMMARGIN, 74 + END + + IDD_RESAMPLE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 145 + TOPMARGIN, 6 + BOTTOMMARGIN, 101 + END + + IDD_DECBPP, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 124 + TOPMARGIN, 7 + BOTTOMMARGIN, 99 + END + + IDD_INCBPP, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 125 + TOPMARGIN, 7 + BOTTOMMARGIN, 64 + END + + IDD_OPTIONS, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 186 + TOPMARGIN, 7 + BOTTOMMARGIN, 197 + END + + IDD_DITHER, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 142 + TOPMARGIN, 7 + BOTTOMMARGIN, 115 + END + + IDD_THRESHOLD, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 136 + TOPMARGIN, 6 + BOTTOMMARGIN, 39 + END + + IDD_COLORIZE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 159 + TOPMARGIN, 6 + BOTTOMMARGIN, 120 + END + + IDD_OPACITY, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 136 + TOPMARGIN, 6 + BOTTOMMARGIN, 39 + END + + IDD_DWNURL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 280 + TOPMARGIN, 7 + BOTTOMMARGIN, 39 + END + + IDD_GAMMA, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 136 + TOPMARGIN, 6 + BOTTOMMARGIN, 39 + END + + IDD_HISTO, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 179 + TOPMARGIN, 7 + BOTTOMMARGIN, 108 + END + + IDD_PALETTE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 264 + TOPMARGIN, 7 + BOTTOMMARGIN, 129 + END + + IDD_COMBINE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 235 + TOPMARGIN, 7 + BOTTOMMARGIN, 112 + END + + IDD_FFT, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 245 + TOPMARGIN, 7 + BOTTOMMARGIN, 72 + END + + IDD_REPAIR, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 179 + TOPMARGIN, 7 + BOTTOMMARGIN, 52 + END + + IDD_TEXT, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 254 + TOPMARGIN, 6 + BOTTOMMARGIN, 160 + END + + IDD_MIX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 238 + TOPMARGIN, 7 + BOTTOMMARGIN, 171 + END + + IDD_SKEW, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 144 + TOPMARGIN, 7 + BOTTOMMARGIN, 115 + END + + IDD_JPEG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 136 + TOPMARGIN, 6 + BOTTOMMARGIN, 85 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog Info +// + +IDD_COMBINE DLGINIT +BEGIN + IDC_COMBO5, 0x403, 5, 0 +0x7267, 0x7961, "\000" + IDC_COMBO5, 0x403, 4, 0 +0x6572, 0x0064, + IDC_COMBO5, 0x403, 6, 0 +0x7267, 0x6565, 0x006e, + IDC_COMBO5, 0x403, 5, 0 +0x6c62, 0x6575, "\000" + IDC_COMBO6, 0x403, 5, 0 +0x7267, 0x7961, "\000" + IDC_COMBO6, 0x403, 4, 0 +0x6572, 0x0064, + IDC_COMBO6, 0x403, 6, 0 +0x7267, 0x6565, 0x006e, + IDC_COMBO6, 0x403, 5, 0 +0x6c62, 0x6575, "\000" + IDC_COMBO7, 0x403, 5, 0 +0x7267, 0x7961, "\000" + IDC_COMBO7, 0x403, 4, 0 +0x6572, 0x0064, + IDC_COMBO7, 0x403, 6, 0 +0x7267, 0x6565, 0x006e, + IDC_COMBO7, 0x403, 5, 0 +0x6c62, 0x6575, "\000" + IDC_COMBO8, 0x403, 5, 0 +0x7267, 0x7961, "\000" + IDC_COMBO8, 0x403, 4, 0 +0x6572, 0x0064, + IDC_COMBO8, 0x403, 6, 0 +0x7267, 0x6565, 0x006e, + IDC_COMBO8, 0x403, 5, 0 +0x6c62, 0x6575, "\000" + IDC_COMBO9, 0x403, 4, 0 +0x4752, 0x0042, + IDC_COMBO9, 0x403, 4, 0 +0x5348, 0x004c, + IDC_COMBO9, 0x403, 4, 0 +0x5559, 0x0056, + IDC_COMBO9, 0x403, 4, 0 +0x4959, 0x0051, + IDC_COMBO9, 0x403, 4, 0 +0x5958, 0x005a, + 0 +END + +IDD_REPAIR DLGINIT +BEGIN + IDC_COMBO9, 0x403, 4, 0 +0x4752, 0x0042, + IDC_COMBO9, 0x403, 4, 0 +0x5348, 0x004c, + IDC_COMBO9, 0x403, 4, 0 +0x5559, 0x0056, + IDC_COMBO9, 0x403, 4, 0 +0x4959, 0x0051, + IDC_COMBO9, 0x403, 4, 0 +0x5958, 0x005a, + 0 +END + +IDD_ROTATE DLGINIT +BEGIN + IDC_COMBO_IM, 0x403, 18, 0 +0x654e, 0x7261, 0x7365, 0x2074, 0x656e, 0x6769, 0x6268, 0x756f, 0x0072, + + IDC_COMBO_IM, 0x403, 9, 0 +0x6942, 0x696c, 0x656e, 0x7261, "\000" + IDC_COMBO_IM, 0x403, 15, 0 +0x6942, 0x7563, 0x6962, 0x2063, 0x6828, 0x7261, 0x2964, "\000" + IDC_COMBO_IM, 0x403, 17, 0 +0x6942, 0x7563, 0x6962, 0x2063, 0x2032, 0x7328, 0x666f, 0x2974, "\000" + IDC_COMBO_IM, 0x403, 15, 0 +0x5342, 0x6c70, 0x6e69, 0x2065, 0x6228, 0x756c, 0x2972, "\000" + IDC_COMBO_IM, 0x403, 16, 0 +0x614c, 0x7a6e, 0x6f63, 0x2073, 0x7328, 0x6168, 0x7072, 0x0029, + IDC_COMBO_IM, 0x403, 8, 0 +0x6548, 0x6d72, 0x7469, 0x0065, + IDC_COMBO_OM, 0x403, 28, 0 +0x6142, 0x6b63, 0x7267, 0x756f, 0x646e, 0x2820, 0x726f, 0x5b20, 0x2c30, +0x5d30, 0x6320, 0x6c6f, 0x726f, 0x0029, + IDC_COMBO_OM, 0x403, 22, 0 +0x6142, 0x6b63, 0x7267, 0x756f, 0x646e, 0x2820, 0x726f, 0x4220, 0x616c, +0x6b63, 0x0029, + IDC_COMBO_OM, 0x403, 22, 0 +0x6142, 0x6b63, 0x7267, 0x756f, 0x646e, 0x2820, 0x726f, 0x5720, 0x6968, +0x6574, 0x0029, + IDC_COMBO_OM, 0x403, 5, 0 +0x7257, 0x7061, "\000" + IDC_COMBO_OM, 0x403, 7, 0 +0x6552, 0x6570, 0x7461, "\000" + IDC_COMBO_OM, 0x403, 7, 0 +0x694d, 0x7272, 0x726f, "\000" + IDC_COMBO_OM, 0x403, 12, 0 +0x7254, 0x6e61, 0x7073, 0x7261, 0x6e65, 0x0074, + 0 +END + +IDD_RESAMPLE DLGINIT +BEGIN + IDC_COMBO_IM, 0x403, 18, 0 +0x654e, 0x7261, 0x7365, 0x2074, 0x656e, 0x6769, 0x6268, 0x756f, 0x0072, + + IDC_COMBO_IM, 0x403, 24, 0 +0x6942, 0x696c, 0x656e, 0x7261, 0x2820, 0x6970, 0x6578, 0x206c, 0x6f63, +0x6e72, 0x7265, 0x0029, + IDC_COMBO_IM, 0x403, 26, 0 +0x6942, 0x696c, 0x656e, 0x7261, 0x3220, 0x2820, 0x6970, 0x6578, 0x206c, +0x6563, 0x746e, 0x7265, 0x0029, + IDC_COMBO_IM, 0x403, 15, 0 +0x6942, 0x7563, 0x6962, 0x2063, 0x6828, 0x7261, 0x2964, "\000" + IDC_COMBO_IM, 0x403, 17, 0 +0x6942, 0x7563, 0x6962, 0x2063, 0x2032, 0x7328, 0x666f, 0x2974, "\000" + IDC_COMBO_IM, 0x403, 15, 0 +0x5342, 0x6c70, 0x6e69, 0x2065, 0x6228, 0x756c, 0x2972, "\000" + IDC_COMBO_IM, 0x403, 16, 0 +0x614c, 0x7a6e, 0x6f63, 0x2073, 0x7328, 0x6168, 0x7072, 0x0029, + IDC_COMBO_IM, 0x403, 8, 0 +0x6548, 0x6d72, 0x7469, 0x0065, + 0 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// JPG +// + +IDR_JPG1 JPG DISCARDABLE "res\\bg.jpg" +IDR_JPG2 JPG DISCARDABLE "res\\bg2.jpg" + +///////////////////////////////////////////////////////////////////////////// +// +// ICO +// + +IDR_ICO1 ICO DISCARDABLE "res\\ico2.bin" + +///////////////////////////////////////////////////////////////////////////// +// +// GIF +// + +IDR_GIF1 GIF DISCARDABLE "res\\bg.gif" + +///////////////////////////////////////////////////////////////////////////// +// +// PNG +// + +IDR_PNG1 PNG DISCARDABLE "res\\us.png" + +///////////////////////////////////////////////////////////////////////////// +// +// TIF +// + +IDR_TIF1 TIF DISCARDABLE "res\\bg.tif" + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE PRELOAD DISCARDABLE +BEGIN + IDR_MAINFRAME "demo" + IDR_DEMOTYPE "\nDemo\nDemo\n\n\nDemo.Document\nDemo Document" +END + +STRINGTABLE PRELOAD DISCARDABLE +BEGIN + AFX_IDS_APP_TITLE "demo" + AFX_IDS_IDLEMESSAGE "Ready" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_INDICATOR_EXT "EXT" + ID_INDICATOR_CAPS "CAP" + ID_INDICATOR_NUM "NUM" + ID_INDICATOR_SCRL "SCRL" + ID_INDICATOR_OVR "OVR" + ID_INDICATOR_REC "REC" + ID_INDICATOR1 " " + ID_INDICATOR2 " " + ID_INDICATOR3 " " + ID_INDICATOR4 " " +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_FILE_NEW "Create a new document\nNew" + ID_FILE_OPEN "Open an existing document\nOpen" + ID_FILE_CLOSE "Close the active document\nClose" + ID_FILE_SAVE "Save the active document\nSave" + ID_FILE_SAVE_AS "Save the active document with a new name\nSave As" + ID_FILE_PAGE_SETUP "Change the printing options\nPage Setup" + ID_FILE_PRINT_SETUP "Change the printer and printing options\nPrint Setup" + ID_FILE_PRINT "Print the active document\nPrint" + ID_FILE_PRINT_PREVIEW "Display full pages\nPrint Preview" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_APP_ABOUT "Display program information, version number and copyright\nAbout" + ID_APP_EXIT "Quit the application; prompts to save documents\nExit" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_FILE_MRU_FILE1 "Open this document" + ID_FILE_MRU_FILE2 "Open this document" + ID_FILE_MRU_FILE3 "Open this document" + ID_FILE_MRU_FILE4 "Open this document" + ID_FILE_MRU_FILE5 "Open this document" + ID_FILE_MRU_FILE6 "Open this document" + ID_FILE_MRU_FILE7 "Open this document" + ID_FILE_MRU_FILE8 "Open this document" + ID_FILE_MRU_FILE9 "Open this document" + ID_FILE_MRU_FILE10 "Open this document" + ID_FILE_MRU_FILE11 "Open this document" + ID_FILE_MRU_FILE12 "Open this document" + ID_FILE_MRU_FILE13 "Open this document" + ID_FILE_MRU_FILE14 "Open this document" + ID_FILE_MRU_FILE15 "Open this document" + ID_FILE_MRU_FILE16 "Open this document" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_NEXT_PANE "Switch to the next window pane\nNext Pane" + ID_PREV_PANE "Switch back to the previous window pane\nPrevious Pane" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_WINDOW_NEW "Open another window for the active document\nNew Window" + ID_WINDOW_ARRANGE "Arrange icons at the bottom of the window\nArrange Icons" + ID_WINDOW_CASCADE "Arrange windows so they overlap\nCascade Windows" + ID_WINDOW_TILE_HORZ "Arrange windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_TILE_VERT "Arrange windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_SPLIT "Split the active window into panes\nSplit" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_EDIT_CLEAR "Erase the selection\nErase" + ID_EDIT_CLEAR_ALL "Erase everything\nErase All" + ID_EDIT_COPY "Copy the selection and put it on the Clipboard\nCopy" + ID_EDIT_CUT "Cut the selection and put it on the Clipboard\nCut" + ID_EDIT_FIND "Find the specified text\nFind" + ID_EDIT_PASTE "Insert Clipboard contents\nPaste" + ID_EDIT_REPEAT "Repeat the last action\nRepeat" + ID_EDIT_REPLACE "Replace specific text with different text\nReplace" + ID_EDIT_SELECT_ALL "Select the entire document\nSelect All" + ID_EDIT_UNDO "Undo the last action\nUndo" + ID_EDIT_REDO "Redo the previously undone action\nRedo" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_VIEW_TOOLBAR "Show or hide the toolbar\nToggle ToolBar" + ID_VIEW_STATUS_BAR "Show or hide the status bar\nToggle StatusBar" +END + +STRINGTABLE DISCARDABLE +BEGIN + AFX_IDS_SCSIZE "Change the window size" + AFX_IDS_SCMOVE "Change the window position" + AFX_IDS_SCMINIMIZE "Reduce the window to an icon" + AFX_IDS_SCMAXIMIZE "Enlarge the window to full size" + AFX_IDS_SCNEXTWINDOW "Switch to the next document window" + AFX_IDS_SCPREVWINDOW "Switch to the previous document window" + AFX_IDS_SCCLOSE "Close the active window and prompts to save the documents" +END + +STRINGTABLE DISCARDABLE +BEGIN + AFX_IDS_SCRESTORE "Restore the window to normal size" + AFX_IDS_SCTASKLIST "Activate Task List" + AFX_IDS_MDICHILD "Activate this window" +END + +STRINGTABLE DISCARDABLE +BEGIN + AFX_IDS_PREVIEW_CLOSE "Close print preview mode\nCancel Preview" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_STRETCH_MODE "Set stretch mode\nStretch mode" + ID_TRANSFORM_ELLIPSE "Ellipse transform\nEllipse transform" + ID_IMAGE_FROM_BITMAP "Make CxImage from Resource\nCxImage from Resource" + ID_CXIMAGE_MIRROR "Mirror\nMirror" + ID_CXIMAGE_FLIP "Flip\nFlip" + ID_WINDOW_DUPLICATE "Duplicate\nDuplicate" + ID_CXIMAGE_NEGATIVE "Negative\nNegative" + ID_CXIMAGE_GRAYSCALE "Gray Scale" + ID_CXIMAGE_ROTATE "Rotate" + ID_CXIMAGE_LOADJPEGRESOURCE "Load JPEG Resource" + ID_CXIMAGE_LOADICONRESOURCE "Load Icon Resource" + ID_CXIMAGE_LOADGIFRESOURCE "Load Gif Resource" + ID_CXIMAGE_LOADPNGRESOURCE "Load Png Resource" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_VIEW_ZOOMIN "Zoom In\nZoom In" + ID_VIEW_ZOOMOUT "Zoom Out\nZoom Out" + ID_VIEW_NORMALVIEWING11 "Normal Viewing (1:1)\nNormal View" + ID_FILE_CAPTURE "Capture..." + ID_CXIMAGE_LOADTIFRESOURCE "Load Tif Resource" + ID_WINDOW_CLOSEALL "Close all" + ID_CXIMAGE_SETTRANSPARENCY "Set Transparency... (click on the image)" + ID_CXIMAGE_REMOVETRANSPARENCY "Remove Transparency" + ID_CXIMAGE_RESAMPLE "Resample" + ID_CXIMAGE_DECREASEBPP "Decrease Bpp..." + ID_CXIMAGE_INCREASEBPP "Increase Bpp..." + ID_CXIMAGE_OPTIONS "Options..." + ID_CXIMAGE_DITHER "Dither" + ID_CXIMAGE_THRESHOLD "Threshold" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_CXIMAGE_EDGE "Edge" + ID_CXIMAGE_ERODE "Erode" + ID_CXIMAGE_DILATE "Dilate" + ID_FILE_SELECTSOURCE "Select Source...\nSelect Source..." + ID_FILE_ACQUIRE "Acquire from Twain source\nAcquire" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_CXIMAGE_SPLITRGB "Split RGB" + ID_CXIMAGE_SPLITYUV "Split YUV" + ID_CXIMAGE_SPLITHSL "Split HSL" + ID_CXIMAGE_PSEUDOCOLORS "Pseudo Colors" + ID_CXIMAGE_SPLITCHANNELS "Split Channels" + ID_CXIMAGE_RESOURCES "Resources" + ID_CXIMAGE_COLORIZE "Colorize..." + ID_CXIMAGE_LIGHTEN "Lighten" + ID_CXIMAGE_DARKEN "Darken" + ID_CXIMAGE_CONTRAST "More Contrast" + ID_CXIMAGE_EMBOSS "Emboss" + ID_CXIMAGE_BLUR "Blur" + ID_CXIMAGE_SOFTEN "Soften" + ID_CXIMAGE_SHARPEN "Sharpen" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_CXIMAGE_CROP "Crop" + ID_CXIMAGE_REMOVEALPHACHANNEL "Remove Alpha Channel" + ID_CXIMAGE_OPACITY "Opacity" + ID_CXIMAGE_INVETALPHA "Invert Alpha Channel" + ID_CXIMAGE_ALPHAPALETTETOGGLE "Toggle Alpha Palette " + ID_CXIMAGE_ALPHASTRIP "Strip Alpha" + ID_CXIMAGE_ROTATEL "Rotate Left" + ID_CXIMAGE_ROTATER "Rotate Right" + ID_CXIMAGE_DEMOSAVEMULTIPAGETIFF "Creates a multi page TIF file " + ID_CXIMAGE_DEMOSAVEANIMATEDGIF "Demo Save Animated GIF" + ID_CXIMAGE_DOWNLOADFROMURL "Download from URL " + ID_CXIMAGE_GAMMA "Gamma" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_VIEW_MENUSTYLE_NORMAL "Default" + ID_VIEW_MENUSTYLE_XP "XP" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_CXIMAGE_MEDIAN "Median" + ID_CXIMAGE_ADDNOISE "Noise" + ID_VIEW_TOOLS_MOVE "Move\nMove" + ID_VIEW_TOOLS_SELECT "Left = Free Hand / Left+Shift = Rect --> Right = Rotate / Right+CTRL = Move\nSelect" + ID_VIEW_FULLSCREEN "Full Screen" + ID_VIEW_TOOLS_ZOOM "Zoom\nZoom" + ID_VIEW_HISTOGRAM "Histogram\nHistogram" + ID_VIEW_PALETTE "Palette\nPalette" + ID_CXIMAGE_COMBINE "Combine" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_CXIMAGE_FFT "FFT" + ID_CXIMAGE_SPLITYIQ "Split YIQ" + ID_CXIMAGE_SPLITXYZ "Split XYZ" + ID_CXIMAGE_REPAIR "Repair..." + ID_FILTERS_SPLIT "Split" + ID_CXIMAGE_ALPHACHANNEL_SPLIT "Split" + ID_VIEW_TOOLS_TEXT "Text" + ID_CXIMAGE_SPLITCMYK "Split to CMYK" + ID_CXIMAGE_ALPHACREATE "Create from lightness" + ID_CXIMAGE_HISTOGRAM_STRETCH "Stretch" + ID_CXIMAGE_HISTOGRAM_EQUALIZE "Equalize" + ID_CXIMAGE_HISTOGRAM_NORMALIZE "Normalize" + ID_CXIMAGE_HISTOGRAM_LOG "Log" + ID_CXIMAGE_HISTOGRAM_ROOT "Root" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_CXIMAGE_GAUSSIAN3X3 "Gaussian 3x3" + ID_CXIMAGE_GAUSSIAN5X5 "Gaussian 5x5" + ID_CXIMAGE_CONTOUR "Contour" + ID_CXIMAGE_FILTERS_LESSCONTRAST "Less Contrast" + ID_CXIMAGE_LESSCONTRAST "Less Contrast" + ID_CXIMAGE_JITTER "Jitter" + ID_FILTERS_MIX "Mix" + ID_CXIMAGE_CIRCLETRANSFORM_PINCH "Pinch" + ID_CXIMAGE_CIRCLETRANSFORM_PUNCH "Punch" + ID_CXIMAGE_CIRCLETRANSFORM_SWIRL "Twirl" + ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER "Cylinder" + ID_FILTERS_CIRCLETRANSFORM_BATHROOM "bathroom" + ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM "bathroom" + ID_CXIMAGE_DEMOCREATEFROMARRAY "CreateFromArray" + ID_CXIMAGE_HISTOGRAM_STRETCH1 "Stretch1" +END + +STRINGTABLE DISCARDABLE +BEGIN + ID_CXIMAGE_HISTOGRAM_STRETCH2 "Stretch2" + ID_FILTERS_NONLINEAR "Non Linear Filters" + ID_FILTERS_NONLINEAR_EDGE "Edge" + ID_CXIMAGE_SKEW "Skew" + ID_VIEW_TOOLS_TRACKER "Tracker" + ID_FILTERS_JPEGCOMPRESSION "JPEG compression ..." + ID_VIEW_SMOOTH "Smooth" +END + +#endif // Neutral resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// English (U.K.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1252)\r\n" + "#endif\r\n" + "#include ""res\\demo.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "#include ""afxprint.rc"" // printing/print preview resources\r\n" + "#endif\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // English (U.K.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE 9, 1 +#pragma code_page(1252) +#endif +#include "res\demo.rc2" // non-Microsoft Visual C++ edited resources +#include "afxres.rc" // Standard components +#include "afxprint.rc" // printing/print preview resources +#endif +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/SlnkDWFImpl/CxImage/demo/demo.sln b/SlnkDWFImpl/CxImage/demo/demo.sln new file mode 100644 index 0000000..1f7e58d --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 7.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "demo", "demo.vcproj", "{474B3F54-51BF-46A5-B172-4D56E102EDEE}" +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + ConfigName.0 = Debug + ConfigName.1 = Release + EndGlobalSection + GlobalSection(ProjectDependencies) = postSolution + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {474B3F54-51BF-46A5-B172-4D56E102EDEE}.Debug.ActiveCfg = Debug|Win32 + {474B3F54-51BF-46A5-B172-4D56E102EDEE}.Debug.Build.0 = Debug|Win32 + {474B3F54-51BF-46A5-B172-4D56E102EDEE}.Release.ActiveCfg = Release|Win32 + {474B3F54-51BF-46A5-B172-4D56E102EDEE}.Release.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/SlnkDWFImpl/CxImage/demo/demo.vcproj b/SlnkDWFImpl/CxImage/demo/demo.vcproj new file mode 100644 index 0000000..3755210 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.vcproj @@ -0,0 +1,1170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/demo/demo.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/demo/demo.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..ec3b65e --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demo.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/demo/demoDLL.dsp b/SlnkDWFImpl/CxImage/demo/demoDLL.dsp new file mode 100644 index 0000000..ff5392b --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demoDLL.dsp @@ -0,0 +1,455 @@ +# Microsoft Developer Studio Project File - Name="demoDll" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Application" 0x0101 + +CFG=demoDll - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "demoDLL.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "demoDLL.mak" CFG="demoDll - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "demoDll - Win32 Release" (based on "Win32 (x86) Application") +!MESSAGE "demoDll - Win32 Debug" (based on "Win32 (x86) Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "demoDll - Win32 Release" + +# PROP BASE Use_MFC 6 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "demoDll___Win32_Release" +# PROP BASE Intermediate_Dir "demoDll___Win32_Release" +# PROP BASE Ignore_Export_Lib 0 +# PROP BASE Target_Dir "" +# PROP Use_MFC 6 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "ReleaseDll" +# PROP Intermediate_Dir "ReleaseDll" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /I "..\cximage" /I "..\jpeg" /I "..\zlib" /I "..\png" /I "..\mng" /I "..\tiff" /I "..\j2000" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /FD /c +# SUBTRACT BASE CPP /YX /Yc /Yu +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\cximage" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /D "VATI_EXTENSIONS" /FD /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "NDEBUG" /d "_AFXDLL" +# ADD RSC /l 0x809 /d "NDEBUG" /d "_AFXDLL" /d "VATI_EXTENSIONS" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 wininet.lib ../cximage/CxImageDLL/Release/cximagecrt.lib /nologo /subsystem:windows /machine:I386 /out:"../bin/demodll.exe" +# ADD LINK32 wininet.lib ../cximage/CxImageDLL/Release/cximagecrt.lib /nologo /subsystem:windows /machine:I386 /out:"../bin/demodll.exe" + +!ELSEIF "$(CFG)" == "demoDll - Win32 Debug" + +# PROP BASE Use_MFC 6 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "demoDll___Win32_Debug" +# PROP BASE Intermediate_Dir "demoDll___Win32_Debug" +# PROP BASE Ignore_Export_Lib 0 +# PROP BASE Target_Dir "" +# PROP Use_MFC 6 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "DebugDll" +# PROP Intermediate_Dir "DebugDll" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\cximage" /I "..\jpeg" /I "..\zlib" /I "..\png" /I "..\mng" /I "..\tiff" /I "..\j2000" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /FD /c +# SUBTRACT BASE CPP /Fr /YX /Yc /Yu +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\cximage" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /D "VATI_EXTENSIONS" /FD /c +# SUBTRACT CPP /Fr /YX /Yc /Yu +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "_DEBUG" /d "_AFXDLL" +# ADD RSC /l 0x809 /d "_DEBUG" /d "_AFXDLL" /d "VATI_EXTENSIONS" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 wininet.lib ../cximage/CxImageDLL/Debug/cximagecrtd.lib /nologo /subsystem:windows /debug /machine:I386 /out:"../bin/demoddll.exe" +# ADD LINK32 wininet.lib ../cximage/CxImageDLL/Debug/cximagecrtd.lib /nologo /subsystem:windows /debug /machine:I386 /out:"../bin/demoddll.exe" + +!ENDIF + +# Begin Target + +# Name "demoDll - Win32 Release" +# Name "demoDll - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90" +# Begin Source File + +SOURCE=.\BCMenu.cpp +# End Source File +# Begin Source File + +SOURCE=.\ChildFrm.cpp +# End Source File +# Begin Source File + +SOURCE=.\demo.cpp +# End Source File +# Begin Source File + +SOURCE=.\demo.rc +# End Source File +# Begin Source File + +SOURCE=.\demoDoc.cpp +# End Source File +# Begin Source File + +SOURCE=.\demoView.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgCapture.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgColorize.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgCombine.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgDecBpp.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgDither.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgFFT.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgGamma.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgHisto.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgIncBpp.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgJpeg.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgMix.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgOpacity.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgOptions.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgPalette.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgRepair.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgResample.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgRotate.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgSkew.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgText.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgThreshold.cpp +# End Source File +# Begin Source File + +SOURCE=.\DlgURL.cpp +# End Source File +# Begin Source File + +SOURCE=.\logomdi.cpp +# End Source File +# Begin Source File + +SOURCE=.\MainFrm.cpp +# End Source File +# Begin Source File + +SOURCE=.\Quantize.cpp +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.cpp +# ADD BASE CPP /Yc"stdafx.h" +# ADD CPP /Yc"stdafx.h" +# End Source File +# Begin Source File + +SOURCE=.\TwainCpp.cpp +# End Source File +# Begin Source File + +SOURCE=.\xTargetButton.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" +# Begin Source File + +SOURCE=.\BCMenu.h +# End Source File +# Begin Source File + +SOURCE=.\ChildFrm.h +# End Source File +# Begin Source File + +SOURCE=.\demo.h +# End Source File +# Begin Source File + +SOURCE=.\demoDoc.h +# End Source File +# Begin Source File + +SOURCE=.\demoView.h +# End Source File +# Begin Source File + +SOURCE=.\DlgCapture.h +# End Source File +# Begin Source File + +SOURCE=.\DlgColorize.h +# End Source File +# Begin Source File + +SOURCE=.\DlgCombine.h +# End Source File +# Begin Source File + +SOURCE=.\DlgDecBpp.h +# End Source File +# Begin Source File + +SOURCE=.\DlgDither.h +# End Source File +# Begin Source File + +SOURCE=.\DlgFFT.h +# End Source File +# Begin Source File + +SOURCE=.\DlgGamma.h +# End Source File +# Begin Source File + +SOURCE=.\DlgHisto.h +# End Source File +# Begin Source File + +SOURCE=.\DlgIncBpp.h +# End Source File +# Begin Source File + +SOURCE=.\DlgJpeg.h +# End Source File +# Begin Source File + +SOURCE=.\DlgMix.h +# End Source File +# Begin Source File + +SOURCE=.\DlgOpacity.h +# End Source File +# Begin Source File + +SOURCE=.\DlgOptions.h +# End Source File +# Begin Source File + +SOURCE=.\DlgPalette.h +# End Source File +# Begin Source File + +SOURCE=.\DlgRepair.h +# End Source File +# Begin Source File + +SOURCE=.\DlgResample.h +# End Source File +# Begin Source File + +SOURCE=.\DlgRotate.h +# End Source File +# Begin Source File + +SOURCE=.\DlgSkew.h +# End Source File +# Begin Source File + +SOURCE=.\DlgText.h +# End Source File +# Begin Source File + +SOURCE=.\DlgThreshold.h +# End Source File +# Begin Source File + +SOURCE=.\DlgURL.h +# End Source File +# Begin Source File + +SOURCE=.\logomdi.h +# End Source File +# Begin Source File + +SOURCE=.\MainFrm.h +# End Source File +# Begin Source File + +SOURCE=.\Quantize.h +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.h +# End Source File +# Begin Source File + +SOURCE=.\TwainCpp.h +# End Source File +# Begin Source File + +SOURCE=.\xTargetButton.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" +# Begin Source File + +SOURCE=.\res\b1.ico +# End Source File +# Begin Source File + +SOURCE=.\res\bg.BMP +# End Source File +# Begin Source File + +SOURCE=.\res\bg.gif +# End Source File +# Begin Source File + +SOURCE=.\res\bg.jpg +# End Source File +# Begin Source File + +SOURCE=.\res\bg2.jpg +# End Source File +# Begin Source File + +SOURCE=.\res\canc.ico +# End Source File +# Begin Source File + +SOURCE=.\res\demo.ico +# End Source File +# Begin Source File + +SOURCE=.\res\demo.rc2 +# End Source File +# Begin Source File + +SOURCE=.\res\demoDoc.ico +# End Source File +# Begin Source File + +SOURCE=.\res\Explorer.ico +# End Source File +# Begin Source File + +SOURCE=.\res\gray.ico +# End Source File +# Begin Source File + +SOURCE=.\res\ico2.bin +# End Source File +# Begin Source File + +SOURCE=.\res\icon1.ico +# End Source File +# Begin Source File + +SOURCE=.\res\no1.ico +# End Source File +# Begin Source File + +SOURCE=.\res\ok.ico +# End Source File +# Begin Source File + +SOURCE=.\res\r1.ico +# End Source File +# Begin Source File + +SOURCE=.\res\testbmp.bmp +# End Source File +# Begin Source File + +SOURCE=.\res\Toolbar.bmp +# End Source File +# Begin Source File + +SOURCE=.\res\toolbar1.bmp +# End Source File +# End Group +# Begin Source File + +SOURCE=.\res\bg.tif +# End Source File +# Begin Source File + +SOURCE=.\res\us.png +# End Source File +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/demo/demoDLL.vcproj b/SlnkDWFImpl/CxImage/demo/demoDLL.vcproj new file mode 100644 index 0000000..7e62874 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demoDLL.vcproj @@ -0,0 +1,1169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/demo/demoDLL.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/demo/demoDLL.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..ec3b65e --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demoDLL.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/demo/demoDoc.cpp b/SlnkDWFImpl/CxImage/demo/demoDoc.cpp new file mode 100644 index 0000000..ed99df3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demoDoc.cpp @@ -0,0 +1,2469 @@ +// demoDoc.cpp : implementation of the CDemoDoc class +// + +#include "stdafx.h" +#include "demo.h" + +#include "MainFrm.h" +#include "demoDoc.h" +#include "demoView.h" +#include "DlgRotate.h" +#include "DlgResample.h" +#include "DlgDecBpp.h" +#include "DlgIncBpp.h" +#include "DlgOptions.h" +#include "DlgDither.h" +#include "DlgThreshold.h" +#include "DlgColorize.h" +#include "Quantize.h" +#include "DlgOpacity.h" +#include "DlgGamma.h" +#include "DlgPalette.h" +#include "DlgCombine.h" +#include "DlgFFT.h" +#include "DlgRepair.h" +#include "DlgText.h" +#include "DlgMix.h" +#include "DlgSkew.h" +#include "DlgJpeg.h" + +#include "ximage.h" +#include +#include + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +////////////////////////////////////////////////////////////////////////////// +// CDemoDoc + +IMPLEMENT_DYNCREATE(CDemoDoc, CDocument) + +BEGIN_MESSAGE_MAP(CDemoDoc, CDocument) + //{{AFX_MSG_MAP(CDemoDoc) + ON_UPDATE_COMMAND_UI(ID_FILE_SAVE_AS, OnUpdateFileSaveAs) + ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, OnUpdateFileSave) + ON_COMMAND(ID_STRETCH_MODE, OnStretchMode) + ON_UPDATE_COMMAND_UI(ID_STRETCH_MODE, OnUpdateStretchMode) + ON_COMMAND(ID_TRANSFORM_ELLIPSE, OnTransformEllipse) + ON_COMMAND(ID_WINDOW_DUPLICATE, OnWindowDuplicate) + ON_COMMAND(ID_EDIT_COPY, OnEditCopy) + ON_COMMAND(ID_CXIMAGE_FLIP, OnCximageFlip) + ON_COMMAND(ID_CXIMAGE_MIRROR, OnCximageMirror) + ON_COMMAND(ID_CXIMAGE_NEGATIVE, OnCximageNegative) + ON_COMMAND(ID_CXIMAGE_GRAYSCALE, OnCximageGrayscale) + ON_COMMAND(ID_CXIMAGE_ROTATE, OnCximageRotate) + ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo) + ON_COMMAND(ID_EDIT_REDO, OnEditRedo) + ON_COMMAND(ID_EDIT_UNDO, OnEditUndo) + ON_UPDATE_COMMAND_UI(ID_EDIT_REDO, OnUpdateEditRedo) + ON_COMMAND(ID_VIEW_ZOOMIN, OnViewZoomin) + ON_COMMAND(ID_VIEW_ZOOMOUT, OnViewZoomout) + ON_UPDATE_COMMAND_UI(ID_VIEW_ZOOMIN, OnUpdateViewZoomin) + ON_UPDATE_COMMAND_UI(ID_VIEW_ZOOMOUT, OnUpdateViewZoomout) + ON_COMMAND(ID_VIEW_NORMALVIEWING11, OnViewNormalviewing11) + ON_UPDATE_COMMAND_UI(ID_VIEW_NORMALVIEWING11, OnUpdateViewNormalviewing11) + ON_COMMAND(ID_CXIMAGE_SETTRANSPARENCY, OnCximageSettransparency) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SETTRANSPARENCY, OnUpdateCximageSettransparency) + ON_COMMAND(ID_CXIMAGE_REMOVETRANSPARENCY, OnCximageRemovetransparency) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_REMOVETRANSPARENCY, OnUpdateCximageRemovetransparency) + ON_COMMAND(ID_CXIMAGE_RESAMPLE, OnCximageResample) + ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_FLIP, OnUpdateCximageFlip) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GRAYSCALE, OnUpdateCximageGrayscale) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_MIRROR, OnUpdateCximageMirror) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_NEGATIVE, OnUpdateCximageNegative) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_RESAMPLE, OnUpdateCximageResample) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ROTATE, OnUpdateCximageRotate) + ON_UPDATE_COMMAND_UI(ID_TRANSFORM_ELLIPSE, OnUpdateTransformEllipse) + ON_COMMAND(ID_CXIMAGE_DECREASEBPP, OnCximageDecreasebpp) + ON_COMMAND(ID_CXIMAGE_INCREASEBPP, OnCximageIncreasebpp) + ON_COMMAND(ID_CXIMAGE_OPTIONS, OnCximageOptions) + ON_COMMAND(ID_CXIMAGE_DITHER, OnCximageDither) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_DITHER, OnUpdateCximageDither) + ON_COMMAND(ID_CXIMAGE_THRESHOLD, OnCximageThreshold) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_THRESHOLD, OnUpdateCximageThreshold) + ON_COMMAND(ID_CXIMAGE_SPLITRGB, OnCximageSplitrgb) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITRGB, OnUpdateCximageSplitrgb) + ON_COMMAND(ID_CXIMAGE_SPLITYUV, OnCximageSplityuv) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITYUV, OnUpdateCximageSplityuv) + ON_COMMAND(ID_CXIMAGE_SPLITHSL, OnCximageSplithsl) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITHSL, OnUpdateCximageSplithsl) + ON_COMMAND(ID_CXIMAGE_PSEUDOCOLORS, OnCximagePseudocolors) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_PSEUDOCOLORS, OnUpdateCximagePseudocolors) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_COLORIZE, OnUpdateCximageFiltersColorize) + ON_COMMAND(ID_CXIMAGE_COLORIZE, OnCximageFiltersColorize) + ON_COMMAND(ID_CXIMAGE_DARKEN, OnCximageDarken) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_DARKEN, OnUpdateCximageDarken) + ON_COMMAND(ID_CXIMAGE_LIGHTEN, OnCximageLighten) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_LIGHTEN, OnUpdateCximageLighten) + ON_COMMAND(ID_CXIMAGE_CONTRAST, OnCximageContrast) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CONTRAST, OnUpdateCximageContrast) + ON_COMMAND(ID_CXIMAGE_EMBOSS, OnCximageEmboss) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_EMBOSS, OnUpdateCximageEmboss) + ON_COMMAND(ID_CXIMAGE_BLUR, OnCximageBlur) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_BLUR, OnUpdateCximageBlur) + ON_COMMAND(ID_CXIMAGE_DILATE, OnCximageDilate) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_DILATE, OnUpdateCximageDilate) + ON_COMMAND(ID_CXIMAGE_EDGE, OnCximageEdge) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_EDGE, OnUpdateCximageEdge) + ON_COMMAND(ID_CXIMAGE_ERODE, OnCximageErode) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ERODE, OnUpdateCximageErode) + ON_COMMAND(ID_CXIMAGE_SHARPEN, OnCximageSharpen) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SHARPEN, OnUpdateCximageSharpen) + ON_COMMAND(ID_CXIMAGE_SOFTEN, OnCximageSoften) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SOFTEN, OnUpdateCximageSoften) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CROP, OnUpdateCximageCrop) + ON_COMMAND(ID_CXIMAGE_CROP, OnCximageCrop) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_REMOVEALPHACHANNEL, OnUpdateCximageRemovealphachannel) + ON_COMMAND(ID_CXIMAGE_REMOVEALPHACHANNEL, OnCximageRemovealphachannel) + ON_COMMAND(ID_CXIMAGE_OPACITY, OnCximageOpacity) + ON_COMMAND(ID_CXIMAGE_INVETALPHA, OnCximageInvetalpha) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_INVETALPHA, OnUpdateCximageInvetalpha) + ON_COMMAND(ID_CXIMAGE_ALPHAPALETTETOGGLE, OnCximageAlphapalettetoggle) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ALPHAPALETTETOGGLE, OnUpdateCximageAlphapalettetoggle) + ON_COMMAND(ID_CXIMAGE_ALPHASTRIP, OnCximageAlphastrip) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ALPHASTRIP, OnUpdateCximageAlphastrip) + ON_COMMAND(ID_CXIMAGE_ROTATEL, OnCximageRotatel) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ROTATEL, OnUpdateCximageRotatel) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ROTATER, OnUpdateCximageRotater) + ON_COMMAND(ID_CXIMAGE_ROTATER, OnCximageRotater) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GAMMA, OnUpdateCximageGamma) + ON_COMMAND(ID_CXIMAGE_GAMMA, OnCximageGamma) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_MEDIAN, OnUpdateCximageMedian) + ON_COMMAND(ID_CXIMAGE_MEDIAN, OnCximageMedian) + ON_COMMAND(ID_CXIMAGE_ADDNOISE, OnCximageAddnoise) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ADDNOISE, OnUpdateCximageAddnoise) + ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_MOVE, OnUpdateViewToolsMove) + ON_COMMAND(ID_VIEW_TOOLS_MOVE, OnViewToolsMove) + ON_COMMAND(ID_VIEW_TOOLS_SELECT, OnViewToolsSelect) + ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_SELECT, OnUpdateViewToolsSelect) + ON_COMMAND(ID_VIEW_TOOLS_ZOOM, OnViewToolsZoom) + ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_ZOOM, OnUpdateViewToolsZoom) + ON_UPDATE_COMMAND_UI(ID_VIEW_PALETTE, OnUpdateViewPalette) + ON_COMMAND(ID_VIEW_PALETTE, OnViewPalette) + ON_COMMAND(ID_CXIMAGE_COMBINE, OnCximageCombine) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_COMBINE, OnUpdateCximageCombine) + ON_COMMAND(ID_CXIMAGE_FFT, OnCximageFft) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_FFT, OnUpdateCximageFft) + ON_COMMAND(ID_CXIMAGE_SPLITYIQ, OnCximageSplityiq) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITYIQ, OnUpdateCximageSplityiq) + ON_COMMAND(ID_CXIMAGE_SPLITXYZ, OnCximageSplitxyz) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITXYZ, OnUpdateCximageSplitxyz) + ON_COMMAND(ID_CXIMAGE_REPAIR, OnCximageRepair) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_REPAIR, OnUpdateCximageRepair) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ALPHACHANNEL_SPLIT, OnUpdateCximageAlphachannelSplit) + ON_COMMAND(ID_CXIMAGE_ALPHACHANNEL_SPLIT, OnCximageAlphachannelSplit) + ON_COMMAND(ID_VIEW_TOOLS_TEXT, OnViewToolsText) + ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_TEXT, OnUpdateViewToolsText) + ON_COMMAND(ID_CXIMAGE_SPLITCMYK, OnCximageSplitcmyk) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITCMYK, OnUpdateCximageSplitcmyk) + ON_COMMAND(ID_CXIMAGE_ALPHACREATE, OnCximageAlphaCreate) + ON_COMMAND(ID_CXIMAGE_HISTOGRAM_LOG, OnCximageFiltersLog) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_LOG, OnUpdateCximageFiltersLog) + ON_COMMAND(ID_CXIMAGE_HISTOGRAM_ROOT, OnCximageFiltersRoot) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_ROOT, OnUpdateCximageFiltersRoot) + ON_COMMAND(ID_CXIMAGE_HISTOGRAM_EQUALIZE, OnCximageHistogramEqualize) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_EQUALIZE, OnUpdateCximageHistogramEqualize) + ON_COMMAND(ID_CXIMAGE_HISTOGRAM_NORMALIZE, OnCximageHistogramNormalize) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_NORMALIZE, OnUpdateCximageHistogramNormalize) + ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCH, OnCximageHistogramStretch) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCH, OnUpdateCximageHistogramStretch) + ON_COMMAND(ID_CXIMAGE_GAUSSIAN3X3, OnCximageGaussian3x3) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GAUSSIAN3X3, OnUpdateCximageGaussian3x3) + ON_COMMAND(ID_CXIMAGE_GAUSSIAN5X5, OnCximageGaussian5x5) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GAUSSIAN5X5, OnUpdateCximageGaussian5x5) + ON_COMMAND(ID_CXIMAGE_CONTOUR, OnCximageContour) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CONTOUR, OnUpdateCximageContour) + ON_COMMAND(ID_CXIMAGE_LESSCONTRAST, OnCximageLesscontrast) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_LESSCONTRAST, OnUpdateCximageLesscontrast) + ON_COMMAND(ID_CXIMAGE_JITTER, OnCximageJitter) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_JITTER, OnUpdateCximageJitter) + ON_UPDATE_COMMAND_UI(ID_WINDOW_DUPLICATE, OnUpdateWindowDuplicate) + ON_UPDATE_COMMAND_UI(ID_FILTERS_MIX, OnUpdateFiltersMix) + ON_COMMAND(ID_FILTERS_MIX, OnFiltersMix) + ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER, OnCximageCircletransformCylinder) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER, OnUpdateCximageCircletransformCylinder) + ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_PINCH, OnCximageCircletransformPinch) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_PINCH, OnUpdateCximageCircletransformPinch) + ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_PUNCH, OnCximageCircletransformPunch) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_PUNCH, OnUpdateCximageCircletransformPunch) + ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_SWIRL, OnCximageCircletransformSwirl) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_SWIRL, OnUpdateCximageCircletransformSwirl) + ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM, OnCximageCircletransformBathroom) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM, OnUpdateCximageCircletransformBathroom) + ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCH1, OnCximageHistogramStretch1) + ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCH2, OnCximageHistogramStretch2) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCH1, OnUpdateCximageHistogramStretch1) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCH2, OnUpdateCximageHistogramStretch2) + ON_COMMAND(ID_FILTERS_NONLINEAR_EDGE, OnFiltersNonlinearEdge) + ON_UPDATE_COMMAND_UI(ID_FILTERS_NONLINEAR_EDGE, OnUpdateFiltersNonlinearEdge) + ON_COMMAND(ID_CXIMAGE_SKEW, OnCximageSkew) + ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SKEW, OnUpdateCximageSkew) + ON_COMMAND(ID_VIEW_TOOLS_TRACKER, OnViewToolsTracker) + ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_TRACKER, OnUpdateViewToolsTracker) + ON_COMMAND(ID_FILTERS_JPEGCOMPRESSION, OnJpegcompression) + ON_UPDATE_COMMAND_UI(ID_FILTERS_JPEGCOMPRESSION, OnUpdateJpegcompression) + ON_COMMAND(ID_VIEW_SMOOTH, OnViewSmooth) + ON_UPDATE_COMMAND_UI(ID_VIEW_SMOOTH, OnUpdateViewSmooth) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +////////////////////////////////////////////////////////////////////////////// +// CDemoDoc construction/destruction +CDemoDoc::CDemoDoc() +{ + image = NULL; + m_WaitingClick = stretchMode = m_bSmoothDisplay = FALSE; + for (int i=0;iSetEscape(1); + // stop the progress bar + if (hProgress){ + ResumeThread(hProgress); //wake up! + WaitForSingleObject(hProgress,INFINITE); + CloseHandle(hProgress); + } + if (hThread){ + WaitForSingleObject(hThread,INFINITE); + CloseHandle(hThread); + } + // free objects + delete image; + for (int i=0;i= 0; i--){ + if (name[i] == '.'){ + return name.Mid(i+1); + } + } + return CString(""); +} +////////////////////////////////////////////////////////////////////////////// +int CDemoDoc::FindType(const CString& ext) +{ + int type = 0; + if (ext == "bmp") type = CXIMAGE_FORMAT_BMP; +#if CXIMAGE_SUPPORT_JPG + else if (ext=="jpg"||ext=="jpeg") type = CXIMAGE_FORMAT_JPG; +#endif +#if CXIMAGE_SUPPORT_GIF + else if (ext == "gif") type = CXIMAGE_FORMAT_GIF; +#endif +#if CXIMAGE_SUPPORT_PNG + else if (ext == "png") type = CXIMAGE_FORMAT_PNG; +#endif +#if CXIMAGE_SUPPORT_MNG + else if (ext=="mng"||ext=="jng") type = CXIMAGE_FORMAT_MNG; +#endif +#if CXIMAGE_SUPPORT_ICO + else if (ext == "ico") type = CXIMAGE_FORMAT_ICO; +#endif +#if CXIMAGE_SUPPORT_TIF + else if (ext=="tiff"||ext=="tif") type = CXIMAGE_FORMAT_TIF; +#endif +#if CXIMAGE_SUPPORT_TGA + else if (ext=="tga") type = CXIMAGE_FORMAT_TGA; +#endif +#if CXIMAGE_SUPPORT_PCX + else if (ext=="pcx") type = CXIMAGE_FORMAT_PCX; +#endif +#if CXIMAGE_SUPPORT_WBMP + else if (ext=="wbmp") type = CXIMAGE_FORMAT_WBMP; +#endif +#if CXIMAGE_SUPPORT_WMF + else if (ext=="wmf"||ext=="emf") type = CXIMAGE_FORMAT_WMF; +#endif +#if CXIMAGE_SUPPORT_J2K + else if (ext=="j2k"||ext=="jp2") type = CXIMAGE_FORMAT_J2K; +#endif +#if CXIMAGE_SUPPORT_JBG + else if (ext=="jbg") type = CXIMAGE_FORMAT_JBG; +#endif +#if CXIMAGE_SUPPORT_JP2 + else if (ext=="jp2"||ext=="j2k") type = CXIMAGE_FORMAT_JP2; +#endif +#if CXIMAGE_SUPPORT_JPC + else if (ext=="jpc"||ext=="j2c") type = CXIMAGE_FORMAT_JPC; +#endif +#if CXIMAGE_SUPPORT_PGX + else if (ext=="pgx") type = CXIMAGE_FORMAT_PGX; +#endif +#if CXIMAGE_SUPPORT_RAS + else if (ext=="ras") type = CXIMAGE_FORMAT_RAS; +#endif +#if CXIMAGE_SUPPORT_PNM + else if (ext=="pnm"||ext=="pgm"||ext=="ppm") type = CXIMAGE_FORMAT_PNM; +#endif + else type = CXIMAGE_FORMAT_UNKNOWN; + + return type; +} +////////////////////////////////////////////////////////////////////////////// +BOOL CDemoDoc::OnOpenDocument(LPCTSTR lpszPathName) +{ + CString filename(lpszPathName); + CString ext(FindExtension(filename)); + ext.MakeLower(); + if (ext == "") return FALSE; + + int type = FindType(ext); + + /*CxImage canvas; + canvas.SetEscape(-1); + CxIOFile file; + file.Open(filename,"rb"); + canvas.Decode(&file, type);*/ + + Stopwatch(0); + image = new CxImage(filename, type); + Stopwatch(1); + + if (!image->IsValid()){ + AfxMessageBox(image->GetLastError()); + delete image; + image = NULL; + return FALSE; + } + + UpdateStatusBar(); + UpdateAllViews(NULL,WM_USER_NEWIMAGE); + + //multiple images (TIFF/ICO) + if (image->GetNumFrames()>1){ + CString s; + s.Format("File with %d images. Read all?",image->GetNumFrames()); + if (AfxMessageBox(s,MB_OKCANCEL)==IDOK){ + + int j; // points to the document name + for(j=strlen(filename)-1;j>=0;j--){ + if (filename[j]=='\\'){ j++; break; } + } + // create the documents for the other images + for(int i=1;iGetNumFrames();i++){ + CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDoc) { + CxImage *newImage = new CxImage(); + newImage->SetFrame(i); + newImage->Load(filename,type); + NewDoc->image = newImage; + CString s; + s.Format("%s (%d)",filename.Mid(j),i+1); + NewDoc->SetTitle(s); + NewDoc->UpdateAllViews(NULL,WM_USER_NEWIMAGE); + } + } + } + } + + // EXIF jpegs + if (image->GetType() == CXIMAGE_FORMAT_JPG){ + FILE* hfile = fopen(filename,"rb"); + m_exif.DecodeExif(hfile); + fclose(hfile); + } + + return TRUE; +} +////////////////////////////////////////////////////////////////////////////// +BOOL CDemoDoc::OnSaveDocument(LPCTSTR lpszPathName) +{ + CString filename(lpszPathName); + CString ext(FindExtension(filename)); + ext.MakeLower(); + if (ext == "") return FALSE; + + int type = FindType(ext); + if (type == CXIMAGE_FORMAT_UNKNOWN) return FALSE; + + if (type == CXIMAGE_FORMAT_GIF && image->GetBpp()>8){ + AfxMessageBox("The image will be saved as a true color GIF!\nThis is ok for CxImage, but not for many other programs.\nFor better compatibility, please use DecreaseBpp to 8 bits or less.",MB_ICONINFORMATION); + } + + bool retval; + Stopwatch(0); + retval = image->Save(filename, type); + Stopwatch(1); + UpdateStatusBar(); + if (retval) return TRUE; + AfxMessageBox(image->GetLastError()); + + return FALSE; +} +////////////////////////////////////////////////////////////////////////////// +BOOL CDemoDoc::DoSave(LPCTSTR pszPathName, BOOL bReplace /*=TRUE*/) +{ + if (!image) return FALSE; + + CString newName = pszPathName; + BOOL bModified = IsModified(); + + BOOL bSaveAs = FALSE; + if (newName.IsEmpty()) bSaveAs = TRUE; + else if (!theApp.GetWritableType(image->GetType())) bSaveAs = TRUE; + + if (bSaveAs){ + newName = m_strPathName; + if (bReplace && newName.IsEmpty()){ + newName = m_strTitle; + int iBad = newName.FindOneOf(_T("#%;/\\")); // dubious filename + if (iBad != -1) //newName.ReleaseBuffer(iBad); + newName = "UntitledImage"; + + // append the default suffix if there is one + if (image->GetType()) newName += theApp.GetExtFromType(image->GetType()).Mid(1,4); + } + + int nDocType = image->GetType(); + if (!theApp.PromptForFileName(newName, + bReplace ? AFX_IDS_SAVEFILE : AFX_IDS_SAVEFILECOPY, + OFN_HIDEREADONLY | OFN_PATHMUSTEXIST, FALSE, &nDocType)) + { + return FALSE; // don't even try to save + } + } + + BeginWaitCursor(); + if (!OnSaveDocument(newName)){ + if (pszPathName == NULL){ + // be sure to delete the file + TRY + { + CFile::Remove(newName); + } + CATCH_ALL(e) + { + TRACE0("Warning: failed to delete file after failed SaveAs\n"); + } + END_CATCH_ALL + } + EndWaitCursor(); + return FALSE; + } + + EndWaitCursor(); + if (bReplace) { + // Reset the title and change the document name + SetPathName(newName, TRUE); + ASSERT(m_strPathName == newName); // must be set + } + else // SaveCopyAs + { + SetModifiedFlag(bModified); + } + return TRUE; // success +} +////////////////////////////////////////////////////////////////////////////// +#define EPSILON (0.0000001) + +int CDemoDoc::ComputePixel(float x, float y, float &x1, float &y1) +{ + double r, nn; + + if (x==0 && y==0) { + x1 = x; + y1 = y; + return 1; + } + + nn = sqrt(x*x + y*y); + r = (fabs(x) > fabs(y)) ? fabs(nn/x): fabs(nn/y); + + x1 = (float)(r*x); + y1 = (float)(r*y); + + return 1; +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateFileSaveAs(CCmdUI* pCmdUI) +{ + pCmdUI->Enable(!(image==0 || hThread)); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateFileSave(CCmdUI* pCmdUI) +{ + pCmdUI->Enable(0); +// pCmdUI->Enable((image != NULL)); //&& theApp.GetWritableType(image->GetType())); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnStretchMode() +{ + stretchMode = !stretchMode; + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateStretchMode(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(stretchMode); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateCximageFlip(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageGrayscale(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageMirror(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageNegative(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageResample(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageRotate(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageRotater(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageRotatel(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageDither(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageThreshold(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSplityuv(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSplitrgb(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSplithsl(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSplityiq(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSplitxyz(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSplitcmyk(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximagePseudocolors(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageFiltersColorize(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageLighten(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageDarken(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageContrast(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageEmboss(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageBlur(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageDilate(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageEdge(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageErode(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSharpen(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSoften(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageCrop(CCmdUI* pCmdUI) +{ if(image==0 || hThread || !image->SelectionIsValid()) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageRemovealphachannel(CCmdUI* pCmdUI) +{ if(image==0 || hThread || !image->AlphaIsValid()) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageInvetalpha(CCmdUI* pCmdUI) +{ if(image==0 || hThread || !image->AlphaIsValid()) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageAlphapalettetoggle(CCmdUI* pCmdUI) +{ if(image==0 || hThread || !image->AlphaPaletteIsValid()) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageAlphastrip(CCmdUI* pCmdUI) +{ if(image==0 || hThread || (!image->AlphaIsValid() && !image->AlphaPaletteIsValid())) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageRemovetransparency(CCmdUI* pCmdUI) +{ if(image==0 || hThread || image->GetTransIndex()<0) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageGamma(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageMedian(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageAddnoise(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageCombine(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageFft(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageRepair(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageAlphachannelSplit(CCmdUI* pCmdUI) +{ if(image==0 || hThread || !image->AlphaIsValid()) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageFiltersLog(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageFiltersRoot(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageHistogramEqualize(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageHistogramNormalize(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageHistogramStretch(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageGaussian3x3(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageGaussian5x5(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageContour(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageLesscontrast(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageJitter(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateWindowDuplicate(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateFiltersMix(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageCircletransformCylinder(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageCircletransformPinch(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageCircletransformPunch(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageCircletransformSwirl(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageCircletransformBathroom(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageHistogramStretch1(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageHistogramStretch2(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateFiltersNonlinearEdge(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateCximageSkew(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} +void CDemoDoc::OnUpdateJpegcompression(CCmdUI* pCmdUI) +{ if(image==0 || hThread) pCmdUI->Enable(0);} + +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateTransformEllipse(CCmdUI* pCmdUI) +{ + if (image==NULL) pCmdUI->Enable(0); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnTransformEllipse() +{ + SubmitUndo(); + DWORD x, y; + float x1, y1; //***bd*** use float source with GetPixelColorInterpolated + float fx, fy, xmid, ymid, ar; + CxImage *image2 = new CxImage(*image,false,false,true); + + xmid = (float) (image->GetWidth()/2.0); + ymid = (float) (image->GetHeight()/2.0); + ar = (float)(image->GetHeight())/(float)(image->GetWidth()); + for (y=0; yGetHeight(); y++) { + for (x=0; xGetWidth(); x++) { + ComputePixel(ar*(x-xmid), y-ymid, fx, fy); + x1 = xmid+fx/ar; + y1 = ymid+fy; + //correct method to use would be GetAreaColorAveraged (but I guess there's not that much aliasing here) + image2->SetPixelColor(x, y, image->GetPixelColorInterpolated(x1, y1, CxImage::IM_BILINEAR, CxImage::OM_BACKGROUND)); + //image2->SetPixelColor(x, y, image->GetPixelColor(x1, y1)); + } + } + delete image; + image = image2; + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnWindowDuplicate() +{ + CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + + if (NewDoc) { + CxImage *newImage = new CxImage(*image); + + NewDoc->image = newImage; + + CString s; + s.Format("Copy %d of %s",((CDemoApp*)AfxGetApp())->m_nDocCount++,GetTitle()); + NewDoc->SetTitle(s); + NewDoc->UpdateAllViews(0,WM_USER_NEWIMAGE); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateEditCopy(CCmdUI* pCmdUI) +{ + if (image==NULL) pCmdUI->Enable(0); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnEditCopy() +{ + HANDLE hDIB=image->CopyToHandle(); + + if (::OpenClipboard(AfxGetApp()->m_pMainWnd->GetSafeHwnd())) { + if(::EmptyClipboard()) { + if (::SetClipboardData(CF_DIB,hDIB) == NULL ) { + AfxMessageBox( "Unable to set Clipboard data" ); + } + } + } + CloseClipboard(); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateEditUndo(CCmdUI* pCmdUI) +{ + if(image==0 || hThread) pCmdUI->Enable(0); + else pCmdUI->Enable(m_UndoLevel>0); + + CString s; + s.Format("Undo (%d)\tCtrl+Z",m_UndoLevel); + pCmdUI->SetText(s); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateEditRedo(CCmdUI* pCmdUI) +{ + if(image==0 || hThread) pCmdUI->Enable(0); + else pCmdUI->Enable((m_UndoLevel<(MAX_UNDO_LEVELS))&& + (imageUndo[m_UndoLevel]!=0)); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnEditUndo() +{ + m_UndoLevel--; + CxImage* tmp = image; + image=imageUndo[m_UndoLevel]; + imageUndo[m_UndoLevel]=tmp; + + UpdateAllViews(0,WM_USER_NEWIMAGE); + UpdateStatusBar(); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnEditRedo() +{ + CxImage* tmp = image; + image=imageUndo[m_UndoLevel]; + imageUndo[m_UndoLevel]=tmp; + m_UndoLevel++; + + UpdateAllViews(0,WM_USER_NEWIMAGE); + UpdateStatusBar(); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::SubmitUndo() +{ + if (m_UndoLevel>=MAX_UNDO_LEVELS){ // Max Undo reached + delete imageUndo[0]; // discard the early undo + for(int i=1;iIsValid()){ + imageUndo[m_UndoLevel] = new CxImage(); + imageUndo[m_UndoLevel]->Copy(*image); + m_UndoLevel++; + } +} +////////////////////////////////////////////////////////////////////////////// +void /*unsigned long _stdcall*/ RunProgressThread(void *lpParam) +{ + CDemoDoc *pDoc = (CDemoDoc *)lpParam; + long n; + POSITION pos; + CView *pView; + while((n=pDoc->image->GetProgress())<100){ + Sleep(333); + if(pDoc->image->GetEscape()) break; + pos = pDoc->GetFirstViewPosition(); + pView = pDoc->GetNextView(pos); + if (pView) SendMessage(pView->m_hWnd, WM_USER_PROGRESS,n,0); + } + pos = pDoc->GetFirstViewPosition(); + pView = pDoc->GetNextView(pos); + if (pView) SendMessage(pView->m_hWnd, WM_USER_PROGRESS,100,0); + Sleep(111); + pos = pDoc->GetFirstViewPosition(); + pView = pDoc->GetNextView(pos); + if (pView) SendMessage(pView->m_hWnd, WM_USER_NEWIMAGE,0,0); + pDoc->hProgress = 0; + _endthread(); + return; +} +////////////////////////////////////////////////////////////////////////////// +void /*unsigned long _stdcall*/ RunCxImageThread(void *lpParam) +{ + CDemoDoc *pDoc = (CDemoDoc *)lpParam; + if (pDoc==NULL) return; + if (pDoc->image==NULL) return; + + //prepare for elaboration + pDoc->image->SetProgress(0); + pDoc->image->SetEscape(0); + + pDoc->SubmitUndo(); + + // auxilary thread for progress bar + pDoc->hProgress = (HANDLE)_beginthread(RunProgressThread,0,pDoc); + + pDoc->Stopwatch(0); + + switch (pDoc->m_MenuCommand) + { +// case ID_FILE_OPEN: +// pDoc->image->ReadFile(*(CString*)pDoc->m_fp[0],(int)pDoc->m_fp[1]); +// break; + case ID_CXIMAGE_FLIP: + pDoc->image->Flip(); + break; + case ID_CXIMAGE_MIRROR: + pDoc->image->Mirror(); + break; + case ID_CXIMAGE_NEGATIVE: + pDoc->image->Negative(); + break; + case ID_CXIMAGE_GRAYSCALE: + pDoc->image->GrayScale(); + break; + case ID_CXIMAGE_DITHER: + pDoc->image->Dither((long)pDoc->m_fp[0]); + break; + case ID_CXIMAGE_THRESHOLD: + pDoc->image->Threshold((BYTE)pDoc->m_fp[0]); + break; + case ID_CXIMAGE_COLORIZE: + if ((BYTE)pDoc->m_fp[0]){ + pDoc->image->Colorize((BYTE)pDoc->m_fp[1],(BYTE)pDoc->m_fp[2],(BYTE)pDoc->m_fp[3]/100.0f); + } else { + pDoc->image->ShiftRGB((long)pDoc->m_fp[1],(long)pDoc->m_fp[2],(long)pDoc->m_fp[3]); + } + break; + case ID_CXIMAGE_LIGHTEN: + pDoc->image->Light(20); + break; + case ID_CXIMAGE_DARKEN: + pDoc->image->Light(-20); + break; + case ID_CXIMAGE_CONTRAST: + pDoc->image->Light((long)pDoc->m_fp[0],25); + break; + case ID_CXIMAGE_LESSCONTRAST: + pDoc->image->Light((long)pDoc->m_fp[0],-25); + break; + case ID_CXIMAGE_DILATE: + pDoc->image->Dilate(); + break; + case ID_CXIMAGE_ERODE: + pDoc->image->Erode(); + break; + case ID_CXIMAGE_CONTOUR: + pDoc->image->Contour(); + break; + case ID_CXIMAGE_ADDNOISE: + pDoc->image->Noise(50); + break; + case ID_CXIMAGE_JITTER: + pDoc->image->Jitter(); + break; + case ID_FILTERS_NONLINEAR_EDGE: + pDoc->image->Edge(); + break; + case ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER: + pDoc->image->CircleTransform(3,0,100); + break; + case ID_CXIMAGE_CIRCLETRANSFORM_PINCH: + pDoc->image->CircleTransform(1,0,100); + break; + case ID_CXIMAGE_CIRCLETRANSFORM_PUNCH: + pDoc->image->CircleTransform(0,0,100); + break; + case ID_CXIMAGE_CIRCLETRANSFORM_SWIRL: + pDoc->image->CircleTransform(2,0,100); + break; + case ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM: + pDoc->image->CircleTransform(4); + break; + case ID_CXIMAGE_EMBOSS: + { + long kernel[]={0,0,-1,0,0,0,1,0,0}; + pDoc->image->Filter(kernel,3,0,127); + break; + } + case ID_CXIMAGE_BLUR: + { + long kernel[]={1,1,1,1,1,1,1,1,1}; + pDoc->image->Filter(kernel,3,9,0); + break; + } + case ID_CXIMAGE_GAUSSIAN3X3: + { + long kernel[]={1,2,1,2,4,2,1,2,1}; + pDoc->image->Filter(kernel,3,16,0); + break; + } + case ID_CXIMAGE_GAUSSIAN5X5: + { + long kernel[]={0,1,2,1,0,1,3,4,3,1,2,4,8,4,2,1,3,4,3,1,0,1,2,1,0}; + pDoc->image->Filter(kernel,5,52,0); + break; + } + case ID_CXIMAGE_SOFTEN: + { + long kernel[]={1,1,1,1,8,1,1,1,1}; + pDoc->image->Filter(kernel,3,16,0); + break; + } + case ID_CXIMAGE_SHARPEN: + { + long kernel[]={-1,-1,-1,-1,15,-1,-1,-1,-1}; + pDoc->image->Filter(kernel,3,7,0); + break; + } + case ID_CXIMAGE_EDGE: + { + long kernel[]={-1,-1,-1,-1,8,-1,-1,-1,-1}; + pDoc->image->Filter(kernel,3,-1,255); + break; + } + case ID_CXIMAGE_MEDIAN: + pDoc->image->Median(3); + break; + case ID_CXIMAGE_GAMMA: + pDoc->image->Gamma((long)pDoc->m_fp[0]/1000.0f); + break; + case ID_CXIMAGE_HISTOGRAM_LOG: + pDoc->image->HistogramLog(); + break; + case ID_CXIMAGE_HISTOGRAM_ROOT: + pDoc->image->HistogramRoot(); + break; + case ID_CXIMAGE_HISTOGRAM_EQUALIZE: + pDoc->image->HistogramEqualize(); + break; + case ID_CXIMAGE_HISTOGRAM_NORMALIZE: + pDoc->image->HistogramNormalize(); + break; + case ID_CXIMAGE_HISTOGRAM_STRETCH: + pDoc->image->HistogramStretch(); + break; + case ID_CXIMAGE_HISTOGRAM_STRETCH1: + pDoc->image->HistogramStretch(1); + break; + case ID_CXIMAGE_HISTOGRAM_STRETCH2: + pDoc->image->HistogramStretch(2); + break; + case ID_CXIMAGE_SKEW: + pDoc->image->Skew((long)pDoc->m_fp[0]/1000.0f,(long)pDoc->m_fp[1]/1000.0f, + (long)pDoc->m_fp[2],(long)pDoc->m_fp[3],(long)pDoc->m_fp[4]!=0); + break; + case ID_CXIMAGE_ROTATE: + //pDoc->image->Rotate((float)(long)pDoc->m_fp[0]/1000); + //***bd*** more rotation options + CxImage::InterpolationMethod intm; + CxImage::OverflowMethod overm; + switch ((int)(pDoc->m_fp[1])) { + case 0: intm=CxImage::IM_NEAREST_NEIGHBOUR; break; + case 1: intm=CxImage::IM_BILINEAR; break; + case 2: intm=CxImage::IM_BICUBIC; break; + case 3: intm=CxImage::IM_BICUBIC2; break; + case 4: intm=CxImage::IM_BSPLINE; break; + case 5: intm=CxImage::IM_LANCZOS; break; + case 6: intm=CxImage::IM_HERMITE; break; + default: throw(0); + }//switch + switch ((int)(pDoc->m_fp[2])) { + case 0: overm=CxImage::OM_BACKGROUND; break; + case 1: overm=CxImage::OM_BACKGROUND; break; + case 2: overm=CxImage::OM_BACKGROUND; break; + case 3: overm=CxImage::OM_WRAP; break; + case 4: overm=CxImage::OM_REPEAT; break; + case 5: overm=CxImage::OM_MIRROR; break; + case 6: overm=CxImage::OM_TRANSPARENT; break; + }//switch + switch ((int)(pDoc->m_fp[2])) { + case 0: { + RGBQUAD bkg = pDoc->image->GetPixelColor(0,0); + pDoc->image->Rotate2((long)pDoc->m_fp[0]/1000.0f, 0, intm, overm, &bkg,true,pDoc->m_fp[3]!=0); + break; } + case 1: { + RGBQUAD bkg = {0,0,0,0}; + pDoc->image->Rotate2((long)pDoc->m_fp[0]/1000.0f, 0, intm, overm, &bkg,true,pDoc->m_fp[3]!=0); + break; } + default: + pDoc->image->Rotate2((long)pDoc->m_fp[0]/1000.0f, 0, intm, overm, 0,true,pDoc->m_fp[3]!=0); + } + break; + case ID_CXIMAGE_ROTATEL: + pDoc->image->RotateLeft(); + break; + case ID_CXIMAGE_ROTATER: + pDoc->image->RotateRight(); + break; + case ID_CXIMAGE_RESAMPLE: + //***bd*** more resample options + CxImage::InterpolationMethod rintm; + switch ((long)(pDoc->m_fp[2])) { + case 0: rintm=CxImage::IM_NEAREST_NEIGHBOUR; break; + case 1: rintm=CxImage::IM_BILINEAR; break; + case 2: rintm=CxImage::IM_BILINEAR; break; + case 3: rintm=CxImage::IM_BICUBIC; break; + case 4: rintm=CxImage::IM_BICUBIC2; break; + case 5: rintm=CxImage::IM_BSPLINE; break; + case 6: rintm=CxImage::IM_LANCZOS; break; + case 7: rintm=CxImage::IM_HERMITE; break; + default: throw(0); + }//switch + switch ((long)(pDoc->m_fp[2])) { + case 0: + pDoc->image->Resample((long)pDoc->m_fp[0],(long)pDoc->m_fp[1],1); + break; + case 1: + pDoc->image->Resample((long)pDoc->m_fp[0],(long)pDoc->m_fp[1],0); + break; + default: + pDoc->image->Resample2((long)pDoc->m_fp[0],(long)pDoc->m_fp[1],rintm,CxImage::OM_REPEAT); + } + break; + case ID_CXIMAGE_INCREASEBPP: + pDoc->image->IncreaseBpp((long)pDoc->m_fp[0]); + break; + case ID_CXIMAGE_DECREASEBPP: + { + long bit=(long)pDoc->m_fp[0]; + long method=(long)pDoc->m_fp[1]; + bool errordiffusion=((long)pDoc->m_fp[2])!=0; + long colors=(long)pDoc->m_fp[3]; + + //pDoc->image->IncreaseBpp(24); + + RGBQUAD* ppal = NULL; + if (method==1){ + switch (bit){ + /*case 1: + { + CQuantizer q(2,8); + q.ProcessImage(pDoc->image->GetDIB()); + ppal=(RGBQUAD*)calloc(2*sizeof(RGBQUAD),1); + q.SetColorTable(ppal); + break; + }*/ + case 4: + { + CQuantizer q(colors,8); + q.ProcessImage(pDoc->image->GetDIB()); + ppal=(RGBQUAD*)calloc(16*sizeof(RGBQUAD),1); + q.SetColorTable(ppal); + break; + } + case 8: + { + CQuantizer q(colors,(colors>16?7:8)); + q.ProcessImage(pDoc->image->GetDIB()); + ppal=(RGBQUAD*)calloc(256*sizeof(RGBQUAD),1); + q.SetColorTable(ppal); + } + } + pDoc->image->DecreaseBpp(bit,errordiffusion,ppal,colors); + } else pDoc->image->DecreaseBpp(bit,errordiffusion,0); + + if (!pDoc->image->AlphaPaletteIsValid()) pDoc->image->AlphaPaletteEnable(0); + + if (ppal) free(ppal); + break; + } + } + + pDoc->Stopwatch(1); + + pDoc->image->SetProgress(100); + + pDoc->hThread=0; + _endthread(); + return ; +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageFlip() +{ + m_MenuCommand=ID_CXIMAGE_FLIP; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageMirror() +{ + m_MenuCommand=ID_CXIMAGE_MIRROR; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageNegative() +{ + m_MenuCommand=ID_CXIMAGE_NEGATIVE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageGrayscale() +{ + m_MenuCommand=ID_CXIMAGE_GRAYSCALE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageDecreasebpp() +{ + if (image==NULL) return; + DlgDecBpp dlg; + dlg.m_bit=4; + dlg.m_maxcolors = 256; + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_DECREASEBPP; + m_fp[0]=(void *)dlg.m_bit; + m_fp[1]=(void *)dlg.m_method; + m_fp[2]=(void *)dlg.m_errordiffusion; + m_fp[3]=(void *)dlg.m_maxcolors; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageIncreasebpp() +{ + if (image==NULL) return; + DlgIncBpp dlg; + dlg.m_bit=24; + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_INCREASEBPP; + m_fp[0]=(void *)dlg.m_bit; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageRotatel() +{ + m_MenuCommand=ID_CXIMAGE_ROTATEL; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageRotater() +{ + m_MenuCommand=ID_CXIMAGE_ROTATER; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageRotate() +{ + if (image==NULL) return; + DlgRotate dlg; + dlg.m_angle=(float)12.345; + dlg.m_method=1; + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_ROTATE; + m_fp[0]=(void *)(long)(dlg.m_angle*1000); + m_fp[1]=(void *)(long)(dlg.m_method); + m_fp[2]=(void *)(long)(dlg.m_overflow); + m_fp[3]=(void *)(long)(dlg.m_keepsize); + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageResample() +{ + if (image==NULL) return; + + DlgResample dlg; + dlg.m_w = image->GetWidth(); + dlg.m_h = image->GetHeight(); + dlg.m_factor=(float)2; + dlg.m_ratio = ((float)image->GetWidth())/((float)image->GetHeight()); + dlg.m_newwidth = 100; + dlg.m_newheight = (DWORD)(dlg.m_newwidth / dlg.m_ratio); + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_RESAMPLE; + + if (dlg.m_sizemode==1){ + dlg.m_newwidth = (DWORD)(dlg.m_w * fabs(dlg.m_factor)); + dlg.m_newheight = (DWORD)(dlg.m_h * fabs(dlg.m_factor)); + } + + m_fp[0]=(void *)(long)(dlg.m_newwidth); + m_fp[1]=(void *)(long)(dlg.m_newheight); + m_fp[2]=(void *)(long)(dlg.m_mode); + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::UpdateStatusBar() +{ + if (image){ + CStatusBar& statusBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetStatusBar(); + CString s,t; + t = theApp.GetDescFromType(image->GetType()); + s.Format("(%dx%dx%d)",image->GetWidth(),image->GetHeight(),image->GetBpp()); + statusBar.SetPaneText(4, s); + statusBar.SetPaneText(3,t.Mid(0,3)); + s.Format("Time (s): %.3f",m_etime); + statusBar.SetPaneText(2, s); + +// ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetProgressBar().SetPos(0); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewZoomin() +{ + if (m_ZoomFactor>=16) return; + + if (m_ZoomFactor == 0.50f) m_ZoomFactor = 0.75f; + else if (m_ZoomFactor == 0.75f) m_ZoomFactor = 1.00f; + else if (m_ZoomFactor == 1.00f) m_ZoomFactor = 1.50f; + else if (m_ZoomFactor == 1.50f) m_ZoomFactor = 2.00f; + else m_ZoomFactor*=2; + + CStatusBar& statusBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetStatusBar(); + CString s; + s.Format("%4.0f %%",m_ZoomFactor*100); + statusBar.SetPaneText(2, s); + + UpdateAllViews(NULL,WM_USER_NEWIMAGE); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewZoomout() +{ + if (m_ZoomFactor<=0.0625) return; + + if (m_ZoomFactor == 2.00f) m_ZoomFactor = 1.50f; + else if (m_ZoomFactor == 1.50f) m_ZoomFactor = 1.00f; + else if (m_ZoomFactor == 1.00f) m_ZoomFactor = 0.75f; + else if (m_ZoomFactor == 0.75f) m_ZoomFactor = 0.50f; + else m_ZoomFactor/=2; + + CStatusBar& statusBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetStatusBar(); + CString s; + s.Format("%4.1f %%",m_ZoomFactor*100); + statusBar.SetPaneText(2, s); + + UpdateAllViews(NULL,WM_USER_NEWIMAGE); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewZoomin(CCmdUI* pCmdUI) +{ + if (stretchMode) pCmdUI->Enable(0); + if (m_ZoomFactor>=16) pCmdUI->Enable(0); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewZoomout(CCmdUI* pCmdUI) +{ + if (stretchMode) pCmdUI->Enable(0); + if (m_ZoomFactor<=0.125) pCmdUI->Enable(0); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewNormalviewing11() +{ + m_ZoomFactor=1; + UpdateAllViews(NULL,WM_USER_NEWIMAGE); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewNormalviewing11(CCmdUI* pCmdUI) +{ + if (stretchMode) pCmdUI->Enable(0); + if (m_ZoomFactor==1) pCmdUI->Enable(0); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateCximageSettransparency(CCmdUI* pCmdUI) +{ + if (image && hThread==0) pCmdUI->Enable(1); + else pCmdUI->Enable(0); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageRemovetransparency() +{ + SubmitUndo(); + if (image) image->SetTransIndex(-1); + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSettransparency() +{ + m_WaitingClick=TRUE; +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::Stopwatch(int start0stop1) +{ + if (start0stop1==0) QueryPerformanceCounter(&m_swStart); + else { + QueryPerformanceCounter(&m_swStop); + if (m_swFreq.LowPart==0 && m_swFreq.HighPart==0) m_etime = -1; + else { + m_etime = (float)(m_swStop.LowPart - m_swStart.LowPart); + if (m_etime < 0) m_etime += 2^32; + m_etime /= (m_swFreq.LowPart+m_swFreq.HighPart * 2^32); + } + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageOptions() +{ + if (image==NULL) return; + + DlgOptions dlg; + dlg.m_quality = image->GetJpegQuality(); + dlg.m_xres = image->GetXDPI(); + dlg.m_yres = image->GetYDPI(); + dlg.m_Opt_tif = image->GetCodecOption(CXIMAGE_FORMAT_TIF); + dlg.m_Opt_gif = image->GetCodecOption(CXIMAGE_FORMAT_GIF); + dlg.m_Opt_jpg = image->GetCodecOption(CXIMAGE_FORMAT_JPG); + dlg.m_Opt_png = image->GetCodecOption(CXIMAGE_FORMAT_PNG); + dlg.m_exif = &m_exif; + if (dlg.DoModal()==IDOK){ + image->SetJpegQuality(dlg.m_quality); + image->SetXDPI(dlg.m_xres); + image->SetYDPI(dlg.m_yres); + image->SetCodecOption(dlg.m_Opt_tif, CXIMAGE_FORMAT_TIF); + image->SetCodecOption(dlg.m_Opt_gif, CXIMAGE_FORMAT_GIF); + image->SetCodecOption(dlg.m_Opt_jpg, CXIMAGE_FORMAT_JPG); + image->SetCodecOption(dlg.m_Opt_png, CXIMAGE_FORMAT_PNG); +#ifdef VATI_EXTENSIONS + theApp.m_optJpegQuality = dlg.m_quality; +#endif + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageDither() +{ + if (image==NULL) return; + + DlgDither dlg; + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_DITHER; + m_fp[0]=(void*)dlg.m_method; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageThreshold() +{ + if (image==NULL) return; + DlgThreshold dlg; + dlg.m_level=(BYTE)image->Mean(); + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_THRESHOLD; + m_fp[0]=(void *)(BYTE)(dlg.m_level); + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSplitrgb() +{ + if (image==NULL) return; + + CxImage *newr = new CxImage(); + CxImage *newg = new CxImage(); + CxImage *newb = new CxImage(); + + Stopwatch(0); + + image->SplitRGB(newr,newg,newb); + + Stopwatch(1); + UpdateStatusBar(); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = newr; + CString s; + s.Format("Red Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocg) { + NewDocg->image = newg; + CString s; + s.Format("Green Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocg->SetTitle(s); + NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocb) { + NewDocb->image = newb; + CString s; + s.Format("Blue Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocb->SetTitle(s); + NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSplityuv() +{ + if (image==NULL) return; + + CxImage *newr = new CxImage(); + CxImage *newg = new CxImage(); + CxImage *newb = new CxImage(); + + Stopwatch(0); + + image->SplitYUV(newr,newg,newb); + + Stopwatch(1); + UpdateStatusBar(); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = newr; + CString s; + s.Format("Y Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocg) { + NewDocg->image = newg; + CString s; + s.Format("U Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocg->SetTitle(s); + NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocb) { + NewDocb->image = newb; + CString s; + s.Format("V Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocb->SetTitle(s); + NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSplithsl() +{ + if (image==NULL) return; + + CxImage *newr = new CxImage(); + CxImage *newg = new CxImage(); + CxImage *newb = new CxImage(); + + Stopwatch(0); + + image->SplitHSL(newr,newg,newb); + + Stopwatch(1); + UpdateStatusBar(); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = newr; + CString s; + s.Format("Hue Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocg) { + NewDocg->image = newg; + CString s; + s.Format("Saturation Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocg->SetTitle(s); + NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocb) { + NewDocb->image = newb; + CString s; + s.Format("Lightness Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocb->SetTitle(s); + NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSplitcmyk() +{ + if (image==NULL) return; + + CxImage *newc = new CxImage(); + CxImage *newm = new CxImage(); + CxImage *newy = new CxImage(); + CxImage *newk = new CxImage(); + + Stopwatch(0); + + image->SplitCMYK(newc,newm,newy,newk); + + Stopwatch(1); + UpdateStatusBar(); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = newc; + CString s; + s.Format("C Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocg) { + NewDocg->image = newm; + CString s; + s.Format("M Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocg->SetTitle(s); + NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocb) { + NewDocb->image = newy; + CString s; + s.Format("Y Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocb->SetTitle(s); + NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDock=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDock) { + NewDock->image = newk; + CString s; + s.Format("K Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDock->SetTitle(s); + NewDock->UpdateAllViews(0,WM_USER_NEWIMAGE); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximagePseudocolors() +{ + if (image==NULL) return; + + SubmitUndo(); + + if (!image->IsGrayScale()) image->GrayScale(); + image->HuePalette(); + +/* POSITION pos = GetFirstViewPosition(); + CDemoView* pView = (CDemoView*)GetNextView(pos); + HDC srcDC = ::GetDC(pView->GetSafeHwnd()); + HDC memDC = ::CreateCompatibleDC(srcDC); + // copy the screen to the bitmap + CSize sz(image->GetWidth(), image->GetHeight()); + int xshift = 0, yshift = 0; + HBITMAP bm =::CreateCompatibleBitmap(srcDC, sz.cx, sz.cy); + HBITMAP oldbm = (HBITMAP)::SelectObject(memDC,bm); + ::BitBlt(memDC, 0, 0, sz.cx, sz.cy, srcDC, xshift, yshift, SRCCOPY); +// image->SetTransIndex(-1); +// image->Draw(memDC); + ::TextOut(memDC,10,10,"test",4); + + CxImage newima; + newima.CreateFromHBITMAP(bm); + image->Transfer(newima); + // free objects + SelectObject(memDC,oldbm); + DeleteObject(memDC);*/ + + UpdateAllViews(NULL,WM_USER_NEWIMAGE); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageFiltersColorize() +{ + if (image==NULL) return; + DlgColorize dlg; + dlg.m_sat=50; + dlg.m_hue=12; + dlg.m_r=50; + dlg.m_g=0; + dlg.m_b=-50; + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_COLORIZE; + if (dlg.m_bHSL){ + m_fp[0]=(void *)(BYTE)(dlg.m_bHSL); + m_fp[1]=(void *)(BYTE)(dlg.m_hue); + m_fp[2]=(void *)(BYTE)(dlg.m_sat); + m_fp[3]=(void *)(BYTE)(dlg.m_blend); + } else { + m_fp[0]=(void *)(BYTE)(dlg.m_bHSL); + m_fp[1]=(void *)(long)(dlg.m_r); + m_fp[2]=(void *)(long)(dlg.m_g); + m_fp[3]=(void *)(long)(dlg.m_b); + } + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageDarken() +{ + m_MenuCommand=ID_CXIMAGE_DARKEN; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageLighten() +{ + m_MenuCommand=ID_CXIMAGE_LIGHTEN; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageContrast() +{ + m_MenuCommand=ID_CXIMAGE_CONTRAST; +// m_fp[0]=(void *)(long)((128-image->Mean())/4); + m_fp[0]=(void *)(long)(0); + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageEmboss() +{ + m_MenuCommand=ID_CXIMAGE_EMBOSS; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageBlur() +{ + m_MenuCommand=ID_CXIMAGE_BLUR; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageDilate() +{ + m_MenuCommand=ID_CXIMAGE_DILATE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageEdge() +{ + m_MenuCommand=ID_CXIMAGE_EDGE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageErode() +{ + m_MenuCommand=ID_CXIMAGE_ERODE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSharpen() +{ + m_MenuCommand=ID_CXIMAGE_SHARPEN; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSoften() +{ + m_MenuCommand=ID_CXIMAGE_SOFTEN; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageCrop() +{ + SubmitUndo(); + RECT r; + +#ifdef VATI_EXTENSIONS + // if there is a valid rectangle selection, then call the CropRotatedRectangle instead original Crop + if (m_isRectSel && m_NumSel==5 ) + { + CPoint top; + long height, width; + float angle; + int topcorner = -1; + + // get upperleft corner + top.x = 999999; + top.y = 999999; + for(int i=0; i<4; i++) + { + if ( top.y >= m_Sel[i].y ) + { + if ( top.y == m_Sel[i].y && top.x < m_Sel[i].x ) + continue; + top.x = m_Sel[i].x; + top.y = m_Sel[i].y; + topcorner = i; + } + } + // get side lengths (-1st and +1st indexes points to 2 sides) + if ( topcorner > 0 && topcorner < 4 ) + height = (long)LEN2D( top.x - m_Sel[topcorner-1].x, top.y - m_Sel[topcorner-1].y ); + else if ( topcorner == 0 ) + height = (long)LEN2D( top.x - m_Sel[3].x, top.y - m_Sel[3].y ); + else + return; // fatal prog error + + width = (long)LEN2D( top.x - m_Sel[topcorner+1].x, top.y - m_Sel[topcorner+1].y ); + angle = (float)atan2( (float)(m_Sel[topcorner+1].y - top.y), (float)(m_Sel[topcorner+1].x - top.x) ); + + image->CropRotatedRectangle( top.x, top.y, width, height, angle ); + } + + else // freehand selection + { + image->SelectionGetBox(r); + r.bottom = image->GetHeight() - 1 -r.bottom; + r.top = image->GetHeight() - 1 -r.top; + image->Crop(r); + } +#else + image->SelectionGetBox(r); + r.bottom = image->GetHeight() - 1 -r.bottom; + r.top = image->GetHeight() - 1 -r.top; + image->Crop(r); +#endif + UpdateStatusBar(); // VAti - to refresh image size in the status bar + UpdateAllViews(NULL,WM_USER_NEWIMAGE); +} + +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageRemovealphachannel() +{ + SubmitUndo(); + image->AlphaDelete(); + image->AlphaSetMax(255); + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageOpacity() +{ + if (image==NULL) return; + DlgOpacity dlg; + dlg.m_level=image->AlphaGetMax(); + if (dlg.DoModal()==IDOK){ + SubmitUndo(); + if (!image->AlphaIsValid()){ + image->AlphaCreate(); + } + image->AlphaSetMax(dlg.m_level); + } + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageInvetalpha() +{ + SubmitUndo(); + image->AlphaInvert(); + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageAlphapalettetoggle() +{ + SubmitUndo(); + image->AlphaPaletteEnable(!image->AlphaPaletteIsEnabled()); + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageAlphastrip() +{ + SubmitUndo(); + RGBQUAD c={255,255,255,0}; + image->SetTransColor(c); + image->AlphaStrip(); + UpdateAllViews(NULL,WM_USER_NEWIMAGE); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageGamma() +{ + if (image==NULL) return; + DlgGamma dlg; + dlg.m_gamma=(float)1.23; + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_GAMMA; + m_fp[0]=(void *)(long)(dlg.m_gamma*1000); + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageMedian() +{ + m_MenuCommand=ID_CXIMAGE_MEDIAN; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageAddnoise() +{ + m_MenuCommand=ID_CXIMAGE_ADDNOISE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewToolsMove() +{ + m_tool=0; +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewToolsMove(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(m_tool==0); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewToolsSelect() +{ + m_tool=1; +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewToolsSelect(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(m_tool==1); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewToolsZoom() +{ + m_tool=2; +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewToolsZoom(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(m_tool==2); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewToolsText() +{ + if (image==NULL) return; + DlgText dlg; + +#ifndef VATI_EXTENSIONS + memcpy(&(dlg.m_font),&m_font,sizeof(m_font)); + dlg.m_text=m_text; + dlg.m_color=m_color; + if (dlg.DoModal()==IDOK){ + m_text=dlg.m_text; + m_color=dlg.m_color; + memcpy(&m_font,&(dlg.m_font),sizeof(m_font)); + m_tool=3; + } +#else + //pass all data about text + memcpy( &(dlg.m_textdata), &theApp.m_text, sizeof(CxImage::CXTEXTINFO) ); + if (dlg.DoModal()==IDOK) + { + //retrieve all data about text + memcpy( &theApp.m_text, &(dlg.m_textdata), sizeof(CxImage::CXTEXTINFO) ); + m_tool=3; + } +#endif +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewToolsText(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(m_tool==3); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewPalette(CCmdUI* pCmdUI) +{ + if(image==0 || hThread || image->GetNumColors()==0) pCmdUI->Enable(0); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewPalette() +{ + if (image==NULL) return; + DlgPalette dlg; + dlg.m_numcolors=image->GetNumColors(); + memcpy(dlg.m_pal,image->GetPalette(),dlg.m_numcolors*sizeof(RGBQUAD)); + if (dlg.DoModal()==IDOK){ + if (dlg.m_changed){ + SubmitUndo(); + switch (dlg.m_replace){ + case 1: + { + image->SetPalette(dlg.m_pal,dlg.m_numcolors); + break; + } + case 2: + { + int bpp=image->GetBpp(); + image->IncreaseBpp(24); + image->DecreaseBpp(bpp,false,dlg.m_pal); + break; + } + case 3: + { + int bpp=image->GetBpp(); + image->IncreaseBpp(24); + image->DecreaseBpp(bpp,true,dlg.m_pal); + break; + } + } + + UpdateAllViews(NULL,WM_USER_NEWIMAGE); + } + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageCombine() +{ + if (image==NULL) return; + DlgCombine dlg; + if (dlg.DoModal()==IDOK){ + SetCursor(LoadCursor(0,IDC_WAIT)); + Stopwatch(0); + CxImage *newr,*newg,*newb,*newa; + newr=newg=newb=newa=NULL; + + newr = new CxImage(); + switch(dlg.pChR){ + case 0: + newr->Copy(*(dlg.pDocR->GetImage()),1,0,0); + newr->GrayScale(); + break; + case 1: + dlg.pDocR->GetImage()->SplitRGB(newr,0,0); + break; + case 2: + dlg.pDocR->GetImage()->SplitRGB(0,newr,0); + break; + case 3: + dlg.pDocR->GetImage()->SplitRGB(0,0,newr); + break; + } + + newg = new CxImage(); + switch(dlg.pChG){ + case 0: + newg->Copy(*(dlg.pDocG->GetImage()),1,0,0); + newg->GrayScale(); + break; + case 1: + dlg.pDocG->GetImage()->SplitRGB(newg,0,0); + break; + case 2: + dlg.pDocG->GetImage()->SplitRGB(0,newg,0); + break; + case 3: + dlg.pDocG->GetImage()->SplitRGB(0,0,newg); + break; + } + + newb = new CxImage(); + switch(dlg.pChB){ + case 0: + newb->Copy(*(dlg.pDocB->GetImage()),1,0,0); + newb->GrayScale(); + break; + case 1: + dlg.pDocB->GetImage()->SplitRGB(newb,0,0); + break; + case 2: + dlg.pDocB->GetImage()->SplitRGB(0,newb,0); + break; + case 3: + dlg.pDocB->GetImage()->SplitRGB(0,0,newb); + break; + } + + if (dlg.pDocA){ + newa = new CxImage(); + switch(dlg.pChA){ + case 0: + newa->Copy(*(dlg.pDocA->GetImage()),1,0,0); + newa->GrayScale(); + break; + case 1: + dlg.pDocA->GetImage()->SplitRGB(newa,0,0); + break; + case 2: + dlg.pDocA->GetImage()->SplitRGB(0,newa,0); + break; + case 3: + dlg.pDocA->GetImage()->SplitRGB(0,0,newa); + break; + } + } + + CxImage *mix = new CxImage(); + mix->Combine(newr,newg,newb,newa,dlg.pChS); + + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = mix; + CString s; + s.Format("NewImage%d",((CDemoApp*)AfxGetApp())->m_nDocCount++); + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + + delete newr; + delete newg; + delete newb; + delete newa; + Stopwatch(1); + UpdateStatusBar(); + SetCursor(LoadCursor(0,IDC_ARROW)); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageFft() +{ + if (image==NULL) return; + DlgFFT dlg; + if (dlg.DoModal()==IDOK){ + SetCursor(LoadCursor(0,IDC_WAIT)); + Stopwatch(0); + + CxImage *srcr,*srci,*dstr,*dsti,tmp; + + srcr = (dlg.pDocReal) ? dlg.pDocReal->GetImage() : 0; + srci = (dlg.pDocImag) ? dlg.pDocImag->GetImage() : 0; + + if (srcr==0 && srci==0) return; + + if (srcr) dstr = new CxImage(*srcr,true,false,false); else dstr=0; + if (srci) dsti = new CxImage(*srci,true,false,false); else dsti=0; + + if (dstr==0){ + dstr = new CxImage(dsti->GetWidth(),dsti->GetHeight(),8); + dstr->Clear(0); + dstr->SetGrayPalette(); + } + if (dsti==0){ + dsti = new CxImage(dstr->GetWidth(),dstr->GetHeight(),8); + dsti->Clear(0); + dsti->SetGrayPalette(); + } + + tmp.FFT2(dstr,dsti,0,0,dlg.bInverse,dlg.bForceFFT!=0,dlg.bMagnitude!=0); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDoci=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDoci) { + NewDoci->image = dsti; + CString s; + if (dlg.bMagnitude){ + s.Format("FFT Phase %d",((CDemoApp*)AfxGetApp())->m_nDocCount); + } else { + s.Format("FFT Imag %d",((CDemoApp*)AfxGetApp())->m_nDocCount); + } + NewDoci->SetTitle(s); + NewDoci->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = dstr; + CString s; + if (dlg.bMagnitude){ + s.Format("FFT Magnitude %d",((CDemoApp*)AfxGetApp())->m_nDocCount); + } else { + s.Format("FFT Real %d",((CDemoApp*)AfxGetApp())->m_nDocCount); + } + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + + Stopwatch(1); + UpdateStatusBar(); + SetCursor(LoadCursor(0,IDC_ARROW)); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSplityiq() +{ + if (image==NULL) return; + + CxImage *newr = new CxImage(); + CxImage *newg = new CxImage(); + CxImage *newb = new CxImage(); + + Stopwatch(0); + + image->SplitYIQ(newr,newg,newb); + + Stopwatch(1); + UpdateStatusBar(); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = newr; + CString s; + s.Format("Y Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocg) { + NewDocg->image = newg; + CString s; + s.Format("I Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocg->SetTitle(s); + NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocb) { + NewDocb->image = newb; + CString s; + s.Format("Q Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocb->SetTitle(s); + NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSplitxyz() +{ + if (image==NULL) return; + + CxImage *newr = new CxImage(); + CxImage *newg = new CxImage(); + CxImage *newb = new CxImage(); + + Stopwatch(0); + + image->SplitXYZ(newr,newg,newb); + + Stopwatch(1); + UpdateStatusBar(); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = newr; + CString s; + s.Format("X Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocg) { + NewDocg->image = newg; + CString s; + s.Format("Y Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocg->SetTitle(s); + NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocb) { + NewDocb->image = newb; + CString s; + s.Format("Z Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocb->SetTitle(s); + NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageRepair() +{ + if (image==NULL) return; + + DlgRepair dlg; + dlg.m_iterations = 2; + dlg.m_radius = (float)0.25; + if (dlg.DoModal()==IDOK){ + SubmitUndo(); + SetCursor(LoadCursor(0,IDC_WAIT)); + Stopwatch(0); + + image->Repair(dlg.m_radius,dlg.m_iterations,dlg.m_ncs); + + Stopwatch(1); + UpdateAllViews(NULL); + UpdateStatusBar(); + SetCursor(LoadCursor(0,IDC_ARROW)); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageAlphachannelSplit() +{ + if (image==NULL) return; + + CxImage *newa = new CxImage(); + + Stopwatch(0); + + image->AlphaSplit(newa); + + Stopwatch(1); + UpdateStatusBar(); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDocr) { + NewDocr->image = newa; + CString s; + s.Format("Alpha Channel %d from %s",((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); + NewDocr->SetTitle(s); + NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageAlphaCreate() +{ + if (image==NULL) return; + CxImage gray(*image,true,false,false); + gray.IncreaseBpp(8); + gray.Negative(); + gray.GrayScale(); + image->AlphaSet(gray); + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageFiltersLog() +{ + m_MenuCommand=ID_CXIMAGE_HISTOGRAM_LOG; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageFiltersRoot() +{ + m_MenuCommand=ID_CXIMAGE_HISTOGRAM_ROOT; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageHistogramEqualize() +{ + m_MenuCommand=ID_CXIMAGE_HISTOGRAM_EQUALIZE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageHistogramNormalize() +{ + m_MenuCommand=ID_CXIMAGE_HISTOGRAM_NORMALIZE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageHistogramStretch() +{ + m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCH; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageGaussian3x3() +{ + m_MenuCommand=ID_CXIMAGE_GAUSSIAN3X3; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageGaussian5x5() +{ + m_MenuCommand=ID_CXIMAGE_GAUSSIAN5X5; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageContour() +{ + m_MenuCommand=ID_CXIMAGE_CONTOUR; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageLesscontrast() +{ + m_MenuCommand=ID_CXIMAGE_LESSCONTRAST; + m_fp[0]=(void *)(long)(0); + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageJitter() +{ + m_MenuCommand=ID_CXIMAGE_JITTER; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnFiltersMix() +{ + if (image==NULL) return; + DlgMix dlg; + if (dlg.DoModal()==IDOK){ + SetCursor(LoadCursor(0,IDC_WAIT)); + Stopwatch(0); + + CxImage *src, *dst, *tmp; + + src = (dlg.pDocSrc) ? dlg.pDocSrc->GetImage() : 0; + dst = (dlg.pDocDst) ? dlg.pDocDst->GetImage() : 0; + + if (src==0 && dst==0) return; + + tmp = new CxImage(*dst); + tmp->Mix(*src,(CxImage::ImageOpType)dlg.OpType,dlg.m_xoffset,dlg.m_yoffset,dlg.m_mixalpha!=0); + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDoci=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDoci) { + NewDoci->image = tmp; + CString s; + s.Format("Mix %d",((CDemoApp*)AfxGetApp())->m_nDocCount); + NewDoci->SetTitle(s); + NewDoci->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + + Stopwatch(1); + UpdateStatusBar(); + SetCursor(LoadCursor(0,IDC_ARROW)); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageCircletransformCylinder() +{ + m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageCircletransformPinch() +{ + m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_PINCH; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageCircletransformPunch() +{ + m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_PUNCH; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageCircletransformSwirl() +{ + m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_SWIRL; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageCircletransformBathroom() +{ + m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageHistogramStretch1() +{ + m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCH1; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageHistogramStretch2() +{ + m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCH2; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnFiltersNonlinearEdge() +{ + m_MenuCommand=ID_FILTERS_NONLINEAR_EDGE; + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnCximageSkew() +{ + if (image==NULL) return; + + DlgSkew dlg; + dlg.m_w = image->GetWidth(); + dlg.m_h = image->GetHeight(); + dlg.m_bEnableInterpolation = TRUE; + if (dlg.DoModal()==IDOK){ + m_MenuCommand=ID_CXIMAGE_SKEW; + + m_fp[0]=(void *)(long)(1000*dlg.m_slopex); + m_fp[1]=(void *)(long)(1000*dlg.m_slopey); + m_fp[2]=(void *)(long)(dlg.m_pivotx); + m_fp[3]=(void *)(long)(dlg.m_pivoty); + m_fp[4]=(void *)(long)(dlg.m_bEnableInterpolation); + + hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewToolsTracker(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(m_tool==4); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewToolsTracker() +{ + m_tool=4; +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnJpegcompression() +{ + if (image==NULL) return; + DlgJpeg dlg; + dlg.m_quality=50; + if (dlg.DoModal()==IDOK){ + + SetCursor(LoadCursor(0,IDC_WAIT)); + Stopwatch(0); + + CxImage *tmp; + tmp = new CxImage(*image); + if (!tmp->IsGrayScale()) tmp->IncreaseBpp(24); + tmp->SetTransIndex(-1); + tmp->SetJpegQuality((BYTE)dlg.m_quality); + + DWORD imagetype = 0; + if (dlg.m_format==0) imagetype = CXIMAGE_FORMAT_JPG; + if (dlg.m_format==1) imagetype = CXIMAGE_FORMAT_JPC; + + CxMemFile tmpFile; + tmpFile.Open(); + + if (tmp->Encode(&tmpFile,imagetype)){ + + tmpFile.Seek(0,SEEK_SET); + if (tmp->Decode(&tmpFile,imagetype)){ + + ((CDemoApp*)AfxGetApp())->m_nDocCount++; + CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); + if (NewDoc) { + NewDoc->image = tmp; + CString s; + s.Format("Jpeg compr. %d, q = %d, size = %d", + ((CDemoApp*)AfxGetApp())->m_nDocCount, dlg.m_quality, tmpFile.Size()); + NewDoc->SetTitle(s); + NewDoc->UpdateAllViews(0,WM_USER_NEWIMAGE); + } + } else { + AfxMessageBox(tmp->GetLastError()); + delete tmp; + } + } else { + AfxMessageBox(tmp->GetLastError()); + delete tmp; + } + + Stopwatch(1); + UpdateStatusBar(); + SetCursor(LoadCursor(0,IDC_ARROW)); + } +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnViewSmooth() +{ + m_bSmoothDisplay = !m_bSmoothDisplay; + UpdateAllViews(NULL); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoDoc::OnUpdateViewSmooth(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(m_bSmoothDisplay); +} +////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/demoDoc.h b/SlnkDWFImpl/CxImage/demo/demoDoc.h new file mode 100644 index 0000000..96adca0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demoDoc.h @@ -0,0 +1,273 @@ +// demoDoc.h : interface of the CDemoDoc class +// +///////////////////////////////////////////////////////////////////////////// +#define MAX_UNDO_LEVELS 8 +#define MAX_SEL_POINTS 8000 + +#define WM_USER_NEWIMAGE WM_USER+1 +#define WM_USER_PROGRESS WM_USER+2 + +// +#define LEN2D(X,Y) sqrt((float)((X)*(X)+(Y)*(Y))) + +#include "ximajpg.h" + +class CxImage; +class CDemoDoc : public CDocument +{ +protected: // create from serialization only + CDemoDoc(); + DECLARE_DYNCREATE(CDemoDoc) + +// Attributes +public: +// enum +// { +// WM_USER_NEWIMAGE = WM_USER+1 +// }; + + CxImage *image; //main image + HANDLE hThread,hProgress; //elaboration thread + + void *m_fp[6]; //function parameters + long m_MenuCommand; + + POINT m_Sel[MAX_SEL_POINTS]; //Selection + long m_NumSel; + int m_tool; + +#ifndef VATI_EXTENSIONS + LOGFONT m_font; + CString m_text; + COLORREF m_color; +#else + int m_isRectSel; +#endif + + long m_hr[256]; //histogram + long m_hg[256]; + long m_hb[256]; + long m_hgray[256]; + long m_hmax; + + CxImageJPG m_exif; + +// Operations +public: + void SubmitUndo(); + inline CxImage *GetImage() { return image; } + inline BOOL GetStretchMode() { return stretchMode; } + inline BOOL GetSmoothMode() { return m_bSmoothDisplay; } + inline BOOL GetWaitingClick() { return m_WaitingClick; } + inline void SetWaitingClick(BOOL b) { m_WaitingClick=b; } + inline float GetZoomFactor() { return m_ZoomFactor; } + int ComputePixel(float x, float y, float &x1, float &y1); + CString FindExtension(const CString& name); + int FindType(const CString& ext); + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CDemoDoc) + public: + virtual BOOL OnNewDocument(); + virtual void Serialize(CArchive& ar); + virtual BOOL OnOpenDocument(LPCTSTR lpszPathName); + virtual BOOL OnSaveDocument(LPCTSTR lpszPathName); + virtual BOOL DoSave(LPCTSTR pszPathName, BOOL bReplace =TRUE); + //}}AFX_VIRTUAL + +// Implementation +public: + void Stopwatch(int start0stop1); + void UpdateStatusBar(); + virtual ~CDemoDoc(); +#ifdef _DEBUG + virtual void AssertValid() const; + virtual void Dump(CDumpContext& dc) const; +#endif + +protected: + +// Generated message map functions +protected: + BOOL stretchMode; + BOOL m_bSmoothDisplay; + CxImage *imageUndo[MAX_UNDO_LEVELS]; + int m_UndoLevel; + float m_ZoomFactor; + BOOL m_WaitingClick; + LARGE_INTEGER m_swFreq, m_swStart, m_swStop; //stopwatch + float m_etime; //elapsed time + long m_progress; + + //{{AFX_MSG(CDemoDoc) + afx_msg void OnUpdateFileSaveAs(CCmdUI* pCmdUI); + afx_msg void OnUpdateFileSave(CCmdUI* pCmdUI); + afx_msg void OnStretchMode(); + afx_msg void OnUpdateStretchMode(CCmdUI* pCmdUI); + afx_msg void OnTransformEllipse(); + afx_msg void OnWindowDuplicate(); + afx_msg void OnEditCopy(); + afx_msg void OnCximageFlip(); + afx_msg void OnCximageMirror(); + afx_msg void OnCximageNegative(); + afx_msg void OnCximageGrayscale(); + afx_msg void OnCximageRotate(); + afx_msg void OnUpdateEditUndo(CCmdUI* pCmdUI); + afx_msg void OnEditRedo(); + afx_msg void OnEditUndo(); + afx_msg void OnUpdateEditRedo(CCmdUI* pCmdUI); + afx_msg void OnViewZoomin(); + afx_msg void OnViewZoomout(); + afx_msg void OnUpdateViewZoomin(CCmdUI* pCmdUI); + afx_msg void OnUpdateViewZoomout(CCmdUI* pCmdUI); + afx_msg void OnViewNormalviewing11(); + afx_msg void OnUpdateViewNormalviewing11(CCmdUI* pCmdUI); + afx_msg void OnCximageSettransparency(); + afx_msg void OnUpdateCximageSettransparency(CCmdUI* pCmdUI); + afx_msg void OnCximageRemovetransparency(); + afx_msg void OnUpdateCximageRemovetransparency(CCmdUI* pCmdUI); + afx_msg void OnCximageResample(); + afx_msg void OnUpdateEditCopy(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageFlip(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageGrayscale(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageMirror(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageNegative(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageResample(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageRotate(CCmdUI* pCmdUI); + afx_msg void OnUpdateTransformEllipse(CCmdUI* pCmdUI); + afx_msg void OnCximageDecreasebpp(); + afx_msg void OnCximageIncreasebpp(); + afx_msg void OnCximageOptions(); + afx_msg void OnCximageDither(); + afx_msg void OnUpdateCximageDither(CCmdUI* pCmdUI); + afx_msg void OnCximageThreshold(); + afx_msg void OnUpdateCximageThreshold(CCmdUI* pCmdUI); + afx_msg void OnCximageSplitrgb(); + afx_msg void OnUpdateCximageSplitrgb(CCmdUI* pCmdUI); + afx_msg void OnCximageSplityuv(); + afx_msg void OnUpdateCximageSplityuv(CCmdUI* pCmdUI); + afx_msg void OnCximageSplithsl(); + afx_msg void OnUpdateCximageSplithsl(CCmdUI* pCmdUI); + afx_msg void OnCximagePseudocolors(); + afx_msg void OnUpdateCximagePseudocolors(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageFiltersColorize(CCmdUI* pCmdUI); + afx_msg void OnCximageFiltersColorize(); + afx_msg void OnCximageDarken(); + afx_msg void OnUpdateCximageDarken(CCmdUI* pCmdUI); + afx_msg void OnCximageLighten(); + afx_msg void OnUpdateCximageLighten(CCmdUI* pCmdUI); + afx_msg void OnCximageContrast(); + afx_msg void OnUpdateCximageContrast(CCmdUI* pCmdUI); + afx_msg void OnCximageEmboss(); + afx_msg void OnUpdateCximageEmboss(CCmdUI* pCmdUI); + afx_msg void OnCximageBlur(); + afx_msg void OnUpdateCximageBlur(CCmdUI* pCmdUI); + afx_msg void OnCximageDilate(); + afx_msg void OnUpdateCximageDilate(CCmdUI* pCmdUI); + afx_msg void OnCximageEdge(); + afx_msg void OnUpdateCximageEdge(CCmdUI* pCmdUI); + afx_msg void OnCximageErode(); + afx_msg void OnUpdateCximageErode(CCmdUI* pCmdUI); + afx_msg void OnCximageSharpen(); + afx_msg void OnUpdateCximageSharpen(CCmdUI* pCmdUI); + afx_msg void OnCximageSoften(); + afx_msg void OnUpdateCximageSoften(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageCrop(CCmdUI* pCmdUI); + afx_msg void OnCximageCrop(); + afx_msg void OnUpdateCximageRemovealphachannel(CCmdUI* pCmdUI); + afx_msg void OnCximageRemovealphachannel(); + afx_msg void OnCximageOpacity(); + afx_msg void OnCximageInvetalpha(); + afx_msg void OnUpdateCximageInvetalpha(CCmdUI* pCmdUI); + afx_msg void OnCximageAlphapalettetoggle(); + afx_msg void OnUpdateCximageAlphapalettetoggle(CCmdUI* pCmdUI); + afx_msg void OnCximageAlphastrip(); + afx_msg void OnUpdateCximageAlphastrip(CCmdUI* pCmdUI); + afx_msg void OnCximageRotatel(); + afx_msg void OnUpdateCximageRotatel(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageRotater(CCmdUI* pCmdUI); + afx_msg void OnCximageRotater(); + afx_msg void OnUpdateCximageGamma(CCmdUI* pCmdUI); + afx_msg void OnCximageGamma(); + afx_msg void OnUpdateCximageMedian(CCmdUI* pCmdUI); + afx_msg void OnCximageMedian(); + afx_msg void OnCximageAddnoise(); + afx_msg void OnUpdateCximageAddnoise(CCmdUI* pCmdUI); + afx_msg void OnUpdateViewToolsMove(CCmdUI* pCmdUI); + afx_msg void OnViewToolsMove(); + afx_msg void OnViewToolsSelect(); + afx_msg void OnUpdateViewToolsSelect(CCmdUI* pCmdUI); + afx_msg void OnViewToolsZoom(); + afx_msg void OnUpdateViewToolsZoom(CCmdUI* pCmdUI); + afx_msg void OnUpdateViewPalette(CCmdUI* pCmdUI); + afx_msg void OnViewPalette(); + afx_msg void OnCximageCombine(); + afx_msg void OnUpdateCximageCombine(CCmdUI* pCmdUI); + afx_msg void OnCximageFft(); + afx_msg void OnUpdateCximageFft(CCmdUI* pCmdUI); + afx_msg void OnCximageSplityiq(); + afx_msg void OnUpdateCximageSplityiq(CCmdUI* pCmdUI); + afx_msg void OnCximageSplitxyz(); + afx_msg void OnUpdateCximageSplitxyz(CCmdUI* pCmdUI); + afx_msg void OnCximageRepair(); + afx_msg void OnUpdateCximageRepair(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageAlphachannelSplit(CCmdUI* pCmdUI); + afx_msg void OnCximageAlphachannelSplit(); + afx_msg void OnViewToolsText(); + afx_msg void OnUpdateViewToolsText(CCmdUI* pCmdUI); + afx_msg void OnCximageSplitcmyk(); + afx_msg void OnUpdateCximageSplitcmyk(CCmdUI* pCmdUI); + afx_msg void OnCximageAlphaCreate(); + afx_msg void OnCximageFiltersLog(); + afx_msg void OnUpdateCximageFiltersLog(CCmdUI* pCmdUI); + afx_msg void OnCximageFiltersRoot(); + afx_msg void OnUpdateCximageFiltersRoot(CCmdUI* pCmdUI); + afx_msg void OnCximageHistogramEqualize(); + afx_msg void OnUpdateCximageHistogramEqualize(CCmdUI* pCmdUI); + afx_msg void OnCximageHistogramNormalize(); + afx_msg void OnUpdateCximageHistogramNormalize(CCmdUI* pCmdUI); + afx_msg void OnCximageHistogramStretch(); + afx_msg void OnUpdateCximageHistogramStretch(CCmdUI* pCmdUI); + afx_msg void OnCximageGaussian3x3(); + afx_msg void OnUpdateCximageGaussian3x3(CCmdUI* pCmdUI); + afx_msg void OnCximageGaussian5x5(); + afx_msg void OnUpdateCximageGaussian5x5(CCmdUI* pCmdUI); + afx_msg void OnCximageContour(); + afx_msg void OnUpdateCximageContour(CCmdUI* pCmdUI); + afx_msg void OnCximageLesscontrast(); + afx_msg void OnUpdateCximageLesscontrast(CCmdUI* pCmdUI); + afx_msg void OnCximageJitter(); + afx_msg void OnUpdateCximageJitter(CCmdUI* pCmdUI); + afx_msg void OnUpdateWindowDuplicate(CCmdUI* pCmdUI); + afx_msg void OnUpdateFiltersMix(CCmdUI* pCmdUI); + afx_msg void OnFiltersMix(); + afx_msg void OnCximageCircletransformCylinder(); + afx_msg void OnUpdateCximageCircletransformCylinder(CCmdUI* pCmdUI); + afx_msg void OnCximageCircletransformPinch(); + afx_msg void OnUpdateCximageCircletransformPinch(CCmdUI* pCmdUI); + afx_msg void OnCximageCircletransformPunch(); + afx_msg void OnUpdateCximageCircletransformPunch(CCmdUI* pCmdUI); + afx_msg void OnCximageCircletransformSwirl(); + afx_msg void OnUpdateCximageCircletransformSwirl(CCmdUI* pCmdUI); + afx_msg void OnCximageCircletransformBathroom(); + afx_msg void OnUpdateCximageCircletransformBathroom(CCmdUI* pCmdUI); + afx_msg void OnCximageHistogramStretch1(); + afx_msg void OnCximageHistogramStretch2(); + afx_msg void OnUpdateCximageHistogramStretch1(CCmdUI* pCmdUI); + afx_msg void OnUpdateCximageHistogramStretch2(CCmdUI* pCmdUI); + afx_msg void OnFiltersNonlinearEdge(); + afx_msg void OnUpdateFiltersNonlinearEdge(CCmdUI* pCmdUI); + afx_msg void OnCximageSkew(); + afx_msg void OnUpdateCximageSkew(CCmdUI* pCmdUI); + afx_msg void OnViewToolsTracker(); + afx_msg void OnUpdateViewToolsTracker(CCmdUI* pCmdUI); + afx_msg void OnJpegcompression(); + afx_msg void OnUpdateJpegcompression(CCmdUI* pCmdUI); + afx_msg void OnViewSmooth(); + afx_msg void OnUpdateViewSmooth(CCmdUI* pCmdUI); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +///////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/demoView.cpp b/SlnkDWFImpl/CxImage/demo/demoView.cpp new file mode 100644 index 0000000..bf4c207 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demoView.cpp @@ -0,0 +1,823 @@ +// demoView.cpp : implementation of the CDemoView class +// + +#include "stdafx.h" +#include "ximage.h" +#include "MainFrm.h" +#include "demo.h" + +#include "demoDoc.h" +#include "demoView.h" +#include "memdc.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +////////////////////////////////////////////////////////////////////////////// +// CDemoView + +IMPLEMENT_DYNCREATE(CDemoView, CScrollView) + +BEGIN_MESSAGE_MAP(CDemoView, CScrollView) + //{{AFX_MSG_MAP(CDemoView) + ON_WM_MOUSEMOVE() + ON_WM_ERASEBKGND() + ON_WM_SETFOCUS() + ON_WM_LBUTTONDOWN() + ON_WM_CONTEXTMENU() + ON_WM_LBUTTONUP() + ON_WM_TIMER() + ON_WM_DESTROY() + ON_WM_CHAR() + ON_WM_RBUTTONDOWN() + ON_WM_SETCURSOR() + //}}AFX_MSG_MAP + // Standard printing commands + ON_COMMAND(ID_FILE_PRINT, CScrollView::OnFilePrint) + ON_COMMAND(ID_FILE_PRINT_DIRECT, CScrollView::OnFilePrint) + ON_COMMAND(ID_FILE_PRINT_PREVIEW, CScrollView::OnFilePrintPreview) + ON_MESSAGE(WM_USER_NEWIMAGE, OnNewImage) + ON_MESSAGE(WM_USER_PROGRESS, OnNewProgress) +END_MESSAGE_MAP() + +////////////////////////////////////////////////////////////////////////////// +// CDemoView construction/destruction +CDemoView::CDemoView() +{ + SetScrollSizes(MM_TEXT, CSize(0, 0)); + + VERIFY(m_brHatch.CreateHatchBrush(HS_DIAGCROSS, RGB(191, 191, 191))); + + m_tracker.m_rect = CRect(0,0,0,0); + m_tracker.m_nStyle = 0; + m_tracker.m_nStyle |= CRectTracker::dottedLine; + m_tracker.m_nStyle |= CRectTracker::resizeOutside; +} +////////////////////////////////////////////////////////////////////////////// +CDemoView::~CDemoView() +{ +} +////////////////////////////////////////////////////////////////////////////// +BOOL CDemoView::PreCreateWindow(CREATESTRUCT& cs) +{ + // TODO: Modify the Window class or styles here by modifying + // the CREATESTRUCT cs + return CScrollView::PreCreateWindow(cs); +} +////////////////////////////////////////////////////////////////////////////// +// CDemoView drawing +void CDemoView::OnDraw(CDC* pDC) +{ + CDemoDoc* pDoc = GetDocument(); + ASSERT_VALID(pDoc); + + BOOL bPrinting = pDC->IsPrinting(); + + CMemDC* pMemDC = NULL; + if (!bPrinting) pDC = pMemDC = new CMemDC(pDC); + + if (!bPrinting && m_brHatch.m_hObject){ + CRect rect; + GetClientRect(&rect); + rect.right = max(rect.right , m_totalDev.cx); + rect.bottom = max(rect.bottom, m_totalDev.cy); + m_brHatch.UnrealizeObject(); + CPoint pt(0, 0); + pDC->LPtoDP(&pt); + pt = pDC->SetBrushOrg(pt.x % 8, pt.y % 8); + CBrush* old = pDC->SelectObject(&m_brHatch); + pDC->FillRect(&rect, &m_brHatch); + pDC->SelectObject(old); + } + + CxImage* ima = pDoc->GetImage(); + if (ima) { + if (bPrinting) { + // get size of printer page (in pixels) + int cxPage = pDC->GetDeviceCaps(HORZRES); + int cyPage = pDC->GetDeviceCaps(VERTRES); + //int dcbpp = pDC->GetDeviceCaps(BITSPIXEL); + //int dcnc = pDC->GetDeviceCaps(NUMCOLORS); + //int dcp = pDC->GetDeviceCaps(PLANES); + // get printer pixels per inch + int cxInch = pDC->GetDeviceCaps(LOGPIXELSX); + int cyInch = pDC->GetDeviceCaps(LOGPIXELSY); + // Best Fit case: create a rectangle which preserves the aspect ratio + int cx=(ima->GetWidth()*cxInch)/ima->GetXDPI(); + int cy=(ima->GetHeight()*cyInch)/ima->GetYDPI(); + // print it! + /*HDC TmpDC=CreateCompatibleDC(pDC->GetSafeHdc()); + HBITMAP bm =::CreateCompatibleBitmap(pDC->GetSafeHdc(), cx, cy); + HBITMAP oldbm = (HBITMAP)::SelectObject(TmpDC,bm); + BitBlt(TmpDC,0,0,cx,cy,0,0,0,WHITENESS); + ima->Draw(TmpDC,CRect(0,0,cx,cy)); + BitBlt(pDC->GetSafeHdc(),100,100,cx,cy,TmpDC,0,0,SRCCOPY); + DeleteObject(SelectObject(TmpDC,oldbm)); + DeleteDC(TmpDC);*/ + CxImage tmp; + tmp.Copy(*ima); + RGBQUAD c={255,255,255,0}; + if (tmp.GetTransIndex()>=0) tmp.SetPaletteColor((BYTE)tmp.GetTransIndex(),c); + tmp.SetTransColor(c); + tmp.AlphaStrip(); + tmp.Stretch(pDC->GetSafeHdc(), CRect(100,100,cx,cy)); + } else { + if (pDoc->GetStretchMode()) { + CRect rect; + GetClientRect(&rect); + ima->Draw(pDC->GetSafeHdc(), rect,0,pDoc->GetSmoothMode()!=0); + } else { + float zoom=pDoc->GetZoomFactor(); + if (zoom==1) + ima->Draw(pDC->GetSafeHdc()); + else + ima->Draw(pDC->GetSafeHdc(), + CRect(0,0,(int)(ima->GetWidth()*zoom),(int)(ima->GetHeight()*zoom)), + 0,pDoc->GetSmoothMode()!=0); + } + + if ( m_tracker.m_rect.Width()>0 && m_tracker.m_rect.Height()>0 ) + m_tracker.Draw(pDC); + } + } + + delete pMemDC; +} +////////////////////////////////////////////////////////////////////////////// +// CDemoView printing +BOOL CDemoView::OnPreparePrinting(CPrintInfo* pInfo) +{ + // default preparation + pInfo->SetMaxPage(1); + return DoPreparePrinting(pInfo); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) +{ + // TODO: add extra initialization before printing +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) +{ + // TODO: add cleanup after printing +} +////////////////////////////////////////////////////////////////////////////// +// CDemoView diagnostics +#ifdef _DEBUG +void CDemoView::AssertValid() const +{ + CScrollView::AssertValid(); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::Dump(CDumpContext& dc) const +{ + CScrollView::Dump(dc); +} +////////////////////////////////////////////////////////////////////////////// +CDemoDoc* CDemoView::GetDocument() // non-debug version is inline +{ + ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDemoDoc))); + return (CDemoDoc*)m_pDocument; +} +#endif //_DEBUG + +////////////////////////////////////////////////////////////////////////////// +void CDemoView::GetImageXY(CDemoDoc *pDoc, CxImage *ima, long *x, long *y) +{ + if (!ima || !pDoc) return; + + CPoint point=GetScrollPosition(); + float fx =(float)(*x + point.x); + float fy =(float)(*y + point.y); + + fx/=pDoc->GetZoomFactor(); + fy/=pDoc->GetZoomFactor(); + + if (pDoc->GetStretchMode()) { + CRect rect; + GetClientRect(&rect); + int width = rect.right - rect.left; + int height = rect.bottom - rect.top; + fx *= ima->GetWidth()/(float)width; + fy *= ima->GetHeight()/(float)height; + } + *x = (long)fx; + *y = (long)fy; +} +////////////////////////////////////////////////////////////////////////////// +// CDemoView message handlers +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnMouseMove(UINT nFlags, CPoint point) +{ + CDemoDoc* pDoc = GetDocument(); + CxImage* ima = pDoc->GetImage(); + if (!ima) return; + + // We'll get the RGB values at the point the user selects + long x = point.x; + long y = point.y; + GetImageXY(pDoc, ima, &x,&y); + + char s[80]; + if (ima->IsInside(x,y)) { + + long yflip = ima->GetHeight() - y - 1; + sprintf(s,"x: %d y: %d idx: %d", x, y, ima->GetPixelIndex(x,yflip)); + RGBQUAD rgb=ima->GetPixelColor(x,yflip); + if (ima->AlphaIsValid()) rgb.rgbReserved=ima->AlphaGet(x,yflip); + else rgb.rgbReserved=ima->GetPaletteColor(ima->GetPixelIndex(x,yflip)).rgbReserved; + sprintf(&s[strlen(s)]," RGBA: (%d, %d, %d, %d)", rgb.rgbRed, rgb.rgbGreen, rgb.rgbBlue, rgb.rgbReserved); + + //Enable these lines if you want draw over the image + //if ((nFlags & MK_LBUTTON)==MK_LBUTTON){ + // ima->SetPixelColor(x,yflip,RGB(rand()/(RAND_MAX/256),rand()/(RAND_MAX/256),rand()/(RAND_MAX/256))); + // Invalidate(0); + //} +#ifdef VATI_EXTENSIONS + if (nFlags & MK_RBUTTON && !(nFlags & MK_LBUTTON)) + { + switch (pDoc->m_tool){ + case 1: // selection + if ( nFlags & MK_CONTROL ) // CTRL+right button: move selection + { + for (int i=0; im_NumSel; i++) + { + pDoc->m_Sel[i].x += (long)(x-m_oldPnt.x); + pDoc->m_Sel[i].y += (long)(y-m_oldPnt.y); + } + m_oldPnt.x = x; + m_oldPnt.y = y; + //redraw selection + CWnd* pFrame=GetParentFrame(); + RECT rClient; + pFrame->GetClientRect(&rClient); + pFrame->RedrawWindow( &rClient, NULL, RDW_INVALIDATE | RDW_UPDATENOW); + DrawSelection(); + } + else if ( !(nFlags & MK_CONTROL) && pDoc->m_isRectSel && pDoc->m_NumSel==5 ) + { + // calculate angle difference looking from rectangle center + double d_angle = + atan2( (y - m_orgPnt.y), (x - m_orgPnt.x) ) + - atan2( (m_oldPnt.y - m_orgPnt.y), (m_oldPnt.x - m_orgPnt.x) ); + m_oldPnt.x = x; + m_oldPnt.y = y; + Dpoint2d p; + + // rotate corner points around center point + for(int i=0;i<5;i++) + { + p.x = m_dpnt[i].x - m_orgPnt.x; + p.y = m_dpnt[i].y - m_orgPnt.y; + m_dpnt[i].x = p.x*cos(d_angle) - p.y*sin(d_angle) + m_orgPnt.x; + m_dpnt[i].y = p.x*sin(d_angle) + p.y*cos(d_angle) + m_orgPnt.y; + // write back to selection + pDoc->m_Sel[i].x = (long)m_dpnt[i].x ; + pDoc->m_Sel[i].y = (long)m_dpnt[i].y ; + + } + // redraw the rectangle + CWnd* pFrame=GetParentFrame(); + RECT rClient; + pFrame->GetClientRect(&rClient); + pFrame->RedrawWindow( &rClient, NULL, RDW_INVALIDATE | RDW_UPDATENOW); + DrawSelection(); + } + break; + } // end switch + } // end if MK_RBUTTON +#endif + + if (nFlags & MK_LBUTTON) + switch (pDoc->m_tool){ + case 0: // move + { + SetCursor(LoadCursor(0,IDC_SIZEALL)); + CSize sz(GetTotalSize()); + CWnd* pFrame=GetParentFrame(); + RECT rClient; + pFrame->GetClientRect(&rClient); + if (sz.cx>rClient.right) SetScrollPos(SB_HORZ,m_RefScroll.x - point.x + m_RefPoint.x); else SetScrollPos(SB_HORZ,0); + if (sz.cy>rClient.bottom) SetScrollPos(SB_VERT,m_RefScroll.y - point.y + m_RefPoint.y); else SetScrollPos(SB_VERT,0); + Invalidate(0); + break; + } + case 1: //selection + SetCursor(LoadCursor(0,IDC_CROSS)); +#if CXIMAGE_DEMO_SELECT +#ifdef VATI_EXTENSIONS + if ( nFlags & MK_SHIFT ) + { + // rectangle selection + pDoc->m_isRectSel = 1; + // in rectangle mode, selection array has 0,1 or 5 points + if (!pDoc->m_NumSel) + { + pDoc->m_Sel[0].x = x; + pDoc->m_Sel[0].y = y; + pDoc->m_NumSel = 1; + } + else // already has at least one corner + { + pDoc->m_Sel[1].x = x; + pDoc->m_Sel[1].y = pDoc->m_Sel[0].y; + pDoc->m_Sel[2].x = x; + pDoc->m_Sel[2].y = y; + pDoc->m_Sel[3].x = pDoc->m_Sel[0].x; + pDoc->m_Sel[3].y = y; + //close the rectangle: + pDoc->m_Sel[4].x = pDoc->m_Sel[0].x; + pDoc->m_Sel[4].y = pDoc->m_Sel[0].y; + pDoc->m_NumSel = 5; + } + // delete old rectangle from display: + CWnd* pFrame=GetParentFrame(); + RECT rClient; + pFrame->GetClientRect(&rClient); + pFrame->RedrawWindow( &rClient, NULL, RDW_INVALIDATE | RDW_UPDATENOW); + // draw the new rectangle + DrawSelection(); + } + else +#endif + { + //freehand selection (original) + float zoom=pDoc->GetZoomFactor(); + CPoint pos(GetScrollPosition()); + int i=pDoc->m_NumSel; + pDoc->m_Sel[i].x = (long)((point.x + pos.x)/zoom); + pDoc->m_Sel[i].y = (long)((point.y + pos.y)/zoom); + if (i<(MAX_SEL_POINTS-2)) pDoc->m_NumSel++; + DrawSelection(); + } +#endif + } //end switch + + } else strcpy(s," "); + + CStatusBar& statusBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetStatusBar(); + statusBar.SetPaneText(0, s); + + CScrollView::OnMouseMove(nFlags, point); +} +////////////////////////////////////////////////////////////////////////////// +BOOL CDemoView::OnEraseBkgnd(CDC* pDC) +{ + return 1; +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnSetFocus(CWnd* pOldWnd) +{ + CScrollView::OnSetFocus(pOldWnd); + + CDemoDoc* pDoc = GetDocument(); + if (pDoc) pDoc->UpdateStatusBar(); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnLButtonDown(UINT nFlags, CPoint point) +{ + CDemoDoc* pDoc = GetDocument(); + if (pDoc) { + switch(pDoc->m_tool){ + case 0: // select + case 1: + { +#ifdef VATI_EXTENSIONS + if ( nFlags & MK_SHIFT ) + pDoc->m_isRectSel = 1; + else + pDoc->m_isRectSel = 0; +#endif + CxImage* ima = pDoc->GetImage(); + if (ima) { + m_RefScroll = GetScrollPosition(); + m_RefPoint.x = point.x; + m_RefPoint.y = point.y; + } + } + break; + case 2: // zoom + if (!pDoc->GetWaitingClick()) PostMessage(WM_COMMAND,ID_VIEW_ZOOMIN); + break; + case 4: // tracker + { + if (m_tracker.HitTest(point) < 0) + { + CRectTracker track; + if (track.TrackRubberBand(this, point, true)) { + track.m_rect.NormalizeRect(); + m_tracker.m_rect = track.m_rect; + SetImageRectSelection(pDoc,&(m_tracker.m_rect)); + } else { + m_tracker.m_rect = CRect(0,0,0,0); + } + } else { + if (m_tracker.Track(this, point, true)){ + m_tracker.m_rect.NormalizeRect(); + SetImageRectSelection(pDoc,&(m_tracker.m_rect)); + } else { + m_tracker.m_rect = CRect(0,0,0,0); + } + } + OnUpdate(0,0,0); + } + break; + case 3: //text + pDoc->m_tool=-1; + CxImage* ima = pDoc->GetImage(); + if (ima){ + pDoc->SubmitUndo(); + long x = point.x; + long y = point.y; + GetImageXY(pDoc, ima, &x,&y); +#ifndef VATI_EXTENSIONS + RGBQUAD c = ima->RGBtoRGBQUAD(pDoc->m_color); + c.rgbReserved=255; + ima->DrawString(0,x,y,pDoc->m_text,c, + pDoc->m_font.lfFaceName, + pDoc->m_font.lfHeight, + pDoc->m_font.lfWeight, + pDoc->m_font.lfItalic, + pDoc->m_font.lfUnderline, + true); +#else + ima->DrawStringEx(0,x,y,&theApp.m_text ); +#endif + } + Invalidate(0); + break; + } + + if (pDoc->GetWaitingClick()){ + pDoc->SetWaitingClick(0); + CxImage* ima = pDoc->GetImage(); + if (ima) { + long x = point.x; + long y = point.y; + GetImageXY(pDoc, ima, &x,&y); + if (ima->IsInside(x,y)) { + pDoc->SubmitUndo(); + long yflip = ima->GetHeight() - y - 1; + ima->SetTransIndex(ima->GetPixelIndex(x,yflip)); + // RGB transparency + ima->SetTransColor(ima->GetPixelColor(x,yflip)); + pDoc->UpdateAllViews(NULL); + } + } + } +#if CXIMAGE_DEMO_SELECT + else { + KillTimer(1); + pDoc->m_NumSel=0; + m_SelShift=0; + } +#endif + } + CScrollView::OnLButtonDown(nFlags, point); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnLButtonUp(UINT nFlags, CPoint point) +{ + CDemoDoc* pDoc = GetDocument(); + +#if CXIMAGE_DEMO_SELECT + if (pDoc && pDoc->m_tool == 1){ + CxImage* ima=pDoc->GetImage(); + if (ima){ + int i=pDoc->m_NumSel; + if (i>2){ +#ifdef VATI_EXTENSIONS + if ( !pDoc->m_isRectSel ) + { + pDoc->m_Sel[i].x = pDoc->m_Sel[0].x; + pDoc->m_Sel[i].y = pDoc->m_Sel[0].y; + pDoc->m_NumSel++; + } +#else + pDoc->m_Sel[i].x = pDoc->m_Sel[0].x; + pDoc->m_Sel[i].y = pDoc->m_Sel[0].y; + pDoc->m_NumSel++; +#endif + SetTimer(1,333,NULL); + + long i; + long n=pDoc->m_NumSel; + POINT* p = (POINT*)malloc(n*sizeof(POINT)); + long h=ima->GetHeight(); + for(i=0;im_Sel[i].x; + p[i].y = h-1-pDoc->m_Sel[i].y; + } + + pDoc->Stopwatch(0); + + ima->SelectionClear(); + ima->SelectionAddPolygon(p,n); + + pDoc->Stopwatch(1); + pDoc->UpdateStatusBar(); + + free(p); + } else { + ima->SelectionDelete(); + } + Invalidate(0); + } + } +#endif + + CScrollView::OnLButtonUp(nFlags, point); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) +{ + switch (lHint) + { + case WM_USER_NEWIMAGE: + { + m_tracker.m_rect = CRect(0,0,0,0); + + CDemoDoc* pDoc = GetDocument(); + CxImage* ima = pDoc->GetImage(); + if (ima) { + int px=GetScrollPos(SB_HORZ); + int py=GetScrollPos(SB_VERT); + CSize sz(GetTotalSize()); + int x=(int)(ima->GetWidth()*pDoc->GetZoomFactor()); + int y=(int)(ima->GetHeight()*pDoc->GetZoomFactor()); + SetScrollSizes(MM_TEXT, CSize(x,y)); + CSize sz2(GetTotalSize()); + + CWnd* pFrame=GetParentFrame(); + RECT rClient; + pFrame->GetClientRect(&rClient); + + if (sz.cx!=0 && sz.cy!=0){ + if (x>rClient.right) SetScrollPos(SB_HORZ,sz2.cx*px/sz.cx); else SetScrollPos(SB_HORZ,0); + if (y>rClient.bottom) SetScrollPos(SB_VERT,sz2.cy*py/sz.cy); else SetScrollPos(SB_VERT,0); + } + + if (!(pFrame->IsIconic()||pFrame->IsZoomed())){ + RECT rMainCl,rFrame,rMainFr; + ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetClientRect(&rMainCl); + ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetWindowRect(&rMainFr); + pFrame->GetWindowRect(&rFrame); + pFrame->SetWindowPos(0,0,0, + (4+rFrame.right-rFrame.left-rClient.right+rClient.left)+ + min(rMainCl.right-(rFrame.left-rMainFr.left+12),x), + (4+rFrame.bottom-rFrame.top-rClient.bottom+rClient.top)+ + min(rMainCl.bottom-(rFrame.top-rMainFr.top+12),y), + SWP_NOMOVE|SWP_NOZORDER); + //ResizeParentToFit(1); + } + + if (!ima->SelectionIsValid()) KillTimer(1); + +#ifdef VATI_EXTENSIONS + ima->SetJpegQuality(theApp.m_optJpegQuality); +#endif + + CMainFrame* pMain = (CMainFrame*) AfxGetMainWnd(); + if (pMain->m_HistoBar.IsWindowVisible()){ + pDoc->m_hmax=ima->Histogram(pDoc->m_hr,pDoc->m_hg,pDoc->m_hb,pDoc->m_hgray); + pMain->m_HistoBar.Invalidate(); + } else { + pDoc->m_hmax = 0; + } + } + + break; + } + default: + { + CDemoDoc* pDoc = GetDocument(); + if (pDoc){ + CxImage* ima = pDoc->GetImage(); + if (ima){ + if (pDoc->GetStretchMode()) SetScrollSizes(MM_TEXT, CSize(0,0)); + else SetScrollSizes(MM_TEXT,CSize((int)(ima->GetWidth()*pDoc->GetZoomFactor()), + (int)(ima->GetHeight()*pDoc->GetZoomFactor()))); + } + } + } + } + CScrollView::OnUpdate(pSender, lHint, pHint); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnContextMenu(CWnd* pWnd, CPoint point) +{ + CDemoDoc* pDoc = GetDocument(); + if (pDoc && pDoc->m_tool==2) return; +#ifdef VATI_EXTENSIONS + // suppress context menu if right-click function was called just now + if ( m_suppressContextMenu == true ) + return; +#endif + static UINT toolbars[]={ + IDR_MAINFRAME, + IDR_TOOLBAR1, + }; + BCMenu menu; + menu.LoadMenu(IDM_CXIMAGE1); + menu.LoadToolbars(toolbars,2); + CMenu *pContextMenu=menu.GetSubMenu(0); + pContextMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_RIGHTBUTTON,point.x,point.y,AfxGetMainWnd()); +} +////////////////////////////////////////////////////////////////////////////// +LRESULT CDemoView::OnNewImage(WPARAM wParam, LPARAM lParam) +{ + CDemoDoc* pDoc = GetDocument(); + pDoc->UpdateAllViews(0,WM_USER_NEWIMAGE); + pDoc->UpdateStatusBar(); + return 0; +} +////////////////////////////////////////////////////////////////////////////// +LRESULT CDemoView::OnNewProgress(WPARAM wParam, LPARAM lParam) +{ + CStatusBar& statusBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetStatusBar(); + CString s; + s.Format("%d %%",(int)wParam); + statusBar.SetPaneText(2, s); + statusBar.Invalidate(1); + +/* CProgressCtrl& progressBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetProgressBar(); + progressBar.SetPos((int)wParam); + progressBar.Invalidate(1);*/ + + return 0; +} +////////////////////////////////////////////////////////////////////////////// +#if CXIMAGE_DEMO_SELECT +void CALLBACK LineDDAProc(int x, int y, CDemoView *pview) +{ + CDC* pDC = pview->GetDC(); + if (pDC) { + pview->m_SelCount++; + if (pview->m_SelCount <= 4) pDC->SetPixelV(x,y,RGB(255,255,255)); + else pDC->SetPixelV(x,y,RGB(0,0,0)); + if (pview->m_SelCount == 8) pview->m_SelCount=0; + } + pview->ReleaseDC(pDC); // +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::DrawSelection() +{ + CDemoDoc* pDoc = GetDocument(); + if (pDoc->m_NumSel>2){ + CPoint pos(GetScrollPosition()); + float zoom=pDoc->GetZoomFactor(); + m_SelCount=m_SelShift; +// pDC->MoveTo(zoom*pDoc->m_Sel[0].x - pos.x,zoom*pDoc->m_Sel[0].y - pos.y); + for(int i=1;im_NumSel;i++){ +// pDC->LineTo(zoom*pDoc->m_Sel[i].x - pos.x,zoom*pDoc->m_Sel[i].y - pos.y); + LineDDA((int)(zoom*pDoc->m_Sel[i-1].x - pos.x), + (int)(zoom*pDoc->m_Sel[i-1].y - pos.y), + (int)(zoom*pDoc->m_Sel[i].x - pos.x), + (int)(zoom*pDoc->m_Sel[i].y - pos.y), + (LINEDDAPROC)LineDDAProc,(LPARAM)this); + } + } +} +#endif +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnDestroy() +{ + CScrollView::OnDestroy(); + ((CMainFrame*)AfxGetMainWnd())->m_HistoBar.Invalidate(); +#if CXIMAGE_DEMO_SELECT + KillTimer(1); +#endif +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnTimer(UINT nIDEvent) +{ +#if CXIMAGE_DEMO_SELECT + m_SelShift++; + if (m_SelShift==8) m_SelShift=0; + DrawSelection(); +#endif + CScrollView::OnTimer(nIDEvent); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) +{ + + if (nChar == VK_ESCAPE){ + CMainFrame* pMain = (CMainFrame*) AfxGetMainWnd(); + if (pMain->m_fullscreen){ + pMain->PostMessage(WM_COMMAND, ID_VIEW_FULLSCREEN); + } + } + + CScrollView::OnChar(nChar, nRepCnt, nFlags); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnRButtonDown(UINT nFlags, CPoint point) +{ + CDemoDoc* pDoc = GetDocument(); + if (pDoc) { + switch(pDoc->m_tool){ + case 1: + { +#ifdef VATI_EXTENSIONS + m_suppressContextMenu = false; //default: Context Menu can be displayed on ButtonUp + CxImage *ima = pDoc->GetImage(); + if ( !(nFlags & MK_CONTROL) && pDoc->m_isRectSel && pDoc->m_NumSel == 5 && ima ) + { + // calculate origo + m_orgPnt.x = (pDoc->m_Sel[0].x + pDoc->m_Sel[1].x)/2; + m_orgPnt.y = (pDoc->m_Sel[0].y + pDoc->m_Sel[3].y)/2; + for(int i=0;i<5;i++) + { + // copy corner coordinates to double-prec array + m_dpnt[i].x = pDoc->m_Sel[i].x ; + m_dpnt[i].y = pDoc->m_Sel[i].y ; + } + + // get real coo from point + long x = point.x; + long y = point.y; + GetImageXY(pDoc, ima, &x,&y); + + // initialise old point var. + m_oldPnt.x = x; + m_oldPnt.y = y; + m_suppressContextMenu = true; // ButtonUp should not invoke context menu + } + else if ( nFlags & MK_CONTROL && ima /* && pDoc->m_isRectSel && pDoc->m_NumSel == 5 */) + { + // get real coo from point + long x = point.x; + long y = point.y; + GetImageXY(pDoc, ima, &x,&y); + + // initialise old point var. + m_oldPnt.x = x; + m_oldPnt.y = y; + m_suppressContextMenu = true; // ButtonUp should not invoke context menu + } +#endif + } + break; + case 2: + if (!pDoc->GetWaitingClick()) PostMessage(WM_COMMAND,ID_VIEW_ZOOMOUT); + return; + break; +#ifdef VATI_EXTENSIONS + default: + m_suppressContextMenu = false; //default: Context Menu can be displayed on ButtonUp +#endif + } // end switch + } // end if pDoc + + CScrollView::OnRButtonDown(nFlags, point); +} +////////////////////////////////////////////////////////////////////////////// +void CDemoView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView) +{ + if (bActivate){ + ((CMainFrame*)AfxGetMainWnd())->m_HistoBar.Invalidate(); + } + + CScrollView::OnActivateView(bActivate, pActivateView, pDeactiveView); +} +////////////////////////////////////////////////////////////////////////////// +BOOL CDemoView::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) +{ + if (m_tracker.SetCursor( pWnd, nHitTest )) return TRUE; + return CScrollView::OnSetCursor(pWnd, nHitTest, message); +} +////////////////////////////////////////////////////////////////////////////// +bool CDemoView::SetImageRectSelection(CDemoDoc *pDoc,CRect *rect) +{ + if (pDoc==0) + return false; + + CxImage* ima = pDoc->GetImage(); + + if (ima==0) + return false; + + long x,y; + RECT rect_img; + x = rect_img.left = rect->left; + y = rect_img.top = rect->top; + GetImageXY(pDoc, ima, &x,&y); + rect_img.top = ima->GetHeight() - 1 - y; + rect_img.left = x; + + x = rect_img.right = rect->right; + y = rect_img.bottom = rect->bottom; + GetImageXY(pDoc, ima, &x,&y); + rect_img.bottom = ima->GetHeight() - 1 - y; + rect_img.right = x; + + ima->SelectionClear(); + ima->SelectionAddRect(rect_img); + + return true; +} +////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/demoView.h b/SlnkDWFImpl/CxImage/demo/demoView.h new file mode 100644 index 0000000..98bc43f --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/demoView.h @@ -0,0 +1,91 @@ +// demoView.h : interface of the CDemoView class +// +///////////////////////////////////////////////////////////////////////////// +#define CXIMAGE_DEMO_SELECT 1 + +// double precision coo type +typedef struct { + double x, y; +} Dpoint2d; + +class CDemoView : public CScrollView +{ +protected: // create from serialization only + CDemoView(); + DECLARE_DYNCREATE(CDemoView) + +// Attributes +public: + CDemoDoc* GetDocument(); + +// Operations +public: + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CDemoView) + public: + virtual void OnDraw(CDC* pDC); // overridden to draw this view + virtual BOOL PreCreateWindow(CREATESTRUCT& cs); + protected: + virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); + virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); + virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); + virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); + virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView); + //}}AFX_VIRTUAL + +// Implementation +public: + void GetImageXY(CDemoDoc *pDoc, CxImage *ima, long *x, long *y); + bool SetImageRectSelection(CDemoDoc *pDoc,CRect *rect); + virtual ~CDemoView(); +#ifdef _DEBUG + virtual void AssertValid() const; + virtual void Dump(CDumpContext& dc) const; +#endif + +#if CXIMAGE_DEMO_SELECT + long m_SelCount; + long m_SelShift; + void DrawSelection(); + CPoint m_RefPoint,m_RefScroll; +#endif +protected: + CBrush m_brHatch; + + CRectTracker m_tracker; + +// Generated message map functions +protected: + //{{AFX_MSG(CDemoView) + afx_msg void OnMouseMove(UINT nFlags, CPoint point); + afx_msg BOOL OnEraseBkgnd(CDC* pDC); + afx_msg void OnSetFocus(CWnd* pOldWnd); + afx_msg void OnLButtonDown(UINT nFlags, CPoint point); + afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); + afx_msg void OnLButtonUp(UINT nFlags, CPoint point); + afx_msg void OnTimer(UINT nIDEvent); + afx_msg void OnDestroy(); + afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); + afx_msg void OnRButtonDown(UINT nFlags, CPoint point); + afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); + //}}AFX_MSG + afx_msg LRESULT OnNewImage(WPARAM wParam, LPARAM lParam); + afx_msg LRESULT OnNewProgress(WPARAM wParam, LPARAM lParam); + DECLARE_MESSAGE_MAP() +#ifdef VATI_EXTENSIONS +private: + bool m_suppressContextMenu; + Dpoint2d m_oldPnt; + Dpoint2d m_orgPnt; + Dpoint2d m_dpnt[6]; +#endif +}; + +#ifndef _DEBUG // debug version in demoView.cpp +inline CDemoDoc* CDemoView::GetDocument() + { return (CDemoDoc*)m_pDocument; } +#endif + +///////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/dlgcapture.cpp b/SlnkDWFImpl/CxImage/demo/dlgcapture.cpp new file mode 100644 index 0000000..34d3376 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/dlgcapture.cpp @@ -0,0 +1,109 @@ +// DlgCapture.cpp : implementation file +// + +#include "stdafx.h" +#include "demo.h" +#include "DlgCapture.h" +#include "enumwnd.h" //global structures for task enumeration + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +////////////////////////////////////////////////////////////////////////////// +BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam) +{ + DWORD i; + RECT r; + CHAR buf[MAX_PATH]; + PTASK_LIST_ENUM te = (PTASK_LIST_ENUM)lParam; + PTASK_LIST tlist = te->tlist; + DWORD numTasks = te->numtasks; + + i=1+tlist[0].dwProcessId; + // max 255 windows (I think it's enough) + if (i<255){ + // filter the windows to capture + if (IsWindowVisible(hwnd) && !IsIconic(hwnd)){ + GetClientRect(hwnd,&r); + // discard strange windows + if (r.right>4 && r.bottom>4){ + // get the window caption + if (GetWindowText(hwnd, buf, sizeof(buf) )) { + tlist[i].hwnd = hwnd; // store hwnd + strcpy( tlist[i].WindowTitle, buf ); // store caption + tlist[0].dwProcessId++; + } + } + } + } + return TRUE; +} +////////////////////////////////////////////////////////////////////////////// +// DlgCapture dialog +////////////////////////////////////////////////////////////////////////////// +DlgCapture::DlgCapture(CWnd* pParent /*=NULL*/) + : CDialog(DlgCapture::IDD, pParent) +{ + //{{AFX_DATA_INIT(DlgCapture) + //}}AFX_DATA_INIT +} +////////////////////////////////////////////////////////////////////////////// +void DlgCapture::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(DlgCapture) + DDX_Control(pDX, IDOK, m_ok); + DDX_Control(pDX, IDCANCEL, m_canc); + DDX_Control(pDX, IDC_LIST1, m_list); + //}}AFX_DATA_MAP +} +////////////////////////////////////////////////////////////////////////////// +BEGIN_MESSAGE_MAP(DlgCapture, CDialog) + //{{AFX_MSG_MAP(DlgCapture) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() +////////////////////////////////////////////////////////////////////////////// +// DlgCapture message handlers +BOOL DlgCapture::OnInitDialog() +{ + CDialog::OnInitDialog(); + m_ok.SetIcon(IDI_G,BS_LEFT); + m_canc.SetIcon(IDI_R,BS_LEFT); + //structures to contain the task info + TASK_LIST_ENUM te; + TASK_LIST tlist[256]; + //reserved slot for task enum + tlist[0].dwProcessId = 0; + // task list + te.tlist = tlist; + // get the windows + EnumWindows(EnumWindowsProc,(LPARAM)(&te)); + + int numtasks=tlist[0].dwProcessId; + int idx; + // always add the desktop + idx = m_list.InsertString(-1,"Desktop"); + m_list.SetItemData(idx,(DWORD)::GetDesktopWindow()); + // fill the list with the other windows + for(int i=1;i 1000 +#pragma once +#endif // _MSC_VER > 1000 +// DlgCapture.h : header file +// + +#include "xTargetButton.h" + +///////////////////////////////////////////////////////////////////////////// +// DlgCapture dialog +class DlgCapture : public CDialog +{ +// Construction +public: + CString m_SelectedTitle; + HWND m_SelectedWnd; + DlgCapture(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(DlgCapture) + enum { IDD = IDD_CAPTURE }; + CxTargetButton m_ok; + CxTargetButton m_canc; + CListBox m_list; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(DlgCapture) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(DlgCapture) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DlgCapture_H__950ECDE3_A3D3_11D5_8DD4_9ED5C4640338__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/demo/enumwnd.h b/SlnkDWFImpl/CxImage/demo/enumwnd.h new file mode 100644 index 0000000..3acf2c2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/enumwnd.h @@ -0,0 +1,15 @@ +//global structures for task enumeration +typedef struct _TASK_LIST { + DWORD dwProcessId; + DWORD dwInheritedFromProcessId; + BOOL flags; + HWND hwnd; + CHAR ProcessName[MAX_PATH]; + CHAR WindowTitle[MAX_PATH]; +} TASK_LIST, *PTASK_LIST; + +typedef struct _TASK_LIST_ENUM { + PTASK_LIST tlist; + DWORD numtasks; +} TASK_LIST_ENUM, *PTASK_LIST_ENUM; + diff --git a/SlnkDWFImpl/CxImage/demo/logomdi.cpp b/SlnkDWFImpl/CxImage/demo/logomdi.cpp new file mode 100644 index 0000000..e442278 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/logomdi.cpp @@ -0,0 +1,127 @@ +// logomdi.cpp : implementation file +// + +#include "stdafx.h" +#include "logomdi.h" +#include "demo.h" + +#ifdef _DEBUG +#undef THIS_FILE +static char BASED_CODE THIS_FILE[] = __FILE__; +#endif + +////////////////////////////////////////////////////////////////////////////// +// CLogoMdi +CLogoMdi::CLogoMdi() : m_sizeClient(0,0) +{ + m_LogoFont.CreateFont(36, 0, 0, 0, FW_BOLD, 1, FALSE, FALSE, + ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, + FIXED_PITCH | FF_ROMAN, "Times New Roman"); + + sLogoString = "CxImage "; + +/* //BITMAP background + HBITMAP bitmap; + if (bitmap = ::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP1))){ + bgImage = new CxImage((HBITMAP)bitmap); + } else { + bgImage = NULL; + }*/ + + //JPEG background + bgImage = new CxImage(); + if (!bgImage->LoadResource(FindResource(NULL,"IDR_JPG1","JPG"),CXIMAGE_FORMAT_JPG)){ + delete bgImage; + bgImage =NULL; + } + if (bgImage) { + COLORREF rgb=GetSysColor(COLOR_APPWORKSPACE); + RGBQUAD hsl=bgImage->RGBtoHSL(bgImage->RGBtoRGBQUAD(rgb)); + bgImage->Colorize(hsl.rgbRed,min(hsl.rgbGreen,100)); + } +} +////////////////////////////////////////////////////////////////////////////// +CLogoMdi::~CLogoMdi() +{ + m_LogoFont.DeleteObject(); + delete bgImage; +} +////////////////////////////////////////////////////////////////////////////// +BEGIN_MESSAGE_MAP(CLogoMdi, CWnd) + //{{AFX_MSG_MAP(CLogoMdi) + ON_WM_ERASEBKGND() + ON_WM_SIZE() + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +////////////////////////////////////////////////////////////////////////////// +// CLogoMdi message handlers +BOOL CLogoMdi::OnEraseBkgnd(CDC* pDC) +{ + // This is where the real work is done printing the logo in the corner.. + + RECT rect,m_rDataBox; + GetClientRect(&rect); + CopyRect(&m_rDataBox,&rect); + + if (bgImage==NULL){ + CBrush NewBrush(GetSysColor(COLOR_DESKTOP)) ; + pDC->SetBrushOrg(0,0) ; + CBrush* pOldBrush = (CBrush*)pDC->SelectObject(&NewBrush); + pDC->PatBlt(rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top ,PATCOPY); + pDC->SelectObject(pOldBrush); + } else { + bgImage->Tile(pDC->GetSafeHdc(),&rect); + } + + TEXTMETRIC tm; + pDC->GetTextMetrics(&tm); + CFont* oldFont = pDC->SelectObject(&m_LogoFont); + CSize sz = pDC->GetTextExtent(sLogoString, sLogoString.GetLength()); + // GetTextExtent calculates the size of the displayed logo + // which depends on the device context.... + // Calculate the box size by subtracting the text width and height from the + // window size. Also subtract 20% of the average character size to keep the + // logo from printing into the borders... + m_rDataBox.left = m_rDataBox.right - sz.cx - tm.tmAveCharWidth/2; + m_rDataBox.top = m_rDataBox.bottom - sz.cy - tm.tmHeight/5; + pDC->SetBkMode(TRANSPARENT); + // shift logo box right, and print black... + COLORREF oldColor = pDC->SetTextColor(RGB(0,0,0)); + pDC->DrawText(sLogoString, sLogoString.GetLength(), &m_rDataBox, DT_VCENTER | DT_SINGLELINE | DT_CENTER); + // shift logo box left and print white + m_rDataBox.left -= 3*tm.tmAveCharWidth/5; + pDC->SetTextColor(RGB(255,255,255)); + pDC->DrawText(sLogoString, sLogoString.GetLength(), &m_rDataBox, DT_VCENTER | DT_SINGLELINE | DT_CENTER); + // Restore original location and print in the button face color + m_rDataBox.left += tm.tmAveCharWidth/5; + pDC->SetTextColor(GetSysColor(COLOR_BTNFACE)); + pDC->DrawText(sLogoString, sLogoString.GetLength(), &m_rDataBox, DT_VCENTER | DT_SINGLELINE | DT_CENTER); + // restore the original properties and release resources... + pDC->SelectObject(oldFont); + pDC->SetTextColor(oldColor); + + return TRUE; +} +////////////////////////////////////////////////////////////////////////////// +void CLogoMdi::OnSize(UINT nType, int cx, int cy) +{ + Default() ; // Same as DefWindowProc(), or CWnd::OnSize(); + // if the app is just starting up, save the window + // dimensions and get out + if ((m_sizeClient.cx == 0) && (m_sizeClient.cy==0)) { + m_sizeClient.cx = cx; + m_sizeClient.cy = cy; + return ; + } + // if the size hasn't changed, break and pass to default + if ((m_sizeClient.cx == cx) && ( m_sizeClient.cy == cy)) + return ; + // window size has changed so save new dimensions and force + // entire background to redraw, including icon backgrounds + m_sizeClient.cx = cx; + m_sizeClient.cy = cy; + RedrawWindow(NULL,NULL,RDW_INVALIDATE|RDW_ERASE|RDW_ERASENOW|RDW_ALLCHILDREN); + return ; +} +////////////////////////////////////////////////////////////////////////////// diff --git a/SlnkDWFImpl/CxImage/demo/logomdi.h b/SlnkDWFImpl/CxImage/demo/logomdi.h new file mode 100644 index 0000000..7fd45cc --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/logomdi.h @@ -0,0 +1,30 @@ +// logomdi.h : header file +///////////////////////////////////////////////////////////////////////////// +// CLogoMdi window +#if !defined(_CLOGOMDI_H) +#define _CLOGOMDI_H + +#include "ximage.h" + +class CLogoMdi : public CWnd +{ +// Construction +public: + CLogoMdi(); +// Implementation +public: + virtual ~CLogoMdi(); + // Generated message map functions +protected: + CSize m_sizeClient ; + CFont m_LogoFont; + CString sLogoString; + CxImage* bgImage; + //{{AFX_MSG(CLogoMdi) + afx_msg BOOL OnEraseBkgnd(CDC* pDC); + afx_msg void OnSize(UINT nType, int cx, int cy); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; +///////////////////////////////////////////////////////////////////////////// +#endif \ No newline at end of file diff --git a/SlnkDWFImpl/CxImage/demo/memdc.h b/SlnkDWFImpl/CxImage/demo/memdc.h new file mode 100644 index 0000000..b17a8c2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/memdc.h @@ -0,0 +1,102 @@ +#ifndef _MEMDC_H_ +#define _MEMDC_H_ + +////////////////////////////////////////////////// +// CMemDC - memory DC +// +// Author: Keith Rule +// Email: keithr@europa.com +// Copyright 1996-1999, Keith Rule +// +// You may freely use or modify this code provided this +// Copyright is included in all derived versions. +// +// History - 10/3/97 Fixed scrolling bug. +// Added print support. - KR +// +// 11/3/99 Fixed most common complaint. Added +// background color fill. - KR +// +// 11/3/99 Added support for mapping modes other than +// MM_TEXT as suggested by Lee Sang Hun. - KR +// +// This class implements a memory Device Context which allows +// flicker free drawing. + +class CMemDC : public CDC { +protected: + CBitmap m_bitmap; // Offscreen bitmap + CBitmap* m_oldBitmap; // bitmap originally found in CMemDC + CDC* m_pDC; // Saves CDC passed in constructor + CRect m_rect; // Rectangle of drawing area. + BOOL m_bMemDC; // TRUE if CDC really is a Memory DC. + + void Construct(CDC* pDC) + { + ASSERT(pDC != NULL); + + // Some initialization + m_pDC = pDC; + m_oldBitmap = NULL; + m_bMemDC = !pDC->IsPrinting(); + + if (m_bMemDC) { + // Create a Memory DC + CreateCompatibleDC(pDC); + pDC->LPtoDP(&m_rect); + + m_bitmap.CreateCompatibleBitmap(pDC, m_rect.Width(), m_rect.Height()); + m_oldBitmap = SelectObject(&m_bitmap); + + SetMapMode(pDC->GetMapMode()); + pDC->DPtoLP(&m_rect); + SetWindowOrg(m_rect.left, m_rect.top); + } else { + // Make a copy of the relevent parts of the current DC for printing + m_bPrinting = pDC->m_bPrinting; + m_hDC = pDC->m_hDC; + m_hAttribDC = pDC->m_hAttribDC; + } + + // Fill background + FillSolidRect(m_rect, pDC->GetBkColor()); + } + +// TRK begin +public: + CMemDC(CDC* pDC ) : CDC() { pDC->GetClipBox(&m_rect); Construct(pDC); } + CMemDC(CDC* pDC, const RECT& rect) : CDC() { m_rect = rect ; Construct(pDC); } +// TRK end + + virtual ~CMemDC() + { + if (m_bMemDC) { + // Copy the offscreen bitmap onto the screen. + m_pDC->BitBlt(m_rect.left, m_rect.top, m_rect.Width(), m_rect.Height(), + this, m_rect.left, m_rect.top, SRCCOPY); + + //Swap back the original bitmap. + SelectObject(m_oldBitmap); + } else { + // All we need to do is replace the DC with an illegal value, + // this keeps us from accidently deleting the handles associated with + // the CDC that was passed to the constructor. + m_hDC = m_hAttribDC = NULL; + } + } + + // Allow usage as a pointer + CMemDC* operator->() + { + return this; + } + + // Allow usage as a pointer + operator CMemDC*() + { + return this; + } +}; + + +#endif diff --git a/SlnkDWFImpl/CxImage/demo/resource.h b/SlnkDWFImpl/CxImage/demo/resource.h new file mode 100644 index 0000000..4a13cae --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/resource.h @@ -0,0 +1,225 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by demo.rc +// +#define ID_FONT 3 +#define IDEXIF 3 +#define IDCOLORS 3 +#define IDD_ABOUTBOX 100 +#define IDR_MAINFRAME 128 +#define IDR_DEMOTYPE 129 +#define IDB_BITMAP1 131 +#define IDD_ROTATE 132 +#define IDR_ICO1 135 +#define IDR_GIF1 136 +#define IDR_PNG1 137 +#define IDD_CAPTURE 138 +#define IDD_RESAMPLE 139 +#define IDR_TIF1 141 +#define IDM_CXIMAGE1 142 +#define IDD_DECBPP 143 +#define IDD_INCBPP 144 +#define IDD_OPTIONS 145 +#define IDD_DITHER 147 +#define IDD_THRESHOLD 148 +#define IDD_COLORIZE 149 +#define IDR_TOOLBAR1 149 +#define IDD_OPACITY 150 +#define IDD_DWNURL 151 +#define IDD_GAMMA 152 +#define IDI_OK 152 +#define IDI_CANC 153 +#define IDI_R 154 +#define IDD_HISTO 154 +#define IDI_G 155 +#define IDI_B 156 +#define IDI_GRAY 157 +#define IDD_PALETTE 158 +#define IDD_COMBINE 159 +#define IDD_FFT 161 +#define IDD_REPAIR 162 +#define IDD_TEXT 163 +#define IDD_MIX 165 +#define IDD_SKEW 167 +#define IDD_JPEG 168 +#define IDC_EDIT1 1000 +#define IDC_LIST1 1001 +#define IDC_EDIT2 1001 +#define IDC_CHECK1 1002 +#define IDC_EDIT3 1002 +#define IDC_RADIO1 1003 +#define IDC_STATUS 1003 +#define IDC_EDIT4 1003 +#define IDC_CHECK3 1003 +#define IDC_RADIO2 1004 +#define IDC_URL 1004 +#define IDC_EDIT5 1004 +#define IDC_CHECK4 1004 +#define IDC_RADIO3 1005 +#define IDC_EDIT6 1005 +#define IDC_RADIO4 1006 +#define IDC_LOG 1006 +#define IDC_LOAD 1006 +#define IDC_EDIT7 1006 +#define IDC_RADIO5 1007 +#define IDC_SAVE 1007 +#define IDC_EDIT8 1007 +#define IDC_CHECK2 1008 +#define IDC_RADIO6 1008 +#define IDC_EDIT9 1008 +#define IDC_BAR 1009 +#define IDC_RADIO7 1009 +#define IDC_COMBO1 1010 +#define IDC_RADIO8 1010 +#define IDC_COMBO2 1011 +#define IDC_RADIO9 1011 +#define IDC_COMBO3 1012 +#define IDC_RADIO10 1012 +#define IDC_COMBO4 1013 +#define IDC_RADIO11 1013 +#define IDC_COMBO5 1014 +#define IDC_RADIO12 1014 +#define IDC_REAL 1015 +#define IDC_COMBO9 1015 +#define IDC_RADIO13 1015 +#define IDC_IMAG 1016 +#define IDC_RADIO14 1016 +#define IDC_COMBO6 1018 +#define IDC_COMBO7 1019 +#define IDC_COMBO_IM 1019 +#define IDC_COMBO8 1020 +#define IDC_COMBO_OM 1020 +#define IDC_BTN_TXTCOLOR 1021 +#define IDC_BTN_BCKCOLOR 1022 +#define IDC_SLIDER_OPACITY 1023 +#define IDC_SLIDER_RADIUS 1024 +#define IDC_STATIC_OP 1025 +#define IDC_STATIC_RADIUS 1026 +#define IDC_DST 1027 +#define IDC_SRC 1028 +#define IDC_OP 1029 +#define IDC_BUTTON1 1030 +#define IDC_PICTURE 1031 +#define IDC_CHECK5 1032 +#define ID_STRETCH_MODE 32771 +#define ID_TRANSFORM_ELLIPSE 32772 +#define ID_IMAGE_FROM_BITMAP 32773 +#define ID_CXIMAGE_MIRROR 32774 +#define ID_CXIMAGE_FLIP 32775 +#define ID_WINDOW_DUPLICATE 32776 +#define ID_CXIMAGE_NEGATIVE 32777 +#define ID_CXIMAGE_GRAYSCALE 32778 +#define ID_CXIMAGE_ROTATE 32779 +#define ID_CXIMAGE_LOADJPEGRESOURCE 32780 +#define ID_CXIMAGE_LOADICONRESOURCE 32781 +#define ID_CXIMAGE_LOADGIFRESOURCE 32782 +#define ID_CXIMAGE_LOADPNGRESOURCE 32783 +#define ID_VIEW_ZOOMIN 32786 +#define ID_VIEW_ZOOMOUT 32787 +#define ID_VIEW_NORMALVIEWING11 32788 +#define ID_FILE_CAPTURE 32789 +#define ID_CXIMAGE_LOADTIFRESOURCE 32790 +#define ID_WINDOW_CLOSEALL 32791 +#define ID_CXIMAGE_SETTRANSPARENCY 32792 +#define ID_CXIMAGE_REMOVETRANSPARENCY 32793 +#define ID_CXIMAGE_RESAMPLE 32794 +#define ID_CXIMAGE_DECREASEBPP 32795 +#define ID_CXIMAGE_INCREASEBPP 32796 +#define ID_CXIMAGE_OPTIONS 32797 +#define ID_CXIMAGE_DITHER 32798 +#define ID_CXIMAGE_THRESHOLD 32799 +#define ID_CXIMAGE_SPLITRGB 32800 +#define ID_CXIMAGE_SPLITYUV 32801 +#define ID_CXIMAGE_SPLITHSL 32802 +#define ID_CXIMAGE_PSEUDOCOLORS 32803 +#define ID_CXIMAGE_SPLITCHANNELS 32804 +#define ID_CXIMAGE_RESOURCES 32805 +#define ID_CXIMAGE_COLORIZE 32808 +#define ID_CXIMAGE_LIGHTEN 32809 +#define ID_CXIMAGE_DARKEN 32810 +#define ID_CXIMAGE_CONTRAST 32811 +#define ID_CXIMAGE_EMBOSS 32812 +#define ID_CXIMAGE_BLUR 32813 +#define ID_CXIMAGE_SOFTEN 32814 +#define ID_CXIMAGE_SHARPEN 32815 +#define ID_CXIMAGE_EDGE 32816 +#define ID_CXIMAGE_ERODE 32817 +#define ID_CXIMAGE_DILATE 32818 +#define ID_FILE_SELECTSOURCE 32824 +#define ID_FILE_ACQUIRE 32825 +#define ID_BUTTON32842 32842 +#define ID_VIEW_MENUSTYLE_NORMAL 32846 +#define ID_VIEW_MENUSTYLE_XP 32847 +#define ID_CXIMAGE_CROP 32848 +#define ID_CXIMAGE_REMOVEALPHACHANNEL 32850 +#define ID_CXIMAGE_OPACITY 32851 +#define ID_CXIMAGE_INVETALPHA 32852 +#define ID_CXIMAGE_ALPHAPALETTETOGGLE 32853 +#define ID_CXIMAGE_ALPHASTRIP 32854 +#define ID_CXIMAGE_ROTATEL 32855 +#define ID_CXIMAGE_ROTATER 32856 +#define ID_CXIMAGE_DEMOSAVEMULTIPAGETIFF 32857 +#define ID_CXIMAGE_DEMOSAVEANIMATEDGIF 32861 +#define ID_CXIMAGE_DOWNLOADFROMURL 32862 +#define ID_CXIMAGE_GAMMA 32863 +#define ID_CXIMAGE_MEDIAN 32864 +#define ID_CXIMAGE_ADDNOISE 32865 +#define ID_VIEW_TOOLS_MOVE 32869 +#define ID_VIEW_TOOLS_SELECT 32871 +#define ID_VIEW_FULLSCREEN 32872 +#define ID_VIEW_TOOLS_ZOOM 32874 +#define ID_VIEW_HISTOGRAM 32876 +#define ID_VIEW_PALETTE 32877 +#define ID_CXIMAGE_COMBINE 32879 +#define ID_CXIMAGE_FFT 32880 +#define ID_CXIMAGE_SPLITYIQ 32881 +#define ID_CXIMAGE_SPLITXYZ 32882 +#define ID_CXIMAGE_REPAIR 32883 +#define ID_FILTERS_SPLIT 32884 +#define ID_CXIMAGE_ALPHACHANNEL_SPLIT 32885 +#define ID_VIEW_TOOLS_TEXT 32886 +#define ID_CXIMAGE_SPLITCMYK 32887 +#define ID_CXIMAGE_ALPHACREATE 32888 +#define ID_CXIMAGE_HISTOGRAM_STRETCH 32889 +#define ID_CXIMAGE_HISTOGRAM_EQUALIZE 32890 +#define ID_CXIMAGE_HISTOGRAM_NORMALIZE 32891 +#define ID_CXIMAGE_HISTOGRAM_LOG 32894 +#define ID_CXIMAGE_HISTOGRAM_ROOT 32895 +#define ID_CXIMAGE_GAUSSIAN3X3 32896 +#define ID_CXIMAGE_GAUSSIAN5X5 32897 +#define ID_CXIMAGE_CONTOUR 32898 +#define ID_CXIMAGE_FILTERS_LESSCONTRAST 32899 +#define ID_CXIMAGE_LESSCONTRAST 32900 +#define ID_CXIMAGE_JITTER 32901 +#define ID_FILTERS_MIX 32903 +#define ID_CXIMAGE_CIRCLETRANSFORM_PINCH 32904 +#define ID_CXIMAGE_CIRCLETRANSFORM_PUNCH 32905 +#define ID_CXIMAGE_CIRCLETRANSFORM_SWIRL 32906 +#define ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER 32907 +#define ID_FILTERS_CIRCLETRANSFORM_BATHROOM 32908 +#define ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM 32909 +#define ID_CXIMAGE_DEMOCREATEFROMARRAY 32910 +#define ID_CXIMAGE_HISTOGRAM_STRETCH1 32911 +#define ID_CXIMAGE_HISTOGRAM_STRETCH2 32912 +#define ID_FILTERS_NONLINEAR 32913 +#define ID_FILTERS_NONLINEAR_EDGE 32914 +#define ID_CXIMAGE_SKEW 32915 +#define ID_VIEW_TOOLS_TRACKER 32916 +#define ID_FILTERS_JPEGCOMPRESSION 32918 +#define ID_VIEW_SMOOTH 32919 +#define ID_INDICATOR1 59142 +#define ID_INDICATOR2 59143 +#define ID_INDICATOR3 59144 +#define ID_INDICATOR4 59145 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_3D_CONTROLS 1 +#define _APS_NEXT_RESOURCE_VALUE 168 +#define _APS_NEXT_COMMAND_VALUE 32920 +#define _APS_NEXT_CONTROL_VALUE 1033 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/SlnkDWFImpl/CxImage/demo/twain.h b/SlnkDWFImpl/CxImage/demo/twain.h new file mode 100644 index 0000000..366ba14 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/twain.h @@ -0,0 +1,1877 @@ +/* ======================================================================== *\ + + Copyright (C) 1991, 1992 TWAIN Working Group: Aldus, Caere, Eastman-Kodak, + Hewlett-Packard and Logitech Corporations. All rights reserved. + + Copyright (C) 1997 TWAIN Working Group: Bell+Howell, Canon, DocuMagix, + Fujitsu, Genoa Technology, Hewlett-Packard, Kofax Imaging Products, and + Ricoh Corporation. All rights reserved. + + Copyright © 1998 TWAIN Working Group: Adobe Systems Incorporated, + Canon Information Systems, Eastman Kodak Company, + Fujitsu Computer Products of America, Genoa Technology, + Hewlett-Packard Company, Intel Corporation, Kofax Image Products, + JFL Peripheral Solutions Inc., Ricoh Corporation, and Xerox Corporation. + All rights reserved. + + TWAIN.h - This is the definitive include file for applications and + data sources written to the TWAIN specification. + It defines constants, data structures, messages etc. + for the public interface to TWAIN. + + Revision History: + version 1.0, March 6, 1992. TWAIN 1.0. + version 1.1, January 1993. Tech Notes 1.1 + version 1.5, June 1993. Specification Update 1.5 + Change DC to TW + Change filename from DC.H to TWAIN.H + version 1.5, July 1993. Remove spaces from country identifiers + + version 1.7, July 1997 Added Capabilities and data structure for + document imaging and digital cameras. + KHL. + version 1.7, July 1997 Inserted Borland compatibile structure packing + directives provided by Mentor. JMH + version 1.7, Aug 1997 Expanded file tabs to spaces. + NOTE: future authors should be sure to have + their editors set to automatically expand tabs + to spaces (original tab setting was 4 spaces). + version 1.7, Sept 1997 Added job control values + Added return codes + version 1.7, Sept 1997 changed definition of pRGBRESPONSE to + pTW_RGBRESPONSE + version 1.7 Aug 1998 Added missing TWEI_BARCODEROTATION values + TWBCOR_ types JMH + version 1.8 August 1998 Added new types and definitions required + for 1.8 Specification JMH + version 1.8 January 1999 Changed search mode from SRCH_ to TWBD_ as + in 1.8 Specification, added TWBT_MAXICODE JMH + version 1.8 January 1999 Removed undocumented duplicate AUTO JMH +\* ======================================================================== */ + +#ifndef TWAIN +#define TWAIN + +/* SDH - 02/08/95 - TWUNK */ +/* Force 32-bit twain to use same packing of twain structures as existing */ +/* 16-bit twain. This allows 16/32-bit thunking. */ +#ifdef WIN32 + #ifdef __BORLANDC__ //(Mentor June 13, 1996) if using a Borland compiler + #pragma option -a2 //(Mentor June 13, 1996) switch to word alignment + #else //(Mentor June 13, 1996) if we're using some other compiler + #pragma pack (push, before_twain) + #pragma pack (2) + #endif //(Mentor June 13, 1996) +#else /* WIN32 */ +#endif /* WIN32 */ + +/**************************************************************************** + * TWAIN Version * + ****************************************************************************/ +#define TWON_PROTOCOLMINOR 8 /* Changed for Version 1.8 */ +#define TWON_PROTOCOLMAJOR 1 + +/**************************************************************************** + * Platform Dependent Definitions and Typedefs * + ****************************************************************************/ + +/* Define one of the following, depending on the platform */ +/* #define _MAC_ */ +/* #define _UNIX_ */ +#define _MSWIN_ + +#ifdef _MSWIN_ + typedef HANDLE TW_HANDLE; + typedef LPVOID TW_MEMREF; + + /* SDH - 05/05/95 - TWUNK */ + /* For common code between 16 and 32 bits. */ + #ifdef WIN32 + #define TW_HUGE + #else /* WIN32 */ + #define TW_HUGE huge + #endif /* WIN32 */ + typedef BYTE TW_HUGE * HPBYTE; + typedef void TW_HUGE * HPVOID; +#endif /* _MSWIN_ */ + +#ifdef _MAC_ + #define PASCAL pascal + #define FAR + typedef Handle TW_HANDLE; + typedef char *TW_MEMREF; +#endif /* _MAC_ */ + +#ifdef _UNIX_ + #define PASCAL pascal + typedef unsigned char *TW_HANDLE; + typedef unsigned char *TW_MEMREF; +#endif /* _UNIX_ */ + +/**************************************************************************** + * Type Definitions * + ****************************************************************************/ + +/* String types. These include room for the strings and a NULL char, * + * or, on the Mac, a length byte followed by the string. * + * TW_STR255 must hold less than 256 chars so length fits in first byte. */ +typedef char TW_STR32[34], FAR *pTW_STR32; +typedef char TW_STR64[66], FAR *pTW_STR64; +typedef char TW_STR128[130], FAR *pTW_STR128; +typedef char TW_STR255[256], FAR *pTW_STR255; + +/* Numeric types. */ +typedef char TW_INT8, FAR *pTW_INT8; +typedef short TW_INT16, FAR *pTW_INT16; +typedef long TW_INT32, FAR *pTW_INT32; +typedef unsigned char TW_UINT8, FAR *pTW_UINT8; +typedef unsigned short TW_UINT16, FAR *pTW_UINT16; +typedef unsigned long TW_UINT32, FAR *pTW_UINT32; +typedef unsigned short TW_BOOL, FAR *pTW_BOOL; + +/* Fixed point structure type. */ +typedef struct { + TW_INT16 Whole; /* maintains the sign */ + TW_UINT16 Frac; +} TW_FIX32, FAR *pTW_FIX32; + +/**************************************************************************** + * Structure Definitions * + ****************************************************************************/ + +/* No DAT needed. */ +typedef struct { + TW_FIX32 X; + TW_FIX32 Y; + TW_FIX32 Z; +} TW_CIEPOINT, FAR * pTW_CIEPOINT; + +/* No DAT needed. */ +typedef struct { + TW_FIX32 StartIn; + TW_FIX32 BreakIn; + TW_FIX32 EndIn; + TW_FIX32 StartOut; + TW_FIX32 BreakOut; + TW_FIX32 EndOut; + TW_FIX32 Gamma; + TW_FIX32 SampleCount; /* if =0 use the gamma */ +} TW_DECODEFUNCTION, FAR * pTW_DECODEFUNCTION; + +/* No DAT needed. */ +typedef struct { + TW_UINT8 Index; /* Value used to index into the color table. */ + TW_UINT8 Channel1; /* First tri-stimulus value (e.g Red) */ + TW_UINT8 Channel2; /* Second tri-stimulus value (e.g Green) */ + TW_UINT8 Channel3; /* Third tri-stimulus value (e.g Blue) */ +} TW_ELEMENT8, FAR * pTW_ELEMENT8; + +/* No DAT. Defines a frame rectangle in ICAP_UNITS coordinates. */ +typedef struct { + TW_FIX32 Left; + TW_FIX32 Top; + TW_FIX32 Right; + TW_FIX32 Bottom; +} TW_FRAME, FAR * pTW_FRAME; + +/* No DAT needed. Used to manage memory buffers. */ +typedef struct { + TW_UINT32 Flags; /* Any combination of the TWMF_ constants. */ + TW_UINT32 Length; /* Number of bytes stored in buffer TheMem. */ + TW_MEMREF TheMem; /* Pointer or handle to the allocated memory buffer. */ +} TW_MEMORY, FAR * pTW_MEMORY; + +/* No DAT needed. */ +typedef struct { + TW_DECODEFUNCTION Decode[3]; + TW_FIX32 Mix[3][3]; +} TW_TRANSFORMSTAGE, FAR * pTW_TRANSFORMSTAGE; + +/* No DAT needed. Describes version of software currently running. */ +typedef struct { + TW_UINT16 MajorNum; /* Major revision number of the software. */ + TW_UINT16 MinorNum; /* Incremental revision number of the software. */ + TW_UINT16 Language; /* e.g. TWLG_SWISSFRENCH */ + TW_UINT16 Country; /* e.g. TWCY_SWITZERLAND */ + TW_STR32 Info; /* e.g. "1.0b3 Beta release" */ +} TW_VERSION, FAR * pTW_VERSION; + +/* TWON_ARRAY. Container for array of values (a simplified TW_ENUMERATION) */ +typedef struct { + TW_UINT16 ItemType; + TW_UINT32 NumItems; /* How many items in ItemList */ + TW_UINT8 ItemList[1]; /* Array of ItemType values starts here */ +} TW_ARRAY, FAR * pTW_ARRAY; + +/* TWON_ENUMERATION. Container for a collection of values. */ +typedef struct { + TW_UINT16 ItemType; + TW_UINT32 NumItems; /* How many items in ItemList */ + TW_UINT32 CurrentIndex; /* Current value is in ItemList[CurrentIndex] */ + TW_UINT32 DefaultIndex; /* Powerup value is in ItemList[DefaultIndex] */ + TW_UINT8 ItemList[1]; /* Array of ItemType values starts here */ +} TW_ENUMERATION, FAR * pTW_ENUMERATION; + +/* TWON_ONEVALUE. Container for one value. */ +typedef struct { + TW_UINT16 ItemType; + TW_UINT32 Item; +} TW_ONEVALUE, FAR * pTW_ONEVALUE; + +/* TWON_RANGE. Container for a range of values. */ +typedef struct { + TW_UINT16 ItemType; + TW_UINT32 MinValue; /* Starting value in the range. */ + TW_UINT32 MaxValue; /* Final value in the range. */ + TW_UINT32 StepSize; /* Increment from MinValue to MaxValue. */ + TW_UINT32 DefaultValue; /* Power-up value. */ + TW_UINT32 CurrentValue; /* The value that is currently in effect. */ +} TW_RANGE, FAR * pTW_RANGE; + +/* DAT_CAPABILITY. Used by application to get/set capability from/in a data source. */ +typedef struct { + TW_UINT16 Cap; /* id of capability to set or get, e.g. CAP_BRIGHTNESS */ + TW_UINT16 ConType; /* TWON_ONEVALUE, _RANGE, _ENUMERATION or _ARRAY */ + TW_HANDLE hContainer; /* Handle to container of type Dat */ +} TW_CAPABILITY, FAR * pTW_CAPABILITY; + +/* DAT_CIECOLOR. */ +typedef struct { + TW_UINT16 ColorSpace; + TW_INT16 LowEndian; + TW_INT16 DeviceDependent; + TW_INT32 VersionNumber; + TW_TRANSFORMSTAGE StageABC; + TW_TRANSFORMSTAGE StageLMN; + TW_CIEPOINT WhitePoint; + TW_CIEPOINT BlackPoint; + TW_CIEPOINT WhitePaper; + TW_CIEPOINT BlackInk; + TW_FIX32 Samples[1]; +} TW_CIECOLOR, FAR * pTW_CIECOLOR; + +/* DAT_EVENT. For passing events down from the application to the DS. */ +typedef struct { + TW_MEMREF pEvent; /* Windows pMSG or Mac pEvent. */ + TW_UINT16 TWMessage; /* TW msg from data source, e.g. MSG_XFERREADY */ +} TW_EVENT, FAR * pTW_EVENT; + +/* DAT_GRAYRESPONSE */ +typedef struct { + TW_ELEMENT8 Response[1]; +} TW_GRAYRESPONSE, FAR * pTW_GRAYRESPONSE; + +/* DAT_IDENTITY. Identifies the program/library/code resource. */ +typedef struct { + TW_UINT32 Id; /* Unique number. In Windows, application hWnd */ + TW_VERSION Version; /* Identifies the piece of code */ + TW_UINT16 ProtocolMajor; /* Application and DS must set to TWON_PROTOCOLMAJOR */ + TW_UINT16 ProtocolMinor; /* Application and DS must set to TWON_PROTOCOLMINOR */ + TW_UINT32 SupportedGroups; /* Bit field OR combination of DG_ constants */ + TW_STR32 Manufacturer; /* Manufacturer name, e.g. "Hewlett-Packard" */ + TW_STR32 ProductFamily; /* Product family name, e.g. "ScanJet" */ + TW_STR32 ProductName; /* Product name, e.g. "ScanJet Plus" */ +} TW_IDENTITY, FAR * pTW_IDENTITY; + +/* DAT_IMAGEINFO. Application gets detailed image info from DS with this. */ +typedef struct { + TW_FIX32 XResolution; /* Resolution in the horizontal */ + TW_FIX32 YResolution; /* Resolution in the vertical */ + TW_INT32 ImageWidth; /* Columns in the image, -1 if unknown by DS*/ + TW_INT32 ImageLength; /* Rows in the image, -1 if unknown by DS */ + TW_INT16 SamplesPerPixel; /* Number of samples per pixel, 3 for RGB */ + TW_INT16 BitsPerSample[8]; /* Number of bits for each sample */ + TW_INT16 BitsPerPixel; /* Number of bits for each padded pixel */ + TW_BOOL Planar; /* True if Planar, False if chunky */ + TW_INT16 PixelType; /* How to interp data; photo interp (TWPT_) */ + TW_UINT16 Compression; /* How the data is compressed (TWCP_xxxx) */ +} TW_IMAGEINFO, FAR * pTW_IMAGEINFO; + +/* DAT_IMAGELAYOUT. Provides image layout information in current units. */ +typedef struct { + TW_FRAME Frame; /* Frame coords within larger document */ + TW_UINT32 DocumentNumber; + TW_UINT32 PageNumber; /* Reset when you go to next document */ + TW_UINT32 FrameNumber; /* Reset when you go to next page */ +} TW_IMAGELAYOUT, FAR * pTW_IMAGELAYOUT; + +/* DAT_IMAGEMEMXFER. Used to pass image data (e.g. in strips) from DS to application.*/ +typedef struct { + TW_UINT16 Compression; /* How the data is compressed */ + TW_UINT32 BytesPerRow; /* Number of bytes in a row of data */ + TW_UINT32 Columns; /* How many columns */ + TW_UINT32 Rows; /* How many rows */ + TW_UINT32 XOffset; /* How far from the side of the image */ + TW_UINT32 YOffset; /* How far from the top of the image */ + TW_UINT32 BytesWritten; /* How many bytes written in Memory */ + TW_MEMORY Memory; /* Mem struct used to pass actual image data */ +} TW_IMAGEMEMXFER, FAR * pTW_IMAGEMEMXFER; + +/* Changed in 1.1: QuantTable, HuffmanDC, HuffmanAC TW_MEMREF -> TW_MEMORY */ +/* DAT_JPEGCOMPRESSION. Based on JPEG Draft International Std, ver 10918-1. */ +typedef struct { + TW_UINT16 ColorSpace; /* One of the TWPT_xxxx values */ + TW_UINT32 SubSampling; /* Two word "array" for subsampling values */ + TW_UINT16 NumComponents; /* Number of color components in image */ + TW_UINT16 RestartFrequency; /* Frequency of restart marker codes in MDU's */ + TW_UINT16 QuantMap[4]; /* Mapping of components to QuantTables */ + TW_MEMORY QuantTable[4]; /* Quantization tables */ + TW_UINT16 HuffmanMap[4]; /* Mapping of components to Huffman tables */ + TW_MEMORY HuffmanDC[2]; /* DC Huffman tables */ + TW_MEMORY HuffmanAC[2]; /* AC Huffman tables */ +} TW_JPEGCOMPRESSION, FAR * pTW_JPEGCOMPRESSION; + +/* DAT_PALETTE8. Color palette when TWPT_PALETTE pixels xfer'd in mem buf. */ +typedef struct { + TW_UINT16 NumColors; /* Number of colors in the color table. */ + TW_UINT16 PaletteType; /* TWPA_xxxx, specifies type of palette. */ + TW_ELEMENT8 Colors[256]; /* Array of palette values starts here. */ +} TW_PALETTE8, FAR * pTW_PALETTE8; + +/* DAT_PENDINGXFERS. Used with MSG_ENDXFER to indicate additional data. */ +typedef struct { + TW_UINT16 Count; + union { + TW_UINT32 EOJ; + TW_UINT32 Reserved; + }; +} TW_PENDINGXFERS, FAR *pTW_PENDINGXFERS; + +/* DAT_RGBRESPONSE */ +typedef struct { + TW_ELEMENT8 Response[1]; +} TW_RGBRESPONSE, FAR * pTW_RGBRESPONSE; + +/* DAT_SETUPFILEXFER. Sets up DS to application data transfer via a file. */ +typedef struct { + TW_STR255 FileName; + TW_UINT16 Format; /* Any TWFF_ constant */ + TW_INT16 VRefNum; /* Used for Mac only */ +} TW_SETUPFILEXFER, FAR * pTW_SETUPFILEXFER; + +/* DAT_SETUPMEMXFER. Sets up DS to application data transfer via a memory buffer. */ +typedef struct { + TW_UINT32 MinBufSize; + TW_UINT32 MaxBufSize; + TW_UINT32 Preferred; +} TW_SETUPMEMXFER, FAR * pTW_SETUPMEMXFER; + +/* DAT_STATUS. Application gets detailed status info from a data source with this. */ +typedef struct { + TW_UINT16 ConditionCode; /* Any TWCC_ constant */ + TW_UINT16 Reserved; /* Future expansion space */ +} TW_STATUS, FAR * pTW_STATUS; + +/* DAT_USERINTERFACE. Coordinates UI between application and data source. */ +typedef struct { + TW_BOOL ShowUI; /* TRUE if DS should bring up its UI */ + TW_BOOL ModalUI; /* For Mac only - true if the DS's UI is modal */ + TW_HANDLE hParent; /* For windows only - Application window handle */ +} TW_USERINTERFACE, FAR * pTW_USERINTERFACE; + +/* SDH - 03/21/95 - TWUNK */ +/* DAT_TWUNKIDENTITY. Provides DS identity and 'other' information necessary */ +/* across thunk link. */ +typedef struct { + TW_IDENTITY identity; /* Identity of data source. */ + TW_STR255 dsPath; /* Full path and file name of data source. */ +} TW_TWUNKIDENTITY, FAR * pTW_TWUNKIDENTITY; + +/* SDH - 03/21/95 - TWUNK */ +/* Provides DS_Entry parameters over thunk link. */ +typedef struct +{ + TW_INT8 destFlag; /* TRUE if dest is not NULL */ + TW_IDENTITY dest; /* Identity of data source (if used) */ + TW_INT32 dataGroup; /* DSM_Entry dataGroup parameter */ + TW_INT16 dataArgType; /* DSM_Entry dataArgType parameter */ + TW_INT16 message; /* DSM_Entry message parameter */ + TW_INT32 pDataSize; /* Size of pData (0 if NULL) */ + // TW_MEMREF pData; /* Based on implementation specifics, a */ + /* pData parameter makes no sense in this */ + /* structure, but data (if provided) will be*/ + /* appended in the data block. */ + } TW_TWUNKDSENTRYPARAMS, FAR * pTW_TWUNKDSENTRYPARAMS; + +/* SDH - 03/21/95 - TWUNK */ +/* Provides DS_Entry results over thunk link. */ +typedef struct +{ + TW_UINT16 returnCode; /* Thunker DsEntry return code. */ + TW_UINT16 conditionCode; /* Thunker DsEntry condition code. */ + TW_INT32 pDataSize; /* Size of pData (0 if NULL) */ + // TW_MEMREF pData; /* Based on implementation specifics, a */ + /* pData parameter makes no sense in this */ + /* structure, but data (if provided) will be*/ + /* appended in the data block. */ +} TW_TWUNKDSENTRYRETURN, FAR * pTW_TWUNKDSENTRYRETURN; + +/* WJD - 950818 */ +/* Added for 1.6 Specification */ +/* TWAIN 1.6 CAP_SUPPORTEDCAPSEXT structure */ +typedef struct +{ + TW_UINT16 Cap; /* Which CAP/ICAP info is relevant to */ + TW_UINT16 Properties; /* Messages this CAP/ICAP supports */ +} TW_CAPEXT, FAR * pTW_CAPEXT; + +/* ----------------------------------------------------------------------- *\ + + Version 1.7: Added Following data structure for Document Imaging + July 1997 Enhancement. + KHL TW_CUSTOMDSDATA -- For Saving and Restoring Source's + state. + TW_INFO -- Each attribute for extended image + information. + TW_EXTIMAGEINFO -- Extended image information structure. + +\* ----------------------------------------------------------------------- */ + +typedef struct { + TW_UINT32 InfoLength; /* Length of Information in bytes. */ + TW_HANDLE hData; /* Place holder for data, DS Allocates */ +}TW_CUSTOMDSDATA, FAR *pTW_CUSTOMDSDATA; + +typedef struct { + TW_UINT16 InfoID; + TW_UINT16 ItemType; + TW_UINT16 NumItems; + TW_UINT16 CondCode; + TW_UINT32 Item; +}TW_INFO, FAR* pTW_INFO; + +typedef struct { + TW_UINT32 NumInfos; + TW_INFO Info[1]; +}TW_EXTIMAGEINFO, FAR* pTW_EXTIMAGEINFO; + +/* Added 1.8 */ + +/* DAT_AUDIOINFO, information about audio data */ +typedef struct { + TW_STR255 Name; /* name of audio data */ + TW_UINT32 Reserved; /* reserved space */ +} TW_AUDIOINFO, FAR * pTW_AUDIOINFO; + +/* DAT_DEVICEEVENT, information about events */ +typedef struct { + TW_UINT32 Event; /* One of the TWDE_xxxx values. */ + TW_STR255 DeviceName; /* The name of the device that generated the event */ + TW_UINT32 BatteryMinutes; /* Battery Minutes Remaining */ + TW_INT16 BatteryPercentage; /* Battery Percentage Remaining */ + TW_INT32 PowerSupply; /* Power Supply */ + TW_FIX32 XResolution; /* Resolution */ + TW_FIX32 YResolution; /* Resolution */ + TW_UINT32 FlashUsed2; /* Flash Used2 */ + TW_UINT32 AutomaticCapture; /* Automatic Capture */ + TW_UINT32 TimeBeforeFirstCapture; /* Automatic Capture */ + TW_UINT32 TimeBetweenCaptures; /* Automatic Capture */ +} TW_DEVICEEVENT, FAR * pTW_DEVICEEVENT; + +/* DAT_FILESYSTEM, information about TWAIN file system */ +typedef struct { + /* DG_CONTROL / DAT_FILESYSTEM / MSG_xxxx fields */ + TW_STR255 InputName; /* The name of the input or source file */ + TW_STR255 OutputName; /* The result of an operation or the name of a destination file */ + TW_MEMREF Context; /* Source specific data used to remember state information */ + /* DG_CONTROL / DAT_FILESYSTEM / MSG_DELETE field */ + int Recursive; /* recursively delete all sub-directories */ + /* DG_CONTROL / DAT_FILESYSTEM / MSG_GETINFO fields */ + TW_INT32 FileType; /* One of the TWFT_xxxx values */ + TW_UINT32 Size; /* Size of current FileType */ + TW_STR32 CreateTimeDate; /* creation date of the file */ + TW_STR32 ModifiedTimeDate; /* last date the file was modified */ + TW_UINT32 FreeSpace; /* bytes of free space on the current device */ + TW_INT32 NewImageSize; /* estimate of the amount of space a new image would take up */ + TW_UINT32 NumberOfFiles; /* number of files, depends on FileType */ + TW_UINT32 NumberOfSnippets; /**/ + char Reserved[512]; /**/ +} TW_FILESYSTEM, FAR * pTW_FILESYSTEM; + +/* DAT_PASSTHRU, device dependant data to pass through Data Source */ +typedef struct { + TW_MEMREF pCommand; /* Pointer to Command buffer */ + TW_UINT32 CommandBytes; /* Number of bytes in Command buffer */ + TW_INT32 Direction; /* One of the TWDR_xxxx values. Defines the direction of data flow */ + TW_MEMREF pData; /* Pointer to Data buffer */ + TW_UINT32 DataBytes; /* Number of bytes in Data buffer */ + TW_UINT32 DataBytesXfered; /* Number of bytes successfully transferred */ +} TW_PASSTHRU, FAR * pTW_PASSTHRU; + +/* DAT_SETUPAUDIOFILEXFER, information required to setup an audio file transfer */ +typedef struct { + TW_STR255 FileName; /* full path target file */ + TW_UINT16 Format; /* one of TWAF_xxxx */ + TW_INT16 VRefNum; +} TW_SETUPAUDIOFILEXFER, FAR * pTW_SETUPAUDIOFILEXFER; + +/**************************************************************************** + * Generic Constants * + ****************************************************************************/ + +#define TWON_ARRAY 3 /* indicates TW_ARRAY container */ +#define TWON_ENUMERATION 4 /* indicates TW_ENUMERATION container */ +#define TWON_ONEVALUE 5 /* indicates TW_ONEVALUE container */ +#define TWON_RANGE 6 /* indicates TW_RANGE container */ + +#define TWON_ICONID 962 /* res Id of icon used in USERSELECT lbox */ +#define TWON_DSMID 461 /* res Id of the DSM version num resource */ +#define TWON_DSMCODEID 63 /* res Id of the Mac SM Code resource */ + +#define TWON_DONTCARE8 0xff +#define TWON_DONTCARE16 0xffff +#define TWON_DONTCARE32 0xffffffff + +/* Flags used in TW_MEMORY structure. */ +#define TWMF_APPOWNS 0x1 +#define TWMF_DSMOWNS 0x2 +#define TWMF_DSOWNS 0x4 +#define TWMF_POINTER 0x8 +#define TWMF_HANDLE 0x10 + +/* Palette types for TW_PALETTE8 */ +#define TWPA_RGB 0 +#define TWPA_GRAY 1 +#define TWPA_CMY 2 + +/* There are four containers used for capabilities negotiation: + * TWON_ONEVALUE, TWON_RANGE, TWON_ENUMERATION, TWON_ARRAY + * In each container structure ItemType can be TWTY_INT8, TWTY_INT16, etc. + * The kind of data stored in the container can be determined by doing + * DCItemSize[ItemType] where the following is defined in TWAIN glue code: + * DCItemSize[]= { sizeof(TW_INT8), + * sizeof(TW_INT16), + * etc. + * sizeof(TW_UINT32) }; + * + */ + +#define TWTY_INT8 0x0000 /* Means Item is a TW_INT8 */ +#define TWTY_INT16 0x0001 /* Means Item is a TW_INT16 */ +#define TWTY_INT32 0x0002 /* Means Item is a TW_INT32 */ + +#define TWTY_UINT8 0x0003 /* Means Item is a TW_UINT8 */ +#define TWTY_UINT16 0x0004 /* Means Item is a TW_UINT16 */ +#define TWTY_UINT32 0x0005 /* Means Item is a TW_UINT32 */ + +#define TWTY_BOOL 0x0006 /* Means Item is a TW_BOOL */ + +#define TWTY_FIX32 0x0007 /* Means Item is a TW_FIX32 */ + +#define TWTY_FRAME 0x0008 /* Means Item is a TW_FRAME */ + +#define TWTY_STR32 0x0009 /* Means Item is a TW_STR32 */ +#define TWTY_STR64 0x000a /* Means Item is a TW_STR64 */ +#define TWTY_STR128 0x000b /* Means Item is a TW_STR128 */ +#define TWTY_STR255 0x000c /* Means Item is a TW_STR255 */ + +/**************************************************************************** + * Capability Constants * + ****************************************************************************/ + +/* ICAP_BITORDER values (BO_ means Bit Order) */ +#define TWBO_LSBFIRST 0 +#define TWBO_MSBFIRST 1 + +/* ICAP_COMPRESSION values (CP_ means ComPression ) */ +#define TWCP_NONE 0 +#define TWCP_PACKBITS 1 +#define TWCP_GROUP31D 2 /* Follows CCITT spec (no End Of Line) */ +#define TWCP_GROUP31DEOL 3 /* Follows CCITT spec (has End Of Line) */ +#define TWCP_GROUP32D 4 /* Follows CCITT spec (use cap for K Factor) */ +#define TWCP_GROUP4 5 /* Follows CCITT spec */ +#define TWCP_JPEG 6 /* Use capability for more info */ +#define TWCP_LZW 7 /* Must license from Unisys and IBM to use */ +#define TWCP_JBIG 8 /* For Bitonal images -- Added 1.7 KHL */ +/* Added 1.8 */ +#define TWCP_PNG 9 +#define TWCP_RLE4 10 +#define TWCP_RLE8 11 +#define TWCP_BITFIELDS 12 + + +/* ICAP_IMAGEFILEFORMAT values (FF_means File Format) */ +#define TWFF_TIFF 0 /* Tagged Image File Format */ +#define TWFF_PICT 1 /* Macintosh PICT */ +#define TWFF_BMP 2 /* Windows Bitmap */ +#define TWFF_XBM 3 /* X-Windows Bitmap */ +#define TWFF_JFIF 4 /* JPEG File Interchange Format */ +#define TWFF_FPX 5 /* Flash Pix */ +#define TWFF_TIFFMULTI 6 /* Multi-page tiff file */ +#define TWFF_PNG 7 +#define TWFF_SPIFF 8 +#define TWFF_EXIF 9 + + +/* ICAP_FILTER values (FT_ means Filter Type) */ +#define TWFT_RED 0 +#define TWFT_GREEN 1 +#define TWFT_BLUE 2 +#define TWFT_NONE 3 +#define TWFT_WHITE 4 +#define TWFT_CYAN 5 +#define TWFT_MAGENTA 6 +#define TWFT_YELLOW 7 +#define TWFT_BLACK 8 + +/* ICAP_LIGHTPATH values (LP_ means Light Path) */ +#define TWLP_REFLECTIVE 0 +#define TWLP_TRANSMISSIVE 1 + +/* ICAP_LIGHTSOURCE values (LS_ means Light Source) */ +#define TWLS_RED 0 +#define TWLS_GREEN 1 +#define TWLS_BLUE 2 +#define TWLS_NONE 3 +#define TWLS_WHITE 4 +#define TWLS_UV 5 +#define TWLS_IR 6 + +/* ICAP_ORIENTATION values (OR_ means ORientation) */ +#define TWOR_ROT0 0 +#define TWOR_ROT90 1 +#define TWOR_ROT180 2 +#define TWOR_ROT270 3 +#define TWOR_PORTRAIT TWOR_ROT0 +#define TWOR_LANDSCAPE TWOR_ROT270 + +/* ICAP_PLANARCHUNKY values (PC_ means Planar/Chunky ) */ +#define TWPC_CHUNKY 0 +#define TWPC_PLANAR 1 + +/* ICAP_PIXELFLAVOR values (PF_ means Pixel Flavor) */ +#define TWPF_CHOCOLATE 0 /* zero pixel represents darkest shade */ +#define TWPF_VANILLA 1 /* zero pixel represents lightest shade */ + +/* ICAP_PIXELTYPE values (PT_ means Pixel Type) */ +#define TWPT_BW 0 /* Black and White */ +#define TWPT_GRAY 1 +#define TWPT_RGB 2 +#define TWPT_PALETTE 3 +#define TWPT_CMY 4 +#define TWPT_CMYK 5 +#define TWPT_YUV 6 +#define TWPT_YUVK 7 +#define TWPT_CIEXYZ 8 + +/* ICAP_SUPPORTEDSIZES values (SS_ means Supported Sizes) */ +#define TWSS_NONE 0 +#define TWSS_A4LETTER 1 +#define TWSS_B5LETTER 2 +#define TWSS_USLETTER 3 +#define TWSS_USLEGAL 4 +/* Added 1.5 */ +#define TWSS_A5 5 +#define TWSS_B4 6 +#define TWSS_B6 7 +//#define TWSS_B 8 +/* Added 1.7 */ +#define TWSS_USLEDGER 9 +#define TWSS_USEXECUTIVE 10 +#define TWSS_A3 11 +#define TWSS_B3 12 +#define TWSS_A6 13 +#define TWSS_C4 14 +#define TWSS_C5 15 +#define TWSS_C6 16 +/* Added 1.8 */ +#define TWSS_4A0 17 +#define TWSS_2A0 18 +#define TWSS_A0 19 +#define TWSS_A1 20 +#define TWSS_A2 21 +#define TWSS_A4 TWSS_A4LETTER +#define TWSS_A7 22 +#define TWSS_A8 23 +#define TWSS_A9 24 +#define TWSS_A10 25 +#define TWSS_ISOB0 26 +#define TWSS_ISOB1 27 +#define TWSS_ISOB2 28 +#define TWSS_ISOB3 TWSS_B3 +#define TWSS_ISOB4 TWSS_B4 +#define TWSS_ISOB5 29 +#define TWSS_ISOB6 TWSS_B6 +#define TWSS_ISOB7 30 +#define TWSS_ISOB8 31 +#define TWSS_ISOB9 32 +#define TWSS_ISOB10 33 +#define TWSS_JISB0 34 +#define TWSS_JISB1 35 +#define TWSS_JISB2 36 +#define TWSS_JISB3 37 +#define TWSS_JISB4 38 +#define TWSS_JISB5 TWSS_B5LETTER +#define TWSS_JISB6 39 +#define TWSS_JISB7 40 +#define TWSS_JISB8 41 +#define TWSS_JISB9 42 +#define TWSS_JISB10 43 +#define TWSS_C0 44 +#define TWSS_C1 45 +#define TWSS_C2 46 +#define TWSS_C3 47 +#define TWSS_C7 48 +#define TWSS_C8 49 +#define TWSS_C9 50 +#define TWSS_C10 51 +#define TWSS_USSTATEMENT 52 +#define TWSS_BUSINESSCARD 53 + +/* ICAP_XFERMECH values (SX_ means Setup XFer) */ +#define TWSX_NATIVE 0 +#define TWSX_FILE 1 +#define TWSX_MEMORY 2 + +/* ICAP_UNITS values (UN_ means UNits) */ +#define TWUN_INCHES 0 +#define TWUN_CENTIMETERS 1 +#define TWUN_PICAS 2 +#define TWUN_POINTS 3 +#define TWUN_TWIPS 4 +#define TWUN_PIXELS 5 + +/* Added 1.5 */ +/* ICAP_BITDEPTHREDUCTION values (BR_ means Bitdepth Reduction) */ +#define TWBR_THRESHOLD 0 +#define TWBR_HALFTONE 1 +#define TWBR_CUSTHALFTONE 2 +#define TWBR_DIFFUSION 3 + +/* Added 1.7 */ +/* ICAP_DUPLEX values */ +#define TWDX_NONE 0 +#define TWDX_1PASSDUPLEX 1 +#define TWDX_2PASSDUPLEX 2 + +/* Added 1.7 */ +/* TWEI_BARCODETYPE values */ +#define TWBT_3OF9 0 +#define TWBT_2OF5INTERLEAVED 1 +#define TWBT_2OF5NONINTERLEAVED 2 +#define TWBT_CODE93 3 +#define TWBT_CODE128 4 +#define TWBT_UCC128 5 +#define TWBT_CODABAR 6 +#define TWBT_UPCA 7 +#define TWBT_UPCE 8 +#define TWBT_EAN8 9 +#define TWBT_EAN13 10 +#define TWBT_POSTNET 11 +#define TWBT_PDF417 12 +/* Added 1.8 */ +#define TWBT_2OF5INDUSTRIAL 13 +#define TWBT_2OF5MATRIX 14 +#define TWBT_2OF5DATALOGIC 15 +#define TWBT_2OF5IATA 16 +#define TWBT_3OF9FULLASCII 17 +#define TWBT_CODABARWITHSTARTSTOP 18 +#define TWBT_MAXICODE 19 + +/* Added 1.7 */ +/* TWEI_DESKEWSTATUS values */ +#define TWDSK_SUCCESS 0 +#define TWDSK_REPORTONLY 1 +#define TWDSK_FAIL 2 +#define TWDSK_DISABLED 3 + +/* Added 1.7 */ +/* TWEI_PATCHCODE values */ +#define TWPCH_PATCH1 0 +#define TWPCH_PATCH2 1 +#define TWPCH_PATCH3 2 +#define TWPCH_PATCH4 3 +#define TWPCH_PATCH6 4 +#define TWPCH_PATCHT 5 + +/* Added 1.7 */ +/* CAP_JOBCONTROL values */ +#define TWJC_NONE 0 +#define TWJC_JSIC 1 +#define TWJC_JSIS 2 +#define TWJC_JSXC 3 +#define TWJC_JSXS 4 + +/* Added 1.7 */ +/* TWEI_BARCODEROTATION values (BCOR_ means barcode rotation) */ +#define TWBCOR_ROT0 0 +#define TWBCOR_ROT90 1 +#define TWBCOR_ROT180 2 +#define TWBCOR_ROT270 3 +#define TWBCOR_ROTX 4 + +/* Added 1.8 */ +/* ACAP_AUDIOFILEFORMAT values (AF_ means audio format) */ +#define TWAF_WAV 0 +#define TWAF_AIFF 1 +#define TWAF_AU 3 +#define TWAF_SND 4 + +/* CAP_ALARMS values (AL_ means alarms) */ +#define TWAL_ALARM 0 +#define TWAL_FEEDERERROR 1 +#define TWAL_FEEDERWARNING 2 +#define TWAL_BARCODE 3 +#define TWAL_DOUBLEFEED 4 +#define TWAL_JAM 5 +#define TWAL_PATCHCODE 6 +#define TWAL_POWER 7 +#define TWAL_SKEW 8 + +/* CAP_CLEARBUFFERS values (CB_ means clear buffers) */ +#define TWCB_AUTO 0 +#define TWCB_CLEAR 1 +#define TWCB_NOCLEAR 2 + +/* CAP_DEVICEEVENT values (DE_ means device event) */ +#define TWDE_CUSTOMEVENTS 0x8000 +#define TWDE_CHECKAUTOMATICCAPTURE 0 +#define TWDE_CHECKBATTERY 1 +#define TWDE_CHECKDEVICEONLINE 2 +#define TWDE_CHECKFLASH 3 +#define TWDE_CHECKPOWERSUPPLY 4 +#define TWDE_CHECKRESOLUTION 5 +#define TWDE_DEVICEADDED 6 +#define TWDE_DEVICEOFFLINE 7 +#define TWDE_DEVICEREADY 8 +#define TWDE_DEVICEREMOVED 9 +#define TWDE_IMAGECAPTURED 10 +#define TWDE_IMAGEDELETED 11 +#define TWDE_PAPERDOUBLEFEED 12 +#define TWDE_PAPERJAM 13 +#define TWDE_LAMPFAILURE 14 +#define TWDE_POWERSAVE 15 +#define TWDE_POWERSAVENOTIFY 16 + +/* CAP_FEEDERALIGNMENT values (FA_ means feeder alignment) */ +#define TWFA_NONE 0 +#define TWFA_LEFT 1 +#define TWFA_CENTER 2 +#define TWFA_RIGHT 3 + +/* CAP_FEEDERORDER values (FO_ means feeder order) */ +#define TWFO_FIRSTPAGEFIRST 0 +#define TWFO_LASTPAGEFIRST 1 + +/* CAP_FILESYSTEM values (FS_ means file system) */ +#define TWFS_FILESYSTEM 0 +#define TWFS_RECURSIVEDELETE 1 + +/* CAP_POWERSUPPLY values (PS_ means power supply) */ +#define TWPS_EXTERNAL 0 +#define TWPS_BATTERY 1 + +/* CAP_PRINTER values (PR_ means printer) */ +#define TWPR_IMPRINTERTOPBEFORE 0 +#define TWPR_IMPRINTERTOPAFTER 1 +#define TWPR_IMPRINTERBOTTOMBEFORE 2 +#define TWPR_IMPRINTERBOTTOMAFTER 3 +#define TWPR_ENDORSERTOPBEFORE 4 +#define TWPR_ENDORSERTOPAFTER 5 +#define TWPR_ENDORSERBOTTOMBEFORE 6 +#define TWPR_ENDORSERBOTTOMAFTER 7 + +/* CAP_PRINTERMODE values (PM_ means printer mode) */ +#define TWPM_SINGLESTRING 0 +#define TWPM_MULTISTRING 1 +#define TWPM_COMPOUNDSTRING 2 + +/* ICAP_BARCODESEARCHMODE values (TWBD_ means search) */ +#define TWBD_HORZ 0 +#define TWBD_VERT 1 +#define TWBD_HORZVERT 2 +#define TWBD_VERTHORZ 3 + +/* ICAP_FLASHUSED2 values (FL_ means flash) */ +#define TWFL_NONE 0 +#define TWFL_OFF 1 +#define TWFL_ON 2 +#define TWFL_AUTO 3 +#define TWFL_REDEYE 4 + +/* ICAP_FLIPROTATION values (FR_ means flip rotation) */ +#define TWFR_BOOK 0 +#define TWFR_FANFOLD 1 + +/* ICAP_IMAGEFILTER values (IF_ means image filter) */ +#define TWIF_NONE 0 +#define TWIF_AUTO 1 +#define TWIF_LOWPASS 2 +#define TWIF_BANDPASS 3 +#define TWIF_HIGHPASS 4 +#define TWIF_TEXT TWIF_BANDPASS +#define TWIF_FINELINE TWIF_HIGHPASS + +/* ICAP_NOISEFILTER values (NF_ means noise filter) */ +#define TWNF_NONE 0 +#define TWNF_AUTO 1 +#define TWNF_LONEPIXEL 2 +#define TWNF_MAJORITYRULE 3 + +/* ICAP_OVERSCAN values (OV_ means overscan) */ +#define TWOV_NONE 0 +#define TWOV_AUTO 1 +#define TWOV_TOPBOTTOM 2 +#define TWOV_LEFTRIGHT 3 +#define TWOV_ALL 4 + +/* TW_FILESYSTEM.FileType values (FT_ means file type) */ +#define TWFY_CAMERA 0 +#define TWFY_CAMERATOP 1 +#define TWFY_CAMERABOTTOM 2 +#define TWFY_CAMERAPREVIEW 3 +#define TWFY_DOMAIN 4 +#define TWFY_HOST 5 +#define TWFY_DIRECTORY 6 +#define TWFY_IMAGE 7 +#define TWFY_UNKNOWN 8 + +/**************************************************************************** + * Country Constants * + ****************************************************************************/ + +#define TWCY_AFGHANISTAN 1001 +#define TWCY_ALGERIA 213 +#define TWCY_AMERICANSAMOA 684 +#define TWCY_ANDORRA 033 +#define TWCY_ANGOLA 1002 +#define TWCY_ANGUILLA 8090 +#define TWCY_ANTIGUA 8091 +#define TWCY_ARGENTINA 54 +#define TWCY_ARUBA 297 +#define TWCY_ASCENSIONI 247 +#define TWCY_AUSTRALIA 61 +#define TWCY_AUSTRIA 43 +#define TWCY_BAHAMAS 8092 +#define TWCY_BAHRAIN 973 +#define TWCY_BANGLADESH 880 +#define TWCY_BARBADOS 8093 +#define TWCY_BELGIUM 32 +#define TWCY_BELIZE 501 +#define TWCY_BENIN 229 +#define TWCY_BERMUDA 8094 +#define TWCY_BHUTAN 1003 +#define TWCY_BOLIVIA 591 +#define TWCY_BOTSWANA 267 +#define TWCY_BRITAIN 6 +#define TWCY_BRITVIRGINIS 8095 +#define TWCY_BRAZIL 55 +#define TWCY_BRUNEI 673 +#define TWCY_BULGARIA 359 +#define TWCY_BURKINAFASO 1004 +#define TWCY_BURMA 1005 +#define TWCY_BURUNDI 1006 +#define TWCY_CAMAROON 237 +#define TWCY_CANADA 2 +#define TWCY_CAPEVERDEIS 238 +#define TWCY_CAYMANIS 8096 +#define TWCY_CENTRALAFREP 1007 +#define TWCY_CHAD 1008 +#define TWCY_CHILE 56 +#define TWCY_CHINA 86 +#define TWCY_CHRISTMASIS 1009 +#define TWCY_COCOSIS 1009 +#define TWCY_COLOMBIA 57 +#define TWCY_COMOROS 1010 +#define TWCY_CONGO 1011 +#define TWCY_COOKIS 1012 +#define TWCY_COSTARICA 506 +#define TWCY_CUBA 005 +#define TWCY_CYPRUS 357 +#define TWCY_CZECHOSLOVAKIA 42 +#define TWCY_DENMARK 45 +#define TWCY_DJIBOUTI 1013 +#define TWCY_DOMINICA 8097 +#define TWCY_DOMINCANREP 8098 +#define TWCY_EASTERIS 1014 +#define TWCY_ECUADOR 593 +#define TWCY_EGYPT 20 +#define TWCY_ELSALVADOR 503 +#define TWCY_EQGUINEA 1015 +#define TWCY_ETHIOPIA 251 +#define TWCY_FALKLANDIS 1016 +#define TWCY_FAEROEIS 298 +#define TWCY_FIJIISLANDS 679 +#define TWCY_FINLAND 358 +#define TWCY_FRANCE 33 +#define TWCY_FRANTILLES 596 +#define TWCY_FRGUIANA 594 +#define TWCY_FRPOLYNEISA 689 +#define TWCY_FUTANAIS 1043 +#define TWCY_GABON 241 +#define TWCY_GAMBIA 220 +#define TWCY_GERMANY 49 +#define TWCY_GHANA 233 +#define TWCY_GIBRALTER 350 +#define TWCY_GREECE 30 +#define TWCY_GREENLAND 299 +#define TWCY_GRENADA 8099 +#define TWCY_GRENEDINES 8015 +#define TWCY_GUADELOUPE 590 +#define TWCY_GUAM 671 +#define TWCY_GUANTANAMOBAY 5399 +#define TWCY_GUATEMALA 502 +#define TWCY_GUINEA 224 +#define TWCY_GUINEABISSAU 1017 +#define TWCY_GUYANA 592 +#define TWCY_HAITI 509 +#define TWCY_HONDURAS 504 +#define TWCY_HONGKONG 852 +#define TWCY_HUNGARY 36 +#define TWCY_ICELAND 354 +#define TWCY_INDIA 91 +#define TWCY_INDONESIA 62 +#define TWCY_IRAN 98 +#define TWCY_IRAQ 964 +#define TWCY_IRELAND 353 +#define TWCY_ISRAEL 972 +#define TWCY_ITALY 39 +#define TWCY_IVORYCOAST 225 +#define TWCY_JAMAICA 8010 +#define TWCY_JAPAN 81 +#define TWCY_JORDAN 962 +#define TWCY_KENYA 254 +#define TWCY_KIRIBATI 1018 +#define TWCY_KOREA 82 +#define TWCY_KUWAIT 965 +#define TWCY_LAOS 1019 +#define TWCY_LEBANON 1020 +#define TWCY_LIBERIA 231 +#define TWCY_LIBYA 218 +#define TWCY_LIECHTENSTEIN 41 +#define TWCY_LUXENBOURG 352 +#define TWCY_MACAO 853 +#define TWCY_MADAGASCAR 1021 +#define TWCY_MALAWI 265 +#define TWCY_MALAYSIA 60 +#define TWCY_MALDIVES 960 +#define TWCY_MALI 1022 +#define TWCY_MALTA 356 +#define TWCY_MARSHALLIS 692 +#define TWCY_MAURITANIA 1023 +#define TWCY_MAURITIUS 230 +#define TWCY_MEXICO 3 +#define TWCY_MICRONESIA 691 +#define TWCY_MIQUELON 508 +#define TWCY_MONACO 33 +#define TWCY_MONGOLIA 1024 +#define TWCY_MONTSERRAT 8011 +#define TWCY_MOROCCO 212 +#define TWCY_MOZAMBIQUE 1025 +#define TWCY_NAMIBIA 264 +#define TWCY_NAURU 1026 +#define TWCY_NEPAL 977 +#define TWCY_NETHERLANDS 31 +#define TWCY_NETHANTILLES 599 +#define TWCY_NEVIS 8012 +#define TWCY_NEWCALEDONIA 687 +#define TWCY_NEWZEALAND 64 +#define TWCY_NICARAGUA 505 +#define TWCY_NIGER 227 +#define TWCY_NIGERIA 234 +#define TWCY_NIUE 1027 +#define TWCY_NORFOLKI 1028 +#define TWCY_NORWAY 47 +#define TWCY_OMAN 968 +#define TWCY_PAKISTAN 92 +#define TWCY_PALAU 1029 +#define TWCY_PANAMA 507 +#define TWCY_PARAGUAY 595 +#define TWCY_PERU 51 +#define TWCY_PHILLIPPINES 63 +#define TWCY_PITCAIRNIS 1030 +#define TWCY_PNEWGUINEA 675 +#define TWCY_POLAND 48 +#define TWCY_PORTUGAL 351 +#define TWCY_QATAR 974 +#define TWCY_REUNIONI 1031 +#define TWCY_ROMANIA 40 +#define TWCY_RWANDA 250 +#define TWCY_SAIPAN 670 +#define TWCY_SANMARINO 39 +#define TWCY_SAOTOME 1033 +#define TWCY_SAUDIARABIA 966 +#define TWCY_SENEGAL 221 +#define TWCY_SEYCHELLESIS 1034 +#define TWCY_SIERRALEONE 1035 +#define TWCY_SINGAPORE 65 +#define TWCY_SOLOMONIS 1036 +#define TWCY_SOMALI 1037 +#define TWCY_SOUTHAFRICA 27 +#define TWCY_SPAIN 34 +#define TWCY_SRILANKA 94 +#define TWCY_STHELENA 1032 +#define TWCY_STKITTS 8013 +#define TWCY_STLUCIA 8014 +#define TWCY_STPIERRE 508 +#define TWCY_STVINCENT 8015 +#define TWCY_SUDAN 1038 +#define TWCY_SURINAME 597 +#define TWCY_SWAZILAND 268 +#define TWCY_SWEDEN 46 +#define TWCY_SWITZERLAND 41 +#define TWCY_SYRIA 1039 +#define TWCY_TAIWAN 886 +#define TWCY_TANZANIA 255 +#define TWCY_THAILAND 66 +#define TWCY_TOBAGO 8016 +#define TWCY_TOGO 228 +#define TWCY_TONGAIS 676 +#define TWCY_TRINIDAD 8016 +#define TWCY_TUNISIA 216 +#define TWCY_TURKEY 90 +#define TWCY_TURKSCAICOS 8017 +#define TWCY_TUVALU 1040 +#define TWCY_UGANDA 256 +#define TWCY_USSR 7 +#define TWCY_UAEMIRATES 971 +#define TWCY_UNITEDKINGDOM 44 +#define TWCY_USA 1 +#define TWCY_URUGUAY 598 +#define TWCY_VANUATU 1041 +#define TWCY_VATICANCITY 39 +#define TWCY_VENEZUELA 58 +#define TWCY_WAKE 1042 +#define TWCY_WALLISIS 1043 +#define TWCY_WESTERNSAHARA 1044 +#define TWCY_WESTERNSAMOA 1045 +#define TWCY_YEMEN 1046 +#define TWCY_YUGOSLAVIA 38 +#define TWCY_ZAIRE 243 +#define TWCY_ZAMBIA 260 +#define TWCY_ZIMBABWE 263 +/* Added for 1.8 */ +#define TWCY_ALBANIA 355 +#define TWCY_ARMENIA 374 +#define TWCY_AZERBAIJAN 994 +#define TWCY_BELARUS 375 +#define TWCY_BOSNIAHERZGO 387 +#define TWCY_CAMBODIA 855 +#define TWCY_CROATIA 385 +#define TWCY_CZECHREPUBLIC 420 +#define TWCY_DIEGOGARCIA 246 +#define TWCY_ERITREA 291 +#define TWCY_ESTONIA 372 +#define TWCY_GEORGIA 995 +#define TWCY_LATVIA 371 +#define TWCY_LESOTHO 266 +#define TWCY_LITHUANIA 370 +#define TWCY_MACEDONIA 389 +#define TWCY_MAYOTTEIS 269 +#define TWCY_MOLDOVA 373 +#define TWCY_MYANMAR 95 +#define TWCY_NORTHKOREA 850 +#define TWCY_PUERTORICO 787 +#define TWCY_RUSSIA 7 +#define TWCY_SERBIA 381 +#define TWCY_SLOVAKIA 421 +#define TWCY_SLOVENIA 386 +#define TWCY_SOUTHKOREA 82 +#define TWCY_UKRAINE 380 +#define TWCY_USVIRGINIS 340 +#define TWCY_VIETNAM 84 + +/**************************************************************************** + * Language Constants * + ****************************************************************************/ + +#define TWLG_DAN 0 /* Danish */ +#define TWLG_DUT 1 /* Dutch */ +#define TWLG_ENG 2 /* International English */ +#define TWLG_FCF 3 /* French Canadian */ +#define TWLG_FIN 4 /* Finnish */ +#define TWLG_FRN 5 /* French */ +#define TWLG_GER 6 /* German */ +#define TWLG_ICE 7 /* Icelandic */ +#define TWLG_ITN 8 /* Italian */ +#define TWLG_NOR 9 /* Norwegian */ +#define TWLG_POR 10 /* Portuguese */ +#define TWLG_SPA 11 /* Spanish */ +#define TWLG_SWE 12 /* Swedish */ +#define TWLG_USA 13 /* U.S. English */ +/* Added for 1.8 */ +#define TWLG_USERLOCALE -1 +#define TWLG_AFRIKAANS 14 +#define TWLG_ALBANIA 15 +#define TWLG_ARABIC 16 +#define TWLG_ARABIC_ALGERIA 17 +#define TWLG_ARABIC_BAHRAIN 18 +#define TWLG_ARABIC_EGYPT 19 +#define TWLG_ARABIC_IRAQ 20 +#define TWLG_ARABIC_JORDAN 21 +#define TWLG_ARABIC_KUWAIT 22 +#define TWLG_ARABIC_LEBANON 23 +#define TWLG_ARABIC_LIBYA 24 +#define TWLG_ARABIC_MOROCCO 25 +#define TWLG_ARABIC_OMAN 26 +#define TWLG_ARABIC_QATAR 27 +#define TWLG_ARABIC_SAUDIARABIA 28 +#define TWLG_ARABIC_SYRIA 29 +#define TWLG_ARABIC_TUNISIA 30 +#define TWLG_ARABIC_UAE 31 /* United Arabic Emirates */ +#define TWLG_ARABIC_YEMEN 32 +#define TWLG_BASQUE 33 +#define TWLG_BYELORUSSIAN 34 +#define TWLG_BULGARIAN 35 +#define TWLG_CATALAN 36 +#define TWLG_CHINESE 37 +#define TWLG_CHINESE_HONGKONG 38 +#define TWLG_CHINESE_PRC 39 /* People's Republic of China */ +#define TWLG_CHINESE_SINGAPORE 40 +#define TWLG_CHINESE_SIMPLIFIED 41 +#define TWLG_CHINESE_TAIWAN 42 +#define TWLG_CHINESE_TRADITIONAL 43 +#define TWLG_CROATIA 44 +#define TWLG_CZECH 45 +#define TWLG_DANISH TWLG_DAN +#define TWLG_DUTCH TWLG_DUT +#define TWLG_DUTCH_BELGIAN 46 +#define TWLG_ENGLISH TWLG_ENG +#define TWLG_ENGLISH_AUSTRALIAN 47 +#define TWLG_ENGLISH_CANADIAN 48 +#define TWLG_ENGLISH_IRELAND 49 +#define TWLG_ENGLISH_NEWZEALAND 50 +#define TWLG_ENGLISH_SOUTHAFRICA 51 +#define TWLG_ENGLISH_UK 52 +#define TWLG_ENGLISH_USA TWLG_USA +#define TWLG_ESTONIAN 53 +#define TWLG_FAEROESE 54 +#define TWLG_FARSI 55 +#define TWLG_FINNISH TWLG_FIN +#define TWLG_FRENCH TWLG_FRN +#define TWLG_FRENCH_BELGIAN 56 +#define TWLG_FRENCH_CANADIAN TWLG_FCF +#define TWLG_FRENCH_LUXEMBOURG 57 +#define TWLG_FRENCH_SWISS 58 +#define TWLG_GERMAN TWLG_GER +#define TWLG_GERMAN_AUSTRIAN 59 +#define TWLG_GERMAN_LUXEMBOURG 60 +#define TWLG_GERMAN_LIECHTENSTEIN 61 +#define TWLG_GERMAN_SWISS 62 +#define TWLG_GREEK 63 +#define TWLG_HEBREW 64 +#define TWLG_HUNGARIAN 65 +#define TWLG_ICELANDIC TWLG_ICE +#define TWLG_INDONESIAN 66 +#define TWLG_ITALIAN TWLG_ITN +#define TWLG_ITALIAN_SWISS 67 +#define TWLG_JAPANESE 68 +#define TWLG_KOREAN 69 +#define TWLG_KOREAN_JOHAB 70 +#define TWLG_LATVIAN 71 +#define TWLG_LITHUANIAN 72 +#define TWLG_NORWEGIAN TWLG_NOR +#define TWLG_NORWEGIAN_BOKMAL 73 +#define TWLG_NORWEGIAN_NYNORSK 74 +#define TWLG_POLISH 75 +#define TWLG_PORTUGUESE TWLG_POR +#define TWLG_PORTUGUESE_BRAZIL 76 +#define TWLG_ROMANIAN 77 +#define TWLG_RUSSIAN 78 +#define TWLG_SERBIAN_LATIN 79 +#define TWLG_SLOVAK 80 +#define TWLG_SLOVENIAN 81 +#define TWLG_SPANISH TWLG_SPA +#define TWLG_SPANISH_MEXICAN 82 +#define TWLG_SPANISH_MODERN 83 +#define TWLG_SWEDISH TWLG_SWE +#define TWLG_THAI 84 +#define TWLG_TURKISH 85 +#define TWLG_UKRANIAN 86 +/* More stuff added for 1.8 */ +#define TWLG_ASSAMESE 87 +#define TWLG_BENGALI 88 +#define TWLG_BIHARI 89 +#define TWLG_BODO 90 +#define TWLG_DOGRI 91 +#define TWLG_GUJARATI 92 +#define TWLG_HARYANVI 93 +#define TWLG_HINDI 94 +#define TWLG_KANNADA 95 +#define TWLG_KASHMIRI 96 +#define TWLG_MALAYALAM 97 +#define TWLG_MARATHI 98 +#define TWLG_MARWARI 99 +#define TWLG_MEGHALAYAN 100 +#define TWLG_MIZO 101 +#define TWLG_NAGA 102 +#define TWLG_ORISSI 103 +#define TWLG_PUNJABI 104 +#define TWLG_PUSHTU 105 +#define TWLG_SERBIAN_CYRILLIC 106 +#define TWLG_SIKKIMI 107 +#define TWLG_SWEDISH_FINLAND 108 +#define TWLG_TAMIL 109 +#define TWLG_TELUGU 110 +#define TWLG_TRIPURI 111 +#define TWLG_URDU 112 +#define TWLG_VIETNAMESE 113 + +/**************************************************************************** + * Data Groups * + ****************************************************************************/ + +/* More Data Groups may be added in the future. + * Possible candidates include text, vector graphics, sound, etc. + * NOTE: Data Group constants must be powers of 2 as they are used + * as bitflags when Application asks DSM to present a list of DSs. + */ + +#define DG_CONTROL 0x0001L /* data pertaining to control */ +#define DG_IMAGE 0x0002L /* data pertaining to raster images */ +/* Added 1.8 */ +#define DG_AUDIO 0x0004L /* data pertaining to audio */ + +/**************************************************************************** + * Data Argument Types * + ****************************************************************************/ + +/* SDH - 03/23/95 - WATCH */ +/* The thunker requires knowledge about size of data being passed in the */ +/* lpData parameter to DS_Entry (which is not readily available due to */ +/* type LPVOID. Thus, we key off the DAT_ argument to determine the size. */ +/* This has a couple implications: */ +/* 1) Any additional DAT_ features require modifications to the thunk code */ +/* for thunker support. */ +/* 2) Any applications which use the custom capabailites are not supported */ +/* under thunking since we have no way of knowing what size data (if */ +/* any) is being passed. */ + +#define DAT_NULL 0x0000 /* No data or structure. */ +#define DAT_CUSTOMBASE 0x8000 /* Base of custom DATs. */ + +/* Data Argument Types for the DG_CONTROL Data Group. */ +#define DAT_CAPABILITY 0x0001 /* TW_CAPABILITY */ +#define DAT_EVENT 0x0002 /* TW_EVENT */ +#define DAT_IDENTITY 0x0003 /* TW_IDENTITY */ +#define DAT_PARENT 0x0004 /* TW_HANDLE, application win handle in Windows */ +#define DAT_PENDINGXFERS 0x0005 /* TW_PENDINGXFERS */ +#define DAT_SETUPMEMXFER 0x0006 /* TW_SETUPMEMXFER */ +#define DAT_SETUPFILEXFER 0x0007 /* TW_SETUPFILEXFER */ +#define DAT_STATUS 0x0008 /* TW_STATUS */ +#define DAT_USERINTERFACE 0x0009 /* TW_USERINTERFACE */ +#define DAT_XFERGROUP 0x000a /* TW_UINT32 */ +/* SDH - 03/21/95 - TWUNK */ +/* Additional message required for thunker to request the special */ +/* identity information. */ +#define DAT_TWUNKIDENTITY 0x000b /* TW_TWUNKIDENTITY */ +#define DAT_CUSTOMDSDATA 0x000c /* TW_CUSTOMDSDATA. */ +/* Added 1.8 */ +#define DAT_DEVICEEVENT 0x000d /* TW_DEVICEEVENT */ +#define DAT_FILESYSTEM 0x000e /* TW_FILESYSTEM */ +#define DAT_PASSTHRU 0x000f /* TW_PASSTHRU */ + +/* Data Argument Types for the DG_IMAGE Data Group. */ +#define DAT_IMAGEINFO 0x0101 /* TW_IMAGEINFO */ +#define DAT_IMAGELAYOUT 0x0102 /* TW_IMAGELAYOUT */ +#define DAT_IMAGEMEMXFER 0x0103 /* TW_IMAGEMEMXFER */ +#define DAT_IMAGENATIVEXFER 0x0104 /* TW_UINT32 loword is hDIB, PICHandle */ +#define DAT_IMAGEFILEXFER 0x0105 /* Null data */ +#define DAT_CIECOLOR 0x0106 /* TW_CIECOLOR */ +#define DAT_GRAYRESPONSE 0x0107 /* TW_GRAYRESPONSE */ +#define DAT_RGBRESPONSE 0x0108 /* TW_RGBRESPONSE */ +#define DAT_JPEGCOMPRESSION 0x0109 /* TW_JPEGCOMPRESSION */ +#define DAT_PALETTE8 0x010a /* TW_PALETTE8 */ +#define DAT_EXTIMAGEINFO 0x010b /* TW_EXTIMAGEINFO -- for 1.7 Spec. */ + +/* Added 1.8 */ +/* Data Argument Types for the DG_AUDIO Data Group. */ +#define DAT_AUDIOFILEXFER 0x0201 /* Null data */ +#define DAT_AUDIOINFO 0x0202 /* TW_AUDIOINFO */ +#define DAT_AUDIONATIVEXFER 0x0203 /* TW_UINT32 handle to WAV, (AIFF Mac) */ + +/**************************************************************************** + * Messages * + ****************************************************************************/ + +/* All message constants are unique. + * Messages are grouped according to which DATs they are used with.*/ + +#define MSG_NULL 0x0000 /* Used in TW_EVENT structure */ +#define MSG_CUSTOMBASE 0x8000 /* Base of custom messages */ + +/* Generic messages may be used with any of several DATs. */ +#define MSG_GET 0x0001 /* Get one or more values */ +#define MSG_GETCURRENT 0x0002 /* Get current value */ +#define MSG_GETDEFAULT 0x0003 /* Get default (e.g. power up) value */ +#define MSG_GETFIRST 0x0004 /* Get first of a series of items, e.g. DSs */ +#define MSG_GETNEXT 0x0005 /* Iterate through a series of items. */ +#define MSG_SET 0x0006 /* Set one or more values */ +#define MSG_RESET 0x0007 /* Set current value to default value */ +#define MSG_QUERYSUPPORT 0x0008 /* Get supported operations on the cap. */ + +/* Messages used with DAT_NULL */ +#define MSG_XFERREADY 0x0101 /* The data source has data ready */ +#define MSG_CLOSEDSREQ 0x0102 /* Request for Application. to close DS */ +#define MSG_CLOSEDSOK 0x0103 /* Tell the Application. to save the state. */ +/* Added 1.8 */ +#define MSG_DEVICEEVENT 0X0104 /* Some event has taken place */ + +/* Messages used with a pointer to a DAT_STATUS structure */ +#define MSG_CHECKSTATUS 0x0201 /* Get status information */ + +/* Messages used with a pointer to DAT_PARENT data */ +#define MSG_OPENDSM 0x0301 /* Open the DSM */ +#define MSG_CLOSEDSM 0x0302 /* Close the DSM */ + +/* Messages used with a pointer to a DAT_IDENTITY structure */ +#define MSG_OPENDS 0x0401 /* Open a data source */ +#define MSG_CLOSEDS 0x0402 /* Close a data source */ +#define MSG_USERSELECT 0x0403 /* Put up a dialog of all DS */ + +/* Messages used with a pointer to a DAT_USERINTERFACE structure */ +#define MSG_DISABLEDS 0x0501 /* Disable data transfer in the DS */ +#define MSG_ENABLEDS 0x0502 /* Enable data transfer in the DS */ +#define MSG_ENABLEDSUIONLY 0x0503 /* Enable for saving DS state only. */ + +/* Messages used with a pointer to a DAT_EVENT structure */ +#define MSG_PROCESSEVENT 0x0601 + +/* Messages used with a pointer to a DAT_PENDINGXFERS structure */ +#define MSG_ENDXFER 0x0701 + +/* Added 1.8 */ +/* Messages used with a pointer to a DAT_FILESYSTEM structure */ +#define MSG_CHANGEDIRECTORY 0x0801 +#define MSG_CREATEDIRECTORY 0x0802 +#define MSG_DELETE 0x0803 +#define MSG_FORMATMEDIA 0x0804 +#define MSG_GETCLOSE 0x0805 +#define MSG_GETFIRSTFILE 0x0806 +#define MSG_GETINFO 0x0807 +#define MSG_GETNEXTFILE 0x0808 +#define MSG_RENAME 0x0809 + +/* Messages used with a pointer to a DAT_PASSTHRU structure */ +#define MSG_PASSTHRU 0x0901 + +/**************************************************************************** + * Capabilities * + ****************************************************************************/ + +#define CAP_CUSTOMBASE 0x8000 /* Base of custom capabilities */ + +/* all data sources are REQUIRED to support these caps */ +#define CAP_XFERCOUNT 0x0001 + +/* image data sources are REQUIRED to support these caps */ +#define ICAP_COMPRESSION 0x0100 +#define ICAP_PIXELTYPE 0x0101 +#define ICAP_UNITS 0x0102 /* default is TWUN_INCHES */ +#define ICAP_XFERMECH 0x0103 + +/* all data sources MAY support these caps */ +#define CAP_AUTHOR 0x1000 +#define CAP_CAPTION 0x1001 +#define CAP_FEEDERENABLED 0x1002 +#define CAP_FEEDERLOADED 0x1003 +#define CAP_TIMEDATE 0x1004 +#define CAP_SUPPORTEDCAPS 0x1005 +#define CAP_EXTENDEDCAPS 0x1006 +#define CAP_AUTOFEED 0x1007 +#define CAP_CLEARPAGE 0x1008 +#define CAP_FEEDPAGE 0x1009 +#define CAP_REWINDPAGE 0x100a +#define CAP_INDICATORS 0x100b /* Added 1.1 */ +#define CAP_SUPPORTEDCAPSEXT 0x100c /* Added 1.6 */ +#define CAP_PAPERDETECTABLE 0x100d /* Added 1.6 */ +#define CAP_UICONTROLLABLE 0x100e /* Added 1.6 */ +#define CAP_DEVICEONLINE 0x100f /* Added 1.6 */ +#define CAP_AUTOSCAN 0x1010 /* Added 1.6 */ +#define CAP_THUMBNAILSENABLED 0x1011 /* Added 1.7 */ +#define CAP_DUPLEX 0x1012 /* Added 1.7 */ +#define CAP_DUPLEXENABLED 0x1013 /* Added 1.7 */ +#define CAP_ENABLEDSUIONLY 0x1014 /* Added 1.7 */ +#define CAP_CUSTOMDSDATA 0x1015 /* Added 1.7 */ +#define CAP_ENDORSER 0x1016 /* Added 1.7 */ +#define CAP_JOBCONTROL 0x1017 /* Added 1.7 */ +#define CAP_ALARMS 0x1018 /* Added 1.8 */ +#define CAP_ALARMVOLUME 0x1019 /* Added 1.8 */ +#define CAP_AUTOMATICCAPTURE 0x101a /* Added 1.8 */ +#define CAP_TIMEBEFOREFIRSTCAPTURE 0x101b /* Added 1.8 */ +#define CAP_TIMEBETWEENCAPTURES 0x101c /* Added 1.8 */ +#define CAP_CLEARBUFFERS 0x101d /* Added 1.8 */ +#define CAP_MAXBATCHBUFFERS 0x101e /* Added 1.8 */ +#define CAP_DEVICETIMEDATE 0x101f /* Added 1.8 */ +#define CAP_POWERSUPPLY 0x1020 /* Added 1.8 */ +#define CAP_CAMERAPREVIEWUI 0x1021 /* Added 1.8 */ +#define CAP_DEVICEEVENT 0x1022 /* Added 1.8 */ +#define CAP_PAGEMULTIPLEACQUIRE 0x1023 /* Added 1.8 */ +#define CAP_SERIALNUMBER 0x1024 /* Added 1.8 */ +#define CAP_FILESYSTEM 0x1025 /* Added 1.8 */ +#define CAP_PRINTER 0x1026 /* Added 1.8 */ +#define CAP_PRINTERENABLED 0x1027 /* Added 1.8 */ +#define CAP_PRINTERINDEX 0x1028 /* Added 1.8 */ +#define CAP_PRINTERMODE 0x1029 /* Added 1.8 */ +#define CAP_PRINTERSTRING 0x102a /* Added 1.8 */ +#define CAP_PRINTERSUFFIX 0x102b /* Added 1.8 */ +#define CAP_LANGUAGE 0x102c /* Added 1.8 */ +#define CAP_FEEDERALIGNMENT 0x102d /* Added 1.8 */ +#define CAP_FEEDERORDER 0x102e /* Added 1.8 */ +#define CAP_PAPERBINDING 0x102f /* Added 1.8 */ +#define CAP_REACQUIREALLOWED 0x1030 /* Added 1.8 */ +#define CAP_PASSTHRU 0x1031 /* Added 1.8 */ +#define CAP_BATTERYMINUTES 0x1032 /* Added 1.8 */ +#define CAP_BATTERYPERCENTAGE 0x1033 /* Added 1.8 */ +#define CAP_POWERDOWNTIME 0x1034 /* Added 1.8 */ + +/* image data sources MAY support these caps */ +#define ICAP_AUTOBRIGHT 0x1100 +#define ICAP_BRIGHTNESS 0x1101 +#define ICAP_CONTRAST 0x1103 +#define ICAP_CUSTHALFTONE 0x1104 +#define ICAP_EXPOSURETIME 0x1105 +#define ICAP_FILTER 0x1106 +#define ICAP_FLASHUSED 0x1107 +#define ICAP_GAMMA 0x1108 +#define ICAP_HALFTONES 0x1109 +#define ICAP_HIGHLIGHT 0x110a +#define ICAP_IMAGEFILEFORMAT 0x110c +#define ICAP_LAMPSTATE 0x110d +#define ICAP_LIGHTSOURCE 0x110e +#define ICAP_ORIENTATION 0x1110 +#define ICAP_PHYSICALWIDTH 0x1111 +#define ICAP_PHYSICALHEIGHT 0x1112 +#define ICAP_SHADOW 0x1113 +#define ICAP_FRAMES 0x1114 +#define ICAP_XNATIVERESOLUTION 0x1116 +#define ICAP_YNATIVERESOLUTION 0x1117 +#define ICAP_XRESOLUTION 0x1118 +#define ICAP_YRESOLUTION 0x1119 +#define ICAP_MAXFRAMES 0x111a +#define ICAP_TILES 0x111b +#define ICAP_BITORDER 0x111c +#define ICAP_CCITTKFACTOR 0x111d +#define ICAP_LIGHTPATH 0x111e +#define ICAP_PIXELFLAVOR 0x111f +#define ICAP_PLANARCHUNKY 0x1120 +#define ICAP_ROTATION 0x1121 +#define ICAP_SUPPORTEDSIZES 0x1122 +#define ICAP_THRESHOLD 0x1123 +#define ICAP_XSCALING 0x1124 +#define ICAP_YSCALING 0x1125 +#define ICAP_BITORDERCODES 0x1126 +#define ICAP_PIXELFLAVORCODES 0x1127 +#define ICAP_JPEGPIXELTYPE 0x1128 +#define ICAP_TIMEFILL 0x112a +#define ICAP_BITDEPTH 0x112b +#define ICAP_BITDEPTHREDUCTION 0x112c /* Added 1.5 */ +#define ICAP_UNDEFINEDIMAGESIZE 0x112d /* Added 1.6 */ +#define ICAP_IMAGEDATASET 0x112e /* Added 1.7 */ +#define ICAP_EXTIMAGEINFO 0x112f /* Added 1.7 */ +#define ICAP_MINIMUMHEIGHT 0x1130 /* Added 1.7 */ +#define ICAP_MINIMUMWIDTH 0x1131 /* Added 1.7 */ +#define ICAP_AUTODISCARDBLANKPAGES 0x1134 /* Added 1.8 */ +#define ICAP_FLIPROTATION 0x1136 /* Added 1.8 */ +#define ICAP_BARCODEDETECTIONENABLED 0x1137 /* Added 1.8 */ +#define ICAP_SUPPORTEDBARCODETYPES 0x1138 /* Added 1.8 */ +#define ICAP_BARCODEMAXSEARCHPRIORITIES 0x1139 /* Added 1.8 */ +#define ICAP_BARCODESEARCHPRIORITIES 0x113a /* Added 1.8 */ +#define ICAP_BARCODESEARCHMODE 0x113b /* Added 1.8 */ +#define ICAP_BARCODEMAXRETRIES 0x113c /* Added 1.8 */ +#define ICAP_BARCODETIMEOUT 0x113d /* Added 1.8 */ +#define ICAP_ZOOMFACTOR 0x113e /* Added 1.8 */ +#define ICAP_PATCHCODEDETECTIONENABLED 0x113f /* Added 1.8 */ +#define ICAP_SUPPORTEDPATCHCODETYPES 0x1140 /* Added 1.8 */ +#define ICAP_PATCHCODEMAXSEARCHPRIORITIES 0x1141 /* Added 1.8 */ +#define ICAP_PATCHCODESEARCHPRIORITIES 0x1142 /* Added 1.8 */ +#define ICAP_PATCHCODESEARCHMODE 0x1143 /* Added 1.8 */ +#define ICAP_PATCHCODEMAXRETRIES 0x1144 /* Added 1.8 */ +#define ICAP_PATCHCODETIMEOUT 0x1145 /* Added 1.8 */ +#define ICAP_FLASHUSED2 0x1146 /* Added 1.8 */ +#define ICAP_IMAGEFILTER 0x1147 /* Added 1.8 */ +#define ICAP_NOISEFILTER 0x1148 /* Added 1.8 */ +#define ICAP_OVERSCAN 0x1149 /* Added 1.8 */ +#define ICAP_AUTOMATICBORDERDETECTION 0x1150 /* Added 1.8 */ +#define ICAP_AUTOMATICDESKEW 0x1151 /* Added 1.8 */ +#define ICAP_AUTOMATICROTATE 0x1152 /* Added 1.8 */ + +/* image data sources MAY support these audio caps */ +#define ACAP_AUDIOFILEFORMAT 0x1201 /* Added 1.8 */ +#define ACAP_XFERMECH 0x1202 /* Added 1.8 */ + +/* ----------------------------------------------------------------------- *\ + + Version 1.7: Following is Extended Image Info Attributes. + July 1997 + KHL + +\* ----------------------------------------------------------------------- */ + +#define TWEI_BARCODEX 0x1200 +#define TWEI_BARCODEY 0x1201 +#define TWEI_BARCODETEXT 0x1202 +#define TWEI_BARCODETYPE 0x1203 +#define TWEI_DESHADETOP 0x1204 +#define TWEI_DESHADELEFT 0x1205 +#define TWEI_DESHADEHEIGHT 0x1206 +#define TWEI_DESHADEWIDTH 0x1207 +#define TWEI_DESHADESIZE 0x1208 +#define TWEI_SPECKLESREMOVED 0x1209 +#define TWEI_HORZLINEXCOORD 0x120A +#define TWEI_HORZLINEYCOORD 0x120B +#define TWEI_HORZLINELENGTH 0x120C +#define TWEI_HORZLINETHICKNESS 0x120D +#define TWEI_VERTLINEXCOORD 0x120E +#define TWEI_VERTLINEYCOORD 0x120F +#define TWEI_VERTLINELENGTH 0x1210 +#define TWEI_VERTLINETHICKNESS 0x1211 +#define TWEI_PATCHCODE 0x1212 +#define TWEI_ENDORSEDTEXT 0x1213 +#define TWEI_FORMCONFIDENCE 0x1214 +#define TWEI_FORMTEMPLATEMATCH 0x1215 +#define TWEI_FORMTEMPLATEPAGEMATCH 0x1216 +#define TWEI_FORMHORZDOCOFFSET 0x1217 +#define TWEI_FORMVERTDOCOFFSET 0x1218 +#define TWEI_BARCODECOUNT 0x1219 +#define TWEI_BARCODECONFIDENCE 0x121A +#define TWEI_BARCODEROTATION 0x121B +#define TWEI_BARCODETEXTLENGTH 0x121C +#define TWEI_DESHADECOUNT 0x121D +#define TWEI_DESHADEBLACKCOUNTOLD 0x121E +#define TWEI_DESHADEBLACKCOUNTNEW 0x121F +#define TWEI_DESHADEBLACKRLMIN 0x1220 +#define TWEI_DESHADEBLACKRLMAX 0x1221 +#define TWEI_DESHADEWHITECOUNTOLD 0x1222 +#define TWEI_DESHADEWHITECOUNTNEW 0x1223 +#define TWEI_DESHADEWHITERLMIN 0x1224 +#define TWEI_DESHADEWHITERLAVE 0x1225 +#define TWEI_DESHADEWHITERLMAX 0x1226 +#define TWEI_BLACKSPECKLESREMOVED 0x1227 +#define TWEI_WHITESPECKLESREMOVED 0x1228 +#define TWEI_HORZLINECOUNT 0x1229 +#define TWEI_VERTLINECOUNT 0x122A +#define TWEI_DESKEWSTATUS 0x122B +#define TWEI_SKEWORIGINALANGLE 0x122C +#define TWEI_SKEWFINALANGLE 0x122D +#define TWEI_SKEWCONFIDENCE 0x122E +#define TWEI_SKEWWINDOWX1 0x122F +#define TWEI_SKEWWINDOWY1 0x1230 +#define TWEI_SKEWWINDOWX2 0x1231 +#define TWEI_SKEWWINDOWY2 0x1232 +#define TWEI_SKEWWINDOWX3 0x1233 +#define TWEI_SKEWWINDOWY3 0x1234 +#define TWEI_SKEWWINDOWX4 0x1235 +#define TWEI_SKEWWINDOWY4 0x1236 + +#define TWEJ_NONE 0x0000 +#define TWEJ_MIDSEPARATOR 0x0001 +#define TWEJ_PATCH1 0x0002 +#define TWEJ_PATCH2 0x0003 +#define TWEJ_PATCH3 0x0004 +#define TWEJ_PATCH4 0x0005 +#define TWEJ_PATCH6 0x0006 +#define TWEJ_PATCHT 0x0007 + +/*************************************************************************** + * Return Codes and Condition Codes section * + ***************************************************************************/ + +/* Return Codes: DSM_Entry and DS_Entry may return any one of these values. */ +#define TWRC_CUSTOMBASE 0x8000 + +#define TWRC_SUCCESS 0 +#define TWRC_FAILURE 1 /* Application may get TW_STATUS for info on failure */ +#define TWRC_CHECKSTATUS 2 /* "tried hard"; get status */ +#define TWRC_CANCEL 3 +#define TWRC_DSEVENT 4 +#define TWRC_NOTDSEVENT 5 +#define TWRC_XFERDONE 6 +#define TWRC_ENDOFLIST 7 /* After MSG_GETNEXT if nothing left */ +#define TWRC_INFONOTSUPPORTED 8 +#define TWRC_DATANOTAVAILABLE 9 + +/* Condition Codes: Application gets these by doing DG_CONTROL DAT_STATUS MSG_GET. */ +#define TWCC_CUSTOMBASE 0x8000 + +#define TWCC_SUCCESS 0 /* It worked! */ +#define TWCC_BUMMER 1 /* Failure due to unknown causes */ +#define TWCC_LOWMEMORY 2 /* Not enough memory to perform operation */ +#define TWCC_NODS 3 /* No Data Source */ +#define TWCC_MAXCONNECTIONS 4 /* DS is connected to max possible applications */ +#define TWCC_OPERATIONERROR 5 /* DS or DSM reported error, application shouldn't */ +#define TWCC_BADCAP 6 /* Unknown capability */ +#define TWCC_BADPROTOCOL 9 /* Unrecognized MSG DG DAT combination */ +#define TWCC_BADVALUE 10 /* Data parameter out of range */ +#define TWCC_SEQERROR 11 /* DG DAT MSG out of expected sequence */ +#define TWCC_BADDEST 12 /* Unknown destination Application/Source in DSM_Entry */ +#define TWCC_CAPUNSUPPORTED 13 /* Capability not supported by source */ +#define TWCC_CAPBADOPERATION 14 /* Operation not supported by capability */ +#define TWCC_CAPSEQERROR 15 /* Capability has dependancy on other capability */ +/* Added 1.8 */ +#define TWCC_DENIED 16 /* File System operation is denied (file is protected) */ +#define TWCC_FILEEXISTS 17 /* Operation failed because file already exists. */ +#define TWCC_FILENOTFOUND 18 /* File not found */ +#define TWCC_NOTEMPTY 19 /* Operation failed because directory is not empty */ +#define TWCC_PAPERJAM 20 /* The feeder is jammed */ +#define TWCC_PAPERDOUBLEFEED 21 /* The feeder detected multiple pages */ +#define TWCC_FILEWRITEERROR 22 /* Error writing the file (meant for things like disk full conditions) */ +#define TWCC_CHECKDEVICEONLINE 23 /* The device went offline prior to or during this operation */ + + +/* bit patterns: for query the operation that are supported by the data source on a capability */ +/* Application gets these through DG_CONTROL/DAT_CAPABILITY/MSG_QUERYSUPPORT */ +/* Added 1.6 */ +#define TWQC_GET 0x0001 +#define TWQC_SET 0x0002 +#define TWQC_GETDEFAULT 0x0004 +#define TWQC_GETCURRENT 0x0008 +#define TWQC_RESET 0x0010 + + +/**************************************************************************** + * Entry Points * + ****************************************************************************/ + +/********************************************************************** + * Function: DSM_Entry, the only entry point into the Data Source Manager. + * + * Parameters: + * pOrigin Identifies the source module of the message. This could + * identify an Application, a Source, or the Source Manager. + * + * pDest Identifies the destination module for the message. + * This could identify an application or a data source. + * If this is NULL, the message goes to the Source Manager. + * + * DG The Data Group. + * Example: DG_IMAGE. + * + * DAT The Data Attribute Type. + * Example: DAT_IMAGEMEMXFER. + * + * MSG The message. Messages are interpreted by the destination module + * with respect to the Data Group and the Data Attribute Type. + * Example: MSG_GET. + * + * pData A pointer to the data structure or variable identified + * by the Data Attribute Type. + * Example: (TW_MEMREF)&ImageMemXfer + * where ImageMemXfer is a TW_IMAGEMEMXFER structure. + * + * Returns: + * ReturnCode + * Example: TWRC_SUCCESS. + * + ********************************************************************/ + +/* Don't mangle the name "DSM_Entry" if we're compiling in C++! */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifdef _MSWIN_ +TW_UINT16 FAR PASCAL DSM_Entry( pTW_IDENTITY pOrigin, + pTW_IDENTITY pDest, + TW_UINT32 DG, + TW_UINT16 DAT, + TW_UINT16 MSG, + TW_MEMREF pData); + +typedef TW_UINT16 (FAR PASCAL *DSMENTRYPROC)(pTW_IDENTITY, pTW_IDENTITY, + TW_UINT32, TW_UINT16, + TW_UINT16, TW_MEMREF); +#else /* _MSWIN_ */ + +FAR PASCAL TW_UINT16 DSM_Entry( pTW_IDENTITY pOrigin, + pTW_IDENTITY pDest, + TW_UINT32 DG, + TW_UINT16 DAT, + TW_UINT16 MSG, + TW_MEMREF pData); + +typedef TW_UINT16 (*DSMENTRYPROC)(pTW_IDENTITY, pTW_IDENTITY, + TW_UINT32, TW_UINT16, + TW_UINT16, TW_MEMREF); +#endif /* _MSWIN_ */ + +#ifdef __cplusplus +} +#endif /* cplusplus */ + + +/********************************************************************** + * Function: DS_Entry, the entry point provided by a Data Source. + * + * Parameters: + * pOrigin Identifies the source module of the message. This could + * identify an application or the Data Source Manager. + * + * DG The Data Group. + * Example: DG_IMAGE. + * + * DAT The Data Attribute Type. + * Example: DAT_IMAGEMEMXFER. + * + * MSG The message. Messages are interpreted by the data source + * with respect to the Data Group and the Data Attribute Type. + * Example: MSG_GET. + * + * pData A pointer to the data structure or variable identified + * by the Data Attribute Type. + * Example: (TW_MEMREF)&ImageMemXfer + * where ImageMemXfer is a TW_IMAGEMEMXFER structure. + * + * Returns: + * ReturnCode + * Example: TWRC_SUCCESS. + * + * Note: + * The DSPROC type is only used by an application when it calls + * a Data Source directly, bypassing the Data Source Manager. + * + ********************************************************************/ +/* Don't mangle the name "DS_Entry" if we're compiling in C++! */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifdef _MSWIN_ + #ifdef _WIN32 + __declspec(dllexport) TW_UINT16 FAR PASCAL DS_Entry (pTW_IDENTITY pOrigin, + TW_UINT32 DG, + TW_UINT16 DAT, + TW_UINT16 MSG, + TW_MEMREF pData); + #else /* _WIN32 */ + TW_UINT16 FAR PASCAL DS_Entry (pTW_IDENTITY pOrigin, + TW_UINT32 DG, + TW_UINT16 DAT, + TW_UINT16 MSG, + TW_MEMREF pData); + #endif /* _WIN32 */ + + typedef TW_UINT16 (FAR PASCAL *DSENTRYPROC) (pTW_IDENTITY pOrigin, + TW_UINT32 DG, + TW_UINT16 DAT, + TW_UINT16 MSG, + TW_MEMREF pData); +#else /* _MSWIN_ */ +FAR PASCAL TW_UINT16 DS_Entry( pTW_IDENTITY pOrigin, + TW_UINT32 DG, + TW_UINT16 DAT, + TW_UINT16 MSG, + TW_MEMREF pData); + +typedef TW_UINT16 (*DSENTRYPROC)(pTW_IDENTITY, + TW_UINT32, TW_UINT16, + TW_UINT16, TW_MEMREF); +#endif /* _MSWIN_ */ + +#ifdef __cplusplus +} +#endif /* cplusplus */ + +/* SDH - 02/08/95 - TWUNK */ +/* Force 32-bit twain to use same packing of twain structures as existing */ +/* 16-bit twain. This allows 16/32-bit thunking. */ +#ifdef WIN32 + #ifdef __BORLANDC__ //(Mentor June 13, 1996) if we're using a Borland compiler + #pragma option -a. //(Mentor October 30, 1996) switch back to original alignment + #else //(Mentor June 13, 1996) if NOT using a Borland compiler + #pragma pack (pop, before_twain) + #endif //(Mentor June 13, 1996) +#else /* WIN32 */ +#endif /* WIN32 */ + +#endif /* TWAIN */ diff --git a/SlnkDWFImpl/CxImage/demo/xTargetButton.cpp b/SlnkDWFImpl/CxImage/demo/xTargetButton.cpp new file mode 100644 index 0000000..4a6d325 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/xTargetButton.cpp @@ -0,0 +1,814 @@ +// CxTargetButton.cpp : implementation file +/** 12/Aug/2001 v1.00 + * - ing.davide.pizzolato@libero.it + */ + +#include "stdafx.h" +#include "xTargetButton.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CxTargetButton +CxTargetButton::CxTargetButton() +{ + m_target = true; + m_Border=1; //draw 3D border + m_FocusRectMargin=3; //focus dotted rect margin + m_TextColor=GetSysColor(COLOR_BTNTEXT); // default button text color + m_flat = m_Checked = m_button_down = m_tracking = false; + + m_Icon=m_IconDown=m_IconHighLight=NULL; // icon handle + m_IconBox.SetRectEmpty(); //icon location + m_IconAlign=BS_CENTER; //icon alignment + m_TextAlign=DT_CENTER; //text alignment + m_pLF=NULL; //font structure pointer +} +///////////////////////////////////////////////////////////////////////////// +CxTargetButton::~CxTargetButton() +{ + m_Font.DeleteObject(); + if (m_pLF) free(m_pLF); + if (m_IconDown!=m_Icon && m_IconDown) DestroyIcon(m_IconDown); + if (m_IconHighLight!=m_Icon && m_IconHighLight) DestroyIcon(m_IconHighLight); + if (m_Icon) DestroyIcon(m_Icon); +} +///////////////////////////////////////////////////////////////////////////// +BEGIN_MESSAGE_MAP(CxTargetButton, CButton) + //{{AFX_MSG_MAP(CxTargetButton) + ON_WM_ERASEBKGND() + ON_WM_LBUTTONDOWN() + ON_WM_LBUTTONUP() + ON_WM_MOUSEMOVE() + ON_WM_LBUTTONDBLCLK() + ON_WM_KILLFOCUS() + //ON_CONTROL_REFLECT_EX(BN_CLICKED, OnClicked) + ON_WM_KEYDOWN() + //}}AFX_MSG_MAP + ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave) + ON_MESSAGE(WM_CXTGT_RADIO , OnRadioInfo) + ON_MESSAGE(BM_SETCHECK , OnBMSetCheck) + ON_MESSAGE(BM_GETCHECK , OnBMGetCheck) +END_MESSAGE_MAP() +///////////////////////////////////////////////////////////////////////////// +// CxTargetButton message handlers +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::PreSubclassWindow() +{ + m_Style=GetStyle(); //get general button styles + m_IsPushLike=((m_Style & BS_PUSHLIKE)!=0); + m_flat=((m_Style & BS_FLAT)!=0); + SetTextAlign(m_Style & 0x0300); + + m_Style=GetButtonStyle(); ///get specific BS_ styles + if ((m_Style & BS_AUTOCHECKBOX)==BS_AUTOCHECKBOX) +// ||((m_Style & BS_CHECKBOX)==BS_CHECKBOX)) + m_Style=BS_CHECKBOX; + else if ((m_Style & BS_AUTORADIOBUTTON)==BS_AUTORADIOBUTTON) +// ||((m_Style & BS_RADIOBUTTON)==BS_RADIOBUTTON)) + m_Style=BS_RADIOBUTTON; + else { m_Style=BS_PUSHBUTTON; m_IsPushLike=true;} + + //default radio & check-box has no border + if (!m_IsPushLike) m_Border = false; + + CButton::PreSubclassWindow(); + ModifyStyle(0, BS_OWNERDRAW); +} +///////////////////////////////////////////////////////////////////////////// +BOOL CxTargetButton::OnEraseBkgnd(CDC* pDC) +{ return 1; } // doesn't erase the button background +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) +{ + ASSERT (lpDrawItemStruct); + //TRACE("* Captured: %08X\n", ::GetCapture()); + + //Check if the button state in not in inconsistent mode... + POINT mouse_position; + if ((m_button_down) && (::GetCapture() == m_hWnd) && (::GetCursorPos(&mouse_position))){ + if (::WindowFromPoint(mouse_position) == m_hWnd){ + if ((GetState() & BST_PUSHED) != BST_PUSHED) { + //TRACE("* Inconsistency up detected! Fixing.\n"); + SetState(TRUE); + return; + } + } else { + if ((GetState() & BST_PUSHED) == BST_PUSHED) { + //TRACE("* Inconsistency up detected! Fixing.\n"); + SetState(FALSE); + return; + } } } + + //TRACE("* Drawing: %08x\n", lpDrawItemStruct->itemState); + bool btargetdone=false; + CString sCaption; + CDC *pRealDC = CDC::FromHandle(lpDrawItemStruct->hDC); // get device context + RECT r=lpDrawItemStruct->rcItem; // context rectangle + int cx = r.right - r.left ; // get width + int cy = r.bottom - r.top ; // get height + // get text box position + RECT tr={r.left+m_FocusRectMargin+2,r.top,r.right-m_FocusRectMargin-2,r.bottom}; + + CDC hdcMem; //create a memory DC to avoid flicker + hdcMem.CreateCompatibleDC(pRealDC); + CDC* pDC = &hdcMem; //(just use pRealDC to paint directly the screen) + CBitmap hBitmap; //create a destination for raster operations + hBitmap.CreateCompatibleBitmap(pRealDC,cx,cy); + CBitmap* pOldBitmap = hdcMem.SelectObject(&hBitmap); //select the destination for MemDC + + GetWindowText(sCaption); // get button text + pDC->SetBkMode(TRANSPARENT); + // with MemDC we need to select the font... + + //get text font + CFont* pOldFont=NULL; + if (m_Font.m_hObject) pOldFont = pDC->SelectObject(&m_Font); + else pDC->SelectObject(GetStockObject(DEFAULT_GUI_FONT)); +// TEXTMETRIC tm; +// pDC->GetTextMetrics(&tm); // get font metrics + + // accommodate text location + if (m_Icon){ + switch (m_IconAlign){ + case BS_LEFT: + tr.left+=m_IconBox.Width(); // shift left + break; + case BS_RIGHT: + tr.right-=m_IconBox.Width(); // shift right + break; + case BS_CENTER: + tr.top+=m_IconBox.bottom; // shift text under the icon + tr.bottom-=m_FocusRectMargin + 1; + } + } + // Select the correct skin + if (lpDrawItemStruct->itemState & ODS_DISABLED){ // DISABLED BUTTON + pDC->FillSolidRect(&r,GetSysColor(COLOR_BTNFACE)); + + if (m_Icon) //draw the icon + pDC->DrawState(m_IconBox.TopLeft(),m_IconBox.Size(), + m_Icon,DSS_DISABLED,(CBrush*)NULL); + + // if needed, draw the standard 3D rectangular border + if ((m_Border)&&(m_flat==FALSE)) pDC->DrawEdge(&r,EDGE_RAISED,BF_RECT); + // paint the etched button text + pDC->SetTextColor(GetSysColor(COLOR_3DHILIGHT)); + pDC->DrawText(sCaption,&tr,m_TextAlign); + pDC->SetTextColor(GetSysColor(COLOR_GRAYTEXT)); + OffsetRect(&tr,-1,-1); + pDC->DrawText(sCaption,&tr,m_TextAlign); + } else { +//--------------------------------------------------------------------------- + if ((lpDrawItemStruct->itemState & ODS_SELECTED)||m_Checked){ //SELECTED (DOWN) BUTTON + + if (m_Style==BS_PUSHBUTTON){ + pDC->FillSolidRect(&r,GetSysColor(COLOR_3DHILIGHT)); + if (m_tracking) { + DrawTarget(pDC,&r,m_TextColor,3,4,3); + } + } else { + if (m_tracking){ + pDC->FillSolidRect(&r,GetSysColor(COLOR_3DHILIGHT)); + DrawTarget(pDC,&r,m_TextColor,3,4,3); + btargetdone=true; + } else { + pDC->FillSolidRect(&r,GetSysColor(COLOR_3DHILIGHT)); + } + } + + if (m_IconDown){ //draw the pushed icon + if (m_IsPushLike) m_IconBox.OffsetRect(1,1); + pDC->DrawState(m_IconBox.TopLeft(),m_IconBox.Size(), + m_IconDown,DSS_NORMAL,(CBrush*)NULL); + if (m_IsPushLike) m_IconBox.OffsetRect(-1,-1); + } + //shift text + if (m_IsPushLike) OffsetRect(&tr,1,1); + // if needed, draw the standard 3D rectangular border + if (m_Border){ + if (m_flat) pDC->Draw3dRect(&r,GetSysColor(COLOR_BTNSHADOW),GetSysColor(COLOR_BTNHILIGHT)); + else pDC->DrawEdge(&r,EDGE_SUNKEN,BF_RECT); + } + + + } else { +//--------------------------------------------------------------------------- + // DEFAULT BUTTON + if (m_tracking){ + pDC->FillSolidRect(&r,GetSysColor(COLOR_3DHILIGHT)); + DrawTarget(pDC,&r,m_TextColor,3,4,3); + btargetdone=true; + } else { + pDC->FillSolidRect(&r,GetSysColor(COLOR_BTNFACE)); + } + + if (m_IconHighLight && m_tracking) { // draw the highlighted icon + pDC->DrawState(m_IconBox.TopLeft(),m_IconBox.Size(), + m_IconHighLight,DSS_NORMAL,(CBrush*)NULL); + } else if (m_Icon) //draw the icon + pDC->DrawState(m_IconBox.TopLeft(),m_IconBox.Size(), + m_Icon,DSS_NORMAL,(CBrush*)NULL); + + // if needed, draw the standard 3D rectangular border + if ((m_Border)&&((m_tracking)||(m_flat==FALSE))){ + if (lpDrawItemStruct->itemState & ODS_DEFAULT){ + pDC->DrawEdge(&r,EDGE_SUNKEN,BF_RECT); + InflateRect(&r,-1,-1); + pDC->DrawEdge(&r,EDGE_RAISED,BF_RECT); + } else { + if (m_flat) pDC->Draw3dRect(&r,GetSysColor(COLOR_BTNHILIGHT),GetSysColor(COLOR_BTNSHADOW)); + //else pDC->DrawEdge(&r,EDGE_RAISED,BF_RECT); + else pDC->Draw3dRect(&r,GetSysColor(COLOR_BTNHILIGHT),GetSysColor(COLOR_BTNSHADOW)); + } + } +//--------------------------------------------------------------------------- + } + // paint the focus rect + if ((lpDrawItemStruct->itemState & ODS_FOCUS)&&(m_FocusRectMargin>0)){ + if (m_tracking || (lpDrawItemStruct->itemState & ODS_SELECTED)){ + if (!btargetdone) { + DrawTarget(pDC,&r,m_TextColor,3,4,3,1); + } + }else{ + DrawTarget(pDC,&r,GetSysColor(COLOR_INFOBK),3,4,3); + } + +// InflateRect(&r,-m_FocusRectMargin,-m_FocusRectMargin); +// m_dh.Draw(pDC->GetSafeHdc(),1+r.left,r.top); +// m_dh.Draw(pDC->GetSafeHdc(),1+r.left,r.bottom); +// m_dv.Draw(pDC->GetSafeHdc(),r.left,1+r.top); +// m_dv.Draw(pDC->GetSafeHdc(),r.right,1+r.top); + } + // paint the enabled button text + pDC->SetTextColor(m_TextColor); + pDC->DrawText(sCaption,&tr,m_TextAlign); + } + + if (pOldFont) pDC->SelectObject(pOldFont); //restore the old font object + + pRealDC->BitBlt(0,0,cx,cy,&hdcMem,0,0,SRCCOPY); //copy in the real world + //restore the old objects to avoid memory leakage + if (pOldBitmap) hdcMem.SelectObject(pOldBitmap); +// hdcMem.DeleteDC(); the destructor will do this for us +// hBitmap.DeleteObject(); the destructor will do this for us + +} +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::DrawTarget(CDC *pDC, RECT *r, DWORD color, int border, int width, int height, int offset) +{ + if (m_target){ + int x,y; + CPen pen; + if (pen.CreatePen(PS_SOLID, 1, color)) + { + CPen* pOldPen = pDC->SelectObject(&pen); + + pDC->MoveTo(offset+border+width,offset+border); + pDC->LineTo(offset+border,offset+border); + pDC->LineTo(offset+border,offset+border+height+1); + + x = r->right - border - 2 +(1-m_IsPushLike); + pDC->MoveTo(offset+x - width,offset+border); + pDC->LineTo(offset+x,offset+border); + pDC->LineTo(offset+x,offset+border+height+1); + + y = r->bottom - border - 2+(1-m_IsPushLike); + pDC->MoveTo(offset+border+width,offset+y); + pDC->LineTo(offset+border,offset+y); + pDC->LineTo(offset+border,offset+y-height-1); + + pDC->MoveTo(offset+x - width,offset+y); + pDC->LineTo(offset+x,offset+y); + pDC->LineTo(offset+x,offset+y-height-1); + + pDC->SelectObject(pOldPen); + } + } +} +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::SetIcon(UINT nIcon, UINT nIconAlign, UINT nIconDown, UINT nIconHighLight) +{ + if (m_IconDown!=m_Icon && m_IconDown) DestroyIcon(m_IconDown); + if (m_IconHighLight!=m_Icon && m_IconHighLight) DestroyIcon(m_IconHighLight); + if (m_Icon) DestroyIcon(m_Icon); + + m_Icon = (HICON)::LoadImage(AfxGetInstanceHandle(), + MAKEINTRESOURCE(nIcon), + IMAGE_ICON, 0, 0, 0); + if (m_Icon){ // if success... + ICONINFO iinfo; // get icon info + GetIconInfo(m_Icon, &iinfo); + m_IconBox.left=m_IconBox.top=0; + m_IconBox.right = iinfo.xHotspot * 2; + m_IconBox.bottom = iinfo.yHotspot * 2; + + long x,y; + RECT rect; + GetWindowRect(&rect); + y=rect.bottom-rect.top; + x=rect.right-rect.left; + switch (nIconAlign){ //set the icon location + case BS_RIGHT: + m_IconAlign=BS_RIGHT; + m_IconBox.OffsetRect(x - iinfo.xHotspot*2 - m_FocusRectMargin, + max(0, (long)(y/2 - iinfo.yHotspot))); + break; + case BS_LEFT: + m_IconAlign=BS_LEFT; + m_IconBox.OffsetRect(m_FocusRectMargin, + max(0, (long)(y/2 - iinfo.yHotspot))); + break; + default: + m_IconAlign=BS_CENTER; + m_IconBox.OffsetRect(max(0, (long)(x/2 - iinfo.xHotspot)), + max(0, (long)(y/2 - 2*iinfo.yHotspot))); + } + + //release icon mask bitmaps (Orioli Alessandro ) + if( iinfo.hbmColor ) DeleteObject( iinfo.hbmColor ); + if( iinfo.hbmMask ) DeleteObject( iinfo.hbmMask ); + + if (nIconDown > 0){ //load down icon + m_IconDown = (HICON)::LoadImage(AfxGetInstanceHandle(), + MAKEINTRESOURCE(nIconDown), + IMAGE_ICON, 0, 0, 0); + if (m_IconDown==NULL) m_IconDown= m_Icon; + } else { m_IconDown= m_Icon; } //reuse resource handle + + if (nIconHighLight > 0){ //load highlighted icon + m_IconHighLight = (HICON)::LoadImage(AfxGetInstanceHandle(), + MAKEINTRESOURCE(nIconHighLight), + IMAGE_ICON, 0, 0, 0); + if (m_IconHighLight==NULL) m_IconHighLight= m_Icon; + } else { m_IconHighLight= m_Icon; } //reuse resource handle + } +} +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::SetTextAlign(UINT nTextAlign) +{ +// see DrawText() styles... + switch (nTextAlign){ + case BS_RIGHT: + m_TextAlign=DT_RIGHT; + break; + case BS_LEFT: + m_TextAlign=DT_LEFT; + break; + default: + m_TextAlign=DT_CENTER; + } + m_TextAlign|=(DT_SINGLELINE|DT_VCENTER); +} +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::SetFlat(bool bFlag) +{ m_flat=bFlag; } //set flat border mode +///////////////////////////////////////////////////////////////////////////// +COLORREF CxTargetButton::SetTextColor(COLORREF new_color) +{ + COLORREF tmp_color=m_TextColor; + m_TextColor=new_color; + return tmp_color; //returns the previous color +} +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::SetToolTipText(CString s, CString sDown) +{ + m_ToolTipUp = s; //normal tooltip + m_ToolTipDw = sDown; //tooltip for checked state + + //select the down tooltip if the button is already checked + if (m_Checked && !m_ToolTipDw.IsEmpty()) s = m_ToolTipDw; + + if(m_tooltip.m_hWnd==NULL){ + if(m_tooltip.Create(this)) //first assignment + if(m_tooltip.AddTool(this, (LPCTSTR)s)){ + m_tooltip.Activate(1); + // enable multiline tooltips + m_tooltip.SendMessage(TTM_SETMAXTIPWIDTH, 0, 300); + } + } else { + m_tooltip.UpdateTipText((LPCTSTR)s,this); + } +} +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::RelayEvent(UINT message, WPARAM wParam, LPARAM lParam) +{ +// This function will create a MSG structure, fill it in a pass it to +// the ToolTip control, m_ttip. Note that we ensure the point is in window +// coordinates (relative to the control's window). + if(NULL != m_tooltip.m_hWnd){ + MSG msg; + msg.hwnd = m_hWnd; + msg.message = message; + msg.wParam = wParam; + msg.lParam = lParam; + msg.time = 0; + msg.pt.x = LOWORD(lParam); + msg.pt.y = HIWORD(lParam); + + m_tooltip.RelayEvent(&msg); + } +} +///////////////////////////////////////////////////////////////////////////// +//Method......: OnLButtonDblClk +//Class.......: CxTargetButton +// +//Author......: Milan Gardian +//Created.....: MAR-2001 +// +//Return value: NONE +//Parameters..: Used only to be forwarded as WM_LBUTTONDOWN message parameters +//Exceptions..: NONE +//------------ +//Description : +// > We do not care about doublelicks - handle this event +// like an ordinary left-button-down event +//--------------------------------------------------------- +void CxTargetButton::OnLButtonDblClk(UINT flags, CPoint point) +{ + SendMessage(WM_LBUTTONDOWN, flags, MAKELPARAM(point.x, point.y)); +} +///////////////////////////////////////////////////////////////////////////// +//Method......: OnLButtonDown +//Class.......: CxTargetButton +// +//Author......: Milan Gardian +//Created.....: MAR-2001 +// +//Return value: NONE +//Parameters..: As follows +// > [in] nFlags: not used +// > [in] point: coordinates of the mouse pointer when this event was spawned +//Exceptions..: NONE +//------------ +//Description : +// > Handle event when left button is pressed down +//--------------------------------------------------------- +void CxTargetButton::OnLButtonDown(UINT nFlags, CPoint point) +{ + //TRACE("* %08X: down\n", ::GetTickCount()); + + //Pass this message to the ToolTip control + RelayEvent(WM_LBUTTONDOWN,(WPARAM)nFlags,MAKELPARAM(LOWORD(point.x),LOWORD(point.y))); + + //If we are tracking this button, cancel it + if (m_tracking) { + TRACKMOUSEEVENT t = { + sizeof(TRACKMOUSEEVENT), + TME_CANCEL | TME_LEAVE, + m_hWnd, 0 + }; + if (::_TrackMouseEvent(&t)) { + m_tracking = false; + } + } + + //Default-process the message + CButton::OnLButtonDown(nFlags, point); + m_button_down = true; +} +///////////////////////////////////////////////////////////////////////////// +//Method......: OnLButtonUp +//Class.......: CxTargetButton +// +//Author......: Milan Gardian +//Created.....: MAR-2001 +// +//Return value: NONE +//Parameters..: As follows +// > [in] nFlags: not used +// > [in] point: coordinates of the mouse pointer when this event was spawned +//Exceptions..: NONE +//------------ +//Description : +// +// > Handle event when left button is released (goes up) +//--------------------------------------------------------- +void CxTargetButton::OnLButtonUp(UINT nFlags, CPoint point) +{ + //TRACE("* %08X: up\n", ::GetTickCount()); + + if (m_Style){ //track mouse for radio & check buttons + POINT p2 = point; + ::ClientToScreen(m_hWnd, &p2); + HWND mouse_wnd = ::WindowFromPoint(p2); + if (mouse_wnd == m_hWnd && m_button_down == true){ // mouse is in button + if (m_Style==BS_CHECKBOX) SetCheck(m_Checked ? 0 : 1); + if (m_Style==BS_RADIOBUTTON) SetCheck(1); + } + } + + //Pass this message to the ToolTip control + RelayEvent(WM_LBUTTONUP,(WPARAM)nFlags,MAKELPARAM(LOWORD(point.x),LOWORD(point.y))); + + //Default-process the message + m_button_down = false; + CButton::OnLButtonUp(nFlags, point); +} +///////////////////////////////////////////////////////////////////////////// +//Method......: OnMouseMove +//Class.......: CxTargetButton +// +//Author......: Milan Gardian +//Created.....: MAR-2001 +// +//Return value: NONE +//Parameters..: As follows +// > [in] nFlags: not used +// > [in] point: coordinates of the mouse pointer when this event was spawned +//Exceptions..: NONE +//------------ +//Description : +// > Handle change of mouse position: see the comments in the +// method for further info. +//--------------------------------------------------------- +void CxTargetButton::OnMouseMove(UINT nFlags, CPoint point) +{ + //TRACE("* %08X: Mouse\n", ::GetTickCount()); + + //Pass this message to the ToolTip control + RelayEvent(WM_MOUSEMOVE,(WPARAM)nFlags,MAKELPARAM(LOWORD(point.x),LOWORD(point.y))); + + //If we are in capture mode, button has been pressed down + //recently and not yet released - therefore check is we are + //actually over the button or somewhere else. If the mouse + //position changed considerably (e.g. we moved mouse pointer + //from the button to some other place outside button area) + //force the control to redraw + // + if ((m_button_down) && (::GetCapture() == m_hWnd)) { + POINT p2 = point; + ::ClientToScreen(m_hWnd, &p2); + HWND mouse_wnd = ::WindowFromPoint(p2); + + bool pressed = ((GetState() & BST_PUSHED) == BST_PUSHED); + bool need_pressed = (mouse_wnd == m_hWnd); + if (pressed != need_pressed) { + //TRACE("* %08X Redraw\n", GetTickCount()); + SetState(need_pressed ? TRUE : FALSE); + Invalidate(); + } + } else { + + //Otherwise the button is released. That means we should + //know when we leave its area - and so if we are not tracking + //this mouse leave event yet, start now! + // + if (!m_tracking) { + TRACKMOUSEEVENT t = { + sizeof(TRACKMOUSEEVENT), + TME_LEAVE, + m_hWnd, + 0 + }; + if (::_TrackMouseEvent(&t)) { + //TRACE("* Mouse enter\n"); + m_tracking = true; + Invalidate(); + } + } + } + + //Forward this event to superclass + CButton::OnMouseMove(nFlags, point); +} +///////////////////////////////////////////////////////////////////////////// +//Method......: OnMouseLeave +//Class.......: CxTargetButton +// +//Author......: Milan Gardian +//Created.....: MAR-2001 +// +//Return value: NULL +//Parameters..: NOT USED +//Exceptions..: NONE +//------------ +//Description : +// > Handle situation when mouse cursor leaves area of this +// window (button). This event might be generated ONLY +// if we explicitely call 'TrackMouseEvent'. This is +// signalled by setting the m_tracking flag (see the assert +// precondition) - in 'OnMouseMove' method +// +// > When a mouse pointer leaves area of this button (i.e. +// when this method is invoked), presumably the look of +// the button changes (e.g. when hover/non-hover images are set) +// and therefore we force the control to redraw. +//--------------------------------------------------------- +LRESULT CxTargetButton::OnMouseLeave(WPARAM, LPARAM) +{ + ASSERT (m_tracking); + //TRACE("* Mouse leave\n"); + m_tracking = false; + Invalidate(); + return 0; +} +///////////////////////////////////////////////////////////////////////////// +//Method......: OnKillFocus +//Class.......: CxTargetButton +// +//Author......: Milan Gardian +//Created.....: MAR-2001 +// +//Return value: NONE +//Parameters..: See superclass documentation +//Exceptions..: NONE +//------------ +//Description : +// > If focus is killed during capture, we may no longer +// have the exclusive access to user input and therefore +// release it. +// +// > Such a situation might happens when the user left-clicks +// this button, keeps the button down and simultaneously +// presses TAB key. +//--------------------------------------------------------- +void CxTargetButton::OnKillFocus(CWnd *new_wnd) +{ + if (::GetCapture() == m_hWnd) { + ::ReleaseCapture(); + ASSERT (!m_tracking); + m_button_down = false; + } + CButton::OnKillFocus(new_wnd); +} +///////////////////////////////////////////////////////////////////////////// +//Method......: OnClicked +//Class.......: CxTargetButton +// +//Author......: Milan Gardian +//Created.....: MAR-2001 +// +//Return value: FALSE (do not stop in this handler - forward to parent) +//Parameters..: NONE +//Exceptions..: NONE +//------------ +//Description : +// > Keep consistency of attributes of this instance before +// submitting click event to the parent. +// +// > Currently NOT used. To use, umcomment line +// "ON_CONTROL_REFLECT_EX(BN_CLICKED, OnClicked)" in message map +// at the beginning of this file. +//--------------------------------------------------------- +BOOL CxTargetButton::OnClicked() +{ + if (::GetCapture() == m_hWnd) { + ::ReleaseCapture(); + ASSERT (!m_tracking); + } + m_button_down = false; + //Invalidate(); + return FALSE; +} +///////////////////////////////////////////////////////////////////////////// +//Method......: OnRadioInfo +//Class.......: CxTargetButton +// +//Author......: Rainer Mangold +//Created.....: JUN-2001 +// +//Return value: NULL +//Parameters..: WPARAM and LPARAM (LPARAM not used) +//Exceptions..: NONE +//------------ +//Description : +// > Handle notification, that a Button in the same group was pushed +//--------------------------------------------------------- +LRESULT CxTargetButton::OnRadioInfo(WPARAM wparam, LPARAM) +{ + if (m_Checked){ //only checked buttons need to be unchecked + m_Checked = false; + if(m_tooltip.m_hWnd!=NULL) + m_tooltip.UpdateTipText((LPCTSTR)m_ToolTipUp,this); + Invalidate(); + } + return 0; +} +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) +{ + if ((m_Style)&&(nChar==' ')){ //needed stuff for check & radio buttons + if (m_Style==BS_CHECKBOX) SetCheck(m_Checked ? 0 : 1); + if (m_Style==BS_RADIOBUTTON) SetCheck(1); + } + CButton::OnKeyDown(nChar, nRepCnt, nFlags); +} +///////////////////////////////////////////////////////////////////////////// +//Method......: SetCheck +//Class.......: CxTargetButton +// +//Author......: Rainer Mangold +//Created.....: JUN-2001 +// +//Return value: NONE +//Parameters..: bool +//Exceptions..: NONE +//------------ +//Description : +// > Set the state of this button (pushed or not). +// Works for both, Radio and CheckBox - Buttons +//--------------------------------------------------------- +LRESULT CxTargetButton::OnBMSetCheck(WPARAM wparam, LPARAM) +{ + m_Checked=wparam!=0; + switch (m_Style) + { + case BS_RADIOBUTTON: + if (m_Checked) { //uncheck the other radio buttons (in the same group) + HWND hthis,hwnd2,hpwnd; + hpwnd=GetParent()->GetSafeHwnd(); //get button parent handle + hwnd2=hthis=GetSafeHwnd(); //get this button handle + if (hthis && hpwnd){ //consistency check + for( ; ; ){ //scan the buttons within the group + hwnd2=::GetNextDlgGroupItem(hpwnd,hwnd2,0); + //until we reach again this button + if ((hwnd2==hthis)||(hwnd2==NULL)) break; + //post the uncheck message + ::PostMessage(hwnd2, WM_CXTGT_RADIO, 0, 0); + } + } + } + break; + case BS_PUSHBUTTON: + m_Checked=false; + ASSERT(false); // Must be a Check or Radio button to use this function + } + + //set the correct tooltip + if (m_tooltip.m_hWnd!=NULL){ + m_tooltip.Pop(); //to avoid flicker + if (m_Checked && !m_ToolTipDw.IsEmpty()) + m_tooltip.UpdateTipText((LPCTSTR)m_ToolTipDw,this); + else + m_tooltip.UpdateTipText((LPCTSTR)m_ToolTipUp,this); + } + Invalidate(); + return 0; +} +///////////////////////////////////////////////////////////////////////////// +LRESULT CxTargetButton::OnBMGetCheck(WPARAM wparam, LPARAM) +{ return m_Checked; } //returns the state for check & radio buttons +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::SetButtonStyle(UINT nStyle, BOOL bRedraw) +{ + // see PreSubclassWindow + m_IsPushLike=((nStyle & BS_PUSHLIKE)!=0); + m_flat=((nStyle & BS_FLAT)!=0); + + if ((nStyle & BS_AUTOCHECKBOX)==BS_AUTOCHECKBOX) +// ||((m_Style & BS_CHECKBOX)==BS_CHECKBOX)) + m_Style=BS_CHECKBOX; + else if ((nStyle & BS_AUTORADIOBUTTON)==BS_AUTORADIOBUTTON) +// ||((m_Style & BS_RADIOBUTTON)==BS_RADIOBUTTON)) + m_Style=BS_RADIOBUTTON; + else { m_Style=BS_PUSHBUTTON; m_IsPushLike=true; m_Checked=false; } + + //default radio & check-box has no border + if (!m_IsPushLike) m_Border = false; + + if (bRedraw) Invalidate(); +} +///////////////////////////////////////////////////////////////////////////// +bool CxTargetButton::SetFont(CString sFontName,long lSize, long lWeight, BYTE bItalic, BYTE bUnderline) +{ + if (m_pLF==NULL) m_pLF=(LOGFONT*)calloc(1,sizeof(LOGFONT)); + if (m_pLF){ + strncpy(m_pLF->lfFaceName,sFontName,31); + m_pLF->lfHeight=lSize; + m_pLF->lfWeight=lWeight; + m_pLF->lfItalic=bItalic; + m_pLF->lfUnderline=bUnderline; + m_Font.DeleteObject(); + if (m_Font.CreateFontIndirect(m_pLF)) return true; + } + return false; +} +///////////////////////////////////////////////////////////////////////////// +bool CxTargetButton::SetFont(LOGFONT* pNewStyle) +{ + if (pNewStyle){ + if (m_pLF==NULL) m_pLF=(LOGFONT*)calloc(1,sizeof(LOGFONT)); + if (m_pLF){ + memcpy(m_pLF,pNewStyle,sizeof(LOGFONT)); + m_Font.DeleteObject(); + if (m_Font.CreateFontIndirect(m_pLF)) return true; + } + } + return false; +} +///////////////////////////////////////////////////////////////////////////// +LOGFONT* CxTargetButton::GetFont() +{ return m_pLF; } +///////////////////////////////////////////////////////////////////////////// +void CxTargetButton::EnableTarget(bool enable) +{ + m_target=enable; +} +///////////////////////////////////////////////////////////////////////////// +//EOF + diff --git a/SlnkDWFImpl/CxImage/demo/xTargetButton.h b/SlnkDWFImpl/CxImage/demo/xTargetButton.h new file mode 100644 index 0000000..773ad06 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo/xTargetButton.h @@ -0,0 +1,85 @@ +#if !defined(AFX_MYTGTBTN_H) +#define AFX_MYTGTBTN_H + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// CxTargetButton.h : header file +///////////////////////////////////////////////////////////////////////////// +#define WM_CXTGT_RADIO WM_USER+0x100 + +class CxTargetButton : public CButton +{ +// Construction +public: + CxTargetButton(); +// Attributes +private: +// Operations +public: +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CxTargetButton) + public: + virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); + protected: + virtual void PreSubclassWindow(); + //}}AFX_VIRTUAL +// Implementation +public: + void EnableTarget(bool enable); + LOGFONT* GetFont(); + bool SetFont(LOGFONT* pNewStyle); + bool SetFont(CString sFontName, long lSize=0, long lWeight=400, BYTE bItalic=0, BYTE bUnderline=0); + void SetButtonStyle( UINT nStyle, BOOL bRedraw = TRUE ); + void SetFlat(bool bFlag); + void SetTextAlign(UINT nTextAlign); + void SetIcon(UINT nIcon, UINT nIconAlign=BS_CENTER, UINT nIconDown=0, UINT nIconHighLight=0); + void SetToolTipText(CString s, CString sDown=""); + COLORREF SetTextColor(COLORREF new_color); + virtual ~CxTargetButton(); + // Generated message map functions +protected: + void DrawTarget(CDC* pDC, RECT* r, DWORD color, int border, int width, int height, int offset=0); + CFont m_Font; //font object + LOGFONT* m_pLF; //font structure + CString m_ToolTipUp,m_ToolTipDw; + bool m_Checked; //radio & check buttons + bool m_IsPushLike; //radio & check buttons + DWORD m_Style; + bool m_tracking; + bool m_button_down; + void RelayEvent(UINT message, WPARAM wParam, LPARAM lParam); + CToolTipCtrl m_tooltip; + short m_FocusRectMargin; //dotted margin offset + COLORREF m_TextColor; //button text color + BOOL m_Border; //0=flat; 1=3D; + HICON m_Icon,m_IconDown,m_IconHighLight; + CRect m_IconBox; + UINT m_TextAlign; + UINT m_IconAlign; + bool m_flat; + bool m_target; +// afx_msg BOOL OnClicked(); + //{{AFX_MSG(CxTargetButton) + afx_msg BOOL OnEraseBkgnd(CDC* pDC); + afx_msg void OnLButtonDown(UINT nFlags, CPoint point); + afx_msg void OnLButtonUp(UINT nFlags, CPoint point); + afx_msg void OnMouseMove(UINT nFlags, CPoint point); + afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); + afx_msg void OnKillFocus(CWnd* pNewWnd); + afx_msg BOOL OnClicked(); + afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); + //}}AFX_MSG + afx_msg LRESULT OnMouseLeave(WPARAM, LPARAM); + afx_msg LRESULT OnRadioInfo(WPARAM, LPARAM); + afx_msg LRESULT OnBMSetCheck(WPARAM, LPARAM); + afx_msg LRESULT OnBMGetCheck(WPARAM, LPARAM); + DECLARE_MESSAGE_MAP() + //afx_msg BOOL OnClicked(); + +}; +///////////////////////////////////////////////////////////////////////////// +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. +#endif // !defined(AFX_MYTGTBTN_H) diff --git a/SlnkDWFImpl/CxImage/demo2/.gitignore b/SlnkDWFImpl/CxImage/demo2/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/demo2/Console.cpp b/SlnkDWFImpl/CxImage/demo2/Console.cpp new file mode 100644 index 0000000..44873a8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo2/Console.cpp @@ -0,0 +1,126 @@ +// Console.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" + +#include "ximage.h" + +CString FindExtension(const CString& name) +{ + int len = name.GetLength(); + int i; + for (i = len-1; i >= 0; i--){ + if (name[i] == '.'){ + return name.Mid(i+1); + } + } + return CString(""); +} + +int FindFormat(const CString& ext) +{ + int type = 0; +// if (ext == "bmp") type = CXIMAGE_FORMAT_BMP; + if (0) {} +#if CXIMAGE_SUPPORT_JPG + else if (ext=="jpg"||ext=="jpeg") type = CXIMAGE_FORMAT_JPG; +#endif +#if CXIMAGE_SUPPORT_GIF + else if (ext == "gif") type = CXIMAGE_FORMAT_GIF; +#endif +#if CXIMAGE_SUPPORT_PNG + else if (ext == "png") type = CXIMAGE_FORMAT_PNG; +#endif +#if CXIMAGE_SUPPORT_MNG + else if (ext=="mng"||ext=="jng") type = CXIMAGE_FORMAT_MNG; +#endif +#if CXIMAGE_SUPPORT_ICO + else if (ext == "ico") type = CXIMAGE_FORMAT_ICO; +#endif +#if CXIMAGE_SUPPORT_TIF + else if (ext=="tiff"||ext=="tif") type = CXIMAGE_FORMAT_TIF; +#endif +#if CXIMAGE_SUPPORT_TGA + else if (ext=="tga") type = CXIMAGE_FORMAT_TGA; +#endif +#if CXIMAGE_SUPPORT_PCX + else if (ext=="pcx") type = CXIMAGE_FORMAT_PCX; +#endif +#if CXIMAGE_SUPPORT_WBMP + else if (ext=="wbmp") type = CXIMAGE_FORMAT_WBMP; +#endif +#if CXIMAGE_SUPPORT_WMF + else if (ext=="wmf"||ext=="emf") type = CXIMAGE_FORMAT_WMF; +#endif +#if CXIMAGE_SUPPORT_J2K + else if (ext=="j2k"||ext=="jp2") type = CXIMAGE_FORMAT_J2K; +#endif +#if CXIMAGE_SUPPORT_JBG + else if (ext=="jbg") type = CXIMAGE_FORMAT_JBG; +#endif +#if CXIMAGE_SUPPORT_JP2 + else if (ext=="jp2"||ext=="j2k") type = CXIMAGE_FORMAT_JP2; +#endif +#if CXIMAGE_SUPPORT_JPC + else if (ext=="jpc"||ext=="j2c") type = CXIMAGE_FORMAT_JPC; +#endif +#if CXIMAGE_SUPPORT_PGX + else if (ext=="pgx") type = CXIMAGE_FORMAT_PGX; +#endif +#if CXIMAGE_SUPPORT_RAS + else if (ext=="ras") type = CXIMAGE_FORMAT_RAS; +#endif +#if CXIMAGE_SUPPORT_PNM + else if (ext=="pnm"||ext=="pgm"||ext=="ppm") type = CXIMAGE_FORMAT_PNM; +#endif + else type = CXIMAGE_FORMAT_UNKNOWN; + + return type; +} + +int main(int argc, char* argv[]) +{ + CxImage image; + + if (argc<3) { + fprintf(stderr, image.GetVersion()); + fprintf(stderr, "\nConsole demo\n"); + fprintf(stderr, "usage: %s input-file output-file\n", argv[0]); + return 1; + } + + CString filein(argv[1]); + CString extin(FindExtension(filein)); + extin.MakeLower(); + int typein = FindFormat(extin); + if (typein == CXIMAGE_FORMAT_UNKNOWN) { + fprintf(stderr, "unknown extension for %s\n", argv[1]); + return 1; + } + + CString fileout(argv[2]); + CString extout(FindExtension(fileout)); + extout.MakeLower(); + int typeout = FindFormat(extout); + if (typeout == CXIMAGE_FORMAT_UNKNOWN) { + fprintf(stderr, "unknown extension for %s\n", argv[2]); + return 1; + } + + + if (!image.Load(argv[1],typein)){ + fprintf(stderr, "%s\n", image.GetLastError()); + fprintf(stderr, "error loading %s\n", argv[1]); + return 1; + } + + if (!image.Save(argv[2],typeout)){ + fprintf(stderr, "%s\n", image.GetLastError()); + fprintf(stderr, "error saving %s\n", argv[2]); + return 1; + } + + printf("Done!\n"); + return 0; +} + diff --git a/SlnkDWFImpl/CxImage/demo2/Console.dsp b/SlnkDWFImpl/CxImage/demo2/Console.dsp new file mode 100644 index 0000000..f68b425 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo2/Console.dsp @@ -0,0 +1,116 @@ +# Microsoft Developer Studio Project File - Name="Console" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Console - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Console.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Console.mak" CFG="Console - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Console - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Console - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Console - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\cximage" /I "..\jpeg" /I "..\zlib" /I "..\png" /I "..\mng" /I "..\tiff" /I "..\j2000" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "_AFXDLL" /Yu"stdafx.h" /FD /c +# ADD BASE RSC /l 0x410 /d "NDEBUG" +# ADD RSC /l 0x410 /d "NDEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# 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 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 ../png/Release/png.lib ../jpeg/Release/jpeg.lib ../zlib/Release/zlib.lib ../tiff/Release/tiff.lib ../j2k/Release/j2k.lib ../jbig/Release/jbig.lib ../cximage/Release/cximage.lib /nologo /subsystem:console /machine:I386 /out:"../bin/console.exe" + +!ELSEIF "$(CFG)" == "Console - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\cximage" /I "..\jpeg" /I "..\zlib" /I "..\png" /I "..\mng" /I "..\tiff" /I "..\j2000" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_AFXDLL" /FD /GZ /c +# SUBTRACT CPP /YX /Yc /Yu +# ADD BASE RSC /l 0x410 /d "_DEBUG" +# ADD RSC /l 0x410 /d "_DEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# 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 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 ../png/Debug/png.lib ../jpeg/Debug/jpeg.lib ../zlib/Debug/zlib.lib ../tiff/Debug/tiff.lib ../j2k/Debug/j2k.lib ../jbig/Debug/jbig.lib ../cximage/Debug/cximage.lib /nologo /subsystem:console /debug /machine:I386 /out:"../bin/consoled.exe" /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "Console - Win32 Release" +# Name "Console - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\Console.cpp +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.cpp +# ADD CPP /Yc"stdafx.h" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\StdAfx.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# Begin Source File + +SOURCE=.\ReadMe.txt +# End Source File +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/demo2/Console.dsw b/SlnkDWFImpl/CxImage/demo2/Console.dsw new file mode 100644 index 0000000..02a0dd0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo2/Console.dsw @@ -0,0 +1,149 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "Console"=.\Console.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name CxImage + End Project Dependency + Begin Project Dependency + Project_Dep_Name Jpeg + End Project Dependency + Begin Project Dependency + Project_Dep_Name png + End Project Dependency + Begin Project Dependency + Project_Dep_Name Tiff + End Project Dependency + Begin Project Dependency + Project_Dep_Name zlib + End Project Dependency + Begin Project Dependency + Project_Dep_Name jbig + End Project Dependency + Begin Project Dependency + Project_Dep_Name j2k + End Project Dependency + Begin Project Dependency + Project_Dep_Name jasper + End Project Dependency +}}} + +############################################################################### + +Project: "CxImage"=..\CxImage\cximage.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "j2k"=..\j2k\j2k.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "jasper"=..\jasper\jasper.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "jbig"=..\jbig\jbig.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "jpeg"=..\jpeg\Jpeg.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "png"=..\png\png.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "tiff"=..\tiff\Tiff.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "zlib"=..\zlib\zlib.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/demo2/Console.sln b/SlnkDWFImpl/CxImage/demo2/Console.sln new file mode 100644 index 0000000..b5baece --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo2/Console.sln @@ -0,0 +1,77 @@ +Microsoft Visual Studio Solution File, Format Version 7.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Console", "Console.vcproj", "{D49F3E77-DBF1-4DB2-8861-59049819E238}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CxImage", "..\CxImage\cximage.vcproj", "{3666AA6D-37C8-437D-9E67-8F7EC2C86107}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "j2k", "..\j2k\j2k.vcproj", "{4B395D07-BEA8-4B91-8655-B4438702D795}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jasper", "..\jasper\jasper.vcproj", "{9F0F573F-EEF1-4625-BF04-F3C84FA0F518}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jbig", "..\jbig\jbig.vcproj", "{413B89C0-0CED-4A89-A5E4-E4EFFE3A4F9E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jpeg", "..\jpeg\Jpeg.vcproj", "{0D8CB324-1BC0-4830-A0B2-A3CF5222EF78}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "png", "..\png\png.vcproj", "{957A7BAF-2C64-4CDC-8334-B2B1B8C8C180}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tiff", "..\tiff\Tiff.vcproj", "{18CC5DE1-979D-4E6C-B897-B43B19B6D3ED}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlib", "..\zlib\zlib.vcproj", "{02717FBF-7F2F-4404-A220-77F671283E4D}" +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + ConfigName.0 = Debug + ConfigName.1 = Release + EndGlobalSection + GlobalSection(ProjectDependencies) = postSolution + {D49F3E77-DBF1-4DB2-8861-59049819E238}.0 = {9F0F573F-EEF1-4625-BF04-F3C84FA0F518} + {D49F3E77-DBF1-4DB2-8861-59049819E238}.1 = {4B395D07-BEA8-4B91-8655-B4438702D795} + {D49F3E77-DBF1-4DB2-8861-59049819E238}.2 = {413B89C0-0CED-4A89-A5E4-E4EFFE3A4F9E} + {D49F3E77-DBF1-4DB2-8861-59049819E238}.3 = {02717FBF-7F2F-4404-A220-77F671283E4D} + {D49F3E77-DBF1-4DB2-8861-59049819E238}.4 = {18CC5DE1-979D-4E6C-B897-B43B19B6D3ED} + {D49F3E77-DBF1-4DB2-8861-59049819E238}.5 = {957A7BAF-2C64-4CDC-8334-B2B1B8C8C180} + {D49F3E77-DBF1-4DB2-8861-59049819E238}.6 = {0D8CB324-1BC0-4830-A0B2-A3CF5222EF78} + {D49F3E77-DBF1-4DB2-8861-59049819E238}.7 = {3666AA6D-37C8-437D-9E67-8F7EC2C86107} + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {D49F3E77-DBF1-4DB2-8861-59049819E238}.Debug.ActiveCfg = Debug|Win32 + {D49F3E77-DBF1-4DB2-8861-59049819E238}.Debug.Build.0 = Debug|Win32 + {D49F3E77-DBF1-4DB2-8861-59049819E238}.Release.ActiveCfg = Release|Win32 + {D49F3E77-DBF1-4DB2-8861-59049819E238}.Release.Build.0 = Release|Win32 + {3666AA6D-37C8-437D-9E67-8F7EC2C86107}.Debug.ActiveCfg = Debug|Win32 + {3666AA6D-37C8-437D-9E67-8F7EC2C86107}.Debug.Build.0 = Debug|Win32 + {3666AA6D-37C8-437D-9E67-8F7EC2C86107}.Release.ActiveCfg = Release|Win32 + {3666AA6D-37C8-437D-9E67-8F7EC2C86107}.Release.Build.0 = Release|Win32 + {4B395D07-BEA8-4B91-8655-B4438702D795}.Debug.ActiveCfg = Debug|Win32 + {4B395D07-BEA8-4B91-8655-B4438702D795}.Debug.Build.0 = Debug|Win32 + {4B395D07-BEA8-4B91-8655-B4438702D795}.Release.ActiveCfg = Release|Win32 + {4B395D07-BEA8-4B91-8655-B4438702D795}.Release.Build.0 = Release|Win32 + {9F0F573F-EEF1-4625-BF04-F3C84FA0F518}.Debug.ActiveCfg = Debug|Win32 + {9F0F573F-EEF1-4625-BF04-F3C84FA0F518}.Debug.Build.0 = Debug|Win32 + {9F0F573F-EEF1-4625-BF04-F3C84FA0F518}.Release.ActiveCfg = Release|Win32 + {9F0F573F-EEF1-4625-BF04-F3C84FA0F518}.Release.Build.0 = Release|Win32 + {413B89C0-0CED-4A89-A5E4-E4EFFE3A4F9E}.Debug.ActiveCfg = Debug|Win32 + {413B89C0-0CED-4A89-A5E4-E4EFFE3A4F9E}.Debug.Build.0 = Debug|Win32 + {413B89C0-0CED-4A89-A5E4-E4EFFE3A4F9E}.Release.ActiveCfg = Release|Win32 + {413B89C0-0CED-4A89-A5E4-E4EFFE3A4F9E}.Release.Build.0 = Release|Win32 + {0D8CB324-1BC0-4830-A0B2-A3CF5222EF78}.Debug.ActiveCfg = Debug|Win32 + {0D8CB324-1BC0-4830-A0B2-A3CF5222EF78}.Debug.Build.0 = Debug|Win32 + {0D8CB324-1BC0-4830-A0B2-A3CF5222EF78}.Release.ActiveCfg = Release|Win32 + {0D8CB324-1BC0-4830-A0B2-A3CF5222EF78}.Release.Build.0 = Release|Win32 + {957A7BAF-2C64-4CDC-8334-B2B1B8C8C180}.Debug.ActiveCfg = Debug|Win32 + {957A7BAF-2C64-4CDC-8334-B2B1B8C8C180}.Debug.Build.0 = Debug|Win32 + {957A7BAF-2C64-4CDC-8334-B2B1B8C8C180}.Release.ActiveCfg = Release|Win32 + {957A7BAF-2C64-4CDC-8334-B2B1B8C8C180}.Release.Build.0 = Release|Win32 + {18CC5DE1-979D-4E6C-B897-B43B19B6D3ED}.Debug.ActiveCfg = Debug|Win32 + {18CC5DE1-979D-4E6C-B897-B43B19B6D3ED}.Debug.Build.0 = Debug|Win32 + {18CC5DE1-979D-4E6C-B897-B43B19B6D3ED}.Release.ActiveCfg = Release|Win32 + {18CC5DE1-979D-4E6C-B897-B43B19B6D3ED}.Release.Build.0 = Release|Win32 + {02717FBF-7F2F-4404-A220-77F671283E4D}.Debug.ActiveCfg = Debug|Win32 + {02717FBF-7F2F-4404-A220-77F671283E4D}.Debug.Build.0 = Debug|Win32 + {02717FBF-7F2F-4404-A220-77F671283E4D}.Release.ActiveCfg = Release|Win32 + {02717FBF-7F2F-4404-A220-77F671283E4D}.Release.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/SlnkDWFImpl/CxImage/demo2/Console.vcproj b/SlnkDWFImpl/CxImage/demo2/Console.vcproj new file mode 100644 index 0000000..77eb294 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo2/Console.vcproj @@ -0,0 +1,163 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/demo2/StdAfx.cpp b/SlnkDWFImpl/CxImage/demo2/StdAfx.cpp new file mode 100644 index 0000000..dcf6387 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo2/StdAfx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// Console.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/SlnkDWFImpl/CxImage/demo2/StdAfx.h b/SlnkDWFImpl/CxImage/demo2/StdAfx.h new file mode 100644 index 0000000..1a91632 --- /dev/null +++ b/SlnkDWFImpl/CxImage/demo2/StdAfx.h @@ -0,0 +1,23 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__F2839003_A1B1_11D6_BB83_AAD68E1F7D6B__INCLUDED_) +#define AFX_STDAFX_H__F2839003_A1B1_11D6_BB83_AAD68E1F7D6B__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + +#include +#include // MFC core and standard components + +// TODO: reference additional headers your program requires here + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__F2839003_A1B1_11D6_BB83_AAD68E1F7D6B__INCLUDED_) diff --git a/SlnkDWFImpl/CxImage/descriptor.xml b/SlnkDWFImpl/CxImage/descriptor.xml new file mode 100644 index 0000000..1ef8945 --- /dev/null +++ b/SlnkDWFImpl/CxImage/descriptor.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/SlnkDWFImpl/CxImage/doc/blank.htm b/SlnkDWFImpl/CxImage/doc/blank.htm new file mode 100644 index 0000000..843c71e --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/blank.htm @@ -0,0 +1,11 @@ + + + +Untitled Document + + + + + + diff --git a/SlnkDWFImpl/CxImage/doc/cximage.htm b/SlnkDWFImpl/CxImage/doc/cximage.htm new file mode 100644 index 0000000..3553fbe --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/cximage.htm @@ -0,0 +1,437 @@ + + + + + + +

CxImage 5.99c

+

+

Introduction

+

CxImage is a C++ class to manage almost any kind of images. +It can load, save, display, transform images in a very simple and fast way.

+

Why another image library? Around there are many good libraries +(OpenIL, FreeImage, PaintLib ...), these are powerful, complete, and constantly +updated. However if you ever try to use them, you may find some difficulties; +because these libraries are mainly platform independent, written in C, sometimes +with a basic C++ wrapper and with tons of compiler switch declarations. Now with +the new GDI+ classes on the scene, maybe CxImage isn't so useful, but at least +here you have the source code. It is not a MFC library, altogether it's a +windows library, because of some particular constructors and the painting +functions, but the backbone is platform independent.

+

CxImage structure

+

In the vertical hierarchy of the library, CxImage stays on the +top of the other modules, it's not a clean OOP approach, but the result was good +since the first release and now it's too late to change again. Anyway you can +always use the derived classes to perform the format specific operations, like +for CxImageTIF to save multipage TIFFs.

+

The glue to connect all the modules and the C libraries is +CxFile, a virtual class that provides the standard methods to +access the data from a file on the disk or in memory.

+

+

A Cximage object is basically a bitmap, with the addition of +some member variables to store useful information:

 class CxImage
+  {
+  ...
+  protected:
+  void* pDib;            //contains the header, the palette, the pixels
+  BITMAPINFOHEADER head; //standard header
+  CXIMAGEINFO info;      //extended information
+  BYTE* pSelection;      //selected region
+  BYTE* pAlpha;          //alpha channel
+  CxImage** pLayers;     //generic layers
+  }
+

CxImage::head is the bitmap header and +CxImage::pDib is a normal bitmap (as you can see in the +implementation of CxImageBMP::Encode).

+

CxImage::info is a handy container of many information shared +between different formats, and for all the member functions.

typedef struct tagCxImageInfo {
+    DWORD   dwEffWidth;       //DWORD aligned scan line width
+    BYTE*   pImage;           //THE IMAGE BITS
+    void*   pGhost;           //if this is a ghost, pGhost point to the body
+    DWORD   dwType;           //original image format
+    char    szLastError[256]; //debugging
+    long    nProgress;        //monitor
+    long    nEscape;          //escape
+    long    nBkgndIndex;      //used for GIF, PNG, MNG
+    RGBQUAD nBkgndColor;      //used for RGB transparency
+    BYTE    nQuality;         //used for JPEG
+    long    nFrame;           //used for TIF, GIF, MNG : actual frame
+    long    nNumFrames;       //used for TIF, GIF, MNG : total number of frames
+    DWORD   dwFrameDelay;     //used for GIF, MNG
+    long    xDPI;             //horizontal resolution
+    long    yDPI;             //vertical resolution
+    RECT    rSelectionBox;    //bounding rectangle
+    BYTE    nAlphaMax;        //max opacity (fade)
+    bool    bAlphaPaletteEnabled;  //true if alpha values in the palette are 
+                              // enabled.
+    bool    bEnabled;         //enables the painting functions
+    long    xOffset;
+    long    yOffset;
+    DWORD   dwEncodeOption;   //for GIF, TIF : 0=def.1=unc,2=fax3,3=fax4,
+                              // 4=pack,5=jpg
+    RGBQUAD last_c;           //for GetNearestIndex optimization
+    BYTE    last_c_index;
+    bool    last_c_isvalid;
+    long    nNumLayers;
+    DWORD   dwFlags;
+} CXIMAGEINFO;
+ + + + + +
+

A CxImage object is also a set of layers. The buffers in each layer are + allocated only when necessary.

+

CxImage::pDib is the background image. + CxImage::pAlpha is the transparency layer. + CxImage::pSelection is the selection layer, used to create + regions of interest for image processing.
Over these 3 specific planes, + you can add other generic layers, stored in CxImage::pLayers. + The generic layers are full CxImage objects, so you can build + complex structures of nested layers.

+

Supported formats and options

+

The whole library is quite big, in the configuration header file +ximacfg.h you'll find the switches to enable or disable a specific +graphic format or feature. Each JPG, PNG and TIFF library adds about 100KB to +the final application, while the CxImage impact is about 50KB. So +you should support and link only the formats that your application really +needs.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
formats#definerequired librariessize [Kbyte]
BMP
GIF
ICO
TGA
PCX
WBMP
WMF
CXIMAGE_SUPPORT_BMP
CXIMAGE_SUPPORT_GIF
CXIMAGE_SUPPORT_ICO
CXIMAGE_SUPPORT_TGA
CXIMAGE_SUPPORT_PCX
CXIMAGE_SUPPORT_WBMP
CXIMAGE_SUPPORT_WMF

built in

24
JPEGCXIMAGE_SUPPORT_JPG

jpeg

88
PNGCXIMAGE_SUPPORT_PNG

png, zlib

104
MNGCXIMAGE_SUPPORT_MNG

mng, zlib, jpeg

148
TIFFCXIMAGE_SUPPORT_TIF

tiff, zlib, jpeg

124
JBIGCXIMAGE_SUPPORT_JBG
jbig

28
PNM,PPM,PGM
RAS
CXIMAGE_SUPPORT_PNM
CXIMAGE_SUPPORT_RAS

jasper

176
JPEG-2000
CXIMAGE_SUPPORT_JP2
CXIMAGE_SUPPORT_JPC
CXIMAGE_SUPPORT_PGX

jasper

176

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Option#defineSize [Kbyte]
CxImage coreall switches off20
geometric transformationsCXIMAGE_SUPPORT_TRANSFORMATION16
image processingCXIMAGE_SUPPORT_DSP24
drawing and windows specific functionsCXIMAGE_SUPPORT_WINDOWS12
transparencyCXIMAGE_SUPPORT_ALPHA4
selectionsCXIMAGE_SUPPORT_SELECTION4
multiple layersCXIMAGE_SUPPORT_LAYERS< 4
graphic formats conversion
CXIMAGE_SUPPORT_DECODE
CXIMAGE_SUPPORT_ENCODE
< 4
+

Using CxImage in your projects

+ + + + + +
+

The CxImgLib.dsw workspace shows the libraries required to build + an application (demo.exe) including almost all the features and the + formats available in CxImage. You must compile all the libraries before + you can link the final application.
In the same workspace you'll find + the projects to build different libraries and applications:

+
    +
  • CxImage : cximage.lib - static library +
  • CxImageCrtDll : cximagecrt.dll - DLL not using mfc +
  • CxImageMfcDll : cximage.dll - DLL using mfc +
  • Demo : demo.exe - program linked with cximage.lib and + the C libraries +
  • DemoDll : demodll.exe - program linked with + cximagecrt.dll +
  • j2k,jasper,jbig,jpeg,png,tiff,zlib : static C libraries
+

Building the projects will need some minutes to complete (the + intermediate files occupy 60MB!). When everything is done, select the demo + project and launch the application.

CxImgLib.dsw
+
+

To use CxImage in your project, you must edit these settings:

+
Project Settings
+ |- C/C++
+ |   |- Code Generation
+ |   |   |- Use run-time library : Multithreaded DLL (must be the same for 
+ |   |   |  all the linked libraries)
+ |   |   |- Struct member alignment : must be the same for all the linked 
+ |   |   |  libraries
+ |   |- Precompiled headers : not using precompiled headers
+ |   |- Preprocessor
+ |       |- Additional Include Directories:  ..\cximage
+ |- Link
+    |- General
+        |- Object/library modules: ../png/Debug/png.lib 
+                                   ../jpeg/Debug/jpeg.lib 
+                                   ../zlib/Debug/zlib.lib 
+                                   ../tiff/Debug/tiff.lib 
+                                   ../jasper/Debug/jasper.lib 
+                                    ../cximage/Debug/cximage.lib  ...
+

+

Adding your custom functions in CxImage

+

Writing a new function for image processing is not so hard with CxImage. Here +I'm going to describe CxImage::Jitter, it's very simple but it +shows many aspects to take care when you work inside CxImage. The first thing, +of course, is the declaration : bool Jitter(long radius=2); in the +CXIMAGE_SUPPORT_DSP section of ximage.h, you can declare the function everywhere +in the public scope of the class. And now the definition:

bool CxImage::Jitter(long radius)
+{
+    // check if the image is valid, this should be always the first line in 
+    // the function 
+    if (!pDib) return false;
+    
+    // local variables
+    long nx,ny;
+    
+    // temporary image to store the partial results of the algorithm
+    CxImage tmp(*this,pSelection!=0,true,true);
+    
+    // limit the effects of the functions only in the smallest rectangle that
+    // holds the selected region (defined with the Selection...() functions ),
+    // this will speed up the loops.
+    long xmin,xmax,ymin,ymax;
+    if (pSelection){
+        xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right;
+        ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top;
+    } else {
+        xmin = ymin = 0;
+        xmax = head.biWidth; ymax=head.biHeight;
+    }
+    
+    // main loop : scan the image in vertical direction
+    for(long y=ymin; y <ymax; y++){
+    
+        // monitor the progress of the loops
+        info.nProgress = (long)(100*y/head.biHeight);
+    
+        // let the application a way to exit quickly
+        if (info.nEscape) break;
+    
+        // main loop : scan the image in horizontal direction
+        for(long x=xmin; x<xmax; x++){
+    
+        // if the feature is enabled, process only the pixels inside the 
+        // selected region
+#if CXIMAGE_SUPPORT_SELECTION
+            if (SelectionIsInside(x,y))
+#endif //CXIMAGE_SUPPORT_SELECTION
+            {
+                // main algorithm
+                nx=x+(long)((rand()/(float)RAND_MAX - 0.5)*(radius*2));
+                ny=y+(long)((rand()/(float)RAND_MAX - 0.5)*(radius*2));
+                if (!IsInside(nx,ny)) {
+                    nx=x;
+                    ny=y;
+                }
+
+                // save the result in the temporary image.
+                // if you can, use PixelColor only for 24 bpp images,
+                // and PixelIndex for 8, 4 and 1 bpp images : it's faster
+                if (head.biClrUsed==0){
+                    tmp.SetPixelColor(x,y,GetPixelColor(nx,ny));
+                } else {
+                    tmp.SetPixelIndex(x,y,GetPixelIndex(nx,ny));
+                }
+
+                // if the feature is enabled, process also the pixels 
+                // in the alpha layer
+#if CXIMAGE_SUPPORT_ALPHA
+                tmp.AlphaSet(x,y,AlphaGet(nx,ny));
+#endif //CXIMAGE_SUPPORT_ALPHA
+            }
+        }
+    }
+
+    // save the result and exit
+    Transfer(tmp);
+    return true;
+}
+
+


+

Examples: how to ...

+

... convert from a format to another

CxImage  image;
+// bmp -> jpg
+image.Load("image.bmp", CXIMAGE_FORMAT_BMP);
+if (image.IsValid()){
+    if(!image.IsGrayScale()) image.IncreaseBpp(24);
+    image.SetJpegQuality(99);
+    image.Save("image.jpg",CXIMAGE_FORMAT_JPG);
+}
+// png -> tif
+image.Load("image.png", CXIMAGE_FORMAT_PNG);
+if (image.IsValid()){
+    image.Save("image.tif",CXIMAGE_FORMAT_TIF);
+}
+
+

... load an image resource

//Load the resource IDR_PNG1 from the PNG resource type
+CxImage* newImage = new CxImage();
+newImage->LoadResource(FindResource(NULL,MAKEINTRESOURCE(IDR_PNG1),
+                       "PNG"),CXIMAGE_FORMAT_PNG);
or
//Load the resource IDR_JPG1 from DLL
+CxImage* newImage = new CxImage();
+HINSTANCE hdll=LoadLibrary("imagelib.dll");
+if (hdll){
+    HRSRC hres=FindResource(hdll,MAKEINTRESOURCE(IDR_JPG1),"JPG");
+    newImage->LoadResource(hres,CXIMAGE_FORMAT_JPG,hdll);
+    FreeLibrary(hdll);
+}
or
//Load a bitmap resource;
+HBITMAP bitmap = ::LoadBitmap(AfxGetInstanceHandle(),
+                              MAKEINTRESOURCE(IDB_BITMAP1)));
+CxImage *newImage = new CxImage();
+newImage->CreateFromHBITMAP(bitmap);
+

... decode an image from memory

CxImage image((BYTE*)buffer,size,image_type);
or
CxMemFile memfile((BYTE*)buffer,size);
+CxImage image(&memfile,image_type);
or
CxMemFile memfile((BYTE*)buffer,size);
+CxImage* image = new CxImage();
+image->Decode(&memfile,type);
+

... encode an image in memory

long size=0;
+BYTE* buffer=0;
+image.Encode(buffer,size,image_type);
+...
+free(buffer);
or
CxMemFile memfile;
+memfile.Open();
+image.Encode(&memfile,image_type);
+BYTE* buffer = memfile.GetBuffer();
+long size = memfile.Size();
+...
+free(buffer);
+

... create a multipage TIFF

CxImage *pimage[3];
+pimage[0]=&image1;
+pimage[1]=&image2;
+pimage[2]=&image3;
+
+FILE* hFile;
+hFile = fopen("multipage.tif","w+b");
+
+CxImageTIF multiimage;
+multiimage.Encode(hFile,pimage,3);
+
+fclose(hFile);
or
FILE* hFile;
+hFile = fopen("c:\\multi.tif","w+b");
+
+CxImageTIF image;
+image.Load("c:\\1.tif",CXIMAGE_FORMAT_TIF);
+image.Encode(hFile,true);
+image.Load("c:\\2.bmp",CXIMAGE_FORMAT_BMP);
+image.Encode(hFile,true);
+image.Load("c:\\3.png",CXIMAGE_FORMAT_PNG);
+image.Encode(hFile);
+
+fclose(hFile);
+
+

... copy/paste an image

//copy
+HANDLE hDIB = image->CopyToHandle();
+if (::OpenClipboard(AfxGetApp()->m_pMainWnd->GetSafeHwnd())) {
+    if(::EmptyClipboard()) {
+        if (::SetClipboardData(CF_DIB,hDIB) == NULL ) {
+            AfxMessageBox( "Unable to set Clipboard data" );
+}    }    }
+CloseClipboard();
+
+//paste
+HANDLE hBitmap=NULL;
+CxImage *newima = new CxImage();
+if (OpenClipboard()) hBitmap=GetClipboardData(CF_DIB);
+if (hBitmap) newima->CreateFromHANDLE(hBitmap);
+CloseClipboard();
+

... display a file in a picture box

+
HBITMAP m_bitmap = NULL;
CxImage image("myfile.png", CXIMAGE_FORMAT_PNG); +... +if (m_bitmap) DeleteObject(m_bitmap);
m_bitmap = image.MakeBitmap(m_picture.GetDC()->m_hDC);
m_picture.SetBitmap(m_bitmap);
+

History and credits.

+

Starting form my CxDib class, that implements memory DIBs only, + I tried to add some members to read images from files. Looking for a solution, + I found a nice MFC class named CImage on the net, release 1.4 (1998). + CImage supports BMP, GIF, PNG and JPG, but suffers many little + bugs and uses a complex class structure, so I decided to strip it to the base + and merge CxDib with the CImage philosophy, to obtain + the new CxImage class. Also I updated the libraries for JPG, PNG + and ZLIB.
+ With CxImage is very easy to add new image types, so I added the + TIFF library (rev. 6) and a minimal support for ICONs, MNG, TGA + and PCX. Finally I added some specific functions to obtain an image from global + HANDLEs (windows clipboard) and objects (windows resources).
+ With the release 5, CxImage has now a good support for memory files, new methods + and file formats, and it is more portable.

+
    +
  • CImage © 1995-1998, Alejandro Aguilar Sierra. +
  • IJG JPEG library ©1994-1998, Thomas G. Lane. +
  • LibPNG version 1.2.7© 1998-2001 Glenn Randers-Pehrson +
  • LibTIFF version 3.5.7 © 1988-1997 Sam Leffler, © 1991-1997 Silicon Graphics, + Inc. +
  • LibMNG version 1.0.2 © 2000,2001 Gerard Juyn. +
  • Gif-RLE © Hutchison Avenue Software Corporation, 1998 +
  • LibJ2K© David Janssens, 2001 - 2002 +
  • LibJBG version 1.6 © Markus Kuhn, 2002 +
  • JasPer version 1.700.2 © Image Power, UBC, Michael David Adams, 2001 + - 2003 +
  • zlib version 1.2.1 © 1995-2003 Jean-loup Gailly and Mark Adler
    +
  • Thanks to Troels Knakkergaard for his precious work in the earlier versions + of CxImage, Rajiv Ramachandran for CTwain code; to Abe for multi + page tiffs code; to Chris Shearer Cooper for memory file suggestions and code; + to Brent Corkum for BCMenu code.
  • +
+

More specific credits and disclaimers are in every header file of each library.
+

+ diff --git a/SlnkDWFImpl/CxImage/doc/cximage.png b/SlnkDWFImpl/CxImage/doc/cximage.png new file mode 100644 index 0000000..5e7cb13 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/cximage.png differ diff --git a/SlnkDWFImpl/CxImage/doc/cximage_history.htm b/SlnkDWFImpl/CxImage/doc/cximage_history.htm new file mode 100644 index 0000000..c24ca2d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/cximage_history.htm @@ -0,0 +1,901 @@ + + + +CxImage History + + + + +

CxImage History

+
+

+

Version 5.99c, 17 - Oct - 2004

+

Bugfixes +

+
    +
  • CxImageTIF::Encode: default compression for 4 bpp image was NONE, now it's LZW.
  • +
  • CxMemFile::Seek: fixed bug introduced in version 5.99b: seeking beyond file size is legal !!!
  • +
+

Version 5.99b, 10 - Oct - 2004

+Bugfixes +
    +
  • fixed SetXDPI and SetYDPI to accept only positive dpi values +
  • fixed EXIF decoder against invalid TAG_EXIF_OFFSET / TAG_INTEROP_OFFSET +
  • fixed missing definitions in ximawnd.cpp when CXIMAGE_SUPPORT_BMP is 0 +
  • fixed CxFileJas constructor to avoid crashes, when Jasper deals + with its temporary files, decoding large images <vho> +
  • removed default imagetype value from CxImage::Save + <Choi Byungtae> +
  • fixed Mean() for images with an active selection <Admir + Hodzic> +
  • fixed GIF decoder for animated images with corrupted frames. +
  • fixed GIF decoder for images with screen descriptor larger than the first frame. +
  • fixed GIF decoder to handle the disposal methods correctly. +
  • CxImageWMF reads images mapped in MM_TEXT, when MM_ANISOTROPIC fails. +
  • fixed Clear for 1 and 4 bpp images. +
  • fixed typo in ximajpg.cpp: ENTRPY_OPT_SUPPORTED -> ENTROPY_OPT_SUPPORTED <Boum> +
  • fixed potential memory overflow in RLE decoder reading corrupted bitmaps. +
  • Better UNICODE support <Cesar M> and fixed TCHAR mappings for Linux. +
  • fixed bug in IsTransparent, for images with a valid alpha layer. +
  • fixed bug in Create: a vaild image was created even if width or height were zero. +
  • CxMemFile: fixed problem for compilers where malloc(0) returns 0, + improvements in Alloc and Seek. +
+Changes and major additions +
    +
  • new functions: Rotate2() <BD>, Resample2() + <BD> QIShrink() <BD> , RedEyeRemove() <???> , Edge(),
    + SelectionSplit(), IsSamePalette, BlendPixelColor, GetVersionNumber, Encode2RGBA +
  • new dithering algorithms: Bayer, Burkes, Stucki, Jarvis-Judice-Ninke, Sierra, Stevenson-Arce + <Franco Gerevini> +
  • renamed AlphaGetBits with AlphaGetPointer <BD> +
  • new compiler switch: CXIMAGE_SUPPORT_INTERPOLATION to enable pixel color + interpolations,
    + implemented in the ximaint.cpp module <BD> +
  • New bEnableInterpolation parameter for Skew() +
  • New blend parameter for Colorize() +
  • color conversion routines now are declared as static +
  • FFT2 now works also with Borland compilers +
  • more interpolation kernels <Vladimír Kloucek> +
  • Smooth stretching parameter for Draw, thanks to <Vladimír Kloucek> and <BD> +
  • Added FreeMemory function, to avoid heap problems using Encode with memory buffers <livecn> +
  • new bMixAlpha parameter and new OpScreen blending mode for Mix() +
  • LZW compression is the default algorithm for GIF compression. +
  • CxImagePNG now can encode interlaced images +
  • Get/SetCodecOption now has an "ImageType" parameter, so that each format keeps its specific options +
  • Faster RotateLeft and RotateRight <BD> +
  • CxImageJPG now can write back the EXIF information (verbatim copy). +
+Project - Libraries - Demo application +
    +
  • Demo: new dialogs for Resample, Rotate, Skew with more options, JPEG compression
  • +
  • New license based on zlib/libpng philosophy, see ximage.h and ./doc/license.txt
  • +
  • Demo: new tool: tracker
  • +
  • Demo: new View/Smooth menu to test smooth drawing in zoom and stretch modes
  • +
  • Demo: more CodecOptions on the Options dialog, enabled LZW compression for GIF and TIF formats.
  • +
  • PNG: updated to libpng 1.2.7
  • +
  • JBIG: updated to version 1.6
  • +
  • Better documentation : now using Doxygen.
  • +
+
+

+

Version 5.99a, 08 - Feb - 2004

+Bugfixes +
    +
  • fixed bug in AlphaCopy, AlphaSet, SelectionCopy <Tacho> +
+Changes and major additions +
    +
  • --- +
+Project - Libraries - Demo application +
    +
  • Demo: fixed save/restore window position and options
  • +
+
+

+

Version 5.99, 31 - Jan - 2004

+Bugfixes +
    +
  • fixed linking problems when CXIMAGE_SUPPORT_ENCODE is 0 <Schuberth> + <Squidge> +
  • fixed missing in parentheses in CreateFromMatrix and CreateFromArray <sihun> + <H.C.Anderson> +
  • fixed incorrect decoding for 4-bit RLE Windows bitmaps <chupeev> +
  • Removed unreachable code in Resample <Lucian Ioan> +
  • CxImagePNG::Encode : removed useless call to iter.GetRow <Chieh An Lu> +
  • fixed color comparison using long integers (if rgbReserved is not 0) in + CxImagePNG and CxImageICO <James Dickson> +
  • CxExifInfo now reads the exif data also in a second directory <Richard + Collins> +
  • Dither now preserves DPI information +
  • fixed PNG decoder for interlaced images with transparent layer +
  • fixed GIF decoder bug for animated images with local color table. +
  • fixed problem in Draw() with indexed images, when 2 indexes hold the same + color and 1 is transparent. +
  • fixed memory overrun in Crop() for 8 and 24 bpp images. <DT> +
  • fixed BMP decoder when loading 8 bit resources with less than 256 colors + <DT> +
  • CxImageTIF now handles TIFFTAG_RESOLUTIONUNIT <Trifon> +
  • Fix for decoding 8 bpp tifs with alpha layer <Nick Holgate> +
  • fixed error in mymngerror() <Arkadiy Olovyannikov> +
  • fixed TIFFTAG_PREDICTOR, saving 1 and 4 bpp images with LZW compression + <Hermann62> +
+Changes and major additions +
    +
  • Renamed DrawText with DrawString +
  • New bGetAlpha parameter for GetPixelColor +
  • CxImageICO now reads also windows cursors (.CUR) +
  • support for UNICODE <Igor Rosenberg> +
  • Renamed Get/SetEncodeOption with Get/SetCodecOption <chupeev> +
  • AlphaCreate also initializes the layer to full opaque. +
  • new functions: DrawStringEx, InitTextInfo, CropRotatedRectangle <VATI>, + MixFrom <Kenneth Ballard>, UnsharpMask <nipper>, Lut +
  • increased default JPEG quality to 90 <VATI> +
  • CxImageTIF::Decode saves original compression in info.dwCodecOption <DPR> +
  • new functions: CxImageTIF::TIFFOpenEx and CxImageTIF::TIFFCloseEx, to handle + directly a TIFF directory. +
  • CxImageJPG::Decode and CxImageJPG::Encode handles more jpeg DECODE_XXX and + ENCODE_XXX methods
    + (through SetCodecOption and SetJpegQuality) <chupeev> +
  • new dwRop parameter for Stretch, allows raster-operation codes. <?> +
  • Faster Filter() for 8bit grayscale images <Thomas M. Boser> +
  • SetEscape(-1) before Decode returns the image width and height only ( for + bmp, jpg, gif, tif ) <ignacio> +
  • new Set/GetJpegScale() before Decode, to open a resized image (for jpeg + only) <ignacio> +
  • new function : CircleTransform for FishEye, Swirle, Cilinder, bathroom effects + <Arkadiy Olovyannikov> +
  • new methos for HistogramStretch: 0 = luminance <dave>, 1 = linked + channels <nipper>, 2 = independent channels <nipper>, and for + grayscale images +
  • faster Light and Gamma <nipper> +
  • CImageIterator new methods: Get/SetCol() to extract a single column. +
  • Better error checking in image initialization functions. +
  • CreateFromHANDLE now reads also RLE compressed bitmaps <Michael Gandyra> +
+Project - Libraries - Demo application +
    +
  • Updated zlib to 1.2.1.<Tuncer M. Ayaz>
  • +
  • Demo: status bar updated after Crop or drag & drop <VATI>
  • +
  • demoview.h : new Dpoint2d structure <VATI>
  • +
  • demodoc.h : new LEN2D macro <VATI>
  • +
  • Demo: save/restore window position <VATI>
  • +
  • Demo: new DlgText features <VATI>
  • +
  • Demo: new Selection tool options: CTRL+Rclick = move selection, shift+Lclick= + rect selection, Rclick on a rect selection = rotate selection <VATI>
  • +
  • Moved tif_xfile.cpp from LibTiff to CxImage directory and workspace
  • +
  • Demo2 : Updated FindFormat
  • +
  • Demo : new Mix dialog and menus for CircleTransform
  • +
+
+

+

Version 5.80, 27 - Sep - 2003

+Bugfixes +
    +
  • Fixed head.biSize initialization: moved from Startup() to Create() <ralphw> +
  • Fixed problem in SetTransColor when rgbReserved is not 0 and in the image + there is an alpha layer. +
  • CxImageBMP::Decode : force rgbReserved=0 in the palette , to avoid problems + with some WinXp bitmaps. <Colin Urquhart> +
  • Fixed warnings for size_t type in iA64 compiler <Frank Sowinski> +
  • GrayScale from 1, 4 and 24 bit images now preserves info and selection layer +
  • CxImageICO::Decode will not create the alpha layer if it's not strictly + necessary;
    + and reads images embedded inside a file <yuandi> +
  • CxImageJPG::Decode : check image allocation before further processing. +
  • Fixed DLL_EXP definition and inlined CxImage destructor for older VC++ compilers + <Wassily Gibin> +
  • Fixed CxFileJas::JasClose() bug with memory files <osamu44> +
  • Added missing casts in floating point functions in CxExifInfo <Branko + Drevenšek> <Tuncer M. Ayaz> +
  • Fixed memory leak in CreateFromHICON <Sims> +
  • Fixed access violation in CxImageTIF::Decode with some CieLab images <Vitaly + Titov> +
  • Fixed GDI leak in CxImage::DrawText() <Henry P.> +
  • Crop now works also with the alpha layer. <oboolo> +
  • Fixed bias and canvas size in CxImage::Rotate() +
  • CxImageGIF now stores the comment before the image body. +
  • Encode() functions now check both file and image handlers with EncodeSafeCheck() +
  • IncreaseBpp to 24 bit from images with simple transparency, now sets the + correct transparent color. +
  • CxImageBMP::DibReadBitmapInfo accepts non standard headers if the stored + information is valid +
  • CxImage::Decode with CXIMAGE_FORMAT_UNKNOWN, now preserves CxImage::info +
  • Fixed sizeof(BITMAPFILEHEADER) in CxImageBMP, to avoid struct alignment + errors +
+Changes and major additions +
    +
  • New functions Get/SetClrImportant() +
  • Added new clrimportant parameter for DecreaseBpp +
  • Faster Light() for full RGB images +
  • GetPixelIndex returns the index of the top-left pixel when the coordinates + are out of the image and no background color is selected +
  • CxImagePNG::Encode saves info.nBkgndColor (or white) as bKGD color, for + IE +
  • Added "bEditAlpha" parameter to DrawText. +
  • New functions:
    + SelectionAddPixel <Anatoly Ivasyuk>,
    + DrawLine <JDL>,
    + IsTransparent(long x, long y) <Sims>,
    + AlphaGetBits(), Expand(), Thumbnail() <Colin Urquhart>
    + CreateFromMatrix(), CreateFromArray() , replace CreateFromARGB() +
  • CXIMAGE_MAX_MEMORY prevents huge allocations +
  • GetBits() returns the pointer to the first byte in a generic row +
  • New bDetachBuffer parameter in CxMemFile::GetBuffer, to get the buffer for + read only purpose <Wassily Gibin> +
  • Faster (x4!) bicubic interpolation and fixed bias error <Kristian Kratzenstein> +
  • CxImagePNG::Encode saves only the minimum number of palette colors for small + images <Basara> +
  • Added "hpal" parameter to CxImage::CreateFromHBITMAP, for indexed + DCs <Zahi Kapeluto> +
  • CxImageTGA::Decode now reads also images with illegal packets <Colin + Urquhart> +
+Project - Libraries - Demo application +
    +
  • Updated CQuantizer to handle color reduction to less than 16 colors +
  • JAS_IMAGE_INMEMTHRESH increased to avoid jasper temporary file +
  • Updated JBig library: JBIG-KIT 1.5 (2003-06-11) +
  • \jpeg\jmorecfg.h : fixed INT32 redefinition for Borland C++ Builder6 +
+
+

+

Version 5.71, 25 - Apr - 2003

+Changes and major additions +
    +
  • new formats: JP2, JPC, PGX, PNM, RAS (through JasPer) +
  • new functions: Set/GetFlags( ), LayerCreate( ), LayerDelete( ), LayerDeleteAll( + ), GetLayer( ), GetParent( ), GetNumLayers( ) +
+Project - Libraries - Demo application +
    +
  • New C library : JasPer 1.700.2 +
+
+

Version 5.70, 19 - Apr - 2003

+Bugfixes +
    +
  • fixed RGB2GRAY macro <H. Muelner> <jurgene> +
  • SelectionAddPolygon and SelectionAddColor compute correctly info.rSelectionBox +
  • fixed SelectionAddPolygon when the polygon touches the image borders. +
  • fixed EXIF reader +
  • fixed CxImageGIF::DecodeExtension
  • +
  • CxImageTIF::EncodeBody : better error handling, and switch for different + compression tags.
  • +
  • CImageIterator : fixed friend declaration in ximaiter.h, line 37 <gazzivan>
  • +
  • fixed DPI default values in CreateFromHANDLE
  • +
  • CxImageBMP now reads OS2 bitmaps
  • +
  • fixed cast problem in Histogram functions <Tuncer M. Ayaz>
  • +
  • fixed memory corruption in RotateLeft( ) RotateRight( ) for 1 bpp images. + <Stroupe David R>
  • +
+Changes and major additions +
    +
  • New MakeBitmap(hdc) implementation when hdc is 0 <jaslet> +
  • Light( ) : shifted down the contrast parameter so that the neutral value + is 0. +
  • New filters: Jitter( ), Skew( )
  • +
  • Negative( ) moved in BASICTRANSFORMATIONS
  • +
+Project - Libraries - Demo application +
    +
  • New CxImageCrtDll.dsp project, to build a dll without mfc <Anatoly Ivasyuk> +
  • fixed bug in Window/Duplicate with no image in the document. <corwinkrisw>
  • +
  • \jpeg\jdmarker.c line 1091 : skip check for unknown marker, to decode partially + corrupted files.
  • +
+
+

+

Version 5.61, 10 - Mar - 2003

+Bugfixes +
    +
  • fixed SplitXYZ and floating point constants in ximadsp.cpp <???>
  • +
+

+
+

+

Version 5.60, 09 - Mar - 2003

+Bugfixes +
    +
  • CxImagePNG read/save DPI +
  • SelectionAddRect computes correctly info.rSelectionBox <arnold wittenberg>
  • +
+Changes and major additions +
    +
  • better RGB2GRAY macro <dave> +
  • new functions: HistogramStretch( ), HistogramEqualize( ), HistogramNormalize( + ), HistogramRoot( ), HistogramLog( ) <dave> +
  • GetPixelColor returns the color of the top-left pixel when the coordinates + are out of the image and no background color is selected +
  • new function: Contour( ) +
  • new bicubic spline interpolation for Resample( ) +
  • Faster GetNearestPixel( ) <RJ>
  • +
+Project - Libraries - Demo application +
    +
  • Demo: fixed "move" tool
  • +
+
+

Version 5.55, 17 - Feb - 2003

+

Changes and major additions

+
    +
  • fixed bug in CreateFromARGB <Olivier Ansquer> +
  • CxImageTGA::Decode flips the alpha channel when required <lioucr> +
  • CxImageGIF::DecodeExtension, fixed problem when extension information is + more than 3 bytes. <TomPeakz>
  • +
+Project - Libraries - Demo application +
    +
  • jpeg\jdcolor.c, line 384 changed again to permit null conversion if the + output space is undefined OR input and output sapaces are the same<DP>
  • +
+
+

Version 5.53, 27 - Jan - 2003

+

Changes and major additions

+
    +
  • New functions: CreateFromHICON +
  • Replaced SetPaletteIndex with SetPaletteColor and GetRGB with GetPaletteColor
  • +
+Project - Libraries - Demo application +
    +
  • Demo : fixed GDI leak in LineDDAProc <jh> +
  • jpeg\jdcolor.c, line 384 changed to permit null conversion if the output + space is undefined (OJPEG) <DP> +
  • tiff\tif_ojpeg.c from line 1374 to line 1407 : avoid sampling factors check + <DP>
  • +
+
+

+

Version 5.51, 19 - Jan - 2003

+Bugfixes +
    +
  • fixed GDI leak in CxImage::Draw when pClipRect is not null <Carsten + Leue>
  • +
+Project - Libraries - Demo application +
    +
  • Updated LIBPNG to 1.2.5 <Tuncer M. Ayaz> +
  • added jpeg_reset_huff_decode function in jpeg\jdhuff.c for the broadest + possible support for OJPEG files
    + (implemented by Scott Marovich at HP <marovich(at)hpl(dot)hp(dot)com>)
    + jpeg\jdmarker.c : line 204 and 261 allow SOI and SOF duplicate only if cinfo->global_state + == DSTATE_INHEADER
    + (should be illegal, but OJPEG files have an illegal structure <DP>) +
  • tiff\tif_jpeg.c from line 673 to line 697 : avoid sampling factors check + <DP>
  • +
+
+

+

Version 5.50, 07 - Jan - 2003

+Bugfixes +
    +
  • CxImageTIF : added support for tiled images +
  • CxImageTIF : faster decoding with TIFFNumberOfDirectories, instead of looping + <Robert Abram> +
  • CxImageTIF : fixed stripsize check when samplesperpixel is more than 1. +
  • DecreaseBpp( ) and IncreaseBpp( ) preserve info +
  • Tile( ) fixed when the rectangle is not a multiple of the image dimension. + <dock> +
  • Added missing casts in floating point functions <Tuncer M. Ayaz> +
  • CxImageGIF : fixed loop counter saving animated gifs <handong> +
  • CxImageGIF::get_byte : fixed overflow when reading corrupted images. +
  • CxImageGIF::get_num_frames : fixed undefined TabCol structure. +
  • CxImageGIF : a palette without white is accepted. +
  • CxImageGIF : avoid byte order problems with Solaris <candan> +
  • CxImageTGA : Encode now saves the last palette entry. +
  • CxImageICO : Decode reads Bpp from the bitmapinfoheader instead of icondirentry + <CoreyRLucier> +
  • CxImageJBG : fixed Encode crash when copying pixels form cximage to the + decoder buffer.
  • +
+

Changes and major additions

+
    +
  • Replaced IsAlphaPaletteEnabled with AlphaPaletteIsEnabled, AlphaIsValidPalette + with AlphaPaletteIsValid, GetSelectionBox with SelectionGetBox +
  • New SplitCMYK( ), GetPixelGray( ), AlphaPaletteSplit( ) +
  • Added the bLocalColorMap parameter to CxImageGIF::Encode, for animated + gifs with local palettes +
  • New AlphaSet(CxImage &from): creates the alpha channel from a gray + scale image. +
  • One or more images can be appended directly to a TIF file, using CxImageTIF::Encode(file,true); + or Encode(hFile,pImages,pagecount) <RJ> +
  • Fast RotateLeft( ) and RotateRight( ) for BW images <Robert Abram> +
  • SetPixelColor( ) and GetPixelColor( ) handle alpha in RGBQUAD::rgbReserved. +
  • IncreaseBpp is faster for conversion to 4 and 8 bpp, AlphaPalette converted + to an alpha channel for conversion to 24 bpp. +
  • info.nProgress updated in the dsp and transformation functions <Anatoly + Ivasyuk>. +
  • New info.dwEncodeOption parameter to select the compression scheme for + GIF and TIF. +
  • New CxImageWMF::Decode parameters: nForceWidth,nForceHeight to force the + final dimension of the image. +
  • CxImageJ2K::Encode : new formula for compression rate, so the quality for + j2k and jpg are similar. +
  • Added CXIMAGE_FORMAT_UNKNOWN for automatic image type detection.
  • +
+

Project - Libraries - Demo application

+
    +
  • Fixed exception in DlgHisto +
  • CQuantize handles palettes with alpha information +
  • better dump of the memory leaks <dave>
  • +
+
+

+

Version 5.11, 29 - Sep - 2002

+Bugfixes +
    +
  • ximadefs.h : added pragma pack(1) for BMP structures alignment with Linux + compilers
  • +
+
+

Version 5.10, 23 - Sep - 2002

+Bugfixes +
    +
  • CxImageGIF : restored lzw algorithm. <Olivier Ansquer> +
  • CxImageTIFF : added support for CIELAB images. +
  • CxImageTGA : fixed problem decoding corrupted files. +
  • CxImageBMP: fixed problem with os2 and 16bit images <Cui Ying Jie>
  • +
+

Changes and major additions

+
    +
  • New DrawText function. +
  • Added iDst parameter in Resample( ) <CSC> +
  • New SelectionToHRGN( ) and SelectionAddColor( ) <elrod> +
  • Replaced HasAlpha with AlphaIsValid, HasSelection with SelectionIsValid, + HasAlphaPalette with AlphaIsValidPalette +
  • New CreateFromARGB( ) <Olivier Ansquer> +
  • Added DLL_EXP for CxImageTIF and CxImageGIF <Olivier Ansquer>
  • +
+
+

+

Version 5.00, 23 - Aug - 2002

+Bugfixes +
    +
  • CxImageTIF::Decode : fixed default orientation. <vho> +
  • CxImageTIF::Encode saves 1bpp always with PHOTOMETRIC_MINISWHITE <abe> +
  • CxImageJPG::Encode : fixed jpg encoder for memory files. +
  • CxImageICO::Encode : fixed problem with 4bpp images with transparency. +
  • CxImagePNG::Encode : fixed problem when info.bColorType was wrong <Kwyshell> +
  • removed info.bColorType and changed GetColorType() implementation. +
  • CxImageBMP::Decode handles TopDown Bitmaps <Flanders>, small bugfix + <CSC> +
  • CxImageTIF::Encode : TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(m_tif, + -1)); gives better compression <REC> +
  • Load( ) returns the correct info.nNumFrame when info.nFrame<0. +
  • removed bug in tif_xfile.c when encoding memory files. +
  • CxImageBMP::Decode loads correctly OS2 bmps. +
  • bugfix in Resample( ) when (newx==width && newy==height) +
  • better operator= definition <Anatoly Ivasyuk>
  • +
+Changes and major additions +
    +
  • new formats: WBMP, WMF - EMF <vho>, JBIG, JPEG2000. +
  • new full codec for PCX, with support for RGBA images. +
  • new methods: GetVersion, IsTransparent <vho>, ShiftRGB, Median, Gamma, + Noise, Combine, FFT, Repair, AlphaSplit +
  • added r/w support for 8bpp TIFFs with alpha layer. +
  • added support for TrueColor, RLE and uncompressed GIFs. +
  • added CXIMAGEJPG_SUPPORT_EXIF for JPGs. +
  • new switches: CXIMAGE_SUPPORT_DECODE, CXIMAGE_SUPPORT_ENCODE,
    + CXIMAGE_SUPPORT_WINDOWS, CXIMAGE_SUPPORT_WINCE <T.Peck> +
  • SetEscape can abort the codecs loops <vho>. +
  • added ximadefs.h to adjust automatically the switches. +
  • the codecs for ICO, PNG, TGA and TIF work also with CXIMAGE_SUPPORT_ALPHA + = 0 <vho> +
  • added DPI information support for jpeg <Koray Geçici> +
  • new CxFile CxMemFile CxIOFile implementations <CSC> +
  • MakeBitmap( ) creates a real DIB if HDC == 0 <CSC> +
  • Draw( ) added pClipRect parameter. +
  • CxImageTIF::Decode : re-enabled error handler for debugging;
  • +
+Project - Libraries - Demo application +
    +
  • Zlib : replaced zlib.rc and zlib.def <Tuncer M. Ayaz>. +
  • Demo: new tools, histogram, palette, replaced xshadebutton with xtargetbutton. +
  • Updated LIBPNG to 1.2.4 +
  • LibTIFF::tiff_read.c::ln188: commented to decode strange images, it's not + dangerous. +
  • LibTIFF small changes to compile under linux (tiff_xfile.cpp, tiff_jpeg.c, + tiff_ojpeg.c, tiffiop.h) +
  • LibJPEG : small changes to compile under linux (jmorecfg.h) +
  • Added project for DLL build and console applications.
  • +
+
+

+

Version 4.10, 01 - Jun - 2002

+Bugfixes +
    +
  • Fixed PNG error handler. +
  • Fixed TGA decoder for RLE encoded pictures with alpha channel <Ole Lange> + and 15 bit pictures. +
  • Fixed BMP decoder for 32 bit images.
  • +
+Changes and major additions +
    +
  • Added Read/Write support for 24 and 32 bit ICONs. +
  • new bAppend parameter in CxImageTIF::Encode() for better multi page TIF + creation. <Abe>
  • +
+Project - Libraries - Demo application +
    +
  • Updated zlib to 1.1.4.<Tuncer M. Ayaz> +
  • Added OJPEG_SUPPORT (not for Wang).
  • +
+
+

+

Version 4.01, 15 - May - 2002

+Changes and major additions +
    +
  • Added some constructors and Encode()/Decode() methods to work with memory + buffers directly.
  • +
+Project - Libraries - Demo application +
    +
  • Changed URL download dialog.
  • +
+

+
+

+

Version 4.00, 12 - May - 2002

+Bugfixes +
    +
  • Fixed JPEG error handler <CSC> +
  • Fixed _tiffSizeProc in tif_c.c to load images with missing stripcount. +
  • Transformations preserve info.dwType perameter <CSC> +
  • Createfromhandle() bugfix for 32bitfield images <JA> +
  • GetPixelColor bugfix when the coordinates are in the outside of the image + <Mpwolski>
  • +
+Changes and major additions +
    +
  • New CxFile class to read/write memory files and disk files. +
  • Added support for Read/Write 32bpp TIFFs with apha channel. +
  • New methods : Mix() <Mpwolski>, Destroy(), IsIndexed() +
  • Read/Write support for Multipage TIFF <Abe> +
  • Read/Write support for Animated GIF (gif89a), with comment, loops and disposal + method +
  • Added xOffset and yOffset in CxImage::info +
  • Changed names : ReadFile -> Load ; SaveFile -> Save +
  • LoadResource uses CxFile
  • +
+Project - Libraries - Demo application +
    +
  • Updated BCMenu: version 3.03. +
  • LibTiff : enabled alpha (tif_getimage.c;Ln:212), enabled ZIP_SUPPORT +
  • Pane view function with "shift+Lbutton" +
  • Updated LibTiff to 3.5.7 +
  • New URL download dialog; WebGrab class by Chris Maunder
  • +
+
+

+

Version 3.21, 11 - Mar - 2002

+Bugfixes +
    +
  • Fixed memory leakage in CxImagePNG::Encode() <Rob Cass>. +
  • Fixed CxImageICO::Decode() problem with 16 colors icons <Rogier>.
  • +
+Changes and major additions +
    +
  • CxImageICO reads/saves icons with transparent pixels. +
  • CxImageTIF::Decode() now takes care of the orientation tag. +
  • New RotateLeft(), RotateRight(), Rotate180() functions <MKVY>. +
  • Faster Draw() implementation for images with transparency <DJT>.
  • +
+Project - Libraries - Demo application +
    +
  • Updated BCMenu: version 3.01. +
  • Replaced CreateThread() with _beginthread() to avoid small memory leaks.
  • +
+
+

+

Version 3.09, 21 - Feb - 2002

+Bugfixes +
    +
  • Rotation() and Resample() handle the alpha channel. <MTA> +
  • CxImagePNG: Encode() merges the transparent color with the alpha channel. +
  • Fixed exceptions and leaks in Draw() <RG> +
  • CxImageBMP now reads 32 bpp BITFIELD images. +
  • Decode() correctly loads multipage ICO and TIF files. <REC>
  • +
+
+

+

Version 3.02, 24 - Jan - 2002

+Bugfixes +
    +
  • CxImagePNG: fixed allocation bug in Decode() +
  • CxImagePNG: cast error saving 8 bpp images.
  • +
+
+

Version 3.00, 20 - Jan - 2002

+Bugfixes +
    +
  • fixed HSLtoRGB() conversion <F. Livraghi > +
  • CxImagePNG: fixed deallocation bug in Encode() <Ranger> +
  • CxImagePNG: now reads 2 bpp images. +
  • CxImageBMP: fixed DPI rounding error <DIH> +
  • CreateFromHANDLE now handles the DPI information <Jeff Hu>
    +
  • +
+Changes and major additions +
    +
  • New pixel ALPHA channel, overall opacity. (14 dedicated functions) +
  • New Alpha Palette. (5 dedicated functions) +
  • New Region Selection (rectangle, ellipse, polygon - 11 dedicated functions). +
  • New "copypixels", "copyselection", "copyalpha" options for constructor/Copy() +
  • New "errordiffusion" option for DecreasBPP(). +
  • New Draw() implementation with support for alpha channel, alpha palette, + opacity, transparency. +
  • New PCX decoder CxImagePCX +
  • New TGA decoder/encoder CxImageTGA (with alpha channel) +
  • High resolution shrink for Resample() <Henrik Stellmann> +
  • CxImagePNG now reads/saves the transparency information (palette and alpha + channel)
    +
  • +
+Project - Libraries - Demo application +
    +
  • Updated PNG library: Libpng version 1.2.1 +
  • Free-hand selection with the left mouse button.
    +
  • +
+
+

Version 2.00, 29 - Dec - 2001

+Bugfixes +
    +
  • fixed deadlock in GIF decoder +
  • PNG decoder reads 16 bit grayscale images. +
  • TIF decoder reads 4 bit grayscale images. +
  • fixed bug in CreateFromHBITMAP() <Wil Stark> +
  • Fixed PNG encoder bug, buffer allocation error with BW images.
    +
  • +
+Changes and major additions +
    +
  • MNG decoder handles the background information.
    +
  • TIF encoder now uses COMPRESSION_JPEG for 24 bit images.
    +
  • LoadResource(): added new parameter to work with dlls. <Tuncer M. Ayaz> +
  • LoadResource() now works with network applications. <Tuncer M. Ayaz> +
  • Changed CxImage() constructors, Copy() and Transfer() interface and implementation + <Kirk> +
  • Added CreateFromHANDLE() and CreateFromHBITMAP() in place of the old constructors. +
  • Automatic file format recognition in ReadFile() <Patrick Hoffmann> +
  • Faster Draw() implementation for transparent images. (Thanks to Paul Reynolds + and Ron Gery) +
  • New Get/SetJpegQuality() for JPEG and TIF encoders. +
  • New Get/SetXDPI(), Get/SetYDPI() for BMP and TIF formats. +
  • New Dither() function, with Floyd-Steinberg or Ordered-Dithering BW conversion + (Thanks to Kenny Hoff and Steve McMahon) +
  • New functions : Crop(), SplitRGB(), SplitYUV(), SplitHSL(). +
  • New functions : Colorize(), Light(), Threshold(), Mean(), Filter(), Dilate(), + Erode().
    +
  • +
+Project - Libraries - Demo application +
    +
  • Removed bad pixels from "Capture Window" <Qiang>
    +
  • New menus: Blur, Soften, Edge, Sharpen, Emboss, Dilate, Erode, Threshold, + Dither, ...
    +
  • +
+
+

Version 1.25, 28 - Oct - 2001

+Bugfixes +
    +
  • Added support for 32 bit PNGs and 16 bit TIFs
  • +
+
+

Version 1.23, 15 - Oct - 2001

+Bugfixes +
    +
  • Fixed PNG reading interlaced and gray scale images. <DP> +
  • Fixed PNG saving 1 & 4 bit images. <DP> +
  • Fixed GIF saving and reading 1 & 4 bit images. <DP> +
  • Added safe checks in CImageIterator::SetRow() <DP> and in CxImagePNG::Decode() + <yeonjun jeong>
  • +
+Changes and major additions
+
    +
  • + Basic MNG encoder/decoder. +
  • + Get/SetTransIndex(): on the fly transparency for indexed images (1, 4, + 8 bpp) <TRK> +
  • + Get/SetTransColor(): on the fly transparency for RGB images (24 bpp) + <DP> +
  • + GIF encoder saves transparency information <TRK> +
  • + PNG encoder saves transparency information <DP> +
  • + SwapIndex() function for palette operations with transparency <DP> +
  • + Resample() function <Steve McMahon> +
  • + Get/SetEscape() to quit the slow loops. +
  • + Get/SetProgress() to monitor the slow loops. +
  • + SetStdPalette() to create a standard palette for 256 and 16 colors images. +
  • + DecreaseBpp()/IncreaseBpp().
    +
  • +
+Project - Libraries - Demo application +
    +
  • Transparency handling menu <DP> +
  • Fixed cast problem in Jcapimin.c, comparing JPEG_LIB_VERSION <F. Livraghi> +
  • Resample, DecreaseBpp, IncreaseBpp menu <DP> +
  • Stopwatch and ProgressBar in the status bar <DP> +
  • Image computations are in a separate thread <DP> +
  • Added CQuantizer class to implement the color reduction with the octree + algorithm. <Jeff Prosise>
  • +
+
+

Version 1.10, 23 - Sep - 2001

+Bugfixes +
    +
  • Better exception handling in CxImagePNG & CxImageBMP. <DP> +
  • Gdi resource leakage and memory corruption in CxImage(HBITMAP). <TRK> +
  • Rotate() didn't handle transparency. <TRK> +
  • Fixed TIFF saving 1 & 4 bit images. <DP>
  • +
+Changes and major additions
+
    +
  • Extended LoadResource() to TIFF format. <DP> +
  • - Removed info.szFileName : never used, and it's not an image related information. + <TRK>
    +
  • Reduced fopen/fclose clutter. <TRK><DP> +
  • Extended constructors with "imagetype" (for future use). <TRK> +
  • Replaced GetPaletteIndex() with GetPaletteColor() : the function returns + a color, not an index. +
  • Replaced GetFileType() with GetType() : to avoid confusion with the file + extension. +
  • GrayScale() now always create an 8 bit gray scale image. <DP> +
  • + Implemented transparency in CxImage::Draw(). Now Draw() can also stretch + the image, so Stretch() became obsolete. <TRK> +
  • + CxImage(FILE * stream) constructor. <TRK> +
  • + JPEG read CMYK format (adobe). <DP> +
  • + Transparency for PNG. <DP> +
  • + Enabled reading of RLE-compressed <TRK> and 16 & 32 bit BITFIELD + <DP> bitmaps. +
  • + Unicode version for ReadFile/SaveFile. +
  • + MakeBitmap() function <Kurt Diesch> +
  • + JPEG can save 8 bit GrayScale images. <DP>
    +
  • +
+Project - Libraries - Demo application +
    +
  • Removed MFC-dependency (#include <afxwin.h>) <TRK> +
  • Changed jconfig.h with HAVE_BOOLEAN stuff <TRK> +
  • + new tiff_c.c module in theTIFF library, for straight C Runtime Library + file functions. <TRK> +
  • Demo : now using Project|Dependencies. +
  • + Zoomin/Zoomout menu <DP> +
  • + Capture window menu <DP> +
  • + Acquire from TWAIN source <DP>
  • +
+
+

Version 1.01, 27 - Aug - 2001

+Bugfixes +
    +
  • PNG Read/Save exceptions with non dword aligned scan lines. +
  • Mirror() doesn't handle the last column. <Brian R. Zielinski>
  • +
+Changes and major additions +
    +
  • + GrayScale(). <TRK>
    +
  • + Rotate().
    +
  • + Read Multiple Image for TIFFs & ICONs
    +
  • + LoadResource(). <DP> +
  • Changed GIF read implementation. Added animation handling. <TRK>
    +
  • +
+Project - Libraries - Demo application +
    +
  • + Demo: added hatched background and Print functionality. <TRK> +
  • + Undo/Redo menu. <DP>
  • +
+
+

Version 1.00, 07 - Aug - 2001

+
+

PEOPLE:

+<DP> : Davide Pizzolato (www(dot)xdp(dot)it)
+<TRK> : Troels Knakkergaard (TRK(at)lyngsoe(dot)com)
+<Brian R(dot) Zielinski> : Brian R. Zielinski (brianz(at)digital(dot)risserimaging(dot)com)
+<Kurt Diesch> : Kurt Diesch (kdiesch(at)enjoysoft(dot)com)
+<F. Livraghi > : Francesco Livraghi (info(at)ceccoing(dot)it)
+<Steve McMahon> : Steve McMahon (steve(at)dogma(dot)demon(dot)co(dot)uk)
+<Tuncer M. Ayaz> : Tuncer M. Ayaz (tuncer(dot)ayaz(at)gmx(dot)de)
+<Kirk> : Kirk Korver (kirk(at)the-right-stuff(dot)com)
+<Qiang> : Qiang Liu (liuq(at)ee(dot)washington(dot)edu)
+<Patrick Hoffmann> : Patrick Hoffmann (hoffmann(at)novacom(dot)net)
+<Wil Stark> : Wil Stark (wil_stark(at)agilent(dot)com)
+<DIH> : Dominic I. Holmes (DIH(dot)Junk(at)DigitalFormation(dot)com)
+<Henrik Stellmann> : Henrik Stellmann (henrik(dot)stellmann(at)volleynet(dot)de)
+<Ranger> : Ranger (RangerMail(at)mail(dot)ru)
+<Jeff Hu> : Jeff Hu (v120160(at)yahoo(dot)com(dot)tw)
+<MTA> : Matthew Armstrong (ArmstroM(at)faro(dot)com)
+<REC> : Robert Edward Caldecott (rec(at)kerridge(dot)com)
+<RG> : Roberto Guerzoni (r(dot)guerzoni(at)infomotion(dot)mo(dot)it)
+<MKVY> : Murali Krishna V Yelchuru (muralikrishnayv(at)yahoo(dot)com)
+<Rogier> Rogier Reedijk (xs4free(at)wish(dot)net)
+<Rob Cass> : Rob Cass (rcass(at)compusult(dot)nf(dot)ca)
+<DJT> : Dave Turnbull (Camel) (dave(at)camel(dot)co(dot)uk)
+<JA> : Jörgen Alfredsson (jorgen(dot)alfredsson(at)kamera(dot)com)
+<Mpwolski> : Mwolski (mpwolski(at)hotmail(dot)com)
+<CSC> : Chris Shearer Cooper (cscooper(at)frii(dot)com)
+<Abe> : Abe (God(dot)bless(at)marihuana(dot)com)
+<Ole Lange> : Ole Lange (ol(at)ams-soft(dot)de)
+<vho> : Volker Horch (vhorch(at)gmx(dot)de)
+<Kwyshell> : Kwyshell (kwyshell(at)yahoo(dot)com(dot)tw)
+<Flanders> : Flanders (flanders(at)2moors(dot)freeserve(dot)co(dot)uk)
+<Anatoly Ivasyuk> : Anatoly Ivasyuk (aivasyuk(at)dtlink(dot)com)
+<T.Peck> : T. Peck (tpeck(at)roundwave(dot)com)
+<Koray Geçici> : Koray Geçici (kgecici(at)tam(dot)net(dot)tr)
+<Olivier Ansquer> : Olivier Ansquer (olivier(dot)ansquer(at)freesbee(dot)fr)
+<elrod> : Mark B. Elrod (elrod(at)bluedoor(dot)com)
+<Cui Ying Jie> : Cui Ying Jie (cuiyj(at)163(dot)net)
+<dock> : dock (dock(at)cmmail(dot)com)
+<handong> : handong (jhandong(at)netian(dot)com)
+<candan> : candan (candan(at)mail(dot)pagic(dot)net)
+<RJ> : Roger Jane (roger(dot)jane(at)microtest(dot)co(dot)uk)
+<Robert Abram> : Robert Abram (robert(dot)abram(at)prgx(dot)com)
+<dave> : dave(at)posortho(dot)com)
+<CoreyRLucier> : CoreyRLucier(at)aol(dot)com)
+<Carsten Leue> : Carsten Leue (carsten(dot)leue(at)iwr(dot)uni-heidelberg(dot)de)
+<jh> : jh (jhprivate(at)fescomail(dot)net)
+<lioucr> : lioucr (lioucr(at)yahoo(dot)ca)
+<TomPeakz> : TomPeakz (topman(at)vip(dot)sina(dot)com)
+<arnold wittenberg> : Arnold Wittenberg (a(dot)wittenberg(at)eramco(dot)nl)
+<H. Muelner> : Helmut Muelner (hmuelner(at)iicm(dot)edu)
+<jurgene> : Jürgen Eidt (jurgene(at)hotmail(dot)com)
+<W. Morrison> : William Morrison (Bill(at)rosinante(dot)com)
+<jaslet> : Bertrand Jaslet (jaslet(at)hotmail(dot)com)
+<corwinkrisw> : corwinkrisw (corwinkrisw(at)yahoo(dot)com)
+<gazzivan> : gazzivan (gazzivan(at)libero(dot)it)
+<Stroupe David R> : Stroupe David R (x5011) (David(dot)Stroupe(at)siemens(dot)com)
+<Frank Sowinski> : Frank Sowinski (Frank(dot)Sowinski(at)fujitsu-siemens(dot)com)
+<JDL> : Jordan DeLozier (support(at)triosade(dot)com)
+<Wassily Gibin> : Wassily Gibin (vasily(at)gibin(dot)net)
+<osamu44> : osamu44 (osamu44(at)juno(dot)ocn(dot)ne(dot)jp)
+<Sims> : Sims (siminfrance(at)hotmail(dot)com)
+<Vitaly Titov> : Vitaly Titov (vitalyt(at)scanvecamiable(dot)com)
+<Branko Drevenšek> / <BD> : Branko Drevenšek (branko(dot)drevensek(at)uni-mb(dot)si)
+<Henry P.>: Henry P. (hdpham(at)allersoft(dot)com)
+<Kristian Kratzenstein> : Kristian Kratzenstein (kristian(at)kratzenstein(dot)dyndns(dot)org)
+<Basara> : Alexey Silinov (basara(at)in-cubus(dot)com)
+<ralphw> : Ralph Walden (ralphw(at)exmsft(dot)com)
+<Zahi Kapeluto> : Zahi Kapeluto (zahi(at)locationet(dot)com)
+<Colin Urquhart> : Colin Urquhart (colin(dot)urquhart(at)primetv(dot)com(dot)au)
+<oboolo> : Ludovic Baillet (oboolo(at)baillet(dot)org)
+<yuandi> : yuandi (yuandi(at)www(dot)ps2love(dot)com)
+<Schuberth> : Sebastian Schuberth (s(dot)schuberth(at)tu-bs(dot)de)
+<Squidge> : Squidge (paulc(at)ibiblio(dot)org)
+<sihun> : sihun (shsung(at)mbc(dot)co(dot)kr)
+<H.C.Anderson> : Howard C. Anderson (howard(dot)anderson(at)anadigm(dot)com)
+<chupeev> : alexander chupeev (chupeev(at)tmn(dot)ru)
+<Lucian Ioan> : Lucian Ioan (xtndd(at)yahoo(dot)com)
+<Chieh An Lu> : Chieh An Lu (calu(at)interactiveedge(dot)com)
+<James Dickson> : James Dickson (Jamie(at)jdnet(dot)co(dot)uk)
+<Richard Collins> : Richard Collins (rtc(at)steel-connections(dot)com)
+<Igor Rosenberg> : Igor Rosenberg (rosenberg(at)infotrust.sk)
+<DT> : Diego Tartara (dtartara(at)hotmail(dot)com)
+<VATI> : Varga Attila (attila_varga(at)freemail(dot)hu)
+<DPR> : DPR (info(at)brutzler(dot)de)
+<Trifon> : Trifon (trifon(dot)alekov(at)dotrix(dot)be)
+<Nick Holgate> : Nick Holgate (nick(at)barhop(dot)co(dot)uk)
+<Kenneth Ballard> : Kenneth Ballard (ken_ballard(at)hotmail(dot)com)
+<Thomas M. Boser> : Thomas M. Boser (tom(dot)boser(at)olimllc(dot)com)
+<ignacio> : Ignacio Alvarez (ignacio(at)xentient(dot)com)
+<Arkadiy Olovyannikov> : Arkadiy Olovyannikov (ark(at)msun(dot)ru)
+<nipper> : nipper (nipper(at)rpnet(dot)cz)
+<Hermann62> : Hermann62 (hild(at)smi-software)
+<Michael Gandyra> : Michael Gandyra (M(dot)Gandyra(at)steinbichler(dot)de)
+<Tacho> : Tacho (tacho_fortin(at)hotmail(dot)com )
+<Franco Gerevini> : Franco Gerevini
+<Admir Hodzic> : Admir Hodzic (fathsoft(at)fathsoft(dot)com)
+<Vladimír Kloucek> : Vladimír Kloucek (vladimir(dot)kloucek(at)samo(dot)cz)
+<Cesar M> : +Cesar Mello (cmello(at)gmail(dot)com)
+

+


+ + diff --git a/SlnkDWFImpl/CxImage/doc/cximage_libraries.htm b/SlnkDWFImpl/CxImage/doc/cximage_libraries.htm new file mode 100644 index 0000000..2a6b01d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/cximage_libraries.htm @@ -0,0 +1,99 @@ + + + +CxImage Linked Libraries + + + + + +

CxImage Linked Libraries

+
+

CxImage must be linked with additional libraries in order to read and write some specific file formats. All these libraries are freely available, with source code, documentation and examples. Some of the libraries distributed with CxImage have been patched, or slightly edited, to add features normally not enabled in the standard distributions, or just to avoid too many warnings from the compiler during the compilation, and mainly to ensure that CxImage can be easily linked with all of them without troubles. Here is a list of the libraries linked with CxImage :

+ +
+

zLib

+

Home page : http://www.gzip.org/zlib/ [^]
+Version : 1.2.1
+Required for : PNG, TIFF, JBIG.
+Patches : none.
+

+
+

LibTIFF

+

Home page : http://www.remotesensing.org/libtiff/ [^]
+ Version : 3.5.7
+ Required for : TIFF.
+Patches :

+
    +
  • added OJPEG format
  • +
  • LZW compression kit
  • +
  • minor configuration editing
  • +
  • see detatils in libtiff_patches.zip
  • +
+
+

LibPNG

+

Home page : http://www.libpng.org [^]
+ Version : 1.2.7
+ Required for : PNG.
+ Patches : none.
+

+
+

LibJPEG

+

Home page : http://www.ijg.org [^]
+ Version : 6b
+ Required for : JPG, TIFF, MNG.
+Patches :

+ +
+

JBIG-Kit

+

Home page : http://www.cl.cam.ac.uk/~mgk25/jbigkit/ [^]
+ Version : 1.6
+ Required for : JBIG.
+ Patches : only some missing cast.
+

+
+

JasPer

+

Home page : http://www.ece.uvic.ca/~mdadams/jasper/ [^]
+ Version : 1.700.2
+ Required for : + + + JP2, + + + JPC, PNM, RAS, + + + PGX.
+ Patches : only some missing cast and minor configuration editing.
+

+
+

LibJ2K

+

This library is a beta version, use JasPer!

+

Home page : http://j2000.org/ [^]
+ Version : 0.0.8
+ Required for : J2K.
+ Patches : I found some different distributions with the same version, so I can't build the diff.
+Many bugs (memory leaks) have been fixed in the version included with CxImage, however
+this library is still not very safe and stable.
+

+ + diff --git a/SlnkDWFImpl/CxImage/doc/cximagelogo.png b/SlnkDWFImpl/CxImage/doc/cximagelogo.png new file mode 100644 index 0000000..1637cc7 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/cximagelogo.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/.gitignore b/SlnkDWFImpl/CxImage/doc/doxy/html/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/annotated.html b/SlnkDWFImpl/CxImage/doc/doxy/html/annotated.html new file mode 100644 index 0000000..a544860 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/annotated.html @@ -0,0 +1,18 @@ + + +CxImage: Class List + + + + +

CxImage Class List

Here are the classes, structs, unions and interfaces with brief descriptions: + + + + +
CxImage
CxImage::rgb_color
CxImage::tagCxImageInfo
CxImage::tagCxTextInfo
+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/class_cx_image-members.html b/SlnkDWFImpl/CxImage/doc/doxy/html/class_cx_image-members.html new file mode 100644 index 0000000..797f8e8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/class_cx_image-members.html @@ -0,0 +1,333 @@ + + +CxImage: Member List + + + + +

CxImage Member List

This is the complete list of members for CxImage, including all inherited members.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AddAveragingCont(RGBQUAD const &color, float const surf, float &rr, float &gg, float &bb, float &aa)CxImage [protected]
AlphaClear()CxImage
AlphaCopy(CxImage &from)CxImage
AlphaCreate()CxImage
AlphaDelete()CxImage
AlphaFlip()CxImage
AlphaGet(const long x, const long y)CxImage
AlphaGetMax() constCxImage
AlphaGetPointer(const long x=0, const long y=0)CxImage
AlphaInvert()CxImage
AlphaIsValid()CxImage
AlphaMirror()CxImage
AlphaPaletteClear()CxImage
AlphaPaletteEnable(bool enable=true)CxImage
AlphaPaletteIsEnabled()CxImage
AlphaPaletteIsValid()CxImage
AlphaPaletteSplit(CxImage *dest)CxImage
AlphaSet(BYTE level)CxImage
AlphaSet(CxImage &from)CxImage
AlphaSet(const long x, const long y, const BYTE level)CxImage
AlphaSetMax(BYTE nAlphaMax)CxImage
AlphaSplit(CxImage *dest)CxImage
AlphaStrip()CxImage
Bitfield2RGB(BYTE *src, WORD redmask, WORD greenmask, WORD bluemask, BYTE bpp)CxImage [protected]
BlendPalette(COLORREF cr, long perc)CxImage
BlendPixelColor(long x, long y, RGBQUAD c, float blend, bool bSetAlpha=false)CxImage
BlindAlphaGet(const long x, const long y)CxImage [protected]
BlindGetPixelColor(const long x, const long y)CxImage [protected]
BlindGetPixelIndex(const long x, const long y)CxImage [protected]
BlindGetPixelPointer(const long x, const long y)CxImage [protected]
blur_line(float *ctable, float *cmatrix, int cmatrix_length, BYTE *cur_col, BYTE *dest_col, int y, long bytes)CxImage [protected]
CircleTransform(int type, long rmax=0, float Koeff=1.0f)CxImage
Clear(BYTE bval=0)CxImage
Colorize(BYTE hue, BYTE sat, float blend=1.0f)CxImage
Combine(CxImage *r, CxImage *g, CxImage *b, CxImage *a, long colorspace=0)CxImage
CompareColors(const void *elem1, const void *elem2)CxImage [protected, static]
Contour()CxImage
Copy(const CxImage &src, bool copypixels=true, bool copyselection=true, bool copyalpha=true)CxImage
CopyInfo(const CxImage &src)CxImage [protected]
CopyToHandle()CxImage
Create(DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype=0)CxImage
CreateFromArray(BYTE *pArray, DWORD dwWidth, DWORD dwHeight, DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage)CxImage
CreateFromHANDLE(HANDLE hMem)CxImage
CreateFromHBITMAP(HBITMAP hbmp, HPALETTE hpal=0)CxImage
CreateFromHICON(HICON hico)CxImage
CreateFromMatrix(BYTE **ppMatrix, DWORD dwWidth, DWORD dwHeight, DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage)CxImage
Crop(long left, long top, long right, long bottom, CxImage *iDst=NULL)CxImage
Crop(const RECT &rect, CxImage *iDst=NULL)CxImage
CropRotatedRectangle(long topx, long topy, long width, long height, float angle, CxImage *iDst=NULL)CxImage
CxImage(DWORD imagetype=0)CxImage
CxImage(DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype=0)CxImage
CxImage(const CxImage &src, bool copypixels=true, bool copyselection=true, bool copyalpha=true)CxImage
CxImage(const TCHAR *filename, DWORD imagetype)CxImage
CxImage(FILE *stream, DWORD imagetype)CxImage
CxImage(CxFile *stream, DWORD imagetype)CxImage
CxImage(BYTE *buffer, DWORD size, DWORD imagetype)CxImage
CXIMAGEINFO typedefCxImage [private]
CXTEXTINFO typedefCxImage
Decode(FILE *hFile, DWORD imagetype)CxImage
Decode(CxFile *hFile, DWORD imagetype)CxImage
Decode(BYTE *buffer, DWORD size, DWORD imagetype)CxImage
DecreaseBpp(DWORD nbit, bool errordiffusion, RGBQUAD *ppal=0, DWORD clrimportant=0)CxImage
Destroy()CxImage
DFT(int dir, long m, double *x1, double *y1, double *x2, double *y2)CxImage [protected]
Dilate(long Ksize=2)CxImage
Dither(long method=0)CxImage
Draw(HDC hdc, long x=0, long y=0, long cx=-1, long cy=-1, RECT *pClipRect=0, bool bSmooth=false)CxImage
Draw(HDC hdc, const RECT &rect, RECT *pClipRect=NULL, bool bSmooth=false)CxImage
Draw2(HDC hdc, long x=0, long y=0, long cx=-1, long cy=-1)CxImage
Draw2(HDC hdc, const RECT &rect)CxImage
DrawLine(int StartX, int EndX, int StartY, int EndY, RGBQUAD color, bool bSetAlpha=false)CxImage
DrawLine(int StartX, int EndX, int StartY, int EndY, COLORREF cr)CxImage
DrawString(HDC hdc, long x, long y, const TCHAR *text, RGBQUAD color, const TCHAR *font, long lSize=0, long lWeight=400, BYTE bItalic=0, BYTE bUnderline=0, bool bSetAlpha=false)CxImage
DrawStringEx(HDC hdc, long x, long y, CXTEXTINFO *pTextType, bool bSetAlpha=false)CxImage
Edge(long Ksize=2)CxImage
Enable(bool enable=true)CxImage
Encode(FILE *hFile, DWORD imagetype)CxImage
Encode(CxFile *hFile, DWORD imagetype)CxImage
Encode(CxFile *hFile, CxImage **pImages, int pagecount, DWORD imagetype)CxImage
Encode(FILE *hFile, CxImage **pImages, int pagecount, DWORD imagetype)CxImage
Encode(BYTE *&buffer, long &size, DWORD imagetype)CxImage
Encode2RGBA(CxFile *hFile)CxImage
Encode2RGBA(BYTE *&buffer, long &size)CxImage
EncodeSafeCheck(CxFile *hFile)CxImage [protected]
Erode(long Ksize=2)CxImage
Expand(long left, long top, long right, long bottom, RGBQUAD canvascolor, CxImage *iDst=0)CxImage
Expand(long newx, long newy, RGBQUAD canvascolor, CxImage *iDst=0)CxImage
FFT(int dir, int m, double *x, double *y)CxImage [protected]
FFT2(CxImage *srcReal, CxImage *srcImag, CxImage *dstReal, CxImage *dstImag, long direction=1, bool bForceFFT=true, bool bMagnitude=true)CxImage
Filter(long *kernel, long Ksize, long Kfactor, long Koffset)CxImage
Flip()CxImage
FreeMemory(void *memblock)CxImage
Gamma(float gamma)CxImage
gen_convolve_matrix(float radius, float **cmatrix_p)CxImage [protected]
gen_lookup_table(float *cmatrix, int cmatrix_length)CxImage [protected]
GetAreaColorInterpolated(float const xc, float const yc, float const w, float const h, InterpolationMethod const inMethod, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)CxImage
GetBits(DWORD row=0)CxImage
GetBpp() constCxImage
GetClrImportant() constCxImage
GetCodecOption(DWORD imagetype=0)CxImage
GetColorType()CxImage
GetDIB() constCxImage
GetEffWidth() constCxImage
GetEscape() constCxImage
GetFlags() constCxImage
GetFrame() constCxImage
GetFrameDelay() constCxImage
GetHeight() constCxImage
GetJpegQuality() constCxImage
GetJpegScale() constCxImage
GetLastError()CxImage
GetLayer(long position)CxImage
GetNearestIndex(RGBQUAD c)CxImage
GetNumColors() constCxImage
GetNumFrames() constCxImage
GetNumLayers() constCxImage
GetOffset(long *x, long *y)CxImage
GetPalette() constCxImage
GetPaletteColor(BYTE idx)CxImage
GetPaletteColor(BYTE i, BYTE *r, BYTE *g, BYTE *b)CxImage
GetPaletteSize()CxImage
GetParent() constCxImage
GetPixelColor(long x, long y, bool bGetAlpha=true)CxImage
GetPixelColorInterpolated(float x, float y, InterpolationMethod const inMethod=IM_BILINEAR, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)CxImage
GetPixelColorWithOverflow(long x, long y, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)CxImage
GetPixelGray(long x, long y)CxImage
GetPixelIndex(long x, long y)CxImage
GetProgress() constCxImage
GetSize()CxImage
GetTransColor()CxImage
GetTransIndex() constCxImage
GetType() constCxImage
GetVersion()CxImage
GetVersionNumber()CxImage
GetWidth() constCxImage
GetXDPI() constCxImage
GetYDPI() constCxImage
Ghost(CxImage *src)CxImage [protected]
GrayScale()CxImage
headCxImage [protected]
Histogram(long *red, long *green=0, long *blue=0, long *gray=0, long colorspace=0)CxImage
HistogramEqualize()CxImage
HistogramLog()CxImage
HistogramNormalize()CxImage
HistogramRoot()CxImage
HistogramStretch(long method=0)CxImage
HSLtoRGB(COLORREF cHSLColor)CxImage [static]
HSLtoRGB(RGBQUAD lHSLColor)CxImage [static]
HuePalette(float correction=1)CxImage
HueToRGB(float n1, float n2, float hue)CxImage [protected, static]
IM_BESSEL enum valueCxImage
IM_BICUBIC enum valueCxImage
IM_BICUBIC2 enum valueCxImage
IM_BILINEAR enum valueCxImage
IM_BLACKMAN enum valueCxImage
IM_BOX enum valueCxImage
IM_BSPLINE enum valueCxImage
IM_CATROM enum valueCxImage
IM_GAUSSIAN enum valueCxImage
IM_HAMMING enum valueCxImage
IM_HERMITE enum valueCxImage
IM_LANCZOS enum valueCxImage
IM_MITCHELL enum valueCxImage
IM_NEAREST_NEIGHBOUR enum valueCxImage
IM_QUADRATIC enum valueCxImage
IM_SINC enum valueCxImage
ImageOpType enum nameCxImage
IncreaseBpp(DWORD nbit)CxImage
infoCxImage [protected]
InitTextInfo(CXTEXTINFO *txt)CxImage
InterpolationMethod enum nameCxImage
IsEnabled() constCxImage
IsGrayScale()CxImage
IsIndexed() constCxImage
IsInside(long x, long y)CxImage
IsPowerof2(long x)CxImage [protected]
IsSamePalette(CxImage &img, bool bCheckAlpha=true)CxImage
IsTransparent() constCxImage
IsTransparent(long x, long y)CxImage
IsValid() constCxImage
Jitter(long radius=2)CxImage
KernelBessel(const float x)CxImage [static]
KernelBessel_J1(const float x)CxImage [static]
KernelBessel_Order1(float x)CxImage [static]
KernelBessel_P1(const float x)CxImage [static]
KernelBessel_Q1(const float x)CxImage [static]
KernelBlackman(const float x)CxImage [static]
KernelBox(const float x)CxImage [static]
KernelBSpline(const float x)CxImage [static]
KernelCatrom(const float x)CxImage [static]
KernelCubic(const float t)CxImage [static]
KernelGaussian(const float x)CxImage [static]
KernelGeneralizedCubic(const float t, const float a=-1)CxImage [static]
KernelHamming(const float x)CxImage [static]
KernelHermite(const float x)CxImage [static]
KernelLanczosSinc(const float t, const float r=3)CxImage [static]
KernelLinear(const float t)CxImage [static]
KernelMitchell(const float x)CxImage [static]
KernelQuadratic(const float x)CxImage [static]
KernelSinc(const float x)CxImage [static]
LayerCreate(long position=-1)CxImage
LayerDelete(long position=-1)CxImage
LayerDeleteAll()CxImage
Light(long brightness, long contrast=0)CxImage
Load(const TCHAR *filename, DWORD imagetype=0)CxImage
LoadResource(HRSRC hRes, DWORD imagetype, HMODULE hModule=NULL)CxImage
Lut(BYTE *pLut)CxImage
Lut(BYTE *pLutR, BYTE *pLutG, BYTE *pLutB, BYTE *pLutA=0)CxImage
MakeBitmap(HDC hdc=NULL)CxImage
Mean()CxImage
Median(long Ksize=3)CxImage
Mirror()CxImage
Mix(CxImage &imgsrc2, ImageOpType op, long lXOffset=0, long lYOffset=0, bool bMixAlpha=false)CxImage
MixFrom(CxImage &imagesrc2, long lXOffset, long lYOffset)CxImage
Negative()CxImage
Noise(long level)CxImage
OM_BACKGROUND enum valueCxImage
OM_COLOR enum valueCxImage
OM_MIRROR enum valueCxImage
OM_REPEAT enum valueCxImage
OM_TRANSPARENT enum valueCxImage
OM_WRAP enum valueCxImage
OpAdd enum valueCxImage
OpAnd enum valueCxImage
OpDstCopy enum valueCxImage
operator=(const CxImage &)CxImage
OpMask enum valueCxImage
OpOr enum valueCxImage
OpScreen enum valueCxImage
OpSrcBlend enum valueCxImage
OpSrcCopy enum valueCxImage
OpSub enum valueCxImage
OpXor enum valueCxImage
OverflowCoordinates(float &x, float &y, OverflowMethod const ofMethod)CxImage
OverflowCoordinates(long &x, long &y, OverflowMethod const ofMethod)CxImage
OverflowMethod enum nameCxImage
pAlphaCxImage [protected]
pDibCxImage [protected]
pLayersCxImage [protected]
pSelectionCxImage [protected]
QIShrink(long newx, long newy, CxImage *const iDst=NULL)CxImage
RedEyeRemove()CxImage
Repair(float radius=0.25f, long niterations=1, long colorspace=0)CxImage
RepairChannel(CxImage *ch, float radius)CxImage [protected]
Resample(long newx, long newy, int mode=1, CxImage *iDst=NULL)CxImage
Resample2(long newx, long newy, InterpolationMethod const inMethod=IM_BICUBIC2, OverflowMethod const ofMethod=OM_REPEAT, CxImage *const iDst=NULL, bool const disableAveraging=false)CxImage
RGBQUADtoRGB(RGBQUAD c)CxImage [static]
RGBtoBGR(BYTE *buffer, int length)CxImage [protected]
RGBtoHSL(RGBQUAD lRGBColor)CxImage [static]
RGBtoRGBQUAD(COLORREF cr)CxImage [static]
RGBtoXYZ(RGBQUAD lRGBColor)CxImage [static]
RGBtoYIQ(RGBQUAD lRGBColor)CxImage [static]
RGBtoYUV(RGBQUAD lRGBColor)CxImage [static]
Rotate(float angle, CxImage *iDst=NULL)CxImage
Rotate180(CxImage *iDst=NULL)CxImage
Rotate2(float angle, CxImage *iDst=NULL, InterpolationMethod inMethod=IM_BILINEAR, OverflowMethod ofMethod=OM_BACKGROUND, RGBQUAD *replColor=0, bool const optimizeRightAngles=true, bool const bKeepOriginalSize=false)CxImage
RotateLeft(CxImage *iDst=NULL)CxImage
RotateRight(CxImage *iDst=NULL)CxImage
Save(const TCHAR *filename, DWORD imagetype)CxImage
SelectionAddColor(RGBQUAD c)CxImage
SelectionAddEllipse(RECT r)CxImage
SelectionAddPixel(int x, int y)CxImage
SelectionAddPolygon(POINT *points, long npoints)CxImage
SelectionAddRect(RECT r)CxImage
SelectionClear()CxImage
SelectionCopy(CxImage &from)CxImage
SelectionCreate()CxImage
SelectionDelete()CxImage
SelectionGetBox(RECT &r)CxImage
SelectionInvert()CxImage
SelectionIsInside(long x, long y)CxImage
SelectionIsValid()CxImage
SelectionSplit(CxImage *dest)CxImage
SelectionToHRGN(HRGN &region)CxImage
SetClrImportant(DWORD ncolors=0)CxImage
SetCodecOption(DWORD opt, DWORD imagetype=0)CxImage
SetEscape(long i)CxImage
SetFlags(DWORD flags, bool bLockReservedFlags=true)CxImage
SetFrame(long nFrame)CxImage
SetFrameDelay(DWORD d)CxImage
SetGrayPalette()CxImage
SetJpegQuality(BYTE q)CxImage
SetJpegScale(BYTE q)CxImage
SetOffset(long x, long y)CxImage
SetPalette(DWORD n, BYTE *r, BYTE *g, BYTE *b)CxImage
SetPalette(RGBQUAD *pPal, DWORD nColors=256)CxImage
SetPalette(rgb_color *rgb, DWORD nColors=256)CxImage
SetPaletteColor(BYTE idx, BYTE r, BYTE g, BYTE b, BYTE alpha=0)CxImage
SetPaletteColor(BYTE idx, RGBQUAD c)CxImage
SetPaletteColor(BYTE idx, COLORREF cr)CxImage
SetPixelColor(long x, long y, RGBQUAD c, bool bSetAlpha=false)CxImage
SetPixelColor(long x, long y, COLORREF cr)CxImage
SetPixelIndex(long x, long y, BYTE i)CxImage
SetProgress(long p)CxImage
SetStdPalette()CxImage
SetTransColor(RGBQUAD rgb)CxImage
SetTransIndex(long idx)CxImage
SetXDPI(long dpi)CxImage
SetYDPI(long dpi)CxImage
ShiftRGB(long r, long g, long b)CxImage
Skew(float xgain, float ygain, long xpivot=0, long ypivot=0, bool bEnableInterpolation=false)CxImage
SplitCMYK(CxImage *c, CxImage *m, CxImage *y, CxImage *k)CxImage
SplitHSL(CxImage *h, CxImage *s, CxImage *l)CxImage
SplitRGB(CxImage *r, CxImage *g, CxImage *b)CxImage
SplitXYZ(CxImage *x, CxImage *y, CxImage *z)CxImage
SplitYIQ(CxImage *y, CxImage *i, CxImage *q)CxImage
SplitYUV(CxImage *y, CxImage *u, CxImage *v)CxImage
Startup(DWORD imagetype=0)CxImage [protected]
Stretch(HDC hdc, long xoffset, long yoffset, long xsize, long ysize, DWORD dwRop=SRCCOPY)CxImage
Stretch(HDC hdc, const RECT &rect, DWORD dwRop=SRCCOPY)CxImage
SwapIndex(BYTE idx1, BYTE idx2)CxImage
Threshold(BYTE level)CxImage
Thumbnail(long newx, long newy, RGBQUAD canvascolor, CxImage *iDst=0)CxImage
Tile(HDC hdc, RECT *rc)CxImage
Transfer(CxImage &from)CxImage
UnsharpMask(float radius=5.0, float amount=0.5, int threshold=0)CxImage
XYZtoRGB(RGBQUAD lXYZColor)CxImage [static]
YIQtoRGB(RGBQUAD lYIQColor)CxImage [static]
YUVtoRGB(RGBQUAD lYUVColor)CxImage [static]
~CxImage()CxImage [inline, virtual]


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/class_cx_image.html b/SlnkDWFImpl/CxImage/doc/doxy/html/class_cx_image.html new file mode 100644 index 0000000..83c7e06 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/class_cx_image.html @@ -0,0 +1,693 @@ + + +CxImage: CxImage Class Reference + + + + +

CxImage Class Reference

#include <ximage.h> +

+List of all members. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Public Types

typedef CxImage::tagCxTextInfo CXTEXTINFO
enum  ImageOpType {
+  OpAdd, +OpAnd, +OpXor, +OpOr, +
+  OpMask, +OpSrcCopy, +OpDstCopy, +OpSub, +
+  OpSrcBlend, +OpScreen +
+ }
enum  InterpolationMethod {
+  IM_NEAREST_NEIGHBOUR = 1, +IM_BILINEAR = 2, +IM_BSPLINE = 3, +IM_BICUBIC = 4, +
+  IM_BICUBIC2 = 5, +IM_LANCZOS = 6, +IM_BOX = 7, +IM_HERMITE = 8, +
+  IM_HAMMING = 9, +IM_SINC = 10, +IM_BLACKMAN = 11, +IM_BESSEL = 12, +
+  IM_GAUSSIAN = 13, +IM_QUADRATIC = 14, +IM_MITCHELL = 15, +IM_CATROM = 16 +
+ }
enum  OverflowMethod {
+  OM_COLOR = 1, +OM_BACKGROUND = 2, +OM_TRANSPARENT = 3, +OM_WRAP = 4, +
+  OM_REPEAT = 5, +OM_MIRROR = 6 +
+ }

Public Member Functions

void AlphaClear ()
bool AlphaCopy (CxImage &from)
void AlphaCreate ()
void AlphaDelete ()
bool AlphaFlip ()
BYTE AlphaGet (const long x, const long y)
BYTE AlphaGetMax () const
BYTE * AlphaGetPointer (const long x=0, const long y=0)
void AlphaInvert ()
bool AlphaIsValid ()
bool AlphaMirror ()
void AlphaPaletteClear ()
void AlphaPaletteEnable (bool enable=true)
bool AlphaPaletteIsEnabled ()
bool AlphaPaletteIsValid ()
bool AlphaPaletteSplit (CxImage *dest)
void AlphaSet (const long x, const long y, const BYTE level)
bool AlphaSet (CxImage &from)
void AlphaSet (BYTE level)
void AlphaSetMax (BYTE nAlphaMax)
bool AlphaSplit (CxImage *dest)
void AlphaStrip ()
void BlendPalette (COLORREF cr, long perc)
void BlendPixelColor (long x, long y, RGBQUAD c, float blend, bool bSetAlpha=false)
bool CircleTransform (int type, long rmax=0, float Koeff=1.0f)
void Clear (BYTE bval=0)
bool Colorize (BYTE hue, BYTE sat, float blend=1.0f)
bool Combine (CxImage *r, CxImage *g, CxImage *b, CxImage *a, long colorspace=0)
bool Contour ()
void Copy (const CxImage &src, bool copypixels=true, bool copyselection=true, bool copyalpha=true)
HANDLE CopyToHandle ()
void * Create (DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype=0)
bool CreateFromArray (BYTE *pArray, DWORD dwWidth, DWORD dwHeight, DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage)
bool CreateFromHANDLE (HANDLE hMem)
bool CreateFromHBITMAP (HBITMAP hbmp, HPALETTE hpal=0)
bool CreateFromHICON (HICON hico)
bool CreateFromMatrix (BYTE **ppMatrix, DWORD dwWidth, DWORD dwHeight, DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage)
bool Crop (const RECT &rect, CxImage *iDst=NULL)
bool Crop (long left, long top, long right, long bottom, CxImage *iDst=NULL)
bool CropRotatedRectangle (long topx, long topy, long width, long height, float angle, CxImage *iDst=NULL)
 CxImage (BYTE *buffer, DWORD size, DWORD imagetype)
 CxImage (CxFile *stream, DWORD imagetype)
 CxImage (FILE *stream, DWORD imagetype)
 CxImage (const TCHAR *filename, DWORD imagetype)
 CxImage (const CxImage &src, bool copypixels=true, bool copyselection=true, bool copyalpha=true)
 CxImage (DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype=0)
 CxImage (DWORD imagetype=0)
bool Decode (BYTE *buffer, DWORD size, DWORD imagetype)
bool Decode (CxFile *hFile, DWORD imagetype)
bool Decode (FILE *hFile, DWORD imagetype)
bool DecreaseBpp (DWORD nbit, bool errordiffusion, RGBQUAD *ppal=0, DWORD clrimportant=0)
bool Destroy ()
bool Dilate (long Ksize=2)
bool Dither (long method=0)
long Draw (HDC hdc, const RECT &rect, RECT *pClipRect=NULL, bool bSmooth=false)
long Draw (HDC hdc, long x=0, long y=0, long cx=-1, long cy=-1, RECT *pClipRect=0, bool bSmooth=false)
long Draw2 (HDC hdc, const RECT &rect)
long Draw2 (HDC hdc, long x=0, long y=0, long cx=-1, long cy=-1)
void DrawLine (int StartX, int EndX, int StartY, int EndY, COLORREF cr)
void DrawLine (int StartX, int EndX, int StartY, int EndY, RGBQUAD color, bool bSetAlpha=false)
long DrawString (HDC hdc, long x, long y, const TCHAR *text, RGBQUAD color, const TCHAR *font, long lSize=0, long lWeight=400, BYTE bItalic=0, BYTE bUnderline=0, bool bSetAlpha=false)
long DrawStringEx (HDC hdc, long x, long y, CXTEXTINFO *pTextType, bool bSetAlpha=false)
bool Edge (long Ksize=2)
void Enable (bool enable=true)
bool Encode (BYTE *&buffer, long &size, DWORD imagetype)
bool Encode (FILE *hFile, CxImage **pImages, int pagecount, DWORD imagetype)
bool Encode (CxFile *hFile, CxImage **pImages, int pagecount, DWORD imagetype)
bool Encode (CxFile *hFile, DWORD imagetype)
bool Encode (FILE *hFile, DWORD imagetype)
bool Encode2RGBA (BYTE *&buffer, long &size)
bool Encode2RGBA (CxFile *hFile)
bool Erode (long Ksize=2)
bool Expand (long newx, long newy, RGBQUAD canvascolor, CxImage *iDst=0)
bool Expand (long left, long top, long right, long bottom, RGBQUAD canvascolor, CxImage *iDst=0)
bool FFT2 (CxImage *srcReal, CxImage *srcImag, CxImage *dstReal, CxImage *dstImag, long direction=1, bool bForceFFT=true, bool bMagnitude=true)
bool Filter (long *kernel, long Ksize, long Kfactor, long Koffset)
bool Flip ()
void FreeMemory (void *memblock)
bool Gamma (float gamma)
RGBQUAD GetAreaColorInterpolated (float const xc, float const yc, float const w, float const h, InterpolationMethod const inMethod, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)
BYTE * GetBits (DWORD row=0)
WORD GetBpp () const
DWORD GetClrImportant () const
DWORD GetCodecOption (DWORD imagetype=0)
BYTE GetColorType ()
void * GetDIB () const
DWORD GetEffWidth () const
long GetEscape () const
DWORD GetFlags () const
long GetFrame () const
DWORD GetFrameDelay () const
DWORD GetHeight () const
BYTE GetJpegQuality () const
BYTE GetJpegScale () const
const char * GetLastError ()
CxImageGetLayer (long position)
BYTE GetNearestIndex (RGBQUAD c)
DWORD GetNumColors () const
long GetNumFrames () const
long GetNumLayers () const
void GetOffset (long *x, long *y)
RGBQUAD * GetPalette () const
bool GetPaletteColor (BYTE i, BYTE *r, BYTE *g, BYTE *b)
RGBQUAD GetPaletteColor (BYTE idx)
DWORD GetPaletteSize ()
CxImageGetParent () const
RGBQUAD GetPixelColor (long x, long y, bool bGetAlpha=true)
RGBQUAD GetPixelColorInterpolated (float x, float y, InterpolationMethod const inMethod=IM_BILINEAR, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)
RGBQUAD GetPixelColorWithOverflow (long x, long y, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)
BYTE GetPixelGray (long x, long y)
BYTE GetPixelIndex (long x, long y)
long GetProgress () const
long GetSize ()
RGBQUAD GetTransColor ()
long GetTransIndex () const
DWORD GetType () const
const TCHAR * GetVersion ()
const float GetVersionNumber ()
DWORD GetWidth () const
long GetXDPI () const
long GetYDPI () const
bool GrayScale ()
long Histogram (long *red, long *green=0, long *blue=0, long *gray=0, long colorspace=0)
bool HistogramEqualize ()
bool HistogramLog ()
bool HistogramNormalize ()
bool HistogramRoot ()
bool HistogramStretch (long method=0)
void HuePalette (float correction=1)
bool IncreaseBpp (DWORD nbit)
void InitTextInfo (CXTEXTINFO *txt)
bool IsEnabled () const
bool IsGrayScale ()
bool IsIndexed () const
bool IsInside (long x, long y)
bool IsSamePalette (CxImage &img, bool bCheckAlpha=true)
bool IsTransparent (long x, long y)
bool IsTransparent () const
bool IsValid () const
bool Jitter (long radius=2)
bool LayerCreate (long position=-1)
bool LayerDelete (long position=-1)
void LayerDeleteAll ()
bool Light (long brightness, long contrast=0)
bool Load (const TCHAR *filename, DWORD imagetype=0)
bool LoadResource (HRSRC hRes, DWORD imagetype, HMODULE hModule=NULL)
bool Lut (BYTE *pLutR, BYTE *pLutG, BYTE *pLutB, BYTE *pLutA=0)
bool Lut (BYTE *pLut)
HBITMAP MakeBitmap (HDC hdc=NULL)
float Mean ()
bool Median (long Ksize=3)
bool Mirror ()
void Mix (CxImage &imgsrc2, ImageOpType op, long lXOffset=0, long lYOffset=0, bool bMixAlpha=false)
void MixFrom (CxImage &imagesrc2, long lXOffset, long lYOffset)
bool Negative ()
bool Noise (long level)
CxImageoperator= (const CxImage &)
void OverflowCoordinates (long &x, long &y, OverflowMethod const ofMethod)
void OverflowCoordinates (float &x, float &y, OverflowMethod const ofMethod)
bool QIShrink (long newx, long newy, CxImage *const iDst=NULL)
bool RedEyeRemove ()
bool Repair (float radius=0.25f, long niterations=1, long colorspace=0)
bool Resample (long newx, long newy, int mode=1, CxImage *iDst=NULL)
bool Resample2 (long newx, long newy, InterpolationMethod const inMethod=IM_BICUBIC2, OverflowMethod const ofMethod=OM_REPEAT, CxImage *const iDst=NULL, bool const disableAveraging=false)
bool Rotate (float angle, CxImage *iDst=NULL)
bool Rotate180 (CxImage *iDst=NULL)
bool Rotate2 (float angle, CxImage *iDst=NULL, InterpolationMethod inMethod=IM_BILINEAR, OverflowMethod ofMethod=OM_BACKGROUND, RGBQUAD *replColor=0, bool const optimizeRightAngles=true, bool const bKeepOriginalSize=false)
bool RotateLeft (CxImage *iDst=NULL)
bool RotateRight (CxImage *iDst=NULL)
bool Save (const TCHAR *filename, DWORD imagetype)
bool SelectionAddColor (RGBQUAD c)
bool SelectionAddEllipse (RECT r)
bool SelectionAddPixel (int x, int y)
bool SelectionAddPolygon (POINT *points, long npoints)
bool SelectionAddRect (RECT r)
bool SelectionClear ()
bool SelectionCopy (CxImage &from)
bool SelectionCreate ()
bool SelectionDelete ()
void SelectionGetBox (RECT &r)
bool SelectionInvert ()
bool SelectionIsInside (long x, long y)
bool SelectionIsValid ()
bool SelectionSplit (CxImage *dest)
bool SelectionToHRGN (HRGN &region)
void SetClrImportant (DWORD ncolors=0)
bool SetCodecOption (DWORD opt, DWORD imagetype=0)
void SetEscape (long i)
void SetFlags (DWORD flags, bool bLockReservedFlags=true)
void SetFrame (long nFrame)
void SetFrameDelay (DWORD d)
void SetGrayPalette ()
void SetJpegQuality (BYTE q)
void SetJpegScale (BYTE q)
void SetOffset (long x, long y)
void SetPalette (rgb_color *rgb, DWORD nColors=256)
void SetPalette (RGBQUAD *pPal, DWORD nColors=256)
void SetPalette (DWORD n, BYTE *r, BYTE *g, BYTE *b)
void SetPaletteColor (BYTE idx, COLORREF cr)
void SetPaletteColor (BYTE idx, RGBQUAD c)
void SetPaletteColor (BYTE idx, BYTE r, BYTE g, BYTE b, BYTE alpha=0)
void SetPixelColor (long x, long y, COLORREF cr)
void SetPixelColor (long x, long y, RGBQUAD c, bool bSetAlpha=false)
void SetPixelIndex (long x, long y, BYTE i)
void SetProgress (long p)
void SetStdPalette ()
void SetTransColor (RGBQUAD rgb)
void SetTransIndex (long idx)
void SetXDPI (long dpi)
void SetYDPI (long dpi)
bool ShiftRGB (long r, long g, long b)
bool Skew (float xgain, float ygain, long xpivot=0, long ypivot=0, bool bEnableInterpolation=false)
bool SplitCMYK (CxImage *c, CxImage *m, CxImage *y, CxImage *k)
bool SplitHSL (CxImage *h, CxImage *s, CxImage *l)
bool SplitRGB (CxImage *r, CxImage *g, CxImage *b)
bool SplitXYZ (CxImage *x, CxImage *y, CxImage *z)
bool SplitYIQ (CxImage *y, CxImage *i, CxImage *q)
bool SplitYUV (CxImage *y, CxImage *u, CxImage *v)
long Stretch (HDC hdc, const RECT &rect, DWORD dwRop=SRCCOPY)
long Stretch (HDC hdc, long xoffset, long yoffset, long xsize, long ysize, DWORD dwRop=SRCCOPY)
void SwapIndex (BYTE idx1, BYTE idx2)
bool Threshold (BYTE level)
bool Thumbnail (long newx, long newy, RGBQUAD canvascolor, CxImage *iDst=0)
long Tile (HDC hdc, RECT *rc)
bool Transfer (CxImage &from)
bool UnsharpMask (float radius=5.0, float amount=0.5, int threshold=0)
virtual ~CxImage ()

Static Public Member Functions

RGBQUAD HSLtoRGB (RGBQUAD lHSLColor)
RGBQUAD HSLtoRGB (COLORREF cHSLColor)
float KernelBessel (const float x)
float KernelBessel_J1 (const float x)
float KernelBessel_Order1 (float x)
float KernelBessel_P1 (const float x)
float KernelBessel_Q1 (const float x)
float KernelBlackman (const float x)
float KernelBox (const float x)
float KernelBSpline (const float x)
float KernelCatrom (const float x)
float KernelCubic (const float t)
float KernelGaussian (const float x)
float KernelGeneralizedCubic (const float t, const float a=-1)
float KernelHamming (const float x)
float KernelHermite (const float x)
float KernelLanczosSinc (const float t, const float r=3)
float KernelLinear (const float t)
float KernelMitchell (const float x)
float KernelQuadratic (const float x)
float KernelSinc (const float x)
COLORREF RGBQUADtoRGB (RGBQUAD c)
RGBQUAD RGBtoHSL (RGBQUAD lRGBColor)
RGBQUAD RGBtoRGBQUAD (COLORREF cr)
RGBQUAD RGBtoXYZ (RGBQUAD lRGBColor)
RGBQUAD RGBtoYIQ (RGBQUAD lRGBColor)
RGBQUAD RGBtoYUV (RGBQUAD lRGBColor)
RGBQUAD XYZtoRGB (RGBQUAD lXYZColor)
RGBQUAD YIQtoRGB (RGBQUAD lYIQColor)
RGBQUAD YUVtoRGB (RGBQUAD lYUVColor)

Protected Member Functions

void AddAveragingCont (RGBQUAD const &color, float const surf, float &rr, float &gg, float &bb, float &aa)
void Bitfield2RGB (BYTE *src, WORD redmask, WORD greenmask, WORD bluemask, BYTE bpp)
BYTE BlindAlphaGet (const long x, const long y)
RGBQUAD BlindGetPixelColor (const long x, const long y)
BYTE BlindGetPixelIndex (const long x, const long y)
void * BlindGetPixelPointer (const long x, const long y)
void blur_line (float *ctable, float *cmatrix, int cmatrix_length, BYTE *cur_col, BYTE *dest_col, int y, long bytes)
void CopyInfo (const CxImage &src)
bool DFT (int dir, long m, double *x1, double *y1, double *x2, double *y2)
bool EncodeSafeCheck (CxFile *hFile)
bool FFT (int dir, int m, double *x, double *y)
int gen_convolve_matrix (float radius, float **cmatrix_p)
float * gen_lookup_table (float *cmatrix, int cmatrix_length)
void Ghost (CxImage *src)
bool IsPowerof2 (long x)
bool RepairChannel (CxImage *ch, float radius)
void RGBtoBGR (BYTE *buffer, int length)
void Startup (DWORD imagetype=0)

Static Protected Member Functions

int CompareColors (const void *elem1, const void *elem2)
float HueToRGB (float n1, float n2, float hue)

Protected Attributes

BITMAPINFOHEADER head
CXIMAGEINFO info
BYTE * pAlpha
void * pDib
CxImage ** pLayers
BYTE * pSelection

Private Types

typedef CxImage::tagCxImageInfo CXIMAGEINFO
+


Member Typedef Documentation

+

+ + + + +
+ + + + +
typedef struct CxImage::tagCxImageInfo CxImage::CXIMAGEINFO [private]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
typedef struct CxImage::tagCxTextInfo CxImage::CXTEXTINFO
+
+ + + + + +
+   + + +

+

+


The documentation for this class was generated from the following files: +
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/doxygen.css b/SlnkDWFImpl/CxImage/doc/doxy/html/doxygen.css new file mode 100644 index 0000000..b07d856 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/doxygen.css @@ -0,0 +1,216 @@ +H1 { + text-align: center; + font-family: Geneva, Arial, Helvetica, sans-serif; +} +H2 { + font-family: Geneva, Arial, Helvetica, sans-serif; +} +CAPTION { font-weight: bold } +DIV.qindex { + width: 100%; + background-color: #eeeeff; + border: 1px solid #B0B0B0; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 120%; +} +A.qindex { + text-decoration: none; + font-weight: bold; + color: #1A419D; + padding: 2px; +} +A.qindex:visited { + text-decoration: none; + font-weight: bold; + color: #1A419D + padding: 2px; +} +A.qindex:hover { + text-decoration: none; + background-color: #ddddff; + padding: 2px; +} +A.qindexHL { + text-decoration: none; + font-weight: bold; + background-color: #6666cc; + color: #ffffff; + padding: 2px 6px; + border: 1px double #9295C2; +} +A.qindexHL:hover { + text-decoration: none; + background-color: #6666cc; + color: #ffffff; + padding: 2px 6px; +} +A.qindexHL:visited { text-decoration: none; background-color: #6666cc; color: #ffffff } +A.el { text-decoration: none; font-weight: bold } +A.elRef { font-weight: bold } +A.code { text-decoration: none; font-weight: normal; color: #1A419D} +A.codeRef { font-weight: normal; color: #1A419D} +A:hover { text-decoration: none; background-color: #f2f2ff } +DL.el { margin-left: -1cm } +PRE.fragment { + border: 1px solid #CCCCCC; + background-color: #f5f5f5; + margin-top: 4px; + margin-bottom: 4px; + margin-left: 2px; + margin-right: 8px; + padding-left: 6px; + padding-right: 6px; + padding-top: 4px; + padding-bottom: 4px; +} +DIV.fragment { + border: 1px solid #CCCCCC; + background-color: #f5f5f5; + padding: 6px; +} +DIV.ah { background-color: black; font-weight: bold; color: #ffffff; margin-bottom: 3px; margin-top: 3px } +TD.md { background-color: #F4F4FB; font-weight: bold; } +TD.mdname1 { background-color: #F4F4FB; font-weight: bold; color: #602020; } +TD.mdname { background-color: #F4F4FB; font-weight: bold; color: #602020; width: 600px; } +DIV.groupHeader { + margin-left: 16px; + margin-top: 12px; + margin-bottom: 6px; + font-weight: bold; + font-family: Geneva, Arial, Helvetica, sans-serif; +} +DIV.groupText { margin-left: 16px; font-style: italic; font-size: 14px } +BODY { + background: white; + color: black; + margin-right: 20px; + margin-left: 20px; +} +TD.indexkey { + background-color: #eeeeff; + font-weight: bold; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; +} +TD.indexvalue { + background-color: #eeeeff; + font-style: italic; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; +} +TR.memlist { + background-color: #f0f0f0; +} +P.formulaDsp { text-align: center; } +IMG.formulaDsp { } +IMG.formulaInl { vertical-align: middle; } +SPAN.keyword { color: #008000 } +SPAN.keywordtype { color: #604020 } +SPAN.keywordflow { color: #e08000 } +SPAN.comment { color: #800000 } +SPAN.preprocessor { color: #806020 } +SPAN.stringliteral { color: #002080 } +SPAN.charliteral { color: #008080 } +.mdTable { + border: 1px solid #868686; + background-color: #F4F4FB; +} +.mdRow { + padding: 8px 10px; +} +.mdescLeft { + padding: 0px 8px 4px 8px; + font-size: 14px; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; +} +.mdescRight { + padding: 0px 8px 4px 8px; + font-size: 14px; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; +} +.memItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-style: solid; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-family: Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; +} +.memItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-style: solid; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-family: Geneva, Arial, Helvetica, sans-serif; + font-size: 13px; +} +.search { color: #003399; + font-weight: bold; +} +FORM.search { + margin-bottom: 0px; + margin-top: 0px; +} +INPUT.search { font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #eeeeff; +} +TD.tiny { font-size: 75%; +} +a { + color: #252E78; +} +a:visited { + color: #3D2185; +} diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/doxygen.png b/SlnkDWFImpl/CxImage/doc/doxy/html/doxygen.png new file mode 100644 index 0000000..9da55f9 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/doxygen.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/files.html b/SlnkDWFImpl/CxImage/doc/doxy/html/files.html new file mode 100644 index 0000000..b840217 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/files.html @@ -0,0 +1,47 @@ + + +CxImage: File Index + + + + +

CxImage File List

Here is a list of all files with brief descriptions: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
tif_xfile.cpp
ximabmp.cpp
ximacfg.h
ximadef.h
ximadsp.cpp
ximaenc.cpp
ximaexif.cpp
ximage.cpp
ximage.h
ximagif.cpp
ximahist.cpp
ximaico.cpp
ximainfo.cpp
ximaint.cpp
ximaj2k.cpp
ximajas.cpp
ximajbg.cpp
ximajpg.cpp
ximalpha.cpp
ximalyr.cpp
ximamng.cpp
ximapal.cpp
ximapcx.cpp
ximapng.cpp
ximasel.cpp
ximatga.cpp
ximath.cpp
ximatif.cpp
ximatran.cpp
ximawbmp.cpp
ximawmf.cpp
ximawnd.cpp
xmemfile.cpp
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2blank.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2blank.png new file mode 100644 index 0000000..493c3c0 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2blank.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2doc.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2doc.png new file mode 100644 index 0000000..f72999f Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2doc.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2folderclosed.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2folderclosed.png new file mode 100644 index 0000000..d6d0634 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2folderclosed.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2folderopen.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2folderopen.png new file mode 100644 index 0000000..bbe2c91 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2folderopen.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2lastnode.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2lastnode.png new file mode 100644 index 0000000..e7b9ba9 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2lastnode.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2link.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2link.png new file mode 100644 index 0000000..14f3fed Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2link.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2mlastnode.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2mlastnode.png new file mode 100644 index 0000000..09ceb6a Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2mlastnode.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2mnode.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2mnode.png new file mode 100644 index 0000000..3254c05 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2mnode.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2node.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2node.png new file mode 100644 index 0000000..c9f06a5 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2node.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2plastnode.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2plastnode.png new file mode 100644 index 0000000..0b07e00 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2plastnode.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2pnode.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2pnode.png new file mode 100644 index 0000000..2001b79 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2pnode.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2vertline.png b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2vertline.png new file mode 100644 index 0000000..b330f3a Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/doxy/html/ftv2vertline.png differ diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/functions.html b/SlnkDWFImpl/CxImage/doc/doxy/html/functions.html new file mode 100644 index 0000000..fefca65 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/functions.html @@ -0,0 +1,396 @@ + + +CxImage: Class Members + + + + + +
a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | x | y | ~
+ +

+ +

+Here is a list of all class members with links to the classes they belong to:

- a -

+

- b -

+

- c -

+

- d -

+

- e -

+

- f -

+

- g -

+

- h -

+

- i -

+

- j -

+

- k -

+

- l -

+

- m -

+

- n -

+

- o -

+

- p -

+

- q -

+

- r -

+

- s -

+

- t -

+

- u -

+

- x -

+

- y -

+

- ~ -

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/functions_enum.html b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_enum.html new file mode 100644 index 0000000..8373603 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_enum.html @@ -0,0 +1,20 @@ + + +CxImage: Class Members - Enumerations + + + + + + +

+

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/functions_eval.html b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_eval.html new file mode 100644 index 0000000..fdb09c0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_eval.html @@ -0,0 +1,54 @@ + + +CxImage: Class Members - Enumeration values + + + + + +
i | o
+ +

+ +

+

- i -

+

- o -

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/functions_func.html b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_func.html new file mode 100644 index 0000000..5094413 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_func.html @@ -0,0 +1,310 @@ + + +CxImage: Class Members - Functions + + + + + +
a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | q | r | s | t | u | x | y | ~
+ +

+ +

+

- a -

+

- b -

+

- c -

+

- d -

+

- e -

+

- f -

+

- g -

+

- h -

+

- i -

+

- j -

+

- k -

+

- l -

+

- m -

+

- n -

+

- o -

+

- q -

+

- r -

+

- s -

+

- t -

+

- u -

+

- x -

+

- y -

+

- ~ -

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/functions_type.html b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_type.html new file mode 100644 index 0000000..600870d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_type.html @@ -0,0 +1,19 @@ + + +CxImage: Class Members - Typedefs + + + + + + +

+

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/functions_vars.html b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_vars.html new file mode 100644 index 0000000..da08896 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/functions_vars.html @@ -0,0 +1,97 @@ + + +CxImage: Class Members - Variables + + + + + +
a | b | d | f | g | h | i | l | n | o | p | r | s | t | x | y
+ +

+ +

+

- a -

+

- b -

+

- d -

+

- f -

+

- g -

+

- h -

+

- i -

+

- l -

+

- n -

+

- o -

+

- p -

+

- r -

+

- s -

+

- t -

+

- x -

+

- y -

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/globals.html b/SlnkDWFImpl/CxImage/doc/doxy/html/globals.html new file mode 100644 index 0000000..8799899 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/globals.html @@ -0,0 +1,137 @@ + + +CxImage: File Members + + + + + +
_ | c | d | e | h | k | m | p | r | w
+ +

+ +

+Here is a list of all file members with links to the files they belong to:

- _ -

+

- c -

+

- d -

+

- e -

+

- h -

+

- k -

+

- m -

+

- p -

+

- r -

+

- w -

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/globals_defs.html b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_defs.html new file mode 100644 index 0000000..7ae3710 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_defs.html @@ -0,0 +1,96 @@ + + +CxImage: File Members - Defines + + + + + +
_ | c | d | h | k | m | p | r
+ +

+ +

+

- _ -

+

- c -

+

- d -

+

- h -

+

- k -

+

- m -

+

- p -

+

- r -

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/globals_enum.html b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_enum.html new file mode 100644 index 0000000..259539d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_enum.html @@ -0,0 +1,18 @@ + + +CxImage: File Members - Enumerations + + + + + + +

+

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/globals_eval.html b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_eval.html new file mode 100644 index 0000000..7184ff0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_eval.html @@ -0,0 +1,34 @@ + + +CxImage: File Members - Enumeration values + + + + + + +

+

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/globals_func.html b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_func.html new file mode 100644 index 0000000..80e1416 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_func.html @@ -0,0 +1,34 @@ + + +CxImage: File Members - Functions + + + + + + +

+

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/globals_vars.html b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_vars.html new file mode 100644 index 0000000..91f7561 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/globals_vars.html @@ -0,0 +1,19 @@ + + +CxImage: File Members - Variables + + + + + + +

+

+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___alpha.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___alpha.html new file mode 100644 index 0000000..182a93e --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___alpha.html @@ -0,0 +1,706 @@ + + +CxImage: Alpha + + + + +

Alpha

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

void CxImage::AlphaClear ()
bool CxImage::AlphaCopy (CxImage &from)
void CxImage::AlphaCreate ()
void CxImage::AlphaDelete ()
bool CxImage::AlphaFlip ()
BYTE CxImage::AlphaGet (const long x, const long y)
BYTE CxImage::AlphaGetMax () const
BYTE * CxImage::AlphaGetPointer (const long x=0, const long y=0)
void CxImage::AlphaInvert ()
bool CxImage::AlphaIsValid ()
bool CxImage::AlphaMirror ()
void CxImage::AlphaPaletteClear ()
void CxImage::AlphaPaletteEnable (bool enable=true)
bool CxImage::AlphaPaletteIsEnabled ()
bool CxImage::AlphaPaletteIsValid ()
bool CxImage::AlphaPaletteSplit (CxImage *dest)
void CxImage::AlphaSet (const long x, const long y, const BYTE level)
bool CxImage::AlphaSet (CxImage &from)
void CxImage::AlphaSet (BYTE level)
void CxImage::AlphaSetMax (BYTE nAlphaMax)
bool CxImage::AlphaSplit (CxImage *dest)
void CxImage::AlphaStrip ()
+

Function Documentation

+

+ + + + +
+ + + + + + + + +
void CxImage::AlphaClear  )  [inherited]
+
+ + + + + +
+   + + +

+Inverts the alpha channel.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::AlphaCopy CxImage from  )  [inherited]
+
+ + + + + +
+   + + +

+Imports an existing alpa channel from another image with the same width and height.

+

+ + + + +
+ + + + + + + + +
void CxImage::AlphaCreate  )  [inherited]
+
+ + + + + +
+   + + +

+Allocates an empty (opaque) alpha channel.

+

+ + + + +
+ + + + + + + + +
void CxImage::AlphaDelete  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::AlphaFlip  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
BYTE CxImage::AlphaGet const long  x,
const long  y
[inherited]
+
+ + + + + +
+   + + +

+Gets the alpha level for a single pixel

+

+ + + + +
+ + + + + + + + +
BYTE CxImage::AlphaGetMax  )  const [inherited]
+
+ + + + + +
+   + + +

+

See also:
AlphaSetMax
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
BYTE * CxImage::AlphaGetPointer const long  x = 0,
const long  y = 0
[inherited]
+
+ + + + + +
+   + + +

+Returns pointer to alpha data for pixel (x,y).

+

Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + +
void CxImage::AlphaInvert  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::AlphaIsValid  )  [inherited]
+
+ + + + + +
+   + + +

+Checks if the image has a valid alpha channel.

+

+ + + + +
+ + + + + + + + +
bool CxImage::AlphaMirror  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
void CxImage::AlphaPaletteClear  )  [inherited]
+
+ + + + + +
+   + + +

+Resets the alpha palette

+

+ + + + +
+ + + + + + + + + +
void CxImage::AlphaPaletteEnable bool  enable = true  )  [inherited]
+
+ + + + + +
+   + + +

+Enables the alpha palette, so the Draw() function changes its behavior.

+

+ + + + +
+ + + + + + + + +
bool CxImage::AlphaPaletteIsEnabled  )  [inherited]
+
+ + + + + +
+   + + +

+True if the alpha palette is enabled for painting.

+

+ + + + +
+ + + + + + + + +
bool CxImage::AlphaPaletteIsValid  )  [inherited]
+
+ + + + + +
+   + + +

+Checks if the image has a valid alpha palette.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::AlphaPaletteSplit CxImage dest  )  [inherited]
+
+ + + + + +
+   + + +

+Exports the alpha palette channel in a 8bpp grayscale image.

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::AlphaSet const long  x,
const long  y,
const BYTE  level
[inherited]
+
+ + + + + +
+   + + +

+Sets the alpha level for a single pixel

+

+ + + + +
+ + + + + + + + + +
bool CxImage::AlphaSet CxImage from  )  [inherited]
+
+ + + + + +
+   + + +

+Creates the alpha channel from a gray scale image.

+

+ + + + +
+ + + + + + + + + +
void CxImage::AlphaSet BYTE  level  )  [inherited]
+
+ + + + + +
+   + + +

+Sets the alpha level for the whole image

+

+ + + + +
+ + + + + + + + + +
void CxImage::AlphaSetMax BYTE  nAlphaMax  )  [inherited]
+
+ + + + + +
+   + + +

+Sets global Alpha (opacity) value applied to the whole image, valid only for painting functions.

Parameters:
+ + +
nAlphaMax: can be from 0 to 255
+
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::AlphaSplit CxImage dest  )  [inherited]
+
+ + + + + +
+   + + +

+Exports the alpha channel in a 8bpp grayscale image.

+

+ + + + +
+ + + + + + + + +
void CxImage::AlphaStrip  )  [inherited]
+
+ + + + + +
+   + + +

+Blends the alpha channel and the alpha palette with the pixels. The result is a 24 bit image. The background color can be selected using SetTransColor().

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___attributes.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___attributes.html new file mode 100644 index 0000000..a56ac3a --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___attributes.html @@ -0,0 +1,1468 @@ + + +CxImage: Attributes + + + + +

Attributes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

void CxImage::Enable (bool enable=true)
BYTE * CxImage::GetBits (DWORD row=0)
WORD CxImage::GetBpp () const
DWORD CxImage::GetClrImportant () const
DWORD CxImage::GetCodecOption (DWORD imagetype=0)
BYTE CxImage::GetColorType ()
void * CxImage::GetDIB () const
DWORD CxImage::GetEffWidth () const
long CxImage::GetEscape () const
DWORD CxImage::GetFlags () const
long CxImage::GetFrame () const
DWORD CxImage::GetFrameDelay () const
DWORD CxImage::GetHeight () const
BYTE CxImage::GetJpegQuality () const
BYTE CxImage::GetJpegScale () const
const char * CxImage::GetLastError ()
DWORD CxImage::GetNumColors () const
long CxImage::GetNumFrames () const
void CxImage::GetOffset (long *x, long *y)
long CxImage::GetProgress () const
long CxImage::GetSize ()
RGBQUAD CxImage::GetTransColor ()
long CxImage::GetTransIndex () const
DWORD CxImage::GetType () const
const TCHAR * CxImage::GetVersion ()
const float CxImage::GetVersionNumber ()
DWORD CxImage::GetWidth () const
long CxImage::GetXDPI () const
long CxImage::GetYDPI () const
bool CxImage::IsEnabled () const
bool CxImage::IsTransparent () const
bool CxImage::IsValid () const
void CxImage::SetClrImportant (DWORD ncolors=0)
bool CxImage::SetCodecOption (DWORD opt, DWORD imagetype=0)
void CxImage::SetEscape (long i)
void CxImage::SetFlags (DWORD flags, bool bLockReservedFlags=true)
void CxImage::SetFrame (long nFrame)
void CxImage::SetFrameDelay (DWORD d)
void CxImage::SetJpegQuality (BYTE q)
void CxImage::SetJpegScale (BYTE q)
void CxImage::SetOffset (long x, long y)
void CxImage::SetProgress (long p)
void CxImage::SetTransColor (RGBQUAD rgb)
void CxImage::SetTransIndex (long idx)
void CxImage::SetXDPI (long dpi)
void CxImage::SetYDPI (long dpi)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + +
void CxImage::Enable bool  enable = true  )  [inherited]
+
+ + + + + +
+   + + +

+Enables/disables the image.

+

+ + + + +
+ + + + + + + + + +
BYTE * CxImage::GetBits DWORD  row = 0  )  [inherited]
+
+ + + + + +
+   + + +

+

Returns:
pointer to the image pixels. USE CAREFULLY
+
+

+ + + + +
+ + + + + + + + +
WORD CxImage::GetBpp  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
: 1, 4, 8, 24.
+
+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetClrImportant  )  const [inherited]
+
+ + + + + +
+   + + +

+

See also:
SetClrImportant
+
+

+ + + + +
+ + + + + + + + + +
DWORD CxImage::GetCodecOption DWORD  imagetype = 0  )  [inherited]
+
+ + + + + +
+   + + +

+

See also:
SetCodecOption
+
+

+ + + + +
+ + + + + + + + +
BYTE CxImage::GetColorType  )  [inherited]
+
+ + + + + +
+   + + +

+

Returns:
1 = indexed, 2 = RGB, 4 = RGBA
+
+

+ + + + +
+ + + + + + + + +
void * CxImage::GetDIB  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
internal hDib object..
+
+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetEffWidth  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
DWORD aligned width of the image.
+
+

+ + + + +
+ + + + + + + + +
long CxImage::GetEscape  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
the escape code.
+
See also:
SetEscape
+
+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetFlags  )  const [inherited]
+
+ + + + + +
+   + + +

+

See also:
SetFlags
+
+

+ + + + +
+ + + + + + + + +
long CxImage::GetFrame  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
the current selected image (zero-based index).
+
+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetFrameDelay  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
current frame delay in milliseconds. Only for GIF and MNG formats.
+
+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetHeight  )  const [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
BYTE CxImage::GetJpegQuality  )  const [inherited]
+
+ + + + + +
+   + + +

+

See also:
SetJpegQuality
+
+

+ + + + +
+ + + + + + + + +
BYTE CxImage::GetJpegScale  )  const [inherited]
+
+ + + + + +
+   + + +

+

See also:
SetJpegScale
+
+

+ + + + +
+ + + + + + + + +
const char * CxImage::GetLastError  )  [inherited]
+
+ + + + + +
+   + + +

+Returns the last reported error.

+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetNumColors  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
2, 16, 256; 0 for RGB images.
+
+

+ + + + +
+ + + + + + + + +
long CxImage::GetNumFrames  )  const [inherited]
+
+ + + + + +
+   + + +

+This function must be used after a Decode() / Load() call. Use the sequence SetFrame(-1); Load(...); GetNumFrames(); to get the number of images without loading the first image.

Returns:
the number of images in the file.
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::GetOffset long *  x,
long *  y
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
long CxImage::GetProgress  )  const [inherited]
+
+ + + + + +
+   + + +

+Used to monitor the slow loops.

Returns:
value is from 0 to 100.
+
See also:
SetProgress
+
+

+ + + + +
+ + + + + + + + +
long CxImage::GetSize  )  [inherited]
+
+ + + + + +
+   + + +

+

Returns:
the size in bytes of the internal pDib object
+
+

+ + + + +
+ + + + + + + + +
RGBQUAD CxImage::GetTransColor  )  [inherited]
+
+ + + + + +
+   + + +

+

Returns:
the color used for transparency, and/or for background color
+
+

+ + + + +
+ + + + + + + + +
long CxImage::GetTransIndex  )  const [inherited]
+
+ + + + + +
+   + + +

+Gets the index used for transparency. Returns -1 for no transparancy.

+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetType  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
original image format
+
See also:
ENUM_CXIMAGE_FORMATS.
+
+

+ + + + +
+ + + + + + + + +
const TCHAR * CxImage::GetVersion  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
const float CxImage::GetVersionNumber  )  [inherited]
+
+ + + + + +
+   + + +

+

Returns:
A.BBCCCDDDD
    +
  • A = main version
  • BB = main revision
  • CCC = minor revision (letter)
  • DDDD = experimental revision
+
+
+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetWidth  )  const [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
long CxImage::GetXDPI  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
Resolution for TIFF, JPEG, PNG and BMP formats.
+
+

+ + + + +
+ + + + + + + + +
long CxImage::GetYDPI  )  const [inherited]
+
+ + + + + +
+   + + +

+

Returns:
Resolution for TIFF, JPEG, PNG and BMP formats.
+
+

+ + + + +
+ + + + + + + + +
bool CxImage::IsEnabled  )  const [inherited]
+
+ + + + + +
+   + + +

+True if the image is enabled for painting.

+

+ + + + +
+ + + + + + + + +
bool CxImage::IsTransparent  )  const [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::IsValid  )  const [inherited]
+
+ + + + + +
+   + + +

+Checks if the image is correctly initializated.

+

+ + + + +
+ + + + + + + + + +
void CxImage::SetClrImportant DWORD  ncolors = 0  )  [inherited]
+
+ + + + + +
+   + + +

+sets the maximum number of colors that some functions like DecreaseBpp() or GetNearestIndex() will use on indexed images

Parameters:
+ + +
ncolors should be less than 2^bpp, or 0 if all the colors are important.
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::SetCodecOption DWORD  opt,
DWORD  imagetype = 0
[inherited]
+
+ + + + + +
+   + + +

+Encode option for GIF, TIF and JPG.

    +
  • GIF : 0 = LZW (default), 1 = none, 2 = RLE.
  • TIF : 0 = automatic (default), or a valid compression code as defined in "tiff.h" (COMPRESSION_NONE = 1, COMPRESSION_CCITTRLE = 2, ...)
  • JPG : valid values stored in enum CODEC_OPTION ( ENCODE_BASELINE = 0x01, ENCODE_PROGRESSIVE = 0x10, ...)
+

+

Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::SetEscape long  i  )  [inherited]
+
+ + + + + +
+   + + +

+Used to quit the slow loops or the codecs.

    +
  • SetEscape(-1) before Decode forces the function to exit, right after the image width and height are available ( for bmp, jpg, gif, tif )
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::SetFlags DWORD  flags,
bool  bLockReservedFlags = true
[inherited]
+
+ + + + + +
+   + + +

+Image flags, for future use

Parameters:
+ + + +
flags 
    +
  • 0x??00000 = reserved for 16 bit, CMYK, multilayer
  • 0x00??0000 = blend modes
  • 0x0000???? = layer id or user flags
+
bLockReservedFlags protects the "reserved" and "blend modes" flags
+
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::SetFrame long  nFrame  )  [inherited]
+
+ + + + + +
+   + + +

+Sets the image number that the next Decode() / Load() call will load

+

+ + + + +
+ + + + + + + + + +
void CxImage::SetFrameDelay DWORD  d  )  [inherited]
+
+ + + + + +
+   + + +

+Sets current frame delay. Only for GIF format.

Parameters:
+ + +
d = delay in milliseconds
+
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::SetJpegQuality BYTE  q  )  [inherited]
+
+ + + + + +
+   + + +

+quality level for JPEG and JPEG2000

Parameters:
+ + +
q: can be from 0 to 100
+
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::SetJpegScale BYTE  q  )  [inherited]
+
+ + + + + +
+   + + +

+scaling down during JPEG decoding valid numbers are 1, 2, 4, 8

Author:
[ignacio]
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::SetOffset long  x,
long  y
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
void CxImage::SetProgress long  p  )  [inherited]
+
+ + + + + +
+   + + +

+Forces the value of the internal progress variable.

Parameters:
+ + +
p should be from 0 to 100.
+
+
See also:
GetProgress
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::SetTransColor RGBQUAD  rgb  )  [inherited]
+
+ + + + + +
+   + + +

+Sets the color used for transparency with 24 bpp images. You must call SetTransIndex(0) to enable the effect, SetTransIndex(-1) to disable it.

+

+ + + + +
+ + + + + + + + + +
void CxImage::SetTransIndex long  idx  )  [inherited]
+
+ + + + + +
+   + + +

+Sets the index used for transparency with 1, 4 and 8 bpp images. Set to -1 to remove the effect.

+

+ + + + +
+ + + + + + + + + +
void CxImage::SetXDPI long  dpi  )  [inherited]
+
+ + + + + +
+   + + +

+Set resolution for TIFF, JPEG, PNG and BMP formats.

+

+ + + + +
+ + + + + + + + + +
void CxImage::SetYDPI long  dpi  )  [inherited]
+
+ + + + + +
+   + + +

+Set resolution for TIFF, JPEG, PNG and BMP formats.

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___basic_transformations.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___basic_transformations.html new file mode 100644 index 0000000..411b7d9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___basic_transformations.html @@ -0,0 +1,193 @@ + + +CxImage: BasicTransformations + + + + +

BasicTransformations

+ + + + + + + + + + + + + + +

Functions

bool CxImage::Flip ()
bool CxImage::GrayScale ()
bool CxImage::Mirror ()
bool CxImage::Negative ()
bool CxImage::RotateLeft (CxImage *iDst=NULL)
bool CxImage::RotateRight (CxImage *iDst=NULL)
+

Function Documentation

+

+ + + + +
+ + + + + + + + +
bool CxImage::Flip  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::GrayScale  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::Mirror  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::Negative  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
bool CxImage::RotateLeft CxImage iDst = NULL  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
bool CxImage::RotateRight CxImage iDst = NULL  )  [inherited]
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___color_space.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___color_space.html new file mode 100644 index 0000000..d45db5b --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___color_space.html @@ -0,0 +1,659 @@ + + +CxImage: ColorSpace + + + + +

ColorSpace

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

RGBQUAD CxImage::HSLtoRGB (RGBQUAD lHSLColor)
RGBQUAD CxImage::HSLtoRGB (COLORREF cHSLColor)
COLORREF CxImage::RGBQUADtoRGB (RGBQUAD c)
RGBQUAD CxImage::RGBtoHSL (RGBQUAD lRGBColor)
RGBQUAD CxImage::RGBtoRGBQUAD (COLORREF cr)
RGBQUAD CxImage::RGBtoXYZ (RGBQUAD lRGBColor)
RGBQUAD CxImage::RGBtoYIQ (RGBQUAD lRGBColor)
RGBQUAD CxImage::RGBtoYUV (RGBQUAD lRGBColor)
bool CxImage::SplitCMYK (CxImage *c, CxImage *m, CxImage *y, CxImage *k)
bool CxImage::SplitHSL (CxImage *h, CxImage *s, CxImage *l)
bool CxImage::SplitRGB (CxImage *r, CxImage *g, CxImage *b)
bool CxImage::SplitXYZ (CxImage *x, CxImage *y, CxImage *z)
bool CxImage::SplitYIQ (CxImage *y, CxImage *i, CxImage *q)
bool CxImage::SplitYUV (CxImage *y, CxImage *u, CxImage *v)
RGBQUAD CxImage::XYZtoRGB (RGBQUAD lXYZColor)
RGBQUAD CxImage::YIQtoRGB (RGBQUAD lYIQColor)
RGBQUAD CxImage::YUVtoRGB (RGBQUAD lYUVColor)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::HSLtoRGB RGBQUAD  lHSLColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::HSLtoRGB COLORREF  cHSLColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
COLORREF CxImage::RGBQUADtoRGB RGBQUAD  c  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::RGBtoHSL RGBQUAD  lRGBColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::RGBtoRGBQUAD COLORREF  cr  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::RGBtoXYZ RGBQUAD  lRGBColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::RGBtoYIQ RGBQUAD  lRGBColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::RGBtoYUV RGBQUAD  lRGBColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::SplitCMYK CxImage c,
CxImage m,
CxImage y,
CxImage k
[inherited]
+
+ + + + + +
+   + + +

+Extract CMYK channels from the image. Each channel is an 8 bit grayscale image.

Parameters:
+ + +
c,m,y,k: pointers to CxImage objects, to store the splited channels
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::SplitHSL CxImage h,
CxImage s,
CxImage l
[inherited]
+
+ + + + + +
+   + + +

+Extract HSL channels from the image. Each channel is an 8 bit grayscale image.

Parameters:
+ + +
h,s,l: pointers to CxImage objects, to store the splited channels
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::SplitRGB CxImage r,
CxImage g,
CxImage b
[inherited]
+
+ + + + + +
+   + + +

+Extract RGB channels from the image. Each channel is an 8 bit grayscale image.

Parameters:
+ + +
r,g,b: pointers to CxImage objects, to store the splited channels
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::SplitXYZ CxImage x,
CxImage y,
CxImage z
[inherited]
+
+ + + + + +
+   + + +

+Extract XYZ channels from the image. Each channel is an 8 bit grayscale image.

Parameters:
+ + +
x,y,z: pointers to CxImage objects, to store the splited channels
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::SplitYIQ CxImage y,
CxImage i,
CxImage q
[inherited]
+
+ + + + + +
+   + + +

+Extract YIQ channels from the image. Each channel is an 8 bit grayscale image.

Parameters:
+ + +
y,i,q: pointers to CxImage objects, to store the splited channels
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::SplitYUV CxImage y,
CxImage u,
CxImage v
[inherited]
+
+ + + + + +
+   + + +

+Extract YUV channels from the image. Each channel is an 8 bit grayscale image.

Parameters:
+ + +
y,u,v: pointers to CxImage objects, to store the splited channels
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::XYZtoRGB RGBQUAD  lXYZColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::YIQtoRGB RGBQUAD  lYIQColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::YUVtoRGB RGBQUAD  lYUVColor  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___constructors.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___constructors.html new file mode 100644 index 0000000..7a0d8d7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___constructors.html @@ -0,0 +1,418 @@ + + +CxImage: Constructors + + + + +

Constructors

+ + + + + + + + + + + + + + + + + + + + +

Functions

 CxImage::CxImage (BYTE *buffer, DWORD size, DWORD imagetype)
 CxImage::CxImage (CxFile *stream, DWORD imagetype)
 CxImage::CxImage (FILE *stream, DWORD imagetype)
 CxImage::CxImage (const TCHAR *filename, DWORD imagetype)
 CxImage::CxImage (const CxImage &src, bool copypixels=true, bool copyselection=true, bool copyalpha=true)
 CxImage::CxImage (DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype=0)
 CxImage::CxImage (DWORD imagetype=0)
CxImageCxImage::operator= (const CxImage &)
virtual CxImage::~CxImage ()
+

Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
CxImage::CxImage BYTE *  buffer,
DWORD  size,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Constructor from memory buffer, see Decode()

Parameters:
+ + + + +
buffer: memory buffer
size: size of buffer
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
CxImage::CxImage CxFile *  stream,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Constructor from CxFile object, see Decode()

Parameters:
+ + + +
stream: file handle (implemented using CxMemFile or CxIOFile), with read access.
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
CxImage::CxImage FILE *  stream,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Constructor from file handle, see Decode()

Parameters:
+ + + +
stream: file handle, with read access.
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
CxImage::CxImage const TCHAR *  filename,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Constructor from file name, see Load()

Parameters:
+ + + +
filename: file name
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CxImage::CxImage const CxImage src,
bool  copypixels = true,
bool  copyselection = true,
bool  copyalpha = true
[inherited]
+
+ + + + + +
+   + + +

+image constructor from existing source

Parameters:
+ + + + + +
src: source image.
copypixels: copy the pixels from the source image into the new image.
copyselection: copy the selection from source
copyalpha: copy the alpha channel from source
+
+
See also:
Copy
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CxImage::CxImage DWORD  dwWidth,
DWORD  dwHeight,
DWORD  wBpp,
DWORD  imagetype = 0
[inherited]
+
+ + + + + +
+   + + +

+Sized image constructor

Parameters:
+ + + + + +
dwWidth: width
dwHeight: height
wBpp: bit per pixel, can be 1, 4, 8, 24
imagetype: (optional) set the image format, see ENUM_CXIMAGE_FORMATS
+
+
+

+ + + + +
+ + + + + + + + + +
CxImage::CxImage DWORD  imagetype = 0  )  [inherited]
+
+ + + + + +
+   + + +

+Empty image constructor

Parameters:
+ + +
imagetype: (optional) set the image format, see ENUM_CXIMAGE_FORMATS
+
+
+

+ + + + +
+ + + + + + + + + +
CxImage & CxImage::operator= const CxImage isrc  )  [inherited]
+
+ + + + + +
+   + + +

+

See also:
Copy
+
+

+ + + + +
+ + + + + + + + +
virtual CxImage::~CxImage  )  [inline, virtual, inherited]
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___d_s_p.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___d_s_p.html new file mode 100644 index 0000000..19a46e0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___d_s_p.html @@ -0,0 +1,1339 @@ + + +CxImage: DSP + + + + +

DSP

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Enumerations

enum  CxImage::ImageOpType {
+  CxImage::OpAdd, +CxImage::OpAnd, +CxImage::OpXor, +CxImage::OpOr, +
+  CxImage::OpMask, +CxImage::OpSrcCopy, +CxImage::OpDstCopy, +CxImage::OpSub, +
+  CxImage::OpSrcBlend, +CxImage::OpScreen +
+ }

Functions

bool CxImage::Colorize (BYTE hue, BYTE sat, float blend=1.0f)
bool CxImage::Combine (CxImage *r, CxImage *g, CxImage *b, CxImage *a, long colorspace=0)
bool CxImage::Contour ()
bool CxImage::Dilate (long Ksize=2)
bool CxImage::Edge (long Ksize=2)
bool CxImage::Erode (long Ksize=2)
bool CxImage::FFT2 (CxImage *srcReal, CxImage *srcImag, CxImage *dstReal, CxImage *dstImag, long direction=1, bool bForceFFT=true, bool bMagnitude=true)
bool CxImage::Filter (long *kernel, long Ksize, long Kfactor, long Koffset)
bool CxImage::Gamma (float gamma)
long CxImage::Histogram (long *red, long *green=0, long *blue=0, long *gray=0, long colorspace=0)
bool CxImage::HistogramEqualize ()
bool CxImage::HistogramLog ()
bool CxImage::HistogramNormalize ()
bool CxImage::HistogramRoot ()
bool CxImage::HistogramStretch (long method=0)
void CxImage::HuePalette (float correction=1)
bool CxImage::Jitter (long radius=2)
bool CxImage::Light (long brightness, long contrast=0)
bool CxImage::Lut (BYTE *pLutR, BYTE *pLutG, BYTE *pLutB, BYTE *pLutA=0)
bool CxImage::Lut (BYTE *pLut)
float CxImage::Mean ()
bool CxImage::Median (long Ksize=3)
void CxImage::Mix (CxImage &imgsrc2, ImageOpType op, long lXOffset=0, long lYOffset=0, bool bMixAlpha=false)
void CxImage::MixFrom (CxImage &imagesrc2, long lXOffset, long lYOffset)
bool CxImage::Noise (long level)
bool CxImage::Repair (float radius=0.25f, long niterations=1, long colorspace=0)
bool CxImage::ShiftRGB (long r, long g, long b)
bool CxImage::Threshold (BYTE level)
bool CxImage::UnsharpMask (float radius=5.0, float amount=0.5, int threshold=0)
+

Enumeration Type Documentation

+

+ + + + +
+ + + + +
enum CxImage::ImageOpType [inherited]
+
+ + + + + +
+   + + +

+

Enumeration values:
+ + + + + + + + + + + +
OpAdd  +
OpAnd  +
OpXor  +
OpOr  +
OpMask  +
OpSrcCopy  +
OpDstCopy  +
OpSub  +
OpSrcBlend  +
OpScreen  +
+
+
+


Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Colorize BYTE  hue,
BYTE  sat,
float  blend = 1.0f
[inherited]
+
+ + + + + +
+   + + +

+Replaces the original hue and saturation values.

Parameters:
+ + + + +
hue: hue
sat: saturation
blend: can be from 0 (no effect) to 1 (full effect)
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Combine CxImage r,
CxImage g,
CxImage b,
CxImage a,
long  colorspace = 0
[inherited]
+
+ + + + + +
+   + + +

+Combines different color components into a single image

Parameters:
+ + + + +
r,g,b: color channels
a: alpha layer, can be NULL
colorspace: 0 = RGB, 1 = HSL, 2 = YUV, 3 = YIQ, 4 = XYZ
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + +
bool CxImage::Contour  )  [inherited]
+
+ + + + + +
+   + + +

+Enhance the variations between adjacent pixels. Similar results can be achieved using Filter(), but the algorithms are different both in Edge() and in Contour().

Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Dilate long  Ksize = 2  )  [inherited]
+
+ + + + + +
+   + + +

+Enhance the light areas of the image

Parameters:
+ + +
Ksize: size of the kernel.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Edge long  Ksize = 2  )  [inherited]
+
+ + + + + +
+   + + +

+Enhance the variations between adjacent pixels. Similar results can be achieved using Filter(), but the algorithms are different both in Edge() and in Contour().

Parameters:
+ + +
Ksize: size of the kernel.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Erode long  Ksize = 2  )  [inherited]
+
+ + + + + +
+   + + +

+Enhance the dark areas of the image

Parameters:
+ + +
Ksize: size of the kernel.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::FFT2 CxImage srcReal,
CxImage srcImag,
CxImage dstReal,
CxImage dstImag,
long  direction = 1,
bool  bForceFFT = true,
bool  bMagnitude = true
[inherited]
+
+ + + + + +
+   + + +

+Computes the bidimensional FFT or DFT of the image.

    +
  • The images are processed as grayscale
  • If the dimensions of the image are a power of, 2 the FFT is performed automatically.
  • If dstReal and/or dstImag are NULL, the resulting images replaces the original(s).
  • Note: with 8 bits there is a HUGE loss in the dynamics. The function tries to keep an acceptable SNR, but 8bit = 48dB...
+

+

Parameters:
+ + + + + + +
srcReal,srcImag: source images: One can be NULL, but not both
dstReal,dstImag: destination images. Can be NULL.
direction: 1 = forward, -1 = inverse.
bForceFFT: if true, the images are resampled to make the dimensions a power of 2.
bMagnitude: if true, the real part returns the magnitude, the imaginary part returns the phase
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Filter long *  kernel,
long  Ksize,
long  Kfactor,
long  Koffset
[inherited]
+
+ + + + + +
+   + + +

+2D linear filter

Parameters:
+ + + + + +
kernel: convolving matrix, in row format.
Ksize: size of the kernel.
Kfactor: normalization constant.
Koffset: bias.
 Example: the "soften" filter uses this kernel:
+	1 1 1
+	1 8 1
+	1 1 1
+ the function needs: kernel={1,1,1,1,8,1,1,1,1}; Ksize=3; Kfactor=16; Koffset=0; 
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Gamma float  gamma  )  [inherited]
+
+ + + + + +
+   + + +

+Adjusts the color balance of the image

Parameters:
+ + +
gamma can be from 0.1 to 5.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
long CxImage::Histogram long *  red,
long *  green = 0,
long *  blue = 0,
long *  gray = 0,
long  colorspace = 0
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::HistogramEqualize  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::HistogramLog  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::HistogramNormalize  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
bool CxImage::HistogramRoot  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
bool CxImage::HistogramStretch long  method = 0  )  [inherited]
+
+ + + + + +
+   + + +

+HistogramStretch

Parameters:
+ + +
method: 0 = luminance (default), 1 = linked channels , 2 = independent channels.
+
+
Returns:
true if everything is ok
+
Author:
[dave] and [nipper]
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::HuePalette float  correction = 1  )  [inherited]
+
+ + + + + +
+   + + +

+Generates a "rainbow" palette with saturated colors

Parameters:
+ + +
correction: 1 generates a single hue spectrum. 0.75 is nice for scientific applications.
+
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Jitter long  radius = 2  )  [inherited]
+
+ + + + + +
+   + + +

+Adds a random offset to each pixel in the image

Parameters:
+ + +
radius: maximum pixel displacement
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Light long  brightness,
long  contrast = 0
[inherited]
+
+ + + + + +
+   + + +

+Changes the brightness and the contrast of the image.

Parameters:
+ + + +
brightness: can be from -255 to 255, if brightness is negative, the image becomes dark.
contrast: can be from -100 to 100, the neutral value is 0.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Lut BYTE *  pLutR,
BYTE *  pLutG,
BYTE *  pLutB,
BYTE *  pLutA = 0
[inherited]
+
+ + + + + +
+   + + +

+Apply an indipendent look up table for each channel

Parameters:
+ + +
pLutR,pLutG,pLutB,pLutA: BYTE[256] look up tables
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Lut BYTE *  pLut  )  [inherited]
+
+ + + + + +
+   + + +

+Apply a look up table to the image.

Parameters:
+ + +
pLut: BYTE[256] look up table
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + +
float CxImage::Mean  )  [inherited]
+
+ + + + + +
+   + + +

+

Returns:
mean lightness of the image. Useful with Threshold() and Light()
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Median long  Ksize = 3  )  [inherited]
+
+ + + + + +
+   + + +

+Adjusts the intensity of each pixel to the median intensity of its surrounding pixels.

Parameters:
+ + +
Ksize: size of the kernel.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::Mix CxImage imgsrc2,
ImageOpType  op,
long  lXOffset = 0,
long  lYOffset = 0,
bool  bMixAlpha = false
[inherited]
+
+ + + + + +
+   + + +

+Blends two images

Parameters:
+ + + + + +
imgsrc2: image to be mixed with this
op: blending method; see ImageOpType
lXOffset,lYOffset: image displacement
bMixAlpha: if true and imgsrc2 has a valid alpha layer, it will be mixed in the destination image.
+
+
Returns:
true if everything is ok
+thanks to Mwolski
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::MixFrom CxImage imagesrc2,
long  lXOffset,
long  lYOffset
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
bool CxImage::Noise long  level  )  [inherited]
+
+ + + + + +
+   + + +

+Adds an uniform noise to the image

Parameters:
+ + +
level: can be from 0 (no noise) to 255 (lot of noise).
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Repair float  radius = 0.25f,
long  niterations = 1,
long  colorspace = 0
[inherited]
+
+ + + + + +
+   + + +

+Smart blurring to remove small defects, dithering or artifacts.

Parameters:
+ + + + +
radius: normally between 0.01 and 0.5
niterations: should be trimmed with radius, to avoid blurring should be (radius*niterations)<1
colorspace: 0 = RGB, 1 = HSL, 2 = YUV, 3 = YIQ, 4 = XYZ
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::ShiftRGB long  r,
long  g,
long  b
[inherited]
+
+ + + + + +
+   + + +

+Adjusts separately the red, green, and blue values in the image.

Parameters:
+ + +
r,g,b: can be from -255 to +255.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Threshold BYTE  level  )  [inherited]
+
+ + + + + +
+   + + +

+Converts the image to B&W. The Mean() function can be used for calculating the optimal threshold.

Parameters:
+ + +
level: the lightness threshold.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::UnsharpMask float  radius = 5.0,
float  amount = 0.5,
int  threshold = 0
[inherited]
+
+ + + + + +
+   + + +

+

Author:
[nipper]
+
+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___decode.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___decode.html new file mode 100644 index 0000000..352207a --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___decode.html @@ -0,0 +1,265 @@ + + +CxImage: Decode + + + + +

Decode

+ + + + + + + + + + + + +

Functions

bool CxImage::Decode (BYTE *buffer, DWORD size, DWORD imagetype)
bool CxImage::Decode (CxFile *hFile, DWORD imagetype)
bool CxImage::Decode (FILE *hFile, DWORD imagetype)
bool CxImage::Load (const TCHAR *filename, DWORD imagetype=0)
bool CxImage::LoadResource (HRSRC hRes, DWORD imagetype, HMODULE hModule=NULL)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Decode BYTE *  buffer,
DWORD  size,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Loads an image from memory buffer

Parameters:
+ + + + +
buffer: memory buffer
size: size of buffer
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Decode CxFile *  hFile,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Loads an image from CxFile object

Parameters:
+ + + +
hFile: file handle (implemented using CxMemFile or CxIOFile), with read access.
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
true if everything is ok
+
See also:
ENUM_CXIMAGE_FORMATS
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Decode FILE *  hFile,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Loads an image from file handle.

Parameters:
+ + + +
hFile: file handle, with read access.
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Load const TCHAR *  filename,
DWORD  imagetype = 0
[inherited]
+
+ + + + + +
+   + + +

+Reads from disk the image in a specific format.

    +
  • If decoding fails using the specified image format, the function will try the automatic file format recognition.
+

+

Parameters:
+ + + +
filename: file name
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::LoadResource HRSRC  hRes,
DWORD  imagetype,
HMODULE  hModule = NULL
[inherited]
+
+ + + + + +
+   + + +

+Loads an image from the application resources.

Parameters:
+ + + + +
hRes: the resource handle returned by FindResource().
imagetype: file format, see ENUM_CXIMAGE_FORMATS.
hModule: NULL for internal resource, or external application/DLL hinstance returned by LoadLibray.
+
+
Returns:
true if everything is ok
+
+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___encode.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___encode.html new file mode 100644 index 0000000..1ab78cb --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___encode.html @@ -0,0 +1,411 @@ + + +CxImage: Encode + + + + +

Encode

+ + + + + + + + + + + + + + + + + + +

Functions

bool CxImage::Encode (BYTE *&buffer, long &size, DWORD imagetype)
bool CxImage::Encode (FILE *hFile, CxImage **pImages, int pagecount, DWORD imagetype)
bool CxImage::Encode (CxFile *hFile, CxImage **pImages, int pagecount, DWORD imagetype)
bool CxImage::Encode (CxFile *hFile, DWORD imagetype)
bool CxImage::Encode (FILE *hFile, DWORD imagetype)
bool CxImage::Encode2RGBA (BYTE *&buffer, long &size)
bool CxImage::Encode2RGBA (CxFile *hFile)
bool CxImage::Save (const TCHAR *filename, DWORD imagetype)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Encode BYTE *&  buffer,
long &  size,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Saves to memory buffer the image in a specific format.

Parameters:
+ + + + +
buffer: output memory buffer pointer. Must be NULL, the function allocates and fill the memory, the application must free the buffer, see also FreeMemory().
size: output memory buffer size.
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Encode FILE *  hFile,
CxImage **  pImages,
int  pagecount,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Saves to disk or memory pagecount images, referenced by an array of CxImage pointers.

Parameters:
+ + + + + +
hFile: file handle.
pImages: array of CxImage pointers.
pagecount: number of images.
imagetype: can be CXIMAGE_FORMAT_TIF or CXIMAGE_FORMAT_GIF.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Encode CxFile *  hFile,
CxImage **  pImages,
int  pagecount,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Saves to disk or memory pagecount images, referenced by an array of CxImage pointers.

Parameters:
+ + + + + +
hFile: file handle (implemented using CxMemFile or CxIOFile).
pImages: array of CxImage pointers.
pagecount: number of images.
imagetype: can be CXIMAGE_FORMAT_TIF or CXIMAGE_FORMAT_GIF.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Encode CxFile *  hFile,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Saves to disk the image in a specific format.

Parameters:
+ + + +
hFile: file handle (implemented using CxMemFile or CxIOFile), open and enabled for writing.
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
true if everything is ok
+
See also:
ENUM_CXIMAGE_FORMATS
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Encode FILE *  hFile,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Saves to disk the image in a specific format.

Parameters:
+ + + +
hFile: file handle, open and enabled for writing.
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Encode2RGBA BYTE *&  buffer,
long &  size
[inherited]
+
+ + + + + +
+   + + +

+exports the image into a RGBA buffer, Useful for OpenGL applications.

Parameters:
+ + + +
buffer: output memory buffer pointer. Must be NULL, the function allocates and fill the memory, the application must free the buffer, see also FreeMemory().
size: output memory buffer size.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::Encode2RGBA CxFile *  hFile  )  [inherited]
+
+ + + + + +
+   + + +

+exports the image into a RGBA buffer, Useful for OpenGL applications.

Parameters:
+ + +
hFile: file handle (implemented using CxMemFile or CxIOFile).
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Save const TCHAR *  filename,
DWORD  imagetype
[inherited]
+
+ + + + + +
+   + + +

+Saves to disk the image in a specific format.

Parameters:
+ + + +
filename: file name
imagetype: file format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
true if everything is ok
+
+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___initialization.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___initialization.html new file mode 100644 index 0000000..2c7799a --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___initialization.html @@ -0,0 +1,400 @@ + + +CxImage: Initialization + + + + +

Initialization

+ + + + + + + + + + + + + + + + + + +

Functions

void CxImage::Clear (BYTE bval=0)
void CxImage::Copy (const CxImage &src, bool copypixels=true, bool copyselection=true, bool copyalpha=true)
void * CxImage::Create (DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype=0)
bool CxImage::CreateFromArray (BYTE *pArray, DWORD dwWidth, DWORD dwHeight, DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage)
bool CxImage::CreateFromMatrix (BYTE **ppMatrix, DWORD dwWidth, DWORD dwHeight, DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage)
bool CxImage::Destroy ()
void CxImage::FreeMemory (void *memblock)
bool CxImage::Transfer (CxImage &from)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + +
void CxImage::Clear BYTE  bval = 0  )  [inherited]
+
+ + + + + +
+   + + +

+Sets the image bits to the specified value

    +
  • for indexed images, the output color is set by the palette entries.
  • for RGB images, the output color is a shade of gray.
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::Copy const CxImage src,
bool  copypixels = true,
bool  copyselection = true,
bool  copyalpha = true
[inherited]
+
+ + + + + +
+   + + +

+Copies the image from an exsisting source

Parameters:
+ + + + + +
src: source image.
copypixels: copy the pixels from the source image into the new image.
copyselection: copy the selection from source
copyalpha: copy the alpha channel from source
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void * CxImage::Create DWORD  dwWidth,
DWORD  dwHeight,
DWORD  wBpp,
DWORD  imagetype = 0
[inherited]
+
+ + + + + +
+   + + +

+Initializes or rebuilds the image.

Parameters:
+ + + + + +
dwWidth: width
dwHeight: height
wBpp: bit per pixel, can be 1, 4, 8, 24
imagetype: (optional) set the image format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
pointer to the internal pDib object; NULL if an error occurs.
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::CreateFromArray BYTE *  pArray,
DWORD  dwWidth,
DWORD  dwHeight,
DWORD  dwBitsperpixel,
DWORD  dwBytesperline,
bool  bFlipImage
[inherited]
+
+ + + + + +
+   + + +

+Creates an image from a generic buffer

Parameters:
+ + + + + + + +
pArray: source memory buffer
dwWidth: image width
dwHeight: image height
dwBitsperpixel: can be 1,4,8,24,32
dwBytesperline: line alignment, in bytes, for a single row stored in pArray
bFlipImage: tune this parameter if the image is upsidedown
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::CreateFromMatrix BYTE **  ppMatrix,
DWORD  dwWidth,
DWORD  dwHeight,
DWORD  dwBitsperpixel,
DWORD  dwBytesperline,
bool  bFlipImage
[inherited]
+
+ + + + + +
+   + + +

+

See also:
CreateFromArray
+
+

+ + + + +
+ + + + + + + + +
bool CxImage::Destroy  )  [inherited]
+
+ + + + + +
+   + + +

+Call this function to destroy image pixels, alpha channel, selection and sub layers.

    +
  • Attributes are not erased, but IsValid returns false.
+

+

Returns:
true if everything is freed, false if the image is a Ghost
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::FreeMemory void *  memblock  )  [inherited]
+
+ + + + + +
+   + + +

+simply calls "if (memblock) free(memblock);". Useful when calling Encode for a memory buffer, from a DLL compiled with different memory management options. CxImage::FreeMemory will use the same memory environment used by Encode.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::Transfer CxImage from  )  [inherited]
+
+ + + + + +
+   + + +

+Transfers the image from an existing source image. The source becomes empty.

Returns:
true if everything is ok
+
+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___initializzation.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___initializzation.html new file mode 100644 index 0000000..5acfe2d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___initializzation.html @@ -0,0 +1,400 @@ + + +CxImage: Initializzation + + + + +

Initializzation

+ + + + + + + + + + + + + + + + + + +

Functions

void CxImage::Clear (BYTE bval=0)
void CxImage::Copy (const CxImage &src, bool copypixels=true, bool copyselection=true, bool copyalpha=true)
void * CxImage::Create (DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype=0)
bool CxImage::CreateFromArray (BYTE *pArray, DWORD dwWidth, DWORD dwHeight, DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage)
bool CxImage::CreateFromMatrix (BYTE **ppMatrix, DWORD dwWidth, DWORD dwHeight, DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage)
bool CxImage::Destroy ()
void CxImage::FreeMemory (void *memblock)
bool CxImage::Transfer (CxImage &from)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + +
void CxImage::Clear BYTE  bval = 0  )  [inherited]
+
+ + + + + +
+   + + +

+Sets the image bits to the specified value

    +
  • for indexed images, the output color is set by the palette entries.
  • for RGB images, the output color is a shade of gray.
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::Copy const CxImage src,
bool  copypixels = true,
bool  copyselection = true,
bool  copyalpha = true
[inherited]
+
+ + + + + +
+   + + +

+Copies the image from an exsisting source

Parameters:
+ + + + + +
src: source image.
copypixels: copy the pixels from the source image into the new image.
copyselection: copy the selection from source
copyalpha: copy the alpha channel from source
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void * CxImage::Create DWORD  dwWidth,
DWORD  dwHeight,
DWORD  wBpp,
DWORD  imagetype = 0
[inherited]
+
+ + + + + +
+   + + +

+Initializes or rebuilds the image.

Parameters:
+ + + + + +
dwWidth: width
dwHeight: height
wBpp: bit per pixel, can be 1, 4, 8, 24
imagetype: (optional) set the image format, see ENUM_CXIMAGE_FORMATS
+
+
Returns:
pointer to the internal pDib object; NULL if an error occurs.
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::CreateFromArray BYTE *  pArray,
DWORD  dwWidth,
DWORD  dwHeight,
DWORD  dwBitsperpixel,
DWORD  dwBytesperline,
bool  bFlipImage
[inherited]
+
+ + + + + +
+   + + +

+Creates an image from a generic buffer

Parameters:
+ + + + + + + +
pArray: source memory buffer
dwWidth: image width
dwHeight: image height
dwBitsperpixel: can be 1,4,8,24,32
dwBytesperline: line alignment, in bytes, for a single row stored in pArray
bFlipImage: tune this parameter if the image is upsidedown
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::CreateFromMatrix BYTE **  ppMatrix,
DWORD  dwWidth,
DWORD  dwHeight,
DWORD  dwBitsperpixel,
DWORD  dwBytesperline,
bool  bFlipImage
[inherited]
+
+ + + + + +
+   + + +

+

See also:
CreateFromArray
+
+

+ + + + +
+ + + + + + + + +
bool CxImage::Destroy  )  [inherited]
+
+ + + + + +
+   + + +

+Call this function to destroy image pixels, alpha channel, selection and sub layers.

    +
  • Attributes are not erased, but IsValid returns false.
+

+

Returns:
true if everything is freed, false if the image is a Ghost
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::FreeMemory void *  memblock  )  [inherited]
+
+ + + + + +
+   + + +

+simply calls "if (memblock) free(memblock);". Useful when calling Encode for a memory buffer, from a DLL compiled with different memory management options. CxImage::FreeMemory will use the same memory environment used by Encode.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::Transfer CxImage from  )  [inherited]
+
+ + + + + +
+   + + +

+Transfers the image from an existing source image. The source becomes empty.

Returns:
true if everything is ok
+
+


Generated on Sun Oct 10 18:22:06 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___interpolation.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___interpolation.html new file mode 100644 index 0000000..38929fa --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___interpolation.html @@ -0,0 +1,464 @@ + + +CxImage: Interpolation + + + + +

Interpolation

+ + + + + + + + + + + + + + + + + +

Enumerations

enum  CxImage::InterpolationMethod {
+  CxImage::IM_NEAREST_NEIGHBOUR = 1, +CxImage::IM_BILINEAR = 2, +CxImage::IM_BSPLINE = 3, +CxImage::IM_BICUBIC = 4, +
+  CxImage::IM_BICUBIC2 = 5, +CxImage::IM_LANCZOS = 6, +CxImage::IM_BOX = 7, +CxImage::IM_HERMITE = 8, +
+  CxImage::IM_HAMMING = 9, +CxImage::IM_SINC = 10, +CxImage::IM_BLACKMAN = 11, +CxImage::IM_BESSEL = 12, +
+  CxImage::IM_GAUSSIAN = 13, +CxImage::IM_QUADRATIC = 14, +CxImage::IM_MITCHELL = 15, +CxImage::IM_CATROM = 16 +
+ }
enum  CxImage::OverflowMethod {
+  CxImage::OM_COLOR = 1, +CxImage::OM_BACKGROUND = 2, +CxImage::OM_TRANSPARENT = 3, +CxImage::OM_WRAP = 4, +
+  CxImage::OM_REPEAT = 5, +CxImage::OM_MIRROR = 6 +
+ }

Functions

RGBQUAD CxImage::GetAreaColorInterpolated (float const xc, float const yc, float const w, float const h, InterpolationMethod const inMethod, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)
RGBQUAD CxImage::GetPixelColorInterpolated (float x, float y, InterpolationMethod const inMethod=IM_BILINEAR, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)
RGBQUAD CxImage::GetPixelColorWithOverflow (long x, long y, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD *const rplColor=0)
void CxImage::OverflowCoordinates (long &x, long &y, OverflowMethod const ofMethod)
void CxImage::OverflowCoordinates (float &x, float &y, OverflowMethod const ofMethod)
+

Enumeration Type Documentation

+

+ + + + +
+ + + + +
enum CxImage::InterpolationMethod [inherited]
+
+ + + + + +
+   + + +

+

Enumeration values:
+ + + + + + + + + + + + + + + + + +
IM_NEAREST_NEIGHBOUR  +
IM_BILINEAR  +
IM_BSPLINE  +
IM_BICUBIC  +
IM_BICUBIC2  +
IM_LANCZOS  +
IM_BOX  +
IM_HERMITE  +
IM_HAMMING  +
IM_SINC  +
IM_BLACKMAN  +
IM_BESSEL  +
IM_GAUSSIAN  +
IM_QUADRATIC  +
IM_MITCHELL  +
IM_CATROM  +
+
+
+

+ + + + +
+ + + + +
enum CxImage::OverflowMethod [inherited]
+
+ + + + + +
+   + + +

+

Enumeration values:
+ + + + + + + +
OM_COLOR  +
OM_BACKGROUND  +
OM_TRANSPARENT  +
OM_WRAP  +
OM_REPEAT  +
OM_MIRROR  +
+
+
+


Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RGBQUAD CxImage::GetAreaColorInterpolated float const  xc,
float const  yc,
float const  w,
float const  h,
InterpolationMethod const  inMethod,
OverflowMethod const  ofMethod = OM_BACKGROUND,
RGBQUAD *const  rplColor = 0
[inherited]
+
+ + + + + +
+   + + +

+This method is similar to GetPixelColorInterpolated, but this method also properly handles subsampling. If you need to sample original image with interval of more than 1 pixel (as when shrinking an image), you should use this method instead of GetPixelColorInterpolated or aliasing will occur. When area width and height are both less than pixel, this method gets pixel color by interpolating color of frame center with selected (inMethod) interpolation by calling GetPixelColorInterpolated. If width and height are more than 1, method calculates color by averaging color of pixels within area. Interpolation method is not used in this case. Pixel color is interpolated by averaging instead. If only one of both is more than 1, method uses combination of interpolation and averaging. Chosen interpolation method is used, but since it is averaged later on, there is little difference between IM_BILINEAR (perhaps best for this case) and better methods. IM_NEAREST_NEIGHBOUR again leads to aliasing artifacts. This method is a bit slower than GetPixelColorInterpolated and when aliasing is not a problem, you should simply use the later.

+

Parameters:
+ + + + + + +
xc,yc - center of (rectangular) area
w,h - width and height of area
inMethod - interpolation method that is used, when interpolation is used (see above)
ofMethod - overflow method used when retrieving individual pixel colors
rplColor - replacement colour to use, in OM_COLOR
+
+
Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RGBQUAD CxImage::GetPixelColorInterpolated float  x,
float  y,
InterpolationMethod const  inMethod = IM_BILINEAR,
OverflowMethod const  ofMethod = OM_BACKGROUND,
RGBQUAD *const  rplColor = 0
[inherited]
+
+ + + + + +
+   + + +

+This method reconstructs image according to chosen interpolation method and then returns pixel (x,y). (x,y) can lie between actual image pixels. If (x,y) lies outside of image, method returns value according to overflow method. This method is very useful for geometrical image transformations, where destination pixel can often assume color value lying between source pixels.

+

Parameters:
+ + + + + +
(x,y) - coordinates of pixel to return GPCI method recreates "analogue" image back from digital data, so x and y are float values and color value of point (1.1,1) will generally not be same as (1,1). Center of first pixel is at (0,0) and center of pixel right to it is (1,0). (0.5,0) is half way between these two pixels.
inMethod - interpolation (reconstruction) method (kernel) to use:
    +
  • IM_NEAREST_NEIGHBOUR - returns colour of nearest lying pixel (causes stairy look of processed images)
  • IM_BILINEAR - interpolates colour from four neighbouring pixels (softens image a bit)
  • IM_BICUBIC - interpolates from 16 neighbouring pixels (can produce "halo" artifacts)
  • IM_BICUBIC2 - interpolates from 16 neighbouring pixels (perhaps a bit less halo artifacts than IM_BICUBIC)
  • IM_BSPLINE - interpolates from 16 neighbouring pixels (softens image, washes colours) (As far as I know, image should be prefiltered for this method to give good results... some other time :) ) This method uses bicubic interpolation kernel from CXImage 5.99a and older versions.
  • IM_LANCZOS - interpolates from 12*12 pixels (slow, ringing artifacts)
+
ofMethod - overflow method (see comments at GetPixelColorWithOverflow)
rplColor - pointer to color used for out of borders pixels in OM_COLOR mode (and other modes if colour can't calculated in a specified way)
+
+
Returns:
interpolated color value (including interpolated alpha value, if image has alpha layer)
+
Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RGBQUAD CxImage::GetPixelColorWithOverflow long  x,
long  y,
OverflowMethod const  ofMethod = OM_BACKGROUND,
RGBQUAD *const  rplColor = 0
[inherited]
+
+ + + + + +
+   + + +

+Method return pixel color. Different methods are implemented for out of bounds pixels. If an image has alpha channel, alpha value is returned in .RGBReserved.

+

Parameters:
+ + + + +
x,y : pixel coordinates
ofMethod : out-of-bounds method:
    +
  • OF_WRAP - wrap over to pixels on other side of the image
  • OF_REPEAT - repeat last pixel on the edge
  • OF_COLOR - return input value of color
  • OF_BACKGROUND - return background color (if not set, return input color)
  • OF_TRANSPARENT - return transparent pixel
+
rplColor : input color (returned for out-of-bound coordinates in OF_COLOR mode and if other mode is not applicable)
+
+
Returns:
color : color of pixel
+
Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::OverflowCoordinates long &  x,
long &  y,
OverflowMethod const  ofMethod
[inherited]
+
+ + + + + +
+   + + +

+Recalculates coordinates according to specified overflow method. If pixel (x,y) lies within image, nothing changes.

+

Parameters:
+ + + +
x,y - coordinates of pixel
ofMethod - overflow method
+
+
Returns:
x, y - new coordinates (pixel (x,y) now lies inside image)
+
Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::OverflowCoordinates float &  x,
float &  y,
OverflowMethod const  ofMethod
[inherited]
+
+ + + + + +
+   + + +

+See OverflowCoordinates for integer version

Author:
***bd*** 2.2004
+
+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___kernels.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___kernels.html new file mode 100644 index 0000000..6b4827a --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___kernels.html @@ -0,0 +1,628 @@ + + +CxImage: Kernels + + + + +

Kernels

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

float CxImage::KernelBessel (const float x)
float CxImage::KernelBessel_J1 (const float x)
float CxImage::KernelBessel_Order1 (float x)
float CxImage::KernelBessel_P1 (const float x)
float CxImage::KernelBessel_Q1 (const float x)
float CxImage::KernelBlackman (const float x)
float CxImage::KernelBox (const float x)
float CxImage::KernelBSpline (const float x)
float CxImage::KernelCatrom (const float x)
float CxImage::KernelCubic (const float t)
float CxImage::KernelGaussian (const float x)
float CxImage::KernelGeneralizedCubic (const float t, const float a=-1)
float CxImage::KernelHamming (const float x)
float CxImage::KernelHermite (const float x)
float CxImage::KernelLanczosSinc (const float t, const float r=3)
float CxImage::KernelLinear (const float t)
float CxImage::KernelMitchell (const float x)
float CxImage::KernelQuadratic (const float x)
float CxImage::KernelSinc (const float x)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelBessel const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelBessel_J1 const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelBessel_Order1 float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelBessel_P1 const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelBessel_Q1 const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelBlackman const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelBox const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelBSpline const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelCatrom const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelCubic const float  t  )  [static, inherited]
+
+ + + + + +
+   + + +

+Bicubic interpolation kernel (a=-1):

+          /
+         | 1-2|t|**2+|t|**3          , if |t| < 1
+  h(t) = | 4-8|t|+5|t|**2-|t|**3     , if 1<=|t|<2
+         | 0                         , otherwise
+          \
+  
***bd*** 2.2004
+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelGaussian const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
float CxImage::KernelGeneralizedCubic const float  t,
const float  a = -1
[static, inherited]
+
+ + + + + +
+   + + +

+Bicubic kernel (for a=-1 it is the same as BicubicKernel):

+          /
+         | (a+2)|t|**3 - (a+3)|t|**2 + 1     , |t| <= 1
+  h(t) = | a|t|**3 - 5a|t|**2 + 8a|t| - 4a   , 1 < |t| <= 2
+         | 0                                 , otherwise
+          \
+  
Often used values for a are -1 and -1/2.
+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelHamming const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelHermite const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
float CxImage::KernelLanczosSinc const float  t,
const float  r = 3
[static, inherited]
+
+ + + + + +
+   + + +

+Lanczos windowed sinc interpolation kernel with radius r.

+          /
+  h(t) = | sinc(t)*sinc(t/r)       , if |t|<r
+         | 0                       , otherwise
+          \
+  
***bd*** 2.2004
+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelLinear const float  t  )  [static, inherited]
+
+ + + + + +
+   + + +

+Bilinear interpolation kernel:

+          /
+         | 1-t           , if  0 <= t <= 1
+  h(t) = | t+1           , if -1 <= t <  0
+         | 0             , otherwise
+          \
+  
***bd*** 2.2004
+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelMitchell const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelQuadratic const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
float CxImage::KernelSinc const float  x  )  [static, inherited]
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___layers.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___layers.html new file mode 100644 index 0000000..55f61a7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___layers.html @@ -0,0 +1,194 @@ + + +CxImage: Layers + + + + +

Layers

+ + + + + + + + + + + + + + +

Functions

CxImageCxImage::GetLayer (long position)
long CxImage::GetNumLayers () const
CxImageCxImage::GetParent () const
bool CxImage::LayerCreate (long position=-1)
bool CxImage::LayerDelete (long position=-1)
void CxImage::LayerDeleteAll ()
+

Function Documentation

+

+ + + + +
+ + + + + + + + + +
CxImage * CxImage::GetLayer long  position  )  [inherited]
+
+ + + + + +
+   + + +

+Returns a pointer to a layer. If position is less than 0, the last layer will be returned

+

+ + + + +
+ + + + + + + + +
long CxImage::GetNumLayers  )  const [inherited]
+
+ + + + + +
+   + + +

+Number of layers allocated directly by the object.

+

+ + + + +
+ + + + + + + + +
CxImage * CxImage::GetParent  )  const [inherited]
+
+ + + + + +
+   + + +

+If the object is an internal layer, GetParent return its parent in the hierarchy.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::LayerCreate long  position = -1  )  [inherited]
+
+ + + + + +
+   + + +

+Creates an empty layer. If position is less than 0, the new layer will be placed in the last position

+

+ + + + +
+ + + + + + + + + +
bool CxImage::LayerDelete long  position = -1  )  [inherited]
+
+ + + + + +
+   + + +

+Deletes a layer. If position is less than 0, the last layer will be deleted

+

+ + + + +
+ + + + + + + + +
void CxImage::LayerDeleteAll  )  [inherited]
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___painting.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___painting.html new file mode 100644 index 0000000..4424118 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___painting.html @@ -0,0 +1,781 @@ + + +CxImage: Painting + + + + +

Painting

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

HANDLE CxImage::CopyToHandle ()
bool CxImage::CreateFromHANDLE (HANDLE hMem)
bool CxImage::CreateFromHBITMAP (HBITMAP hbmp, HPALETTE hpal=0)
bool CxImage::CreateFromHICON (HICON hico)
long CxImage::Draw (HDC hdc, const RECT &rect, RECT *pClipRect=NULL, bool bSmooth=false)
long CxImage::Draw (HDC hdc, long x=0, long y=0, long cx=-1, long cy=-1, RECT *pClipRect=0, bool bSmooth=false)
long CxImage::Draw2 (HDC hdc, const RECT &rect)
long CxImage::Draw2 (HDC hdc, long x=0, long y=0, long cx=-1, long cy=-1)
long CxImage::DrawString (HDC hdc, long x, long y, const TCHAR *text, RGBQUAD color, const TCHAR *font, long lSize=0, long lWeight=400, BYTE bItalic=0, BYTE bUnderline=0, bool bSetAlpha=false)
long CxImage::DrawStringEx (HDC hdc, long x, long y, CXTEXTINFO *pTextType, bool bSetAlpha=false)
void CxImage::InitTextInfo (CXTEXTINFO *txt)
HBITMAP CxImage::MakeBitmap (HDC hdc=NULL)
long CxImage::Stretch (HDC hdc, const RECT &rect, DWORD dwRop=SRCCOPY)
long CxImage::Stretch (HDC hdc, long xoffset, long yoffset, long xsize, long ysize, DWORD dwRop=SRCCOPY)
long CxImage::Tile (HDC hdc, RECT *rc)
+

Function Documentation

+

+ + + + +
+ + + + + + + + +
HANDLE CxImage::CopyToHandle  )  [inherited]
+
+ + + + + +
+   + + +

+Transfer the image in a global bitmap handle (clipboard copy)

+

+ + + + +
+ + + + + + + + + +
bool CxImage::CreateFromHANDLE HANDLE  hMem  )  [inherited]
+
+ + + + + +
+   + + +

+Global object (clipboard paste) constructor

Parameters:
+ + +
hMem: source bitmap object, the clipboard format must be CF_DIB
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::CreateFromHBITMAP HBITMAP  hbmp,
HPALETTE  hpal = 0
[inherited]
+
+ + + + + +
+   + + +

+Bitmap resource constructor

Parameters:
+ + + +
hbmp : bitmap resource handle
hpal : (optional) palette, useful for 8bpp DC
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::CreateFromHICON HICON  hico  )  [inherited]
+
+ + + + + +
+   + + +

+icon resource constructor

Parameters:
+ + +
hico : icon resource handle
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
long CxImage::Draw HDC  hdc,
const RECT &  rect,
RECT *  pClipRect = NULL,
bool  bSmooth = false
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
long CxImage::Draw HDC  hdc,
long  x = 0,
long  y = 0,
long  cx = -1,
long  cy = -1,
RECT *  pClipRect = 0,
bool  bSmooth = false
[inherited]
+
+ + + + + +
+   + + +

+Draws the image in the specified device context, with support for alpha channel, alpha palette, transparency, opacity.

Parameters:
+ + + + + + +
hdc : destination device context
x,y : (optional) offset
cx,cy : (optional) size.
    +
  • If cx or cy are not specified (or less than 0), the normal width or height will be used
  • If cx or cy are different than width or height, the image will be stretched
+
pClipRect : limit the drawing operations inside a given rectangle in the output device context.
bSmooth : activates a bilinear filter that will enhance the appearence for zommed pictures. Quite slow. Needs CXIMAGE_SUPPORT_INTERPOLATION.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
long CxImage::Draw2 HDC  hdc,
const RECT &  rect
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
long CxImage::Draw2 HDC  hdc,
long  x = 0,
long  y = 0,
long  cx = -1,
long  cy = -1
[inherited]
+
+ + + + + +
+   + + +

+Draws (stretch) the image with single transparency support

Parameters:
+ + + + +
hdc : destination device context
x,y : (optional) offset
cx,cy : (optional) size.
    +
  • If cx or cy are not specified (or less than 0), the normal width or height will be used
  • If cx or cy are different than width or height, the image will be stretched
+
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
long CxImage::DrawString HDC  hdc,
long  x,
long  y,
const TCHAR *  text,
RGBQUAD  color,
const TCHAR *  font,
long  lSize = 0,
long  lWeight = 400,
BYTE  bItalic = 0,
BYTE  bUnderline = 0,
bool  bSetAlpha = false
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
long CxImage::DrawStringEx HDC  hdc,
long  x,
long  y,
CXTEXTINFO pTextType,
bool  bSetAlpha = false
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
void CxImage::InitTextInfo CXTEXTINFO txt  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
HBITMAP CxImage::MakeBitmap HDC  hdc = NULL  )  [inherited]
+
+ + + + + +
+   + + +

+Transfer the image in a bitmap handle

Parameters:
+ + +
hdc: target device context (the screen, usually)
+
+
Returns:
bitmap handle, or NULL if an error occurs.
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
long CxImage::Stretch HDC  hdc,
const RECT &  rect,
DWORD  dwRop = SRCCOPY
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
long CxImage::Stretch HDC  hdc,
long  xoffset,
long  yoffset,
long  xsize,
long  ysize,
DWORD  dwRop = SRCCOPY
[inherited]
+
+ + + + + +
+   + + +

+Stretch the image. Obsolete: use Draw() or Draw2()

Parameters:
+ + + + + +
hdc : destination device context
xoffset,yoffset : (optional) offset
xsize,ysize : size.
dwRop : raster operation code (see BitBlt documentation)
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
long CxImage::Tile HDC  hdc,
RECT *  rc
[inherited]
+
+ + + + + +
+   + + +

+Tiles the device context in the specified rectangle with the image.

Parameters:
+ + + +
hdc : destination device context
rc : tiled rectangle in the output device context
+
+
Returns:
true if everything is ok
+
+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___palette.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___palette.html new file mode 100644 index 0000000..d822912 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___palette.html @@ -0,0 +1,697 @@ + + +CxImage: Palette + + + + +

Palette

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

void CxImage::BlendPalette (COLORREF cr, long perc)
BYTE CxImage::GetNearestIndex (RGBQUAD c)
RGBQUAD * CxImage::GetPalette () const
bool CxImage::GetPaletteColor (BYTE i, BYTE *r, BYTE *g, BYTE *b)
RGBQUAD CxImage::GetPaletteColor (BYTE idx)
DWORD CxImage::GetPaletteSize ()
bool CxImage::IsGrayScale ()
bool CxImage::IsIndexed () const
bool CxImage::IsSamePalette (CxImage &img, bool bCheckAlpha=true)
void CxImage::SetGrayPalette ()
void CxImage::SetPalette (rgb_color *rgb, DWORD nColors=256)
void CxImage::SetPalette (RGBQUAD *pPal, DWORD nColors=256)
void CxImage::SetPalette (DWORD n, BYTE *r, BYTE *g, BYTE *b)
void CxImage::SetPaletteColor (BYTE idx, COLORREF cr)
void CxImage::SetPaletteColor (BYTE idx, RGBQUAD c)
void CxImage::SetPaletteColor (BYTE idx, BYTE r, BYTE g, BYTE b, BYTE alpha=0)
void CxImage::SetStdPalette ()
void CxImage::SwapIndex (BYTE idx1, BYTE idx2)
+

Detailed Description

+These functions have no effects on RGB images and in this case the returned value is always 0.

Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::BlendPalette COLORREF  cr,
long  perc
[inherited]
+
+ + + + + +
+   + + +

+Colorize the palette.

See also:
Colorize
+
+

+ + + + +
+ + + + + + + + + +
BYTE CxImage::GetNearestIndex RGBQUAD  c  )  [inherited]
+
+ + + + + +
+   + + +

+Returns the best palette index that matches a specified color.

+

+ + + + +
+ + + + + + + + +
RGBQUAD * CxImage::GetPalette  )  const [inherited]
+
+ + + + + +
+   + + +

+returns the pointer to the first palette index

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::GetPaletteColor BYTE  i,
BYTE *  r,
BYTE *  g,
BYTE *  b
[inherited]
+
+ + + + + +
+   + + +

+Returns the color of the specified index.

Parameters:
+ + + +
i = palette index
r,g,b = output color channels
+
+
+

+ + + + +
+ + + + + + + + + +
RGBQUAD CxImage::GetPaletteColor BYTE  idx  )  [inherited]
+
+ + + + + +
+   + + +

+Returns the color of the specified index.

+

+ + + + +
+ + + + + + + + +
DWORD CxImage::GetPaletteSize  )  [inherited]
+
+ + + + + +
+   + + +

+returns the palette dimension in byte

+

+ + + + +
+ + + + + + + + +
bool CxImage::IsGrayScale  )  [inherited]
+
+ + + + + +
+   + + +

+Returns true if the image has 256 colors and a linear grey scale palette.

+

+ + + + +
+ + + + + + + + +
bool CxImage::IsIndexed  )  const [inherited]
+
+ + + + + +
+   + + +

+Returns true if the image has 256 colors or less.

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::IsSamePalette CxImage img,
bool  bCheckAlpha = true
[inherited]
+
+ + + + + +
+   + + +

+Checks if image has the same palette, if any.

Parameters:
+ + + +
img = image to compare.
bCheckAlpha = check also the rgbReserved field.
+
+
+

+ + + + +
+ + + + + + + + +
void CxImage::SetGrayPalette  )  [inherited]
+
+ + + + + +
+   + + +

+Sets (or replaces) the palette to gray scale palette. The function doesn't change the pixels; for standard gray scale conversion use GrayScale().

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::SetPalette rgb_color rgb,
DWORD  nColors = 256
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::SetPalette RGBQUAD *  pPal,
DWORD  nColors = 256
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::SetPalette DWORD  n,
BYTE *  r,
BYTE *  g,
BYTE *  b
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::SetPaletteColor BYTE  idx,
COLORREF  cr
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::SetPaletteColor BYTE  idx,
RGBQUAD  c
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::SetPaletteColor BYTE  idx,
BYTE  r,
BYTE  g,
BYTE  b,
BYTE  alpha = 0
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + +
void CxImage::SetStdPalette  )  [inherited]
+
+ + + + + +
+   + + +

+Sets a palette with standard colors for 4 and 8 bpp images.

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::SwapIndex BYTE  idx1,
BYTE  idx2
[inherited]
+
+ + + + + +
+   + + +

+swap two indexes in the image and their colors in the palette

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___pixel.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___pixel.html new file mode 100644 index 0000000..6ebd777 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___pixel.html @@ -0,0 +1,545 @@ + + +CxImage: Pixel + + + + +

Pixel

+ + + + + + + + + + + + + + + + + + + + + + + + +

Functions

void CxImage::BlendPixelColor (long x, long y, RGBQUAD c, float blend, bool bSetAlpha=false)
void CxImage::DrawLine (int StartX, int EndX, int StartY, int EndY, COLORREF cr)
void CxImage::DrawLine (int StartX, int EndX, int StartY, int EndY, RGBQUAD color, bool bSetAlpha=false)
RGBQUAD CxImage::GetPixelColor (long x, long y, bool bGetAlpha=true)
BYTE CxImage::GetPixelGray (long x, long y)
BYTE CxImage::GetPixelIndex (long x, long y)
bool CxImage::IsInside (long x, long y)
bool CxImage::IsTransparent (long x, long y)
void CxImage::SetPixelColor (long x, long y, COLORREF cr)
void CxImage::SetPixelColor (long x, long y, RGBQUAD c, bool bSetAlpha=false)
void CxImage::SetPixelIndex (long x, long y, BYTE i)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::BlendPixelColor long  x,
long  y,
RGBQUAD  c,
float  blend,
bool  bSetAlpha = false
[inherited]
+
+ + + + + +
+   + + +

+Blends the current pixel color with a new color.

Parameters:
+ + + + + +
x,y = pixel
c = new color
blend = can be from 0 (no effect) to 1 (full effect).
bSetAlpha = if true, blends also the alpha component stored in c.rgbReserved
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::DrawLine int  StartX,
int  EndX,
int  StartY,
int  EndY,
COLORREF  cr
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::DrawLine int  StartX,
int  EndX,
int  StartY,
int  EndY,
RGBQUAD  color,
bool  bSetAlpha = false
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
RGBQUAD CxImage::GetPixelColor long  x,
long  y,
bool  bGetAlpha = true
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
BYTE CxImage::GetPixelGray long  x,
long  y
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
BYTE CxImage::GetPixelIndex long  x,
long  y
[inherited]
+
+ + + + + +
+   + + +

+Returns the palette index of the specified pixel.

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::IsInside long  x,
long  y
[inherited]
+
+ + + + + +
+   + + +

+Checks if the coordinates are inside the image

Returns:
true if x and y are both inside the image
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::IsTransparent long  x,
long  y
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::SetPixelColor long  x,
long  y,
COLORREF  cr
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::SetPixelColor long  x,
long  y,
RGBQUAD  c,
bool  bSetAlpha = false
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::SetPixelIndex long  x,
long  y,
BYTE  i
[inherited]
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___protected.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___protected.html new file mode 100644 index 0000000..90e0f7a --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___protected.html @@ -0,0 +1,1042 @@ + + +CxImage: Protected + + + + +

Protected

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

void CxImage::AddAveragingCont (RGBQUAD const &color, float const surf, float &rr, float &gg, float &bb, float &aa)
void CxImage::Bitfield2RGB (BYTE *src, WORD redmask, WORD greenmask, WORD bluemask, BYTE bpp)
BYTE CxImage::BlindAlphaGet (const long x, const long y)
RGBQUAD CxImage::BlindGetPixelColor (const long x, const long y)
BYTE CxImage::BlindGetPixelIndex (const long x, const long y)
void * CxImage::BlindGetPixelPointer (const long x, const long y)
void CxImage::blur_line (float *ctable, float *cmatrix, int cmatrix_length, BYTE *cur_col, BYTE *dest_col, int y, long bytes)
int CxImage::CompareColors (const void *elem1, const void *elem2)
void CxImage::CopyInfo (const CxImage &src)
bool CxImage::DFT (int dir, long m, double *x1, double *y1, double *x2, double *y2)
bool CxImage::EncodeSafeCheck (CxFile *hFile)
bool CxImage::FFT (int dir, int m, double *x, double *y)
int CxImage::gen_convolve_matrix (float radius, float **cmatrix_p)
float * CxImage::gen_lookup_table (float *cmatrix, int cmatrix_length)
void CxImage::Ghost (CxImage *src)
float CxImage::HueToRGB (float n1, float n2, float hue)
bool CxImage::IsPowerof2 (long x)
bool CxImage::RepairChannel (CxImage *ch, float radius)
void CxImage::RGBtoBGR (BYTE *buffer, int length)
void CxImage::Startup (DWORD imagetype=0)

Variables

BITMAPINFOHEADER CxImage::head
CXIMAGEINFO CxImage::info
BYTE * CxImage::pAlpha
void * CxImage::pDib
CxImage ** CxImage::pLayers
BYTE * CxImage::pSelection
+

Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::AddAveragingCont RGBQUAD const &  color,
float const  surf,
float &  rr,
float &  gg,
float &  bb,
float &  aa
[protected, inherited]
+
+ + + + + +
+   + + +

+Helper function for GetAreaColorInterpolated. Adds 'surf' portion of image pixel with color 'color' to (rr,gg,bb,aa).

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::Bitfield2RGB BYTE *  src,
WORD  redmask,
WORD  greenmask,
WORD  bluemask,
BYTE  bpp
[protected, inherited]
+
+ + + + + +
+   + + +

+turns a 16 or 32 bit bitfield image into a RGB image

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
BYTE CxImage::BlindAlphaGet const long  x,
const long  y
[protected, inherited]
+
+ + + + + +
+   + + +

+Get alpha value without boundscheck (a bit faster). Pixel must be inside the image.

+

Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
RGBQUAD CxImage::BlindGetPixelColor const long  x,
const long  y
[protected, inherited]
+
+ + + + + +
+   + + +

+This is (a bit) faster version of GetPixelColor. It tests bounds only in debug mode (_DEBUG defined).

+It is an error to request out-of-borders pixel with this method. In DEBUG mode an exception will be thrown, and data will be violated in non-DEBUG mode.

Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
BYTE CxImage::BlindGetPixelIndex const long  x,
const long  y
[protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void * CxImage::BlindGetPixelPointer const long  x,
const long  y
[protected, inherited]
+
+ + + + + +
+   + + +

+Returns pointer to pixel. Currently implemented only for truecolor images.

+

Parameters:
+ + +
x,y - coordinates
+
+
Returns:
pointer to first byte of pixel data
+
Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void CxImage::blur_line float *  ctable,
float *  cmatrix,
int  cmatrix_length,
BYTE *  cur_col,
BYTE *  dest_col,
int  y,
long  bytes
[protected, inherited]
+
+ + + + + +
+   + + +

+this function is written as if it is blurring a column at a time, even though it can operate on rows, too. There is no difference in the processing of the lines, at least to the blur_line function.

Author:
[nipper]
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
int CxImage::CompareColors const void *  elem1,
const void *  elem2
[static, protected, inherited]
+
+ + + + + +
+   + + +

+

Returns:
lightness difference between elem1 and elem2
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::CopyInfo const CxImage src  )  [protected, inherited]
+
+ + + + + +
+   + + +

+Copies the image attributes from an existing image.

    +
  • Works only on an empty image, and the image will be still empty.
  • Use it before Create()
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::DFT int  dir,
long  m,
double *  x1,
double *  y1,
double *  x2,
double *  y2
[protected, inherited]
+
+ + + + + +
+   + + +

+Direct fourier transform o(n)=n^2 Written by Paul Bourke, July 1998

+

+ + + + +
+ + + + + + + + + +
bool CxImage::EncodeSafeCheck CxFile *  hFile  )  [protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::FFT int  dir,
int  m,
double *  x,
double *  y
[protected, inherited]
+
+ + + + + +
+   + + +

+This computes an in-place complex-to-complex FFT x and y are the real and imaginary arrays of n=2^m points. o(n)=n*log2(n) dir = 1 gives forward transform dir = -1 gives reverse transform Written by Paul Bourke, July 1998 FFT algorithm by Cooley and Tukey, 1965

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
int CxImage::gen_convolve_matrix float  radius,
float **  cmatrix_p
[protected, inherited]
+
+ + + + + +
+   + + +

+generates a 1-D convolution matrix to be used for each pass of a two-pass gaussian blur. Returns the length of the matrix.

Author:
[nipper]
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
float * CxImage::gen_lookup_table float *  cmatrix,
int  cmatrix_length
[protected, inherited]
+
+ + + + + +
+   + + +

+generates a lookup table for every possible product of 0-255 and each value in the convolution matrix. The returned array is indexed first by matrix position, then by input multiplicand (?) value.

Author:
[nipper]
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::Ghost CxImage from  )  [protected, inherited]
+
+ + + + + +
+   + + +

+(this) points to the same pDib owned by (*from), the image remains in (*from) but (this) has the access to the pixels. Use carefully !!!

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
float CxImage::HueToRGB float  n1,
float  n2,
float  hue
[static, protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
bool CxImage::IsPowerof2 long  x  )  [protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::RepairChannel CxImage ch,
float  radius
[protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
void CxImage::RGBtoBGR BYTE *  buffer,
int  length
[protected, inherited]
+
+ + + + + +
+   + + +

+swaps the blue and red components (for RGB images)

Parameters:
+ + + +
buffer : pointer to the pixels
length : number of bytes to swap. lenght may not exceed the scan line.
+
+
+

+ + + + +
+ + + + + + + + + +
void CxImage::Startup DWORD  imagetype = 0  )  [protected, inherited]
+
+ + + + + +
+   + + +

+Initialize the internal structures

+


Variable Documentation

+

+ + + + +
+ + + + +
BITMAPINFOHEADER CxImage::head [protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
CXIMAGEINFO CxImage::info [protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
BYTE* CxImage::pAlpha [protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
void* CxImage::pDib [protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
CxImage** CxImage::pLayers [protected, inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
BYTE* CxImage::pSelection [protected, inherited]
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___selection.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___selection.html new file mode 100644 index 0000000..db1d70d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___selection.html @@ -0,0 +1,489 @@ + + +CxImage: Selection + + + + +

Selection

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

bool CxImage::SelectionAddColor (RGBQUAD c)
bool CxImage::SelectionAddEllipse (RECT r)
bool CxImage::SelectionAddPixel (int x, int y)
bool CxImage::SelectionAddPolygon (POINT *points, long npoints)
bool CxImage::SelectionAddRect (RECT r)
bool CxImage::SelectionClear ()
bool CxImage::SelectionCopy (CxImage &from)
bool CxImage::SelectionCreate ()
bool CxImage::SelectionDelete ()
void CxImage::SelectionGetBox (RECT &r)
bool CxImage::SelectionInvert ()
bool CxImage::SelectionIsInside (long x, long y)
bool CxImage::SelectionIsValid ()
bool CxImage::SelectionSplit (CxImage *dest)
bool CxImage::SelectionToHRGN (HRGN &region)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + +
bool CxImage::SelectionAddColor RGBQUAD  c  )  [inherited]
+
+ + + + + +
+   + + +

+Adds to the selection all the pixels matching the specified color.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::SelectionAddEllipse RECT  r  )  [inherited]
+
+ + + + + +
+   + + +

+Adds an ellipse to the existing selection.

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::SelectionAddPixel int  x,
int  y
[inherited]
+
+ + + + + +
+   + + +

+Adds a single pixel to the existing selection.

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::SelectionAddPolygon POINT *  points,
long  npoints
[inherited]
+
+ + + + + +
+   + + +

+Adds a polygonal region to the existing selection. points points to an array of POINT structures. Each structure specifies the x-coordinate and y-coordinate of one vertex of the polygon. npoints specifies the number of POINT structures in the array pointed to by points.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::SelectionAddRect RECT  r  )  [inherited]
+
+ + + + + +
+   + + +

+Adds a rectangle to the existing selection.

+

+ + + + +
+ + + + + + + + +
bool CxImage::SelectionClear  )  [inherited]
+
+ + + + + +
+   + + +

+Empties the selection.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::SelectionCopy CxImage from  )  [inherited]
+
+ + + + + +
+   + + +

+Imports an existing region from another image with the same width and height.

+

+ + + + +
+ + + + + + + + +
bool CxImage::SelectionCreate  )  [inherited]
+
+ + + + + +
+   + + +

+Allocates an empty selection.

+

+ + + + +
+ + + + + + + + +
bool CxImage::SelectionDelete  )  [inherited]
+
+ + + + + +
+   + + +

+Deallocates the selction.

+

+ + + + +
+ + + + + + + + + +
void CxImage::SelectionGetBox RECT &  r  )  [inherited]
+
+ + + + + +
+   + + +

+Gets the smallest rectangle that contains the selection

+

+ + + + +
+ + + + + + + + +
bool CxImage::SelectionInvert  )  [inherited]
+
+ + + + + +
+   + + +

+Inverts the selection.

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::SelectionIsInside long  x,
long  y
[inherited]
+
+ + + + + +
+   + + +

+Checks if the coordinates are inside the selection.

+

+ + + + +
+ + + + + + + + +
bool CxImage::SelectionIsValid  )  [inherited]
+
+ + + + + +
+   + + +

+Checks if the image has a valid selection.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::SelectionSplit CxImage dest  )  [inherited]
+
+ + + + + +
+   + + +

+Exports the selection channel in a 8bpp grayscale image.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::SelectionToHRGN HRGN &  region  )  [inherited]
+
+ + + + + +
+   + + +

+Converts the selection in a HRGN object.

+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/group___transformations.html b/SlnkDWFImpl/CxImage/doc/doxy/html/group___transformations.html new file mode 100644 index 0000000..044ccac --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/group___transformations.html @@ -0,0 +1,967 @@ + + +CxImage: Transformations + + + + +

Transformations

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

bool CxImage::CircleTransform (int type, long rmax=0, float Koeff=1.0f)
bool CxImage::Crop (const RECT &rect, CxImage *iDst=NULL)
bool CxImage::Crop (long left, long top, long right, long bottom, CxImage *iDst=NULL)
bool CxImage::CropRotatedRectangle (long topx, long topy, long width, long height, float angle, CxImage *iDst=NULL)
bool CxImage::DecreaseBpp (DWORD nbit, bool errordiffusion, RGBQUAD *ppal=0, DWORD clrimportant=0)
bool CxImage::Dither (long method=0)
bool CxImage::Expand (long newx, long newy, RGBQUAD canvascolor, CxImage *iDst=0)
bool CxImage::Expand (long left, long top, long right, long bottom, RGBQUAD canvascolor, CxImage *iDst=0)
bool CxImage::IncreaseBpp (DWORD nbit)
bool CxImage::QIShrink (long newx, long newy, CxImage *const iDst=NULL)
bool CxImage::RedEyeRemove ()
bool CxImage::Resample (long newx, long newy, int mode=1, CxImage *iDst=NULL)
bool CxImage::Resample2 (long newx, long newy, InterpolationMethod const inMethod=IM_BICUBIC2, OverflowMethod const ofMethod=OM_REPEAT, CxImage *const iDst=NULL, bool const disableAveraging=false)
bool CxImage::Rotate (float angle, CxImage *iDst=NULL)
bool CxImage::Rotate180 (CxImage *iDst=NULL)
bool CxImage::Rotate2 (float angle, CxImage *iDst=NULL, InterpolationMethod inMethod=IM_BILINEAR, OverflowMethod ofMethod=OM_BACKGROUND, RGBQUAD *replColor=0, bool const optimizeRightAngles=true, bool const bKeepOriginalSize=false)
bool CxImage::Skew (float xgain, float ygain, long xpivot=0, long ypivot=0, bool bEnableInterpolation=false)
bool CxImage::Thumbnail (long newx, long newy, RGBQUAD canvascolor, CxImage *iDst=0)
+

Function Documentation

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::CircleTransform int  type,
long  rmax = 0,
float  Koeff = 1.0f
[inherited]
+
+ + + + + +
+   + + +

+Perform circle_based transformations.

Parameters:
+ + + + +
type - for different transformations
    +
  • 0 for normal (proturberant) FishEye
  • 1 for reverse (concave) FishEye
  • 2 for Swirle
  • 3 for Cilinder mirror
  • 4 for bathroom
+
rmax - effect radius. If 0, the whole image is processed
Koeff - only for swirle
+
+
Author:
Arkadiy Olovyannikov ark(at)msun(dot)ru
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Crop const RECT &  rect,
CxImage iDst = NULL
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Crop long  left,
long  top,
long  right,
long  bottom,
CxImage iDst = NULL
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::CropRotatedRectangle long  topx,
long  topy,
long  width,
long  height,
float  angle,
CxImage iDst = NULL
[inherited]
+
+ + + + + +
+   + + +

+CropRotatedRectangle

Parameters:
+ + + + + + +
topx,topy : topmost and leftmost point of the rectangle (topmost, and if there are 2 topmost points, the left one)
width : size of the right hand side of rect, from (topx,topy) roundwalking clockwise
height : size of the left hand side of rect, from (topx,topy) roundwalking clockwise
angle : angle of the right hand side of rect, from (topx,topy)
iDst : pointer to destination image (if 0, this image is modified)
+
+
Author:
[VATI]
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::DecreaseBpp DWORD  nbit,
bool  errordiffusion,
RGBQUAD *  ppal = 0,
DWORD  clrimportant = 0
[inherited]
+
+ + + + + +
+   + + +

+Reduces the number of bits per pixel to nbit (1, 4 or 8). ppal points to a valid palette for the final image; if not supplied the function will use a standard palette. ppal is not necessary for reduction to 1 bpp.

+

+ + + + +
+ + + + + + + + + +
bool CxImage::Dither long  method = 0  )  [inherited]
+
+ + + + + +
+   + + +

+Converts the image to B&W using the desired method :

    +
  • 0 = Floyd-Steinberg
  • 1 = Ordered-Dithering (4x4)
  • 2 = Burkes
  • 3 = Stucki
  • 4 = Jarvis-Judice-Ninke
  • 5 = Sierra
  • 6 = Stevenson-Arce
  • 7 = Bayer (4x4 ordered dithering)
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Expand long  newx,
long  newy,
RGBQUAD  canvascolor,
CxImage iDst = 0
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Expand long  left,
long  top,
long  right,
long  bottom,
RGBQUAD  canvascolor,
CxImage iDst = 0
[inherited]
+
+ + + + + +
+   + + +

+Expands the borders.

Parameters:
+ + + + +
left,top,right,bottom = additional dimensions, should be greater than 0.
canvascolor = border color
iDst = pointer to destination image (if it's 0, this image is modified)
+
+
Returns:
true if everything is ok
+
Author:
[Colin Urquhart]
+
+

+ + + + +
+ + + + + + + + + +
bool CxImage::IncreaseBpp DWORD  nbit  )  [inherited]
+
+ + + + + +
+   + + +

+Increases the number of bits per pixel of the image.

Parameters:
+ + +
nbit: 4, 8, 24
+
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::QIShrink long  newx,
long  newy,
CxImage *const  iDst = NULL
[inherited]
+
+ + + + + +
+   + + +

+Faster way to almost properly shrink image. Algorithm produces results comparable with "high resoultion shrink" when resulting image is much smaller (that would be 3 times or more) than original. When resulting image is only slightly smaller, results are closer to nearest pixel. This algorithm works by averaging, but it does not calculate fractions of pixels. It adds whole source pixels to the best destionation. It is not geometrically "correct". It's main advantage over "high" resulution shrink is speed, so it's useful, when speed is most important (preview thumbnails, "map" view, ...). Method is optimized for RGB24 images.

+

Parameters:
+ + + +
newx,newy - size of destination image (must be smaller than original!)
iDst - pointer to destination image (if it's 0, this image is modified)
+
+
Returns:
true if everything is ok
+
Author:
[bd], 9.2004
+
+

+ + + + +
+ + + + + + + + +
bool CxImage::RedEyeRemove  )  [inherited]
+
+ + + + + +
+   + + +

+Use the RedEyeRemove function to remove the red-eye effect that frequently occurs in photographs of humans and animals. You must select the region where the function will filter the red channel.

Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Resample long  newx,
long  newy,
int  mode = 1,
CxImage iDst = NULL
[inherited]
+
+ + + + + +
+   + + +

+Resizes the image. mode can be 0 for slow (bilinear) method , 1 for fast (nearest pixel) method, or 2 for accurate (bicubic spline interpolation) method. The function is faster with 24 and 1 bpp images, slow for 4 bpp images and slowest for 8 bpp images.

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Resample2 long  newx,
long  newy,
InterpolationMethod const  inMethod = IM_BICUBIC2,
OverflowMethod const  ofMethod = OM_REPEAT,
CxImage *const  iDst = NULL,
bool const  disableAveraging = false
[inherited]
+
+ + + + + +
+   + + +

+New simpler resample. Adds new interpolation methods and simplifies code (using GetPixelColorInterpolated and GetAreaColorInterpolated). It also (unlike old method) interpolates alpha layer.

+

Parameters:
+ + + + + + +
newx,newy - size of resampled image
inMethod - interpolation method to use (see comments at GetPixelColorInterpolated) If image size is being reduced, averaging is used instead (or simultaneously with) inMethod.
ofMethod - what to replace outside pixels by (only significant for bordering pixels of enlarged image)
iDst - pointer to destination CxImage or NULL.
disableAveraging - force no averaging when shrinking images (Produces aliasing. You probably just want to leave this off...)
+
+
Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
bool CxImage::Rotate float  angle,
CxImage iDst = NULL
[inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
bool CxImage::Rotate180 CxImage iDst = NULL  )  [inherited]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Rotate2 float  angle,
CxImage iDst = NULL,
InterpolationMethod  inMethod = IM_BILINEAR,
OverflowMethod  ofMethod = OM_BACKGROUND,
RGBQUAD *  replColor = 0,
bool const  optimizeRightAngles = true,
bool const  bKeepOriginalSize = false
[inherited]
+
+ + + + + +
+   + + +

+Rotates image around it's center. Method can use interpolation with paletted images, but does not change pallete, so results vary. (If you have only four colours in a palette, there's not much room for interpolation.)

+

Parameters:
+ + + + + + + + +
angle - angle in degrees (positive values rotate clockwise)
*iDst - destination image (if null, this image is changed)
inMethod - interpolation method used (IM_NEAREST_NEIGHBOUR produces aliasing (fast), IM_BILINEAR softens picture a bit (slower) IM_SHARPBICUBIC is slower and produces some halos...)
ofMethod - overflow method (how to choose colour of pixels that have no source)
replColor - replacement colour to use (OM_COLOR, OM_BACKGROUND with no background colour...)
optimizeRightAngles - call faster methods for 90, 180, and 270 degree rotations. Faster methods are called for angles, where error (in location of corner pixels) is less than 0.25 pixels.
bKeepOriginalSize - rotates the image without resizing.
+
+
Author:
***bd*** 2.2004
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Skew float  xgain,
float  ygain,
long  xpivot = 0,
long  ypivot = 0,
bool  bEnableInterpolation = false
[inherited]
+
+ + + + + +
+   + + +

+

Parameters:
+ + + + +
xgain,ygain : can be from 0 to 1.
xpivot,ypivot : is the center of the transformation.
bEnableInterpolation : if true, enables bilinear interpolation.
+
+
Returns:
true if everything is ok
+
+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bool CxImage::Thumbnail long  newx,
long  newy,
RGBQUAD  canvascolor,
CxImage iDst = 0
[inherited]
+
+ + + + + +
+   + + +

+Resamples the image with the correct aspect ratio, and fills the borders.

Parameters:
+ + + + +
newx,newy = thumbnail size.
canvascolor = border color.
iDst = pointer to destination image (if it's 0, this image is modified).
+
+
Returns:
true if everything is ok.
+
Author:
[Colin Urquhart]
+
+


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/index.html b/SlnkDWFImpl/CxImage/doc/doxy/html/index.html new file mode 100644 index 0000000..50edd91 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/index.html @@ -0,0 +1,8 @@ + + +CxImage + + + + + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/main.html b/SlnkDWFImpl/CxImage/doc/doxy/html/main.html new file mode 100644 index 0000000..289b08b --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/main.html @@ -0,0 +1,15 @@ + + +CxImage: Main Page + + + + +

CxImage Documentation

+

+

version 5.99c

+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/modules.html b/SlnkDWFImpl/CxImage/doc/doxy/html/modules.html new file mode 100644 index 0000000..9b2a21d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/modules.html @@ -0,0 +1,32 @@ + + +CxImage: Module Index + + + + +

CxImage Modules

Here is a list of all modules: +
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1rgb__color-members.html b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1rgb__color-members.html new file mode 100644 index 0000000..d7383b0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1rgb__color-members.html @@ -0,0 +1,16 @@ + + +CxImage: Member List + + + + +

CxImage::rgb_color Member List

This is the complete list of members for CxImage::rgb_color, including all inherited members.

+ + + +
bCxImage::rgb_color
gCxImage::rgb_color
rCxImage::rgb_color


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1rgb__color.html b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1rgb__color.html new file mode 100644 index 0000000..758bbaa --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1rgb__color.html @@ -0,0 +1,96 @@ + + +CxImage: CxImage::rgb_color Struct Reference + + + + +

CxImage::rgb_color Struct Reference

#include <ximage.h> +

+List of all members. + + + + + + + + +

Public Attributes

BYTE b
BYTE g
BYTE r
+


Member Data Documentation

+

+ + + + +
+ + + + +
BYTE CxImage::rgb_color::b
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
BYTE CxImage::rgb_color::g
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
BYTE CxImage::rgb_color::r
+
+ + + + + +
+   + + +

+

+


The documentation for this struct was generated from the following file: +
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_image_info-members.html b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_image_info-members.html new file mode 100644 index 0000000..9661156 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_image_info-members.html @@ -0,0 +1,42 @@ + + +CxImage: Member List + + + + +

CxImage::tagCxImageInfo Member List

This is the complete list of members for CxImage::tagCxImageInfo, including all inherited members.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
bAlphaPaletteEnabledCxImage::tagCxImageInfo
bEnabledCxImage::tagCxImageInfo
dwCodecOptCxImage::tagCxImageInfo
dwEffWidthCxImage::tagCxImageInfo
dwFlagsCxImage::tagCxImageInfo
dwFrameDelayCxImage::tagCxImageInfo
dwTypeCxImage::tagCxImageInfo
last_cCxImage::tagCxImageInfo
last_c_indexCxImage::tagCxImageInfo
last_c_isvalidCxImage::tagCxImageInfo
nAlphaMaxCxImage::tagCxImageInfo
nBkgndColorCxImage::tagCxImageInfo
nBkgndIndexCxImage::tagCxImageInfo
nEscapeCxImage::tagCxImageInfo
nFrameCxImage::tagCxImageInfo
nJpegScaleCxImage::tagCxImageInfo
nNumFramesCxImage::tagCxImageInfo
nNumLayersCxImage::tagCxImageInfo
nProgressCxImage::tagCxImageInfo
nQualityCxImage::tagCxImageInfo
pGhostCxImage::tagCxImageInfo
pImageCxImage::tagCxImageInfo
pParentCxImage::tagCxImageInfo
rSelectionBoxCxImage::tagCxImageInfo
szLastErrorCxImage::tagCxImageInfo
xDPICxImage::tagCxImageInfo
xOffsetCxImage::tagCxImageInfo
yDPICxImage::tagCxImageInfo
yOffsetCxImage::tagCxImageInfo


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_image_info.html b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_image_info.html new file mode 100644 index 0000000..84e9ac8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_image_info.html @@ -0,0 +1,816 @@ + + +CxImage: CxImage::tagCxImageInfo Struct Reference + + + + +

CxImage::tagCxImageInfo Struct Reference

List of all members. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Public Attributes

bool bAlphaPaletteEnabled
 true if alpha values in the palette are enabled.
bool bEnabled
 enables the painting functions
DWORD dwCodecOpt [CMAX_IMAGE_FORMATS]
 for GIF, TIF : 0=def.1=unc,2=fax3,3=fax4,4=pack,5=jpg
DWORD dwEffWidth
 DWORD aligned scan line width.
DWORD dwFlags
 0x??00000 = reserved, 0x00??0000 = blend mode, 0x0000???? = layer id - user flags
DWORD dwFrameDelay
 used for GIF, MNG
DWORD dwType
 original image format
RGBQUAD last_c
 for GetNearestIndex optimization
BYTE last_c_index
bool last_c_isvalid
BYTE nAlphaMax
 max opacity (fade)
RGBQUAD nBkgndColor
 used for RGB transparency
long nBkgndIndex
 used for GIF, PNG, MNG
long nEscape
 escape
long nFrame
 used for TIF, GIF, MNG : actual frame
BYTE nJpegScale
 used for JPEG [ignacio]
long nNumFrames
 used for TIF, GIF, MNG : total number of frames
long nNumLayers
long nProgress
 monitor
BYTE nQuality
 used for JPEG
CxImagepGhost
 if this is a ghost, pGhost points to the body
BYTE * pImage
 THE IMAGE BITS.
CxImagepParent
 if this is a layer, pParent points to the body
RECT rSelectionBox
 bounding rectangle
char szLastError [256]
 debugging
long xDPI
 horizontal resolution
long xOffset
long yDPI
 vertical resolution
long yOffset
+

Member Data Documentation

+

+ + + + +
+ + + + +
bool CxImage::tagCxImageInfo::bAlphaPaletteEnabled
+
+ + + + + +
+   + + +

+true if alpha values in the palette are enabled. +

+

+

+ + + + +
+ + + + +
bool CxImage::tagCxImageInfo::bEnabled
+
+ + + + + +
+   + + +

+enables the painting functions +

+

+

+ + + + +
+ + + + +
DWORD CxImage::tagCxImageInfo::dwCodecOpt[CMAX_IMAGE_FORMATS]
+
+ + + + + +
+   + + +

+for GIF, TIF : 0=def.1=unc,2=fax3,3=fax4,4=pack,5=jpg +

+

+

+ + + + +
+ + + + +
DWORD CxImage::tagCxImageInfo::dwEffWidth
+
+ + + + + +
+   + + +

+DWORD aligned scan line width. +

+

+

+ + + + +
+ + + + +
DWORD CxImage::tagCxImageInfo::dwFlags
+
+ + + + + +
+   + + +

+0x??00000 = reserved, 0x00??0000 = blend mode, 0x0000???? = layer id - user flags +

+

+

+ + + + +
+ + + + +
DWORD CxImage::tagCxImageInfo::dwFrameDelay
+
+ + + + + +
+   + + +

+used for GIF, MNG +

+

+

+ + + + +
+ + + + +
DWORD CxImage::tagCxImageInfo::dwType
+
+ + + + + +
+   + + +

+original image format +

+

+

+ + + + +
+ + + + +
RGBQUAD CxImage::tagCxImageInfo::last_c
+
+ + + + + +
+   + + +

+for GetNearestIndex optimization +

+

+

+ + + + +
+ + + + +
BYTE CxImage::tagCxImageInfo::last_c_index
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
bool CxImage::tagCxImageInfo::last_c_isvalid
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
BYTE CxImage::tagCxImageInfo::nAlphaMax
+
+ + + + + +
+   + + +

+max opacity (fade) +

+

+

+ + + + +
+ + + + +
RGBQUAD CxImage::tagCxImageInfo::nBkgndColor
+
+ + + + + +
+   + + +

+used for RGB transparency +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::nBkgndIndex
+
+ + + + + +
+   + + +

+used for GIF, PNG, MNG +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::nEscape
+
+ + + + + +
+   + + +

+escape +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::nFrame
+
+ + + + + +
+   + + +

+used for TIF, GIF, MNG : actual frame +

+

+

+ + + + +
+ + + + +
BYTE CxImage::tagCxImageInfo::nJpegScale
+
+ + + + + +
+   + + +

+used for JPEG [ignacio] +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::nNumFrames
+
+ + + + + +
+   + + +

+used for TIF, GIF, MNG : total number of frames +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::nNumLayers
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::nProgress
+
+ + + + + +
+   + + +

+monitor +

+

+

+ + + + +
+ + + + +
BYTE CxImage::tagCxImageInfo::nQuality
+
+ + + + + +
+   + + +

+used for JPEG +

+

+

+ + + + +
+ + + + +
CxImage* CxImage::tagCxImageInfo::pGhost
+
+ + + + + +
+   + + +

+if this is a ghost, pGhost points to the body +

+

+

+ + + + +
+ + + + +
BYTE* CxImage::tagCxImageInfo::pImage
+
+ + + + + +
+   + + +

+THE IMAGE BITS. +

+

+

+ + + + +
+ + + + +
CxImage* CxImage::tagCxImageInfo::pParent
+
+ + + + + +
+   + + +

+if this is a layer, pParent points to the body +

+

+

+ + + + +
+ + + + +
RECT CxImage::tagCxImageInfo::rSelectionBox
+
+ + + + + +
+   + + +

+bounding rectangle +

+

+

+ + + + +
+ + + + +
char CxImage::tagCxImageInfo::szLastError[256]
+
+ + + + + +
+   + + +

+debugging +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::xDPI
+
+ + + + + +
+   + + +

+horizontal resolution +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::xOffset
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::yDPI
+
+ + + + + +
+   + + +

+vertical resolution +

+

+

+ + + + +
+ + + + +
long CxImage::tagCxImageInfo::yOffset
+
+ + + + + +
+   + + +

+

+


The documentation for this struct was generated from the following file: +
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_text_info-members.html b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_text_info-members.html new file mode 100644 index 0000000..c9736eb --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_text_info-members.html @@ -0,0 +1,22 @@ + + +CxImage: Member List + + + + +

CxImage::tagCxTextInfo Member List

This is the complete list of members for CxImage::tagCxTextInfo, including all inherited members.

+ + + + + + + + + +
alignCxImage::tagCxTextInfo
b_opacityCxImage::tagCxTextInfo
b_outlineCxImage::tagCxTextInfo
b_roundCxImage::tagCxTextInfo
bcolorCxImage::tagCxTextInfo
fcolorCxImage::tagCxTextInfo
lfontCxImage::tagCxTextInfo
opaqueCxImage::tagCxTextInfo
textCxImage::tagCxTextInfo


Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_text_info.html b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_text_info.html new file mode 100644 index 0000000..9fb6b54 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/struct_cx_image_1_1tag_cx_text_info.html @@ -0,0 +1,270 @@ + + +CxImage: CxImage::tagCxTextInfo Struct Reference + + + + +

CxImage::tagCxTextInfo Struct Reference

#include <ximage.h> +

+List of all members. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Public Attributes

long align
 DT_CENTER, DT_RIGHT, DT_LEFT aligment for multiline text.
float b_opacity
 opacity value for background between 0.0-1.0 Default is 0. (opaque)
BYTE b_outline
 outline width for background (zero: no outline)
BYTE b_round
COLORREF bcolor
 background color
COLORREF fcolor
 foreground color
LOGFONT lfont
 font and codepage data
BYTE opaque
 data for background (ignored if .opaque==FALSE)
TCHAR text [4096]
 text (char -> TCHAR for UNICODE [Cesar M])
+


Member Data Documentation

+

+ + + + +
+ + + + +
long CxImage::tagCxTextInfo::align
+
+ + + + + +
+   + + +

+DT_CENTER, DT_RIGHT, DT_LEFT aligment for multiline text. +

+

+

+ + + + +
+ + + + +
float CxImage::tagCxTextInfo::b_opacity
+
+ + + + + +
+   + + +

+opacity value for background between 0.0-1.0 Default is 0. (opaque) +

+

+

+ + + + +
+ + + + +
BYTE CxImage::tagCxTextInfo::b_outline
+
+ + + + + +
+   + + +

+outline width for background (zero: no outline) +

+

+

+ + + + +
+ + + + +
BYTE CxImage::tagCxTextInfo::b_round
+
+ + + + + +
+   + + +

+rounding radius for background rectangle. of the height, between 0-50. Default is 10. (backgr. always has a frame: width = 3 pixel + 10% of height by default.)

+

+ + + + +
+ + + + +
COLORREF CxImage::tagCxTextInfo::bcolor
+
+ + + + + +
+   + + +

+background color +

+

+

+ + + + +
+ + + + +
COLORREF CxImage::tagCxTextInfo::fcolor
+
+ + + + + +
+   + + +

+foreground color +

+

+

+ + + + +
+ + + + +
LOGFONT CxImage::tagCxTextInfo::lfont
+
+ + + + + +
+   + + +

+font and codepage data +

+

+

+ + + + +
+ + + + +
BYTE CxImage::tagCxTextInfo::opaque
+
+ + + + + +
+   + + +

+data for background (ignored if .opaque==FALSE) +

+text has background or hasn't. Default is true.

+

+ + + + +
+ + + + +
TCHAR CxImage::tagCxTextInfo::text[4096]
+
+ + + + + +
+   + + +

+text (char -> TCHAR for UNICODE [Cesar M]) +

+

+


The documentation for this struct was generated from the following file: +
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/tif__xfile_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/tif__xfile_8cpp.html new file mode 100644 index 0000000..857765c --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/tif__xfile_8cpp.html @@ -0,0 +1,769 @@ + + +CxImage: tif_xfile.cpp File Reference + + + + +

tif_xfile.cpp File Reference

#include <windows.h>
+#include <stdio.h>
+#include "ximage.h"
+#include "../tiff/tiffiop.h"
+#include "xfile.h"
+#include <sys/stat.h>
+#include <malloc.h>
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

int _tiffCloseProcEx (thandle_t fd)
TIFF * _TIFFFdOpen (int fd, const char *name, const char *mode)
void _TIFFfree (tdata_t p)
tdata_t _TIFFmalloc (tsize_t s)
int _tiffMapProcEx (thandle_t fd, tdata_t *pbase, toff_t *psize)
int _TIFFmemcmp (const tdata_t p1, const tdata_t p2, tsize_t c)
void _TIFFmemcpy (tdata_t d, const tdata_t s, tsize_t c)
void _TIFFmemset (tdata_t p, int v, tsize_t c)
TIFF * _TIFFOpenEx (CxFile *stream, const char *mode)
tsize_t _tiffReadProcEx (thandle_t fd, tdata_t buf, tsize_t size)
tdata_t _TIFFrealloc (tdata_t p, tsize_t s)
toff_t _tiffSeekProcEx (thandle_t fd, toff_t off, int whence)
toff_t _tiffSizeProcEx (thandle_t fd)
void _tiffUnmapProcEx (thandle_t fd, tdata_t base, toff_t size)
tsize_t _tiffWriteProcEx (thandle_t fd, tdata_t buf, tsize_t size)
void Win32ErrorHandler (const char *module, const char *fmt, va_list ap)
void Win32WarningHandler (const char *module, const char *fmt, va_list ap)

Variables

TIFFErrorHandler _TIFFerrorHandler = Win32ErrorHandler
TIFFErrorHandler _TIFFwarningHandler = Win32WarningHandler
+

Function Documentation

+

+ + + + +
+ + + + + + + + + +
int _tiffCloseProcEx thandle_t  fd  )  [static]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
TIFF* _TIFFFdOpen int  fd,
const char *  name,
const char *  mode
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
void _TIFFfree tdata_t  p  ) 
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
tdata_t _TIFFmalloc tsize_t  s  ) 
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
int _tiffMapProcEx thandle_t  fd,
tdata_t *  pbase,
toff_t *  psize
[static]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
int _TIFFmemcmp const tdata_t  p1,
const tdata_t  p2,
tsize_t  c
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void _TIFFmemcpy tdata_t  d,
const tdata_t  s,
tsize_t  c
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void _TIFFmemset tdata_t  p,
int  v,
tsize_t  c
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
TIFF* _TIFFOpenEx CxFile *  stream,
const char *  mode
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
tsize_t _tiffReadProcEx thandle_t  fd,
tdata_t  buf,
tsize_t  size
[static]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + +
tdata_t _TIFFrealloc tdata_t  p,
tsize_t  s
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
toff_t _tiffSeekProcEx thandle_t  fd,
toff_t  off,
int  whence
[static]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + +
toff_t _tiffSizeProcEx thandle_t  fd  )  [static]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void _tiffUnmapProcEx thandle_t  fd,
tdata_t  base,
toff_t  size
[static]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
tsize_t _tiffWriteProcEx thandle_t  fd,
tdata_t  buf,
tsize_t  size
[static]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void Win32ErrorHandler const char *  module,
const char *  fmt,
va_list  ap
[static]
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
void Win32WarningHandler const char *  module,
const char *  fmt,
va_list  ap
[static]
+
+ + + + + +
+   + + +

+

+


Variable Documentation

+

+ + + + +
+ + + + +
TIFFErrorHandler _TIFFerrorHandler = Win32ErrorHandler
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
TIFFErrorHandler _TIFFwarningHandler = Win32WarningHandler
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/tree.html b/SlnkDWFImpl/CxImage/doc/doxy/html/tree.html new file mode 100644 index 0000000..8abf071 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/tree.html @@ -0,0 +1,183 @@ + + + + + + + TreeView + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximabmp_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximabmp_8cpp.html new file mode 100644 index 0000000..f355e97 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximabmp_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximabmp.cpp File Reference + + + + +

ximabmp.cpp File Reference

#include "ximabmp.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximacfg_8h.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximacfg_8h.html new file mode 100644 index 0000000..bc5027e --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximacfg_8h.html @@ -0,0 +1,853 @@ + + +CxImage: ximacfg.h File Reference + + + + +

ximacfg.h File Reference

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Defines

#define __ximaCFG_h
#define CXIMAGE_ERR_NOFILE   "null file handler"
#define CXIMAGE_ERR_NOIMAGE   "null image!!!"
#define CXIMAGE_MAX_MEMORY   256000000
#define CXIMAGE_SUPPORT_ALPHA   1
#define CXIMAGE_SUPPORT_BMP   1
#define CXIMAGE_SUPPORT_DECODE   1
#define CXIMAGE_SUPPORT_DSP   1
#define CXIMAGE_SUPPORT_ENCODE   1
#define CXIMAGE_SUPPORT_GIF   1
#define CXIMAGE_SUPPORT_ICO   1
#define CXIMAGE_SUPPORT_INTERPOLATION   1
#define CXIMAGE_SUPPORT_J2K   0
#define CXIMAGE_SUPPORT_JBG   0
#define CXIMAGE_SUPPORT_JP2   1
#define CXIMAGE_SUPPORT_JPC   1
#define CXIMAGE_SUPPORT_JPG   1
#define CXIMAGE_SUPPORT_LAYERS   1
#define CXIMAGE_SUPPORT_MNG   0
#define CXIMAGE_SUPPORT_PCX   1
#define CXIMAGE_SUPPORT_PGX   1
#define CXIMAGE_SUPPORT_PNG   1
#define CXIMAGE_SUPPORT_PNM   1
#define CXIMAGE_SUPPORT_RAS   1
#define CXIMAGE_SUPPORT_SELECTION   1
#define CXIMAGE_SUPPORT_TGA   1
#define CXIMAGE_SUPPORT_TIF   1
#define CXIMAGE_SUPPORT_TRANSFORMATION   1
#define CXIMAGE_SUPPORT_WBMP   1
#define CXIMAGE_SUPPORT_WINCE   0
#define CXIMAGE_SUPPORT_WINDOWS   1
#define CXIMAGE_SUPPORT_WMF   1
#define RGB2GRAY(r, g, b)   (((b)*117 + (g)*601 + (r)*306) >> 10)
+

Define Documentation

+

+ + + + +
+ + + + +
#define __ximaCFG_h
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_ERR_NOFILE   "null file handler"
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_ERR_NOIMAGE   "null image!!!"
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_MAX_MEMORY   256000000
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_ALPHA   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_BMP   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_DECODE   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_DSP   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_ENCODE   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_GIF   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_ICO   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_INTERPOLATION   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_J2K   0
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_JBG   0
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_JP2   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_JPC   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_JPG   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_LAYERS   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_MNG   0
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_PCX   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_PGX   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_PNG   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_PNM   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_RAS   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_SELECTION   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_TGA   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_TIF   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_TRANSFORMATION   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_WBMP   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_WINCE   0
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_WINDOWS   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_WMF   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + + + + +
#define RGB2GRAY r,
g,
 )    (((b)*117 + (g)*601 + (r)*306) >> 10)
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximadef_8h.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximadef_8h.html new file mode 100644 index 0000000..ee8f9fa --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximadef_8h.html @@ -0,0 +1,263 @@ + + +CxImage: ximadef.h File Reference + + + + +

ximadef.h File Reference

#include "ximacfg.h"
+#include <windows.h>
+#include <tchar.h>
+#include <stdio.h>
+#include <math.h>
+ + + + + + + + + + + + + + + + + + + + + +

Defines

#define __ximadefs_h
#define CXIMAGE_SUPPORT_BASICTRANSFORMATIONS   1
#define CXIMAGE_SUPPORT_INTERPOLATION   1
#define CXIMAGE_SUPPORT_JASPER   1
#define CXIMAGE_SUPPORT_TRANSFORMATION   1
#define DLL_EXP
#define max(a, b)   (((a)>(b))?(a):(b))
#define min(a, b)   (((a)<(b))?(a):(b))
#define PI   3.141592653589793f
+

Define Documentation

+

+ + + + +
+ + + + +
#define __ximadefs_h
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_BASICTRANSFORMATIONS   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_INTERPOLATION   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_JASPER   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define CXIMAGE_SUPPORT_TRANSFORMATION   1
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define DLL_EXP
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + +
#define max a,
 )    (((a)>(b))?(a):(b))
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + + + + + + + + + +
#define min a,
 )    (((a)<(b))?(a):(b))
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define PI   3.141592653589793f
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximadsp_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximadsp_8cpp.html new file mode 100644 index 0000000..b6c3f9d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximadsp_8cpp.html @@ -0,0 +1,94 @@ + + +CxImage: ximadsp.cpp File Reference + + + + +

ximadsp.cpp File Reference

#include "ximage.h"
+#include "ximaiter.h"
+ + + + + + + + + +

Defines

#define HSLMAX   255
#define HSLUNDEFINED   (HSLMAX*2/3)
#define RGBMAX   255
+

Define Documentation

+

+ + + + +
+ + + + +
#define HSLMAX   255
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define HSLUNDEFINED   (HSLMAX*2/3)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define RGBMAX   255
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximaenc_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaenc_8cpp.html new file mode 100644 index 0000000..0275415 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaenc_8cpp.html @@ -0,0 +1,27 @@ + + +CxImage: ximaenc.cpp File Reference + + + + +

ximaenc.cpp File Reference

#include "ximage.h"
+#include "ximajpg.h"
+#include "ximagif.h"
+#include "ximapng.h"
+#include "ximabmp.h"
+#include "ximaico.h"
+#include "ximatif.h"
+#include "ximatga.h"
+#include "ximapcx.h"
+#include "ximawbmp.h"
+#include "ximawmf.h"
+#include "ximajas.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximaexif_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaexif_8cpp.html new file mode 100644 index 0000000..9c08fdc --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaexif_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximaexif.cpp File Reference + + + + +

ximaexif.cpp File Reference

#include "ximajpg.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximage_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximage_8cpp.html new file mode 100644 index 0000000..fe1180b --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximage_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximage.cpp File Reference + + + + +

ximage.cpp File Reference

#include "ximage.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximage_8h.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximage_8h.html new file mode 100644 index 0000000..bc2a39c --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximage_8h.html @@ -0,0 +1,143 @@ + + +CxImage: ximage.h File Reference + + + + +

ximage.h File Reference

#include "xfile.h"
+#include "xiofile.h"
+#include "xmemfile.h"
+#include "ximadef.h"
+ + + + + + + + + + + + + + + + + +

Classes

class  CxImage
struct  CxImage::rgb_color
struct  CxImage::tagCxImageInfo
struct  CxImage::tagCxTextInfo

Defines

#define __CXIMAGE_H

Enumerations

enum  ENUM_CXIMAGE_FORMATS {
+  CXIMAGE_FORMAT_UNKNOWN, +CXIMAGE_FORMAT_BMP, +CXIMAGE_FORMAT_GIF, +CXIMAGE_FORMAT_JPG, +
+  CXIMAGE_FORMAT_PNG, +CXIMAGE_FORMAT_ICO, +CXIMAGE_FORMAT_TIF, +CXIMAGE_FORMAT_TGA, +
+  CXIMAGE_FORMAT_PCX, +CXIMAGE_FORMAT_WBMP, +CXIMAGE_FORMAT_WMF, +CXIMAGE_FORMAT_JP2, +
+  CXIMAGE_FORMAT_JPC, +CXIMAGE_FORMAT_PGX, +CXIMAGE_FORMAT_PNM, +CXIMAGE_FORMAT_RAS, +
+  CMAX_IMAGE_FORMATS +
+ }
+

Define Documentation

+

+ + + + +
+ + + + +
#define __CXIMAGE_H
+
+ + + + + +
+   + + +

+

+


Enumeration Type Documentation

+

+ + + + +
+ + + + +
enum ENUM_CXIMAGE_FORMATS
+
+ + + + + +
+   + + +

+

Enumeration values:
+ + + + + + + + + + + + + + + + + + +
CXIMAGE_FORMAT_UNKNOWN  +
CXIMAGE_FORMAT_BMP  +
CXIMAGE_FORMAT_GIF  +
CXIMAGE_FORMAT_JPG  +
CXIMAGE_FORMAT_PNG  +
CXIMAGE_FORMAT_ICO  +
CXIMAGE_FORMAT_TIF  +
CXIMAGE_FORMAT_TGA  +
CXIMAGE_FORMAT_PCX  +
CXIMAGE_FORMAT_WBMP  +
CXIMAGE_FORMAT_WMF  +
CXIMAGE_FORMAT_JP2  +
CXIMAGE_FORMAT_JPC  +
CXIMAGE_FORMAT_PGX  +
CXIMAGE_FORMAT_PNM  +
CXIMAGE_FORMAT_RAS  +
CMAX_IMAGE_FORMATS  +
+
+
+


Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximagif_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximagif_8cpp.html new file mode 100644 index 0000000..9fe140f --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximagif_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximagif.cpp File Reference + + + + +

ximagif.cpp File Reference

#include "ximagif.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximahist_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximahist_8cpp.html new file mode 100644 index 0000000..2e5575d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximahist_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximahist.cpp File Reference + + + + +

ximahist.cpp File Reference

#include "ximage.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximaico_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaico_8cpp.html new file mode 100644 index 0000000..916a2cc --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaico_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximaico.cpp File Reference + + + + +

ximaico.cpp File Reference

#include "ximaico.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximainfo_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximainfo_8cpp.html new file mode 100644 index 0000000..9c36d61 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximainfo_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximainfo.cpp File Reference + + + + +

ximainfo.cpp File Reference

#include "ximage.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximaint_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaint_8cpp.html new file mode 100644 index 0000000..4378f4b --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaint_8cpp.html @@ -0,0 +1,244 @@ + + +CxImage: ximaint.cpp File Reference + + + + +

ximaint.cpp File Reference

#include "ximage.h"
+#include "ximath.h"
+ + + + + + + + + + + + + + + + + + + + + +

Defines

#define KM_B   (1.0f/3.0f)
#define KM_C   (1.0f/3.0f)
#define KM_P0   (( 6.0f - 2.0f * KM_B ) / 6.0f)
#define KM_P2   ((-18.0f + 12.0f * KM_B + 6.0f * KM_C) / 6.0f)
#define KM_P3   (( 12.0f - 9.0f * KM_B - 6.0f * KM_C) / 6.0f)
#define KM_Q0   (( 8.0f * KM_B + 24.0f * KM_C) / 6.0f)
#define KM_Q1   ((-12.0f * KM_B - 48.0f * KM_C) / 6.0f)
#define KM_Q2   (( 6.0f * KM_B + 30.0f * KM_C) / 6.0f)
#define KM_Q3   (( -1.0f * KM_B - 6.0f * KM_C) / 6.0f)
+

Define Documentation

+

+ + + + +
+ + + + +
#define KM_B   (1.0f/3.0f)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define KM_C   (1.0f/3.0f)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define KM_P0   (( 6.0f - 2.0f * KM_B ) / 6.0f)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define KM_P2   ((-18.0f + 12.0f * KM_B + 6.0f * KM_C) / 6.0f)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define KM_P3   (( 12.0f - 9.0f * KM_B - 6.0f * KM_C) / 6.0f)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define KM_Q0   (( 8.0f * KM_B + 24.0f * KM_C) / 6.0f)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define KM_Q1   ((-12.0f * KM_B - 48.0f * KM_C) / 6.0f)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define KM_Q2   (( 6.0f * KM_B + 30.0f * KM_C) / 6.0f)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define KM_Q3   (( -1.0f * KM_B - 6.0f * KM_C) / 6.0f)
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximaj2k_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaj2k_8cpp.html new file mode 100644 index 0000000..e883104 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximaj2k_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximaj2k.cpp File Reference + + + + +

ximaj2k.cpp File Reference

#include "ximaj2k.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximajas_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximajas_8cpp.html new file mode 100644 index 0000000..6b0cf18 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximajas_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximajas.cpp File Reference + + + + +

ximajas.cpp File Reference

#include "ximajas.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximajbg_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximajbg_8cpp.html new file mode 100644 index 0000000..99ec5b3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximajbg_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximajbg.cpp File Reference + + + + +

ximajbg.cpp File Reference

#include "ximajbg.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximajpg_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximajpg_8cpp.html new file mode 100644 index 0000000..4ec77d3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximajpg_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximajpg.cpp File Reference + + + + +

ximajpg.cpp File Reference

#include "ximajpg.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximalpha_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximalpha_8cpp.html new file mode 100644 index 0000000..a163272 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximalpha_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximalpha.cpp File Reference + + + + +

ximalpha.cpp File Reference

#include "ximage.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximalyr_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximalyr_8cpp.html new file mode 100644 index 0000000..a7d2332 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximalyr_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximalyr.cpp File Reference + + + + +

ximalyr.cpp File Reference

#include "ximage.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximamng_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximamng_8cpp.html new file mode 100644 index 0000000..d198b1f --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximamng_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximamng.cpp File Reference + + + + +

ximamng.cpp File Reference

#include "ximamng.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximapal_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximapal_8cpp.html new file mode 100644 index 0000000..5149c9d --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximapal_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximapal.cpp File Reference + + + + +

ximapal.cpp File Reference

#include "ximage.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximapcx_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximapcx_8cpp.html new file mode 100644 index 0000000..5e7e010 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximapcx_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximapcx.cpp File Reference + + + + +

ximapcx.cpp File Reference

#include "ximapcx.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximapng_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximapng_8cpp.html new file mode 100644 index 0000000..bff1f44 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximapng_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximapng.cpp File Reference + + + + +

ximapng.cpp File Reference

#include "ximapng.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximasel_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximasel_8cpp.html new file mode 100644 index 0000000..20d9b60 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximasel_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximasel.cpp File Reference + + + + +

ximasel.cpp File Reference

#include "ximage.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximatga_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximatga_8cpp.html new file mode 100644 index 0000000..2b47869 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximatga_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximatga.cpp File Reference + + + + +

ximatga.cpp File Reference

#include "ximatga.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximath_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximath_8cpp.html new file mode 100644 index 0000000..6d8c0cf --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximath_8cpp.html @@ -0,0 +1,18 @@ + + +CxImage: ximath.cpp File Reference + + + + +

ximath.cpp File Reference

#include "ximage.h"
+#include "ximath.h"
+#include <math.h>
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximatif_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximatif_8cpp.html new file mode 100644 index 0000000..f9546b2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximatif_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximatif.cpp File Reference + + + + +

ximatif.cpp File Reference

#include "ximatif.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximatran_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximatran_8cpp.html new file mode 100644 index 0000000..ce246f6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximatran_8cpp.html @@ -0,0 +1,244 @@ + + +CxImage: ximatran.cpp File Reference + + + + +

ximatran.cpp File Reference

#include "ximage.h"
+#include "ximath.h"
+ + + + + + + + + + + + + + + + + + + + + +

Defines

#define dth_MaxDitherIntensityVal   (dth_NumRows*dth_NumCols*(dth_NumIntensityLevels-1))
#define dth_MaxIntensityVal   255
#define dth_NumCols   4
#define dth_NumColsLessOne   (dth_NumCols-1)
#define dth_NumIntensityLevels   2
#define dth_NumRows   4
#define dth_NumRowsLessOne   (dth_NumRows-1)
#define dth_RowsXCols   (dth_NumRows*dth_NumCols)
#define RBLOCK   64
+

Define Documentation

+

+ + + + +
+ + + + +
#define dth_MaxDitherIntensityVal   (dth_NumRows*dth_NumCols*(dth_NumIntensityLevels-1))
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define dth_MaxIntensityVal   255
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define dth_NumCols   4
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define dth_NumColsLessOne   (dth_NumCols-1)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define dth_NumIntensityLevels   2
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define dth_NumRows   4
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define dth_NumRowsLessOne   (dth_NumRows-1)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define dth_RowsXCols   (dth_NumRows*dth_NumCols)
+
+ + + + + +
+   + + +

+

+

+ + + + +
+ + + + +
#define RBLOCK   64
+
+ + + + + +
+   + + +

+

+


Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximawbmp_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximawbmp_8cpp.html new file mode 100644 index 0000000..43600fe --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximawbmp_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximawbmp.cpp File Reference + + + + +

ximawbmp.cpp File Reference

#include "ximawbmp.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximawmf_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximawmf_8cpp.html new file mode 100644 index 0000000..ac85667 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximawmf_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: ximawmf.cpp File Reference + + + + +

ximawmf.cpp File Reference

#include "ximawmf.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/ximawnd_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/ximawnd_8cpp.html new file mode 100644 index 0000000..1d41326 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/ximawnd_8cpp.html @@ -0,0 +1,18 @@ + + +CxImage: ximawnd.cpp File Reference + + + + +

ximawnd.cpp File Reference

#include "ximage.h"
+#include "ximaiter.h"
+#include "ximabmp.h"
+ + +
+
Generated on Mon Oct 11 22:30:17 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxy/html/xmemfile_8cpp.html b/SlnkDWFImpl/CxImage/doc/doxy/html/xmemfile_8cpp.html new file mode 100644 index 0000000..a14e54a --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxy/html/xmemfile_8cpp.html @@ -0,0 +1,16 @@ + + +CxImage: xmemfile.cpp File Reference + + + + +

xmemfile.cpp File Reference

#include "xmemfile.h"
+ + +
+
Generated on Mon Oct 11 22:30:18 2004 for CxImage by + +doxygen 1.3.8
+ + diff --git a/SlnkDWFImpl/CxImage/doc/doxyfile.txt b/SlnkDWFImpl/CxImage/doc/doxyfile.txt new file mode 100644 index 0000000..b43e241 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/doxyfile.txt @@ -0,0 +1,226 @@ +# Doxyfile 1.3.8 + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- +PROJECT_NAME = CxImage +PROJECT_NUMBER = "version 5.99c" +OUTPUT_DIRECTORY = D:/Dev/cximage/cximage599b/doc/doxy +CREATE_SUBDIRS = NO +OUTPUT_LANGUAGE = English +USE_WINDOWS_ENCODING = YES +BRIEF_MEMBER_DESC = YES +REPEAT_BRIEF = YES +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the +ALWAYS_DETAILED_SEC = NO +INLINE_INHERITED_MEMB = NO +FULL_PATH_NAMES = NO +STRIP_FROM_PATH = "H:/Documents and Settings/Administrator/" +STRIP_FROM_INC_PATH = +SHORT_NAMES = NO +JAVADOC_AUTOBRIEF = NO +MULTILINE_CPP_IS_BRIEF = NO +DETAILS_AT_TOP = NO +INHERIT_DOCS = YES +DISTRIBUTE_GROUP_DOC = NO +TAB_SIZE = 8 +ALIASES = +OPTIMIZE_OUTPUT_FOR_C = NO +OPTIMIZE_OUTPUT_JAVA = NO +SUBGROUPING = YES +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- +EXTRACT_ALL = YES +EXTRACT_PRIVATE = YES +EXTRACT_STATIC = YES +EXTRACT_LOCAL_CLASSES = YES +EXTRACT_LOCAL_METHODS = NO +HIDE_UNDOC_MEMBERS = NO +HIDE_UNDOC_CLASSES = NO +HIDE_FRIEND_COMPOUNDS = NO +HIDE_IN_BODY_DOCS = NO +INTERNAL_DOCS = NO +CASE_SENSE_NAMES = NO +HIDE_SCOPE_NAMES = NO +SHOW_INCLUDE_FILES = YES +INLINE_INFO = YES +SORT_MEMBER_DOCS = YES +SORT_BRIEF_DOCS = YES +SORT_BY_SCOPE_NAME = YES +GENERATE_TODOLIST = YES +GENERATE_TESTLIST = YES +GENERATE_BUGLIST = YES +GENERATE_DEPRECATEDLIST= YES +ENABLED_SECTIONS = +MAX_INITIALIZER_LINES = 30 +SHOW_USED_FILES = YES +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- +QUIET = NO +WARNINGS = YES +WARN_IF_UNDOCUMENTED = YES +WARN_IF_DOC_ERROR = YES +WARN_FORMAT = "$file:$line: $text" +WARN_LOGFILE = +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- +INPUT = D:/Dev/cximage/cximage599b/CxImage +FILE_PATTERNS = *.cpp \ + ximadef.h \ + ximacfg.h \ + ximage.h +RECURSIVE = NO +EXCLUDE = +EXCLUDE_SYMLINKS = NO +EXCLUDE_PATTERNS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = * +EXAMPLE_RECURSIVE = NO +IMAGE_PATH = +INPUT_FILTER = +FILTER_PATTERNS = +FILTER_SOURCE_FILES = NO +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- +SOURCE_BROWSER = NO +INLINE_SOURCES = NO +STRIP_CODE_COMMENTS = YES +REFERENCED_BY_RELATION = NO +REFERENCES_RELATION = NO +VERBATIM_HEADERS = NO +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- +ALPHABETICAL_INDEX = NO +COLS_IN_ALPHA_INDEX = 5 +IGNORE_PREFIX = +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- +GENERATE_HTML = YES +HTML_OUTPUT = html +HTML_FILE_EXTENSION = .html +HTML_HEADER = +HTML_FOOTER = +HTML_STYLESHEET = +HTML_ALIGN_MEMBERS = YES +GENERATE_HTMLHELP = NO +CHM_FILE = +HHC_LOCATION = +GENERATE_CHI = NO +BINARY_TOC = NO +TOC_EXPAND = NO +DISABLE_INDEX = NO +ENUM_VALUES_PER_LINE = 4 +GENERATE_TREEVIEW = YES +TREEVIEW_WIDTH = 250 +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- +GENERATE_LATEX = NO +LATEX_OUTPUT = latex +LATEX_CMD_NAME = latex +MAKEINDEX_CMD_NAME = makeindex +COMPACT_LATEX = NO +PAPER_TYPE = a4wide +EXTRA_PACKAGES = +LATEX_HEADER = +PDF_HYPERLINKS = NO +USE_PDFLATEX = NO +LATEX_BATCHMODE = NO +LATEX_HIDE_INDICES = NO +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- +GENERATE_RTF = NO +RTF_OUTPUT = rtf +COMPACT_RTF = NO +RTF_HYPERLINKS = NO +RTF_STYLESHEET_FILE = +RTF_EXTENSIONS_FILE = +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- +GENERATE_MAN = NO +MAN_OUTPUT = man +MAN_EXTENSION = .3 +MAN_LINKS = NO +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- +GENERATE_XML = NO +XML_OUTPUT = xml +XML_SCHEMA = +XML_DTD = +XML_PROGRAMLISTING = YES +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- +GENERATE_AUTOGEN_DEF = NO +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- +GENERATE_PERLMOD = NO +PERLMOD_LATEX = NO +PERLMOD_PRETTY = YES +PERLMOD_MAKEVAR_PREFIX = +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = NO +EXPAND_ONLY_PREDEF = NO +SEARCH_INCLUDES = YES +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +PREDEFINED = WIN32 +EXPAND_AS_DEFINED = +SKIP_FUNCTION_MACROS = YES +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- +TAGFILES = +GENERATE_TAGFILE = +ALLEXTERNALS = NO +EXTERNAL_GROUPS = YES +PERL_PATH = /usr/bin/perl +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- +CLASS_DIAGRAMS = NO +HIDE_UNDOC_RELATIONS = YES +HAVE_DOT = NO +CLASS_GRAPH = YES +COLLABORATION_GRAPH = YES +UML_LOOK = NO +TEMPLATE_RELATIONS = NO +INCLUDE_GRAPH = YES +INCLUDED_BY_GRAPH = YES +CALL_GRAPH = NO +GRAPHICAL_HIERARCHY = YES +DOT_IMAGE_FORMAT = png +DOT_PATH = +DOTFILE_DIRS = +MAX_DOT_GRAPH_WIDTH = 1024 +MAX_DOT_GRAPH_HEIGHT = 1024 +MAX_DOT_GRAPH_DEPTH = 1000 +GENERATE_LEGEND = YES +DOT_CLEANUP = YES +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- +SEARCHENGINE = NO diff --git a/SlnkDWFImpl/CxImage/doc/layers.jpg b/SlnkDWFImpl/CxImage/doc/layers.jpg new file mode 100644 index 0000000..8d699ad Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/layers.jpg differ diff --git a/SlnkDWFImpl/CxImage/doc/libjpeg_patches.zip b/SlnkDWFImpl/CxImage/doc/libjpeg_patches.zip new file mode 100644 index 0000000..cceb478 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/libjpeg_patches.zip differ diff --git a/SlnkDWFImpl/CxImage/doc/libtiff_patches.zip b/SlnkDWFImpl/CxImage/doc/libtiff_patches.zip new file mode 100644 index 0000000..0f0a11d Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/libtiff_patches.zip differ diff --git a/SlnkDWFImpl/CxImage/doc/structure2.png b/SlnkDWFImpl/CxImage/doc/structure2.png new file mode 100644 index 0000000..97b71f5 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/structure2.png differ diff --git a/SlnkDWFImpl/CxImage/doc/top.htm b/SlnkDWFImpl/CxImage/doc/top.htm new file mode 100644 index 0000000..0e3b5c8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/top.htm @@ -0,0 +1,13 @@ + + + CxImage Index + + + + + + +


+|[ home ]|[ article ]|[ reference ]|[ history ]|[ license ]|[ linked libraries ]|

+ + diff --git a/SlnkDWFImpl/CxImage/doc/tree.png b/SlnkDWFImpl/CxImage/doc/tree.png new file mode 100644 index 0000000..84e3b32 Binary files /dev/null and b/SlnkDWFImpl/CxImage/doc/tree.png differ diff --git a/SlnkDWFImpl/CxImage/doc/xdp.css b/SlnkDWFImpl/CxImage/doc/xdp.css new file mode 100644 index 0000000..5b11171 --- /dev/null +++ b/SlnkDWFImpl/CxImage/doc/xdp.css @@ -0,0 +1,89 @@ +FONT { + FONT-SIZE: 12px; FONT-FAMILY: Verdana,Helvetica +} +P { + FONT-SIZE: 12px; FONT-FAMILY: Verdana,Helvetica +} +DIV { + FONT-SIZE: 12px; FONT-FAMILY: Verdana,Helvetica +} +TD { + FONT-SIZE: 12px; FONT-FAMILY: Verdana,Helvetica +} +LI { + FONT-SIZE: 12px; FONT-FAMILY: Verdana,Helvetica; line-height: 18px; +} +DD { + FONT-SIZE: 12pt; FONT-FAMILY: Verdana, Helvetica; COLOR: Navy; line-height: 18px; +} +BODY { + FONT-SIZE: 12px; + FONT-FAMILY: Verdana,Helvetica; +} +H2 { + FONT-SIZE: 15px; FONT-FAMILY: Verdana,Helvetica; letter-spacing: 2px; +} +H3 { + FONT-SIZE: 13px; FONT-FAMILY: Verdana,Helvetica; letter-spacing: 2px; +} +INPUT { + FONT-SIZE: 11px; FONT-FAMILY: Verdana,Helvetica +} +TEXTAREA { + FONT-SIZE: 11px; FONT-FAMILY: Verdana,Helvetica +} +FORM { + FONT-SIZE: 11px; FONT-FAMILY: Verdana,Helvetica +} +SELECT { + FONT-SIZE: 11px; FONT-FAMILY: Verdana,Helvetica +} +PRE { + font-size: 11px; font-family: "Courier New", Courier, monospace; background-color: #F8F4F4; + border: 1px solid Black; padding: 3px; background-image: url(img5/gridpre.gif); width: 80%; +} +CODE { + font-size: 12px; font-family: "Courier New", Courier, monospace; color: #800000; +} +A:link { + FONT-SIZE: 12px; FONT-FAMILY: Verdana, Helvetica; COLOR: #4169E1; TEXT-DECORATION: none +} +A:active { + FONT-SIZE: 12px; FONT-FAMILY: Verdana, Helvetica; COLOR: Red; TEXT-DECORATION: none +} +A:visited { + FONT-SIZE: 12px; FONT-FAMILY: Verdana, Helvetica; COLOR: #4682B4; TEXT-DECORATION: none +} +A:hover { + FONT-SIZE: 12px; FONT-FAMILY: Verdana, Helvetica; COLOR: Blue; TEXT-DECORATION: underline; +} +.title { + FONT-SIZE: 15px; FONT-FAMILY: Verdana, Helvetica; COLOR: #003399; font-weight: bold; +} +.chapter { + FONT-SIZE: 14px; FONT-FAMILY: Verdana,Helvetica; letter-spacing: 2px; + text-align: center; font-weight: bold; +} +.content { + FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; COLOR: #000000 +} +.grayed { + FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; COLOR: #999999 +} +.frozen { + FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; COLOR: #0099FF +} +.comment { + FONT-SIZE: 11px; FONT-FAMILY: "Courier New", Courier, monospace; COLOR: green; font-style: italic; +} +.active { + FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; COLOR: #FF0000 +} +.option { + FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; FONT-WEIGHT: bold; + BACKGROUND: none transparent scroll repeat 0% 0%; COLOR: #ffffff; TEXT-DECORATION: none +} +.tiny { + FONT-SIZE: 9px; FONT-FAMILY: Verdana, Helvetica; COLOR: #4682B4; FONT-WEIGHT: normal; + font-style: italic; BACKGROUND: none transparent scroll repeat 0% 0%; +} diff --git a/SlnkDWFImpl/CxImage/index.htm b/SlnkDWFImpl/CxImage/index.htm new file mode 100644 index 0000000..dfa3109 --- /dev/null +++ b/SlnkDWFImpl/CxImage/index.htm @@ -0,0 +1,14 @@ + + + +CxImage + + + + + + + +<body> +</body> + diff --git a/SlnkDWFImpl/CxImage/j2k/.gitignore b/SlnkDWFImpl/CxImage/j2k/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/j2k/bio.c b/SlnkDWFImpl/CxImage/j2k/bio.c new file mode 100644 index 0000000..3f8e456 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/bio.c @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "bio.h" +#include + +unsigned char *bio_start, *bio_end, *bio_bp; +unsigned int bio_buf; +int bio_ct; + +extern jmp_buf j2k_error; + +/// +/// Number of bytes written. +/// +int bio_numbytes() { + return bio_bp-bio_start; +} + +/// +/// Init encoder. +/// +/// Output buffer +/// Output buffer length +void bio_init_enc(unsigned char *bp, int len) { + bio_start=bp; + bio_end=bp+len; + bio_bp=bp; + bio_buf=0; + bio_ct=8; +} + +/// +/// Init decoder. +/// +/// Input buffer +/// Input buffer length +void bio_init_dec(unsigned char *bp, int len) { + bio_start=bp; + bio_end=bp+len; + bio_bp=bp; + bio_buf=0; + bio_ct=0; +} + +/// +/// Write byte. +/// +void bio_byteout() { + bio_buf=(bio_buf<<8)&0xffff; + bio_ct=bio_buf==0xff00?7:8; + if (bio_bp>=bio_end) longjmp(j2k_error, 1); + *bio_bp++=bio_buf>>8; +} + +/// +/// Read byte. +/// +void bio_bytein() { + bio_buf=(bio_buf<<8)&0xffff; + bio_ct=bio_buf==0xff00?7:8; + if (bio_bp>=bio_end) longjmp(j2k_error, 1); + bio_buf|=*bio_bp++; +} + +/// +/// Write bit. +/// +/// Bit to write (0 or 1) +void bio_putbit(int b) { + if (bio_ct==0) { + bio_byteout(); + } + bio_ct--; + bio_buf|=b< +/// Read bit. +/// +int bio_getbit() { + if (bio_ct==0) { + bio_bytein(); + } + bio_ct--; + return (bio_buf>>bio_ct)&1; +} + +/// +/// Write bits. +/// +/// Value of bits +/// Number of bits to write +void bio_write(int v, int n) { + int i; + for (i=n-1; i>=0; i--) { + bio_putbit((v>>i)&1); + } +} + +/// +/// Read bits. +/// +/// Number of bits to read +int bio_read(int n) { + int i, v; + v=0; + for (i=n-1; i>=0; i--) { + v+=bio_getbit()< +/// Flush bits. +/// +void bio_flush() { + bio_ct=0; + bio_byteout(); + if (bio_ct==7) { + bio_ct=0; + bio_byteout(); + } +} + +/// +/// +void bio_inalign() { + bio_ct=0; + if ((bio_buf&0xff)==0xff) { + bio_bytein(); + bio_ct=0; + } +} diff --git a/SlnkDWFImpl/CxImage/j2k/bio.h b/SlnkDWFImpl/CxImage/j2k/bio.h new file mode 100644 index 0000000..ca29c07 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/bio.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __BIO_H +#define __BIO_H + +int bio_numbytes(); +void bio_init_enc(unsigned char *bp, int len); +void bio_init_dec(unsigned char *bp, int len); +void bio_write(int v, int n); +int bio_read(int n); +void bio_flush(); +void bio_inalign(); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/cio.c b/SlnkDWFImpl/CxImage/j2k/cio.c new file mode 100644 index 0000000..61f5522 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/cio.c @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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. + */ + +// TODO check bit stuffing issues + +#include "cio.h" +#include + +unsigned char *cio_start, *cio_end, *cio_bp; + +extern jmp_buf j2k_error; + +/// +/// Number of bytes written. +/// +int cio_numbytes() { + return cio_bp-cio_start; +} + +/// +/// Get position in byte stream. +/// +int cio_tell() { + return cio_bp-cio_start; +} + +/// +/// Set position in byte stream. +/// +void cio_seek(int pos) { + cio_bp=cio_start+pos; +} + +/// +/// Number of bytes left before the end of the stream. +/// +int cio_numbytesleft() { + return cio_end-cio_bp; +} + +/// +/// Get pointer to the current position in the stream. +/// +unsigned char *cio_getbp() { + return cio_bp; +} + +/// +/// Initialize byte IO. +/// +void cio_init(unsigned char *bp, int len) { + cio_start=bp; + cio_end=bp+len; + cio_bp=bp; +} + +/// +/// Write a byte. +/// +void cio_byteout(unsigned char v) { + if (cio_bp>=cio_end) longjmp(j2k_error, 1); + *cio_bp++=v; +} + +/// +/// Read a byte. +/// +unsigned char cio_bytein() { + if (cio_bp>=cio_end) longjmp(j2k_error, 1); + return *cio_bp++; +} + +/// +/// Write a byte. +/// +void cio_write(unsigned int v, int n) { + int i; + for (i=n-1; i>=0; i--) { + cio_byteout((unsigned char)((v>>(i<<3))&0xff)); + } +} + +/// +/// Read some bytes. +/// +unsigned int cio_read(int n) { + int i; + unsigned int v; + v=0; + for (i=n-1; i>=0; i--) { + v+=cio_bytein()<<(i<<3); + } + return v; +} + +/// +/// Write some bytes. +/// +void cio_skip(int n) { + cio_bp+=n; +} diff --git a/SlnkDWFImpl/CxImage/j2k/cio.h b/SlnkDWFImpl/CxImage/j2k/cio.h new file mode 100644 index 0000000..4cba617 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/cio.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __CIO_H +#define __CIO_H + +int cio_tell(); +void cio_seek(int pos); +int cio_numbytes(); +int cio_numbytesleft(); +unsigned char *cio_getbp(); +void cio_init(unsigned char *bp, int len); +void cio_write(unsigned int v, int n); +unsigned int cio_read(int n); +void cio_skip(int n); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/dwt.c b/SlnkDWFImpl/CxImage/j2k/dwt.c new file mode 100644 index 0000000..9e218a9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/dwt.c @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "dwt.h" +#include "int.h" +#include "fix.h" +#include + +#define S(i) a[x*(i)*2] +#define D(i) a[x*(1+(i)*2)] +#define S_(i) ((i)<0?S(0):((i)>=sn?S(sn-1):S(i))) +#define D_(i) ((i)<0?D(0):((i)>=dn?D(dn-1):D(i))) + +/// +/// This table contains the norms of the 5-3 wavelets for different bands. +/// +double dwt_norms[4][10]={ + {1.000, 1.500, 2.750, 5.375, 10.68, 21.34, 42.67, 85.33, 170.7, 341.3}, + {1.038, 1.592, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9}, + {1.038, 1.592, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9}, + {.7186, .9218, 1.586, 3.043, 6.019, 12.01, 24.00, 47.97, 95.93} +}; + +/// +/// This table contains the norms of the 9-7 wavelets for different bands. +/// +double dwt_norms_real[4][10]={ + {1.000, 1.965, 4.177, 8.403, 16.90, 33.84, 67.69, 135.3, 270.6, 540.9}, + {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0}, + {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0}, + {2.080, 3.865, 8.307, 17.18, 34.71, 69.59, 139.3, 278.6, 557.2} +}; + +/// +/// Forward lazy transform. +/// +void dwt_deinterleave(int *a, int n, int x) { + int dn, sn, i; + int *b; + dn=n/2; + sn=(n+1)/2; + b=(int*)malloc(n*sizeof(int)); + for (i=0; i +/// Inverse lazy transform. +/// +void dwt_interleave(int *a, int n, int x) { + int dn, sn, i; + int *b; + dn=n/2; + sn=(n+1)/2; + b=(int*)malloc(n*sizeof(int)); + for (i=0; i +/// Forward 5-3 wavelet tranform in 1-D. +/// +void dwt_encode_1(int *a, int n, int x) +{ + int dn, sn, i; + dn=n/2; + sn=1+(n-1)/2; + for (i=0; i>1; + for (i=0; i>2; + dwt_deinterleave(a, n, x); +} + +/// +/// Inverse 5-3 wavelet tranform in 1-D. +/// +void dwt_decode_1(int *a, int n, int x) +{ + int dn, sn, i; + dn=n/2; + sn=1+(n-1)/2; + dwt_interleave(a, n, x); + for (i=0; i>2; + for (i=0; i>1; +} + +/// +/// Forward 5-3 wavelet tranform in 2-D. +/// +void dwt_encode(int* a, int w, int h, int l) +{ + int i, j, rw, rh; + for (i=0; i +/// Inverse 5-3 wavelet tranform in 2-D. +/// +void dwt_decode(int* a, int w, int h, int l) +{ + int i, j, rw, rh; + for (i=l-1; i>=0; i--) { + rw=int_ceildivpow2(w, i); + rh=int_ceildivpow2(h, i); + for (j=0; j +/// Get gain of 5-3 wavelet transform. +/// +int dwt_getgain(int orient) { + if (orient==0) return 0; + if (orient==1 || orient==2) return 1; + return 2; +} + +/// +/// Get norm of 5-3 wavelet. +/// +double dwt_getnorm(int level, int orient) { + return dwt_norms[orient][level]; +} + +/// +/// Forward 9-7 wavelet transform in 1-D. +/// +void dwt_encode_1_real(int *a, int n, int x) +{ + int dn, sn, i; + dn=n/2; + sn=1+(n-1)/2; + for (i=0; i +/// Inverse 9-7 wavelet transform in 1-D. +/// +void dwt_decode_1_real(int *a, int n, int x) +{ + int dn, sn, i; + dn=n/2; + sn=1+(n-1)/2; + dwt_interleave(a, n, x); + for (i=0; i +/// Forward 9-7 wavelet transform in 2-D. +/// +void dwt_encode_real(int* a, int w, int h, int l) +{ + int i, j, rw, rh; + for (i=0; i +/// Inverse 9-7 wavelet transform in 2-D. +/// +void dwt_decode_real(int* a, int w, int h, int l) +{ + int i, j, rw, rh; + for (i=l-1; i>=0; i--) { + rw=int_ceildivpow2(w, i); + rh=int_ceildivpow2(h, i); + for (j=0; j +/// Get gain of 9-7 wavelet transform. +/// +int dwt_getgain_real(int orient) { + return 0; +} + +/// +/// Get norm of 9-7 wavelet. +/// +double dwt_getnorm_real(int level, int orient) { + return dwt_norms_real[orient][level]; +} diff --git a/SlnkDWFImpl/CxImage/j2k/dwt.h b/SlnkDWFImpl/CxImage/j2k/dwt.h new file mode 100644 index 0000000..be3d6fd --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/dwt.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __DWT_H +#define __DWT_H + +void dwt_encode(int* a, int w, int h, int l); +void dwt_decode(int* a, int w, int h, int l); +int dwt_getgain(int orient); +double dwt_getnorm(int level, int orient); + +void dwt_encode_real(int* a, int w, int h, int l); +void dwt_decode_real(int* a, int w, int h, int l); +int dwt_getgain_real(int orient); +double dwt_getnorm_real(int level, int orient); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/fix.c b/SlnkDWFImpl/CxImage/j2k/fix.c new file mode 100644 index 0000000..5a21284 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/fix.c @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "fix.h" + +#ifdef WIN32 +#define int64 __int64 +#else +#define int64 long long +#endif + +/// +/// Multiply two fixed-precision rational numbers. +/// +int fix_mul(int a, int b) { + return (int)((int64)a*(int64)b>>13); +} diff --git a/SlnkDWFImpl/CxImage/j2k/fix.h b/SlnkDWFImpl/CxImage/j2k/fix.h new file mode 100644 index 0000000..f7495ff --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/fix.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __FIX_H +#define __FIX_H + +int fix_mul(int a, int b); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/int.c b/SlnkDWFImpl/CxImage/j2k/int.c new file mode 100644 index 0000000..92dae3d --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/int.c @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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. + */ + +/// +/// Get the minimum of two integers. +/// +int int_min(int a, int b) { + return a +/// Get the maximum of two integers. +/// +int int_max(int a, int b) { + return a>b?a:b; +} + +/// +/// Clamp an integer inside an interval. +/// +int int_clamp(int a, int min, int max) { + if (amax) return max; + return a; +} + +/// +/// Get absolute value of integer. +/// +int int_abs(int a) { + return a<0?-a:a; +} + +/// +/// Divide an integer and round upwards. +/// +int int_ceildiv(int a, int b) { + return (a+b-1)/b; +} + +/// +/// Divide an integer by a power of 2 and round upwards. +/// +int int_ceildivpow2(int a, int b) { + return (a+(1<>b; +} + +/// +/// Divide an integer by a power of 2 and round downwards. +/// +int int_floordivpow2(int a, int b) { + return a>>b; +} + +/// +/// Get logarithm of an integer and round downwards. +/// +int int_floorlog2(int a) { + int l; + for (l=0; a>1; l++) { + a>>=1; + } + return l; +} diff --git a/SlnkDWFImpl/CxImage/j2k/int.h b/SlnkDWFImpl/CxImage/j2k/int.h new file mode 100644 index 0000000..c554b01 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/int.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __INT_H +#define __INT_H + +int int_min(int a, int b); +int int_max(int a, int b); +int int_clamp(int a, int min, int max); +int int_abs(int a); +int int_ceildiv(int a, int b); +int int_ceildivpow2(int a, int b); +int int_floordivpow2(int a, int b); +int int_floorlog2(int a); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/j2k.c b/SlnkDWFImpl/CxImage/j2k/j2k.c new file mode 100644 index 0000000..2e87b1a --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/j2k.c @@ -0,0 +1,752 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "j2k.h" +#include "cio.h" +#include "tcd.h" +#include "dwt.h" +#include "int.h" + +#define J2K_MS_SOC 0xff4f +#define J2K_MS_SOT 0xff90 +#define J2K_MS_SOD 0xff93 +#define J2K_MS_EOC 0xffd9 +#define J2K_MS_SIZ 0xff51 +#define J2K_MS_COD 0xff52 +#define J2K_MS_COC 0xff53 +#define J2K_MS_RGN 0xff5e +#define J2K_MS_QCD 0xff5c +#define J2K_MS_QCC 0xff5d +#define J2K_MS_POC 0xff5f +#define J2K_MS_TLM 0xff55 +#define J2K_MS_PLM 0xff57 +#define J2K_MS_PLT 0xff58 +#define J2K_MS_PPM 0xff60 +#define J2K_MS_PPT 0xff61 +#define J2K_MS_SOP 0xff91 +#define J2K_MS_EPH 0xff92 +#define J2K_MS_CRG 0xff63 +#define J2K_MS_COM 0xff64 + +#define J2K_STATE_MHSOC 0x0001 +#define J2K_STATE_MHSIZ 0x0002 +#define J2K_STATE_MH 0x0004 +#define J2K_STATE_TPHSOT 0x0008 +#define J2K_STATE_TPH 0x0010 +#define J2K_STATE_MT 0x0020 + +jmp_buf j2k_error; + +int j2k_state; +int j2k_curtileno; +j2k_tcp_t j2k_default_tcp; +unsigned char *j2k_eot; +int j2k_sot_start; + +j2k_image_t *j2k_img; +j2k_cp_t *j2k_cp; + +unsigned char **j2k_tile_data; +int *j2k_tile_len; + +#if J2K_DUMP_ENABLED +void j2k_dump_image(j2k_image_t *img) { + int compno; + fprintf(stderr, "image {\n"); + fprintf(stderr, " x0=%d, y0=%d, x1=%d, y1=%d\n", img->x0, img->y0, img->x1, img->y1); + fprintf(stderr, " numcomps=%d\n", img->numcomps); + for (compno=0; compnonumcomps; compno++) { + j2k_comp_t *comp=&img->comps[compno]; + fprintf(stderr, " comp %d {\n", compno); + fprintf(stderr, " dx=%d, dy=%d\n", comp->dx, comp->dy); + fprintf(stderr, " prec=%d\n", comp->prec); + fprintf(stderr, " sgnd=%d\n", comp->sgnd); + fprintf(stderr, " }\n"); + } + fprintf(stderr, "}\n"); +} + +void j2k_dump_cp(j2k_image_t *img, j2k_cp_t *cp) { + int tileno, compno, layno, bandno, resno, numbands; + fprintf(stderr, "coding parameters {\n"); + fprintf(stderr, " tx0=%d, ty0=%d\n", cp->tx0, cp->ty0); + fprintf(stderr, " tdx=%d, tdy=%d\n", cp->tdx, cp->tdy); + fprintf(stderr, " tw=%d, th=%d\n", cp->tw, cp->th); + for (tileno=0; tilenotw*cp->th; tileno++) { + j2k_tcp_t *tcp=&cp->tcps[tileno]; + fprintf(stderr, " tile %d {\n", tileno); + fprintf(stderr, " csty=%x\n", tcp->csty); + fprintf(stderr, " prg=%d\n", tcp->prg); + fprintf(stderr, " numlayers=%d\n", tcp->numlayers); + fprintf(stderr, " mct=%d\n", tcp->mct); + fprintf(stderr, " rates="); + for (layno=0; laynonumlayers; layno++) { + fprintf(stderr, "%d ", tcp->rates[layno]); + } + fprintf(stderr, "\n"); + for (compno=0; compnonumcomps; compno++) { + j2k_tccp_t *tccp=&tcp->tccps[compno]; + fprintf(stderr, " comp %d {\n", compno); + fprintf(stderr, " csty=%x\n", tccp->csty); + fprintf(stderr, " numresolutions=%d\n", tccp->numresolutions); + fprintf(stderr, " cblkw=%d\n", tccp->cblkw); + fprintf(stderr, " cblkh=%d\n", tccp->cblkh); + fprintf(stderr, " cblksty=%x\n", tccp->cblksty); + fprintf(stderr, " qmfbid=%d\n", tccp->qmfbid); + fprintf(stderr, " qntsty=%d\n", tccp->qntsty); + fprintf(stderr, " numgbits=%d\n", tccp->numgbits); + fprintf(stderr, " roishift=%d\n", tccp->roishift); + fprintf(stderr, " stepsizes="); + numbands=tccp->qntsty==J2K_CCP_QNTSTY_SIQNT?1:tccp->numresolutions*3-2; + for (bandno=0; bandnostepsizes[bandno].mant, tccp->stepsizes[bandno].expn); + } + fprintf(stderr, "\n"); + if (tccp->csty&J2K_CCP_CSTY_PRT) { + fprintf(stderr, " prcw="); + for (resno=0; resnonumresolutions; resno++) { + fprintf(stderr, "%d ", tccp->prcw[resno]); + } + fprintf(stderr, "\n"); + fprintf(stderr, " prch="); + for (resno=0; resnonumresolutions; resno++) { + fprintf(stderr, "%d ", tccp->prch[resno]); + } + fprintf(stderr, "\n"); + } + fprintf(stderr, " }\n"); + } + fprintf(stderr, " }\n"); + } + fprintf(stderr, "}\n"); +} +#endif //J2K_DUMP_ENABLED +void j2k_write_soc() { + J2KDUMP("%.8x: SOC\n", cio_tell()) + cio_write(J2K_MS_SOC, 2); +} + +void j2k_read_soc() { + J2KDUMP("%.8x: SOC\n", cio_tell()-2) + j2k_state=J2K_STATE_MHSIZ; +} + +void j2k_write_siz() { + int i; + int lenp, len; + J2KDUMP("%.8x: SIZ\n", cio_tell()) + cio_write(J2K_MS_SIZ, 2); + lenp=cio_tell(); + cio_skip(2); + cio_write(0, 2); + cio_write(j2k_img->x1, 4); + cio_write(j2k_img->y1, 4); + cio_write(j2k_img->x0, 4); + cio_write(j2k_img->y0, 4); + cio_write(j2k_cp->tdx, 4); + cio_write(j2k_cp->tdy, 4); + cio_write(j2k_cp->tx0, 4); + cio_write(j2k_cp->ty0, 4); + cio_write(j2k_img->numcomps, 2); + for (i=0; inumcomps; i++) { + cio_write(j2k_img->comps[i].prec-1+(j2k_img->comps[i].sgnd<<7), 1); + cio_write(j2k_img->comps[i].dx, 1); + cio_write(j2k_img->comps[i].dy, 1); + } + len=cio_tell()-lenp; + cio_seek(lenp); + cio_write(len, 2); + cio_seek(lenp+len); +} + +void j2k_read_siz() { + int len, i; + J2KDUMP("%.8x: SIZ\n", cio_tell()-2) + len=cio_read(2); + cio_read(2); + j2k_img->x1=cio_read(4); + j2k_img->y1=cio_read(4); + j2k_img->x0=cio_read(4); + j2k_img->y0=cio_read(4); + j2k_cp->tdx=cio_read(4); + j2k_cp->tdy=cio_read(4); + j2k_cp->tx0=cio_read(4); + j2k_cp->ty0=cio_read(4); + j2k_img->numcomps=cio_read(2); + j2k_img->comps=(j2k_comp_t*)malloc(j2k_img->numcomps*sizeof(j2k_comp_t)); + for (i=0; inumcomps; i++) { + int tmp, w, h; + tmp=cio_read(1); + j2k_img->comps[i].prec=(tmp&0x7f)+1; + j2k_img->comps[i].sgnd=tmp>>7; + j2k_img->comps[i].dx=cio_read(1); + j2k_img->comps[i].dy=cio_read(1); + w=int_ceildiv(j2k_img->x1-j2k_img->x0, j2k_img->comps[i].dx); + h=int_ceildiv(j2k_img->y1-j2k_img->y0, j2k_img->comps[i].dy); + j2k_img->comps[i].data=(int*)malloc(sizeof(int)*w*h); + } + j2k_cp->tw=int_ceildiv(j2k_img->x1-j2k_img->x0, j2k_cp->tdx); + j2k_cp->th=int_ceildiv(j2k_img->y1-j2k_img->y0, j2k_cp->tdy); + j2k_cp->tcps=(j2k_tcp_t*)calloc(sizeof(j2k_tcp_t), j2k_cp->tw*j2k_cp->th); + j2k_default_tcp.tccps=(j2k_tccp_t*)calloc(sizeof(j2k_tccp_t), j2k_img->numcomps); + for (i=0; itw*j2k_cp->th; i++) { + j2k_cp->tcps[i].tccps=(j2k_tccp_t*)calloc(sizeof(j2k_tccp_t), j2k_img->numcomps); + } + j2k_tile_data=(unsigned char**)calloc(j2k_cp->tw*j2k_cp->th, sizeof(char*)); + j2k_tile_len=(int*)calloc(j2k_cp->tw*j2k_cp->th, sizeof(int)); + j2k_state=J2K_STATE_MH; +} + +void j2k_write_com() { + unsigned int i; + int lenp, len; + char str[256]; + sprintf(str, "Creator: J2000 codec"); + J2KDUMP("%.8x: COM\n", cio_tell()) + cio_write(J2K_MS_COM, 2); + lenp=cio_tell(); + cio_skip(2); + cio_write(0, 2); + for (i=0; itcps[j2k_curtileno]; + tccp=&tcp->tccps[compno]; + cio_write(tccp->numresolutions-1, 1); + cio_write(tccp->cblkw-2, 1); + cio_write(tccp->cblkh-2, 1); + cio_write(tccp->cblksty, 1); + cio_write(tccp->qmfbid, 1); + if (tccp->csty&J2K_CCP_CSTY_PRT) { + for (i=0; inumresolutions; i++) { + cio_write(tccp->prcw[i]+(tccp->prch[i]<<4), 1); + } + } +} + +void j2k_read_cox(int compno) { + int i; + j2k_tcp_t *tcp; + j2k_tccp_t *tccp; + tcp=j2k_state==J2K_STATE_TPH?&j2k_cp->tcps[j2k_curtileno]:&j2k_default_tcp; + tccp=&tcp->tccps[compno]; + tccp->numresolutions=cio_read(1)+1; + tccp->cblkw=cio_read(1)+2; + tccp->cblkh=cio_read(1)+2; + tccp->cblksty=cio_read(1); + tccp->qmfbid=cio_read(1); + if (tccp->csty&J2K_CP_CSTY_PRT) { + for (i=0; inumresolutions; i++) { + int tmp=cio_read(1); + tccp->prcw[i]=tmp&0xf; + tccp->prch[i]=tmp>>4; + } + } +} + +void j2k_write_cod() { + j2k_tcp_t *tcp; + int lenp, len; + J2KDUMP("%.8x: COD\n", cio_tell()) + cio_write(J2K_MS_COD, 2); + lenp=cio_tell(); + cio_skip(2); + tcp=&j2k_cp->tcps[j2k_curtileno]; + cio_write(tcp->csty, 1); + cio_write(tcp->prg, 1); + cio_write(tcp->numlayers, 2); + cio_write(tcp->mct, 1); + j2k_write_cox(0); + len=cio_tell()-lenp; + cio_seek(lenp); + cio_write(len, 2); + cio_seek(lenp+len); +} + +void j2k_read_cod() { + int len, i, pos; + j2k_tcp_t *tcp; + J2KDUMP("%.8x: COD\n", cio_tell()-2) + tcp=j2k_state==J2K_STATE_TPH?&j2k_cp->tcps[j2k_curtileno]:&j2k_default_tcp; + len=cio_read(2); + tcp->csty=cio_read(1); + tcp->prg=cio_read(1); + tcp->numlayers=cio_read(2); + tcp->mct=cio_read(1); + pos=cio_tell(); + for (i=0; inumcomps; i++) { + tcp->tccps[i].csty=tcp->csty&J2K_CP_CSTY_PRT; + cio_seek(pos); + j2k_read_cox(i); + } +} + +void j2k_write_coc(int compno) { + j2k_tcp_t *tcp; + int lenp, len; + J2KDUMP("%.8x: COC\n", cio_tell()) + cio_write(J2K_MS_COC, 2); + lenp=cio_tell(); + cio_skip(2); + tcp=&j2k_cp->tcps[j2k_curtileno]; + cio_write(compno, j2k_img->numcomps<=256?1:2); + cio_write(tcp->tccps[compno].csty, 1); + j2k_write_cox(compno); + len=cio_tell()-lenp; + cio_seek(lenp); + cio_write(len, 2); + cio_seek(lenp+len); +} + +void j2k_read_coc() { + int len, compno; + j2k_tcp_t *tcp; + J2KDUMP("%.8x: COC\n", cio_tell()-2) + tcp=j2k_state==J2K_STATE_TPH?&j2k_cp->tcps[j2k_curtileno]:&j2k_default_tcp; + len=cio_read(2); + compno=cio_read(j2k_img->numcomps<=256?1:2); + tcp->tccps[compno].csty=cio_read(1); + j2k_read_cox(compno); +} + +void j2k_write_qcx(int compno) { + j2k_tcp_t *tcp; + j2k_tccp_t *tccp; + int bandno, numbands; + tcp=&j2k_cp->tcps[j2k_curtileno]; + tccp=&tcp->tccps[compno]; + cio_write(tccp->qntsty+(tccp->numgbits<<5), 1); + numbands=tccp->qntsty==J2K_CCP_QNTSTY_SIQNT?1:tccp->numresolutions*3-2; + for (bandno=0; bandnostepsizes[bandno].expn; + mant=tccp->stepsizes[bandno].mant; + if (tccp->qntsty==J2K_CCP_QNTSTY_NOQNT) { + cio_write(expn<<3, 1); + } else { + cio_write((expn<<11)+mant, 2); + } + } +} + +void j2k_read_qcx(int compno, int len) { + int tmp; + j2k_tcp_t *tcp; + j2k_tccp_t *tccp; + int bandno, numbands; + tcp=j2k_state==J2K_STATE_TPH?&j2k_cp->tcps[j2k_curtileno]:&j2k_default_tcp; + tccp=&tcp->tccps[compno]; + tmp=cio_read(1); + tccp->qntsty=tmp&0x1f; + tccp->numgbits=tmp>>5; + numbands=tccp->qntsty==J2K_CCP_QNTSTY_SIQNT?1:(tccp->qntsty==J2K_CCP_QNTSTY_NOQNT?len-1:(len-1)/2); + for (bandno=0; bandnoqntsty==J2K_CCP_QNTSTY_NOQNT) { // WHY STEPSIZES WHEN NOQNT ? + expn=cio_read(1)>>3; + mant=0; + } else { + tmp=cio_read(2); + expn=tmp>>11; + mant=tmp&0x7ff; + } + tccp->stepsizes[bandno].expn=expn; + tccp->stepsizes[bandno].mant=mant; + } +} + +void j2k_write_qcd() { + int lenp, len; + J2KDUMP("%.8x: QCD\n", cio_tell()) + cio_write(J2K_MS_QCD, 2); + lenp=cio_tell(); + cio_skip(2); + j2k_write_qcx(0); + len=cio_tell()-lenp; + cio_seek(lenp); + cio_write(len, 2); + cio_seek(lenp+len); +} + +void j2k_read_qcd() { + int len, i, pos; + J2KDUMP("%.8x: QCD\n", cio_tell()-2) + len=cio_read(2); + pos=cio_tell(); + for (i=0; inumcomps; i++) { + cio_seek(pos); + j2k_read_qcx(i, len-2); + } +} + +void j2k_write_qcc(int compno) { + int lenp, len; + J2KDUMP("%.8x: QCC\n", cio_tell()) + cio_write(J2K_MS_QCC, 2); + lenp=cio_tell(); + cio_skip(2); + cio_write(compno, j2k_img->numcomps<=256?1:2); + j2k_write_qcx(compno); + len=cio_tell()-lenp; + cio_seek(lenp); + cio_write(len, 2); + cio_seek(lenp+len); +} + +void j2k_read_qcc() { + int len, compno; + J2KDUMP("%.8x: QCC\n", cio_tell()-2) + len=cio_read(2); + compno=cio_read(j2k_img->numcomps<=256?1:2); + j2k_read_qcx(compno, len-2-(j2k_img->numcomps<=256?1:2)); +} + +void j2k_read_poc() { + int len, numpchgs, i; + j2k_tcp_t *tcp; + J2KWARNING("WARNING: POC marker segment processing not fully implemented\n") + tcp=j2k_state==J2K_STATE_TPH?&j2k_cp->tcps[j2k_curtileno]:&j2k_default_tcp; + len=cio_read(2); + numpchgs=(len-2)/(5+2*(j2k_img->numcomps<=256?1:2)); + for (i=0; inumcomps<=256?1:2); + layerno1=cio_read(2); + resno1=cio_read(1); + compno1=cio_read(j2k_img->numcomps<=256?1:2); + prg=cio_read(1); + tcp->prg=prg; + } +} + +void j2k_read_crg() { + int len; + len=cio_read(2); + J2KWARNING("WARNING: CRG marker segment processing not implemented\n") + cio_skip(len-2); +} + +void j2k_read_tlm() { + int len; + len=cio_read(2); + J2KWARNING("WARNING: TLM marker segment processing not implemented\n") + cio_skip(len-2); +} + +void j2k_read_plm() { + int len; + len=cio_read(2); + J2KWARNING("WARNING: PLM marker segment processing not implemented\n") + cio_skip(len-2); +} + +void j2k_read_plt() { + int len; + len=cio_read(2); + J2KWARNING("WARNING: PLT marker segment processing not implemented\n") + cio_skip(len-2); +} + +void j2k_read_ppm() { + int len; + len=cio_read(2); + J2KWARNING("WARNING: PPM marker segment processing not implemented\n") + cio_skip(len-2); +} + +void j2k_read_ppt() { + int len; + len=cio_read(2); + J2KWARNING("WARNING: PPT marker segment processing not implemented\n") + cio_skip(len-2); +} + +void j2k_write_sot() { + int lenp, len; + J2KDUMP("%.8x: SOT\n", cio_tell()) + j2k_sot_start=cio_tell(); + cio_write(J2K_MS_SOT, 2); + lenp=cio_tell(); + cio_skip(2); + cio_write(j2k_curtileno, 2); + cio_skip(4); + cio_write(0, 1); + cio_write(1, 1); + len=cio_tell()-lenp; + cio_seek(lenp); + cio_write(len, 2); + cio_seek(lenp+len); +} + +void j2k_read_sot() { + int len, tileno, totlen, partno, numparts, i; + j2k_tcp_t *tcp; + j2k_tccp_t *tmp; + J2KDUMP("%.8x: SOT\n", cio_tell()-2) + len=cio_read(2); + tileno=cio_read(2); + totlen=cio_read(4); + partno=cio_read(1); + numparts=cio_read(1); + j2k_curtileno=tileno; + j2k_eot=cio_getbp()-12+totlen; + j2k_state=J2K_STATE_TPH; + tcp=&j2k_cp->tcps[j2k_curtileno]; + tmp=tcp->tccps; + *tcp=j2k_default_tcp; + tcp->tccps=tmp; + for (i=0; inumcomps; i++) { + tcp->tccps[i]=j2k_default_tcp.tccps[i]; + } +} + +void j2k_write_sod() { + int l, layno; + int totlen; + j2k_tcp_t *tcp; + J2KDUMP("%.8x: SOD\n", cio_tell()) + cio_write(J2K_MS_SOD, 2); + tcp=&j2k_cp->tcps[j2k_curtileno]; + for (layno=0; laynonumlayers; layno++) { + tcp->rates[layno]-=cio_tell(); + J2KDUMP2("tcp->rates[%d]=%d\n", layno, tcp->rates[layno]) + } + J2KDUMP("cio_numbytesleft=%d\n", cio_numbytesleft()) + tcd_init(j2k_img, j2k_cp); + l=tcd_encode_tile(j2k_curtileno, cio_getbp(), cio_numbytesleft()-2); + totlen=cio_tell()+l-j2k_sot_start; + cio_seek(j2k_sot_start+6); + cio_write(totlen, 4); + cio_seek(j2k_sot_start+totlen); +} + +void j2k_read_sod() { + int len; + unsigned char *data; + J2KDUMP("%.8x: SOD\n", cio_tell()-2) + len=int_min(j2k_eot-cio_getbp(), cio_numbytesleft()); + j2k_tile_len[j2k_curtileno]+=len; + data=(unsigned char*)realloc(j2k_tile_data[j2k_curtileno], j2k_tile_len[j2k_curtileno]); + memcpy(data, cio_getbp(), len); + j2k_tile_data[j2k_curtileno]=data; + cio_skip(len); + j2k_state=J2K_STATE_TPHSOT; +} + +void j2k_read_rgn() { + int len, compno, roisty; + j2k_tcp_t *tcp; + J2KDUMP("%.8x: RGN\n", cio_tell()-2) + tcp=j2k_state==J2K_STATE_TPH?&j2k_cp->tcps[j2k_curtileno]:&j2k_default_tcp; + len=cio_read(2); + compno=cio_read(j2k_img->numcomps<=256?1:2); + roisty=cio_read(1); + tcp->tccps[compno].roishift=cio_read(1); +} + +void j2k_write_eoc() { + J2KDUMP("%.8x: EOC\n", cio_tell()) + cio_write(J2K_MS_EOC, 2); +} + +void j2k_read_eoc() { + int tileno; +#if J2K_DUMP_ENABLED + J2KDUMP("%.8x: EOC\n", cio_tell()-2) + j2k_dump_image(j2k_img); + j2k_dump_cp(j2k_img, j2k_cp); +#endif //J2K_DUMP_ENABLED + tcd_init(j2k_img, j2k_cp); + for (tileno=0; tilenotw*j2k_cp->th; tileno++) { + tcd_decode_tile(j2k_tile_data[tileno], j2k_tile_len[tileno], tileno); + } + j2k_state=J2K_STATE_MT; + longjmp(j2k_error, 1); +} + +void j2k_read_unk() { + J2KWARNING("warning: unknown marker\n") +} + +LIBJ2K_API int j2k_encode(j2k_image_t *img, j2k_cp_t *cp, unsigned char *dest, int len) { + int tileno, compno; + if (setjmp(j2k_error)) { + return 0; + } + cio_init(dest, len); + j2k_img=img; + j2k_cp=cp; +#if J2K_DUMP_ENABLED + j2k_dump_cp(j2k_img, j2k_cp); +#endif //J2K_DUMP_ENABLED + j2k_write_soc(); + j2k_write_siz(); + j2k_write_com(); + for (tileno=0; tilenotw*cp->th; tileno++) { + j2k_curtileno=tileno; + j2k_write_sot(); + j2k_write_cod(); + j2k_write_qcd(); + for (compno=1; compnonumcomps; compno++) { + j2k_write_coc(compno); + j2k_write_qcc(compno); + } + j2k_write_sod(); + } + j2k_write_eoc(); + return cio_tell(); +} + +typedef struct { + int id; + int states; + void (*handler)(); +} j2k_dec_mstabent_t; + +j2k_dec_mstabent_t j2k_dec_mstab[]={ + {J2K_MS_SOC, J2K_STATE_MHSOC, j2k_read_soc}, + {J2K_MS_SOT, J2K_STATE_MH|J2K_STATE_TPHSOT, j2k_read_sot}, + {J2K_MS_SOD, J2K_STATE_TPH, j2k_read_sod}, + {J2K_MS_EOC, J2K_STATE_TPHSOT, j2k_read_eoc}, + {J2K_MS_SIZ, J2K_STATE_MHSIZ, j2k_read_siz}, + {J2K_MS_COD, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_cod}, + {J2K_MS_COC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_coc}, + {J2K_MS_RGN, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_rgn}, + {J2K_MS_QCD, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_qcd}, + {J2K_MS_QCC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_qcc}, + {J2K_MS_POC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_poc}, + {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm}, + {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm}, + {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt}, + {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm}, + {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt}, + {J2K_MS_SOP, 0, 0}, + {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg}, + {J2K_MS_COM, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_com}, + {0, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_unk} +}; + +j2k_dec_mstabent_t *j2k_dec_mstab_lookup(int id) { + j2k_dec_mstabent_t *e; + for (e=j2k_dec_mstab; e->id!=0; e++) { + if (e->id==id) { + break; + } + } + return e; +} + +LIBJ2K_API int j2k_decode(unsigned char *src, int len, j2k_image_t **img, j2k_cp_t **cp) { + if (setjmp(j2k_error)) { + if (j2k_state!=J2K_STATE_MT) { + J2KWARNING("WARNING: incomplete bitstream\n") + return 0; + } + return cio_numbytes(); + } + j2k_img=(j2k_image_t*)malloc(sizeof(j2k_image_t)); + j2k_cp=(j2k_cp_t*)malloc(sizeof(j2k_cp_t)); + *img=j2k_img; + *cp=j2k_cp; + j2k_state=J2K_STATE_MHSOC; + cio_init(src, len); + for (;;) { + j2k_dec_mstabent_t *e; + int id=cio_read(2); + if (id>>8!=0xff) { + J2KDUMP2("%.8x: expected a marker instead of %x\n", cio_tell()-2, id); + return 0; + } + e=j2k_dec_mstab_lookup(id); + if (!(j2k_state & e->states)) { + J2KDUMP2("%.8x: unexpected marker %x\n", cio_tell()-2, id); + return 0; + } + if (e->handler) { + (*e->handler)(); + } + } +} + +LIBJ2K_API void j2k_destroy(j2k_image_t **img, j2k_cp_t **cp) +{ + int i; + tcd_destroy(*img, *cp); + free(j2k_tile_len); j2k_tile_len =0; + if (j2k_tile_data) for(i=0;i<((*cp)->tw*(*cp)->th);i++) { free(j2k_tile_data[i]); j2k_tile_data[i]=0;} + free(j2k_tile_data); j2k_tile_data=0; + free(j2k_default_tcp.tccps); j2k_default_tcp.tccps = 0; + if ((*cp)->tcps) for(i=0;i<((*cp)->tw*(*cp)->th);i++) {free((*cp)->tcps[i].tccps); (*cp)->tcps[i].tccps=0;} + free((*cp)->tcps); (*cp)->tcps=0; + + if ((*img)->comps) for(i=0;i<(*img)->numcomps;i++) {free((*img)->comps[i].data); (*img)->comps[i].data=0;} + free((*img)->comps); (*img)->comps = 0; + + free(*img); *img=0; + free(*cp); *cp=0; +} + + +/* +#ifdef WIN32 +#include + +BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} +#endif +*/ diff --git a/SlnkDWFImpl/CxImage/j2k/j2k.dsp b/SlnkDWFImpl/CxImage/j2k/j2k.dsp new file mode 100644 index 0000000..ce0f226 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/j2k.dsp @@ -0,0 +1,198 @@ +# Microsoft Developer Studio Project File - Name="j2k" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=j2k - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "j2k.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "j2k.mak" CFG="j2k - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "j2k - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "j2k - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "j2k - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D "LIBJ2K_EXPORTS" /D "_AFXDLL" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x410 /d "NDEBUG" +# ADD RSC /l 0x410 /d "NDEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "j2k - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_AFXDLL" /D "LIBJ2K_EXPORTS" /FD /GZ /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x410 /d "_DEBUG" +# ADD RSC /l 0x410 /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "j2k - Win32 Release" +# Name "j2k - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\bio.c +# End Source File +# Begin Source File + +SOURCE=.\cio.c +# End Source File +# Begin Source File + +SOURCE=.\dwt.c +# End Source File +# Begin Source File + +SOURCE=.\fix.c +# End Source File +# Begin Source File + +SOURCE=.\int.c +# End Source File +# Begin Source File + +SOURCE=.\j2k.c +# End Source File +# Begin Source File + +SOURCE=.\mct.c +# End Source File +# Begin Source File + +SOURCE=.\mqc.c +# End Source File +# Begin Source File + +SOURCE=.\pi.c +# End Source File +# Begin Source File + +SOURCE=.\t1.c +# End Source File +# Begin Source File + +SOURCE=.\t2.c +# End Source File +# Begin Source File + +SOURCE=.\tcd.c +# End Source File +# Begin Source File + +SOURCE=.\tgt.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\bio.h +# End Source File +# Begin Source File + +SOURCE=.\cio.h +# End Source File +# Begin Source File + +SOURCE=.\dwt.h +# End Source File +# Begin Source File + +SOURCE=.\fix.h +# End Source File +# Begin Source File + +SOURCE=.\int.h +# End Source File +# Begin Source File + +SOURCE=.\j2k.h +# End Source File +# Begin Source File + +SOURCE=.\mct.h +# End Source File +# Begin Source File + +SOURCE=.\mqc.h +# End Source File +# Begin Source File + +SOURCE=.\pi.h +# End Source File +# Begin Source File + +SOURCE=.\t1.h +# End Source File +# Begin Source File + +SOURCE=.\t2.h +# End Source File +# Begin Source File + +SOURCE=.\tcd.h +# End Source File +# Begin Source File + +SOURCE=.\tgt.h +# End Source File +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/j2k/j2k.dsw b/SlnkDWFImpl/CxImage/j2k/j2k.dsw new file mode 100644 index 0000000..9329700 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/j2k.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "j2k"=.\j2k.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/j2k/j2k.h b/SlnkDWFImpl/CxImage/j2k/j2k.h new file mode 100644 index 0000000..d7750d5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/j2k.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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. + * + */ +/* + * tcd -> tile coder/decoder + * t1 -> tier 1 coder/decoder + * mqc -> MQ-coder/decoder + * t2 -> tier 2 coder/decoder + * pi -> packet iterator + * tgt -> tag-tree coder/decoder + * dwt -> discrete wavelet transform + * mct -> multiple component transform + * bio -> bit input/output + * cio -> byte (char) input/output + */ + +#define VERSION "0.0.8" + +#ifdef WIN32 +#ifdef LIBJ2K_EXPORTS +#define LIBJ2K_API __declspec(dllexport) +#else +#define LIBJ2K_API __declspec(dllimport) +#endif +#else +#define LIBJ2K_API +#endif + +#ifndef __J2K_H +#define __J2K_H + +#define J2K_DUMP_ENABLED 0 + +#if J2K_DUMP_ENABLED +#define J2KWARNING(a) fprintf(stderr,a); +#define J2KDUMP(a,b) fprintf(stderr,a,b); +#define J2KDUMP2(a,b,c) fprintf(stderr,a,b,c); +#else +#define J2KWARNING(a) +#define J2KDUMP(a,b) +#define J2KDUMP2(a,b,c) +#endif + +#define J2K_MAXRLVLS 33 +#define J2K_MAXBANDS (3*J2K_MAXRLVLS+1) + +#define J2K_CP_CSTY_PRT 0x01 +#define J2K_CP_CSTY_SOP 0x02 +#define J2K_CP_CSTY_EPH 0x04 +#define J2K_CCP_CSTY_PRT 0x01 +#define J2K_CCP_CBLKSTY_LAZY 0x01 +#define J2K_CCP_CBLKSTY_RESET 0x02 +#define J2K_CCP_CBLKSTY_TERMALL 0x04 +#define J2K_CCP_CBLKSTY_VSC 0x08 +#define J2K_CCP_CBLKSTY_PTERM 0x10 +#define J2K_CCP_CBLKSTY_SEGSYM 0x20 +#define J2K_CCP_QNTSTY_NOQNT 0 +#define J2K_CCP_QNTSTY_SIQNT 1 +#define J2K_CCP_QNTSTY_SEQNT 2 + +typedef struct { + int dx, dy; // XRsiz, YRsiz + int prec; // precision + int sgnd; // signed + int *data; // image-component data +} j2k_comp_t; + +typedef struct { + int x0, y0; // XOsiz, YOsiz + int x1, y1; // Xsiz, Ysiz + int numcomps; // number of components + j2k_comp_t *comps; // image-components +} j2k_image_t; + +typedef struct { + int expn; // exponent + int mant; // mantissa +} j2k_stepsize_t; + +typedef struct { + int csty; // coding style + int numresolutions; // number of resolutions + int cblkw; // width of code-blocks + int cblkh; // height of code-blocks + int cblksty; // code-block coding style + int qmfbid; // discrete wavelet transform identifier + int qntsty; // quantisation style + j2k_stepsize_t stepsizes[J2K_MAXBANDS]; // stepsizes used for quantisation + int numgbits; // number of guard bits + int roishift; // Region Of Interest shift + int prcw[J2K_MAXRLVLS]; // Precinct width + int prch[J2K_MAXRLVLS]; // Precinct height +} j2k_tccp_t; + +typedef struct { + int resno0, compno0; + int layno1, resno1, compno1; + int prg; +} j2k_poc_t; + +typedef struct { + int csty; // coding style + int prg; // progression order + int numlayers; // number of layers + int mct; // multi-component transform identifier + int rates[32]; // rates of layers + int numpocs; // number of progression order changes + j2k_poc_t pocs[32]; // progression order changes + j2k_tccp_t *tccps; // tile-component coding parameters +} j2k_tcp_t; + +typedef struct { + int tx0, ty0; // XTOsiz, YTOsiz + int tdx, tdy; // XTsiz, YTsiz + int tw, th; + j2k_tcp_t *tcps; // tile coding parameters +} j2k_cp_t; + +LIBJ2K_API int j2k_encode(j2k_image_t *i, j2k_cp_t *cp, unsigned char *dest, int len); +LIBJ2K_API int j2k_decode(unsigned char *src, int len, j2k_image_t **i, j2k_cp_t **cp); +LIBJ2K_API void j2k_destroy(j2k_image_t **img, j2k_cp_t **cp); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/j2k.vcproj b/SlnkDWFImpl/CxImage/j2k/j2k.vcproj new file mode 100644 index 0000000..9833225 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/j2k.vcproj @@ -0,0 +1,492 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/j2k/j2k.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/j2k/j2k.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..f57b253 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/j2k.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/j2k/mct.c b/SlnkDWFImpl/CxImage/j2k/mct.c new file mode 100644 index 0000000..ab83217 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/mct.c @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "mct.h" +#include "fix.h" + +/// +/// This table contains the norms of the basis function of the reversible MCT. +/// +double mct_norms[3]={1.732, .8292, .8292}; + +/// +/// This table contains the norms of the basis function of the irreversible MCT. +/// +double mct_norms_real[3]={1.732, 1.805, 1.573}; + +/// +/// Foward reversible MCT. +/// +void mct_encode(int *c0, int *c1, int *c2, int n) +{ + int i; + for (i=0; i>2; + u=b-g; + v=r-g; + c0[i]=y; c1[i]=u; c2[i]=v; + } +} + +/// +/// Inverse reversible MCT. +/// +void mct_decode(int *c0, int *c1, int *c2, int n) +{ + int i; + for (i=0; i>2); + r=v+g; + b=u+g; + c0[i]=r; c1[i]=g; c2[i]=b; + } +} + +/// +/// Get norm of basis function of reversible MCT. +/// +double mct_getnorm(int compno) { + return mct_norms[compno]; +} + +/// +/// Foward irreversible MCT. +/// +void mct_encode_real(int *c0, int *c1, int *c2, int n) +{ + int i; + for (i=0; i +/// Inverse irreversible MCT. +/// +void mct_decode_real(int *c0, int *c1, int *c2, int n) +{ + int i; + for (i=0; i +/// Get norm of basis function of irreversible MCT. +/// +double mct_getnorm_real(int compno) { + return mct_norms_real[compno]; +} diff --git a/SlnkDWFImpl/CxImage/j2k/mct.h b/SlnkDWFImpl/CxImage/j2k/mct.h new file mode 100644 index 0000000..efdb588 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/mct.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __MCT_H +#define __MCT_H + +void mct_encode(int *c0, int *c1, int *c2, int n); +void mct_decode(int *c0, int *c1, int *c2, int n); +double mct_getnorm(int compno); + +void mct_encode_real(int *c0, int *c1, int *c2, int n); +void mct_decode_real(int *c0, int *c1, int *c2, int n); +double mct_getnorm_real(int compno); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/mqc.c b/SlnkDWFImpl/CxImage/j2k/mqc.c new file mode 100644 index 0000000..7a31a37 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/mqc.c @@ -0,0 +1,440 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "mqc.h" + +/// +/// This struct defines the state of a context. +/// +typedef struct mqc_state_s { + unsigned int qeval; + int mps; + struct mqc_state_s *nmps; + struct mqc_state_s *nlps; +} mqc_state_t; + +/// +/// This array defines all the possible states for a context. +/// +mqc_state_t mqc_states[47*2]={ + {0x5601, 0, &mqc_states[2], &mqc_states[3]}, + {0x5601, 1, &mqc_states[3], &mqc_states[2]}, + {0x3401, 0, &mqc_states[4], &mqc_states[12]}, + {0x3401, 1, &mqc_states[5], &mqc_states[13]}, + {0x1801, 0, &mqc_states[6], &mqc_states[18]}, + {0x1801, 1, &mqc_states[7], &mqc_states[19]}, + {0x0ac1, 0, &mqc_states[8], &mqc_states[24]}, + {0x0ac1, 1, &mqc_states[9], &mqc_states[25]}, + {0x0521, 0, &mqc_states[10], &mqc_states[58]}, + {0x0521, 1, &mqc_states[11], &mqc_states[59]}, + {0x0221, 0, &mqc_states[76], &mqc_states[66]}, + {0x0221, 1, &mqc_states[77], &mqc_states[67]}, + {0x5601, 0, &mqc_states[14], &mqc_states[13]}, + {0x5601, 1, &mqc_states[15], &mqc_states[12]}, + {0x5401, 0, &mqc_states[16], &mqc_states[28]}, + {0x5401, 1, &mqc_states[17], &mqc_states[29]}, + {0x4801, 0, &mqc_states[18], &mqc_states[28]}, + {0x4801, 1, &mqc_states[19], &mqc_states[29]}, + {0x3801, 0, &mqc_states[20], &mqc_states[28]}, + {0x3801, 1, &mqc_states[21], &mqc_states[29]}, + {0x3001, 0, &mqc_states[22], &mqc_states[34]}, + {0x3001, 1, &mqc_states[23], &mqc_states[35]}, + {0x2401, 0, &mqc_states[24], &mqc_states[36]}, + {0x2401, 1, &mqc_states[25], &mqc_states[37]}, + {0x1c01, 0, &mqc_states[26], &mqc_states[40]}, + {0x1c01, 1, &mqc_states[27], &mqc_states[41]}, + {0x1601, 0, &mqc_states[58], &mqc_states[42]}, + {0x1601, 1, &mqc_states[59], &mqc_states[43]}, + {0x5601, 0, &mqc_states[30], &mqc_states[29]}, + {0x5601, 1, &mqc_states[31], &mqc_states[28]}, + {0x5401, 0, &mqc_states[32], &mqc_states[28]}, + {0x5401, 1, &mqc_states[33], &mqc_states[29]}, + {0x5101, 0, &mqc_states[34], &mqc_states[30]}, + {0x5101, 1, &mqc_states[35], &mqc_states[31]}, + {0x4801, 0, &mqc_states[36], &mqc_states[32]}, + {0x4801, 1, &mqc_states[37], &mqc_states[33]}, + {0x3801, 0, &mqc_states[38], &mqc_states[34]}, + {0x3801, 1, &mqc_states[39], &mqc_states[35]}, + {0x3401, 0, &mqc_states[40], &mqc_states[36]}, + {0x3401, 1, &mqc_states[41], &mqc_states[37]}, + {0x3001, 0, &mqc_states[42], &mqc_states[38]}, + {0x3001, 1, &mqc_states[43], &mqc_states[39]}, + {0x2801, 0, &mqc_states[44], &mqc_states[38]}, + {0x2801, 1, &mqc_states[45], &mqc_states[39]}, + {0x2401, 0, &mqc_states[46], &mqc_states[40]}, + {0x2401, 1, &mqc_states[47], &mqc_states[41]}, + {0x2201, 0, &mqc_states[48], &mqc_states[42]}, + {0x2201, 1, &mqc_states[49], &mqc_states[43]}, + {0x1c01, 0, &mqc_states[50], &mqc_states[44]}, + {0x1c01, 1, &mqc_states[51], &mqc_states[45]}, + {0x1801, 0, &mqc_states[52], &mqc_states[46]}, + {0x1801, 1, &mqc_states[53], &mqc_states[47]}, + {0x1601, 0, &mqc_states[54], &mqc_states[48]}, + {0x1601, 1, &mqc_states[55], &mqc_states[49]}, + {0x1401, 0, &mqc_states[56], &mqc_states[50]}, + {0x1401, 1, &mqc_states[57], &mqc_states[51]}, + {0x1201, 0, &mqc_states[58], &mqc_states[52]}, + {0x1201, 1, &mqc_states[59], &mqc_states[53]}, + {0x1101, 0, &mqc_states[60], &mqc_states[54]}, + {0x1101, 1, &mqc_states[61], &mqc_states[55]}, + {0x0ac1, 0, &mqc_states[62], &mqc_states[56]}, + {0x0ac1, 1, &mqc_states[63], &mqc_states[57]}, + {0x09c1, 0, &mqc_states[64], &mqc_states[58]}, + {0x09c1, 1, &mqc_states[65], &mqc_states[59]}, + {0x08a1, 0, &mqc_states[66], &mqc_states[60]}, + {0x08a1, 1, &mqc_states[67], &mqc_states[61]}, + {0x0521, 0, &mqc_states[68], &mqc_states[62]}, + {0x0521, 1, &mqc_states[69], &mqc_states[63]}, + {0x0441, 0, &mqc_states[70], &mqc_states[64]}, + {0x0441, 1, &mqc_states[71], &mqc_states[65]}, + {0x02a1, 0, &mqc_states[72], &mqc_states[66]}, + {0x02a1, 1, &mqc_states[73], &mqc_states[67]}, + {0x0221, 0, &mqc_states[74], &mqc_states[68]}, + {0x0221, 1, &mqc_states[75], &mqc_states[69]}, + {0x0141, 0, &mqc_states[76], &mqc_states[70]}, + {0x0141, 1, &mqc_states[77], &mqc_states[71]}, + {0x0111, 0, &mqc_states[78], &mqc_states[72]}, + {0x0111, 1, &mqc_states[79], &mqc_states[73]}, + {0x0085, 0, &mqc_states[80], &mqc_states[74]}, + {0x0085, 1, &mqc_states[81], &mqc_states[75]}, + {0x0049, 0, &mqc_states[82], &mqc_states[76]}, + {0x0049, 1, &mqc_states[83], &mqc_states[77]}, + {0x0025, 0, &mqc_states[84], &mqc_states[78]}, + {0x0025, 1, &mqc_states[85], &mqc_states[79]}, + {0x0015, 0, &mqc_states[86], &mqc_states[80]}, + {0x0015, 1, &mqc_states[87], &mqc_states[81]}, + {0x0009, 0, &mqc_states[88], &mqc_states[82]}, + {0x0009, 1, &mqc_states[89], &mqc_states[83]}, + {0x0005, 0, &mqc_states[90], &mqc_states[84]}, + {0x0005, 1, &mqc_states[91], &mqc_states[85]}, + {0x0001, 0, &mqc_states[90], &mqc_states[86]}, + {0x0001, 1, &mqc_states[91], &mqc_states[87]}, + {0x5601, 0, &mqc_states[92], &mqc_states[92]}, + {0x5601, 1, &mqc_states[93], &mqc_states[93]}, +}; + +#define MQC_NUMCTXS 32 + +unsigned int mqc_c; +unsigned int mqc_a; +unsigned int mqc_ct; +unsigned char *mqc_bp; +unsigned char *mqc_start; +unsigned char *mqc_end; +mqc_state_t *mqc_ctxs[MQC_NUMCTXS]; +mqc_state_t **mqc_curctx; + +/// +/// Return the number of bytes already encoded. +/// +int mqc_numbytes() { + return mqc_bp-mqc_start; +} + +/// +/// Output a byte. +/// +void mqc_byteout() +{ + if (*mqc_bp==0xff) { + mqc_bp++; + *mqc_bp=mqc_c>>20; + mqc_c&=0xfffff; + mqc_ct=7; + } else { + if ((mqc_c&0x8000000)==0) { + mqc_bp++; + *mqc_bp=mqc_c>>19; + mqc_c&=0x7ffff; + mqc_ct=8; + } else { + (*mqc_bp)++; + if (*mqc_bp==0xff) { + mqc_c&=0x7ffffff; + mqc_bp++; + *mqc_bp=mqc_c>>20; + mqc_c&=0xfffff; + mqc_ct=7; + } else { + mqc_bp++; + *mqc_bp=mqc_c>>19; + mqc_c&=0x7ffff; + mqc_ct=8; + } + } + } +} + +/// +/// Renormalize mqc_a and mqc_c while encoding. +/// +void mqc_renorme() +{ + do { + mqc_a<<=1; + mqc_c<<=1; + mqc_ct--; + if (mqc_ct==0) { + mqc_byteout(); + } + } while ((mqc_a&0x8000)==0); +} + +/// +/// Encode the most probable symbol. +/// +void mqc_codemps() +{ + mqc_a-=(*mqc_curctx)->qeval; + if ((mqc_a&0x8000)==0) { + if (mqc_a<(*mqc_curctx)->qeval) { + mqc_a=(*mqc_curctx)->qeval; + } else { + mqc_c+=(*mqc_curctx)->qeval; + } + *mqc_curctx=(*mqc_curctx)->nmps; + mqc_renorme(); + } else { + mqc_c+=(*mqc_curctx)->qeval; + } +} + +/// +/// Encode the most least symbol. +/// +void mqc_codelps() +{ + mqc_a-=(*mqc_curctx)->qeval; + if (mqc_a<(*mqc_curctx)->qeval) { + mqc_c+=(*mqc_curctx)->qeval; + } else { + mqc_a=(*mqc_curctx)->qeval; + } + *mqc_curctx=(*mqc_curctx)->nlps; + mqc_renorme(); +} + +/// +/// Initialize encoder. +/// +/// Output buffer. +void mqc_init_enc(unsigned char *bp) +{ + mqc_setcurctx(0); + mqc_a=0x8000; + mqc_c=0; + mqc_bp=bp-1; + mqc_ct=12; + if (*mqc_bp==0xff) { + mqc_ct=13; + } + mqc_start=bp; +} + +/// +/// Set current context. +/// +/// Context number. +void mqc_setcurctx(int ctxno) +{ + mqc_curctx=&mqc_ctxs[ctxno]; +} + +/// +/// Encode a symbol using the MQ-coder. +/// +/// The symbol to be encoded (0 or 1). +void mqc_encode(int d) +{ + if ((*mqc_curctx)->mps==d) { + mqc_codemps(); + } else { + mqc_codelps(); + } +} + +/// +/// +void mqc_setbits() +{ + unsigned int tempc=mqc_c+mqc_a; + mqc_c|=0xffff; + if (mqc_c>=tempc) { + mqc_c-=0x8000; + } +} + +/// +/// Flush encoded data. +/// +void mqc_flush() +{ + mqc_setbits(); + mqc_c<<=mqc_ct; + mqc_byteout(); + mqc_c<<=mqc_ct; + mqc_byteout(); + if (*mqc_bp!=0xff) { + mqc_bp++; + } +} + +/// +/// +int mqc_mpsexchange() +{ + int d; + if (mqc_a<(*mqc_curctx)->qeval) { + d=1-(*mqc_curctx)->mps; + *mqc_curctx=(*mqc_curctx)->nlps; + } else { + d=(*mqc_curctx)->mps; + *mqc_curctx=(*mqc_curctx)->nmps; + } + return d; +} + +/// +/// +int mqc_lpsexchange() +{ + int d; + if (mqc_a<(*mqc_curctx)->qeval) { + mqc_a=(*mqc_curctx)->qeval; + d=(*mqc_curctx)->mps; + *mqc_curctx=(*mqc_curctx)->nmps; + } else { + mqc_a=(*mqc_curctx)->qeval; + d=1-(*mqc_curctx)->mps; + *mqc_curctx=(*mqc_curctx)->nlps; + } + return d; +} + +/// +/// Input a byte. +/// +void mqc_bytein() +{ + if (mqc_bp!=mqc_end) { + unsigned int c; + if (mqc_bp+1!=mqc_end) { + c=*(mqc_bp+1); + } else { + c=0xff; + } + if (*mqc_bp==0xff) { + if (c>0x8f) { + mqc_c+=0xff00; + mqc_ct=8; + } else { + mqc_bp++; + mqc_c+=c<<9; + mqc_ct=7; + } + } else { + mqc_bp++; + mqc_c+=c<<8; + mqc_ct=8; + } + } else { + mqc_c+=0xff00; + mqc_ct=8; + } +} + +/// +/// Renormalize mqc_a and mqc_c while decoding. +/// +void mqc_renormd() +{ + do { + if (mqc_ct==0) { + mqc_bytein(); + } + mqc_a<<=1; + mqc_c<<=1; + mqc_ct--; + } while (mqc_a<0x8000); +} + +/// +/// Initialize decoder. +/// +void mqc_init_dec(unsigned char *bp, int len) +{ + mqc_setcurctx(0); + mqc_start=bp; + mqc_end=bp+len; + mqc_bp=bp; + mqc_c=*mqc_bp<<16; + mqc_bytein(); + mqc_c<<=7; + mqc_ct-=7; + mqc_a=0x8000; +} + +/// +/// Decode a symbol. +/// +int mqc_decode() +{ + int d; + mqc_a-=(*mqc_curctx)->qeval; + if ((mqc_c>>16)<(*mqc_curctx)->qeval) { + d=mqc_lpsexchange(); + mqc_renormd(); + } else { + mqc_c-=(*mqc_curctx)->qeval<<16; + if ((mqc_a&0x8000)==0) { + d=mqc_mpsexchange(); + mqc_renormd(); + } else { + d=(*mqc_curctx)->mps; + } + } + return d; +} + +/// +/// Reset states of all contexts. +/// +void mqc_resetstates() { + int i; + for (i=0; i +/// Set the state for a context. +/// +/// Context number +/// Most significant bit +/// Index to the probability of symbols +void mqc_setstate(int ctxno, int msb, int prob) { + mqc_ctxs[ctxno]=&mqc_states[msb+(prob<<1)]; +} diff --git a/SlnkDWFImpl/CxImage/j2k/mqc.h b/SlnkDWFImpl/CxImage/j2k/mqc.h new file mode 100644 index 0000000..ea01b90 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/mqc.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __MQC_H +#define __MQC_H + +int mqc_numbytes(); +void mqc_init_enc(unsigned char *bp); +void mqc_setcurctx(int ctxno); +void mqc_encode(int d); +void mqc_flush(); +void mqc_init_dec(unsigned char *bp, int len); +int mqc_decode(); +void mqc_resetstates(); +void mqc_setstate(int ctxno, int msb, int prob); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/pi.c b/SlnkDWFImpl/CxImage/j2k/pi.c new file mode 100644 index 0000000..14d41df --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/pi.c @@ -0,0 +1,370 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "pi.h" +#include "int.h" +#include + +/// +/// Create a packet iterator. +/// +pi_iterator_t *pi_create(j2k_image_t *img, j2k_cp_t *cp, int tileno) { + int p, q; + int compno, resno; + int maxres=0; + pi_iterator_t *pi; + j2k_tcp_t *tcp; + j2k_tccp_t *tccp; + tcp=&cp->tcps[tileno]; + pi=(pi_iterator_t*)malloc(sizeof(pi_iterator_t)); + p=tileno%cp->tw; + q=tileno/cp->tw; + pi->tx0=int_max(cp->tx0+p*cp->tdx, img->x0); + pi->ty0=int_max(cp->ty0+q*cp->tdy, img->y0); + pi->tx1=int_min(cp->tx0+(p+1)*cp->tdx, img->x1); + pi->ty1=int_min(cp->ty0+(q+1)*cp->tdy, img->y1); + pi->numcomps=img->numcomps; + pi->comps=(pi_comp_t*)malloc(img->numcomps*sizeof(pi_comp_t)); + for (compno=0; compnonumcomps; compno++) { + int tcx0, tcy0, tcx1, tcy1; + pi_comp_t *comp=&pi->comps[compno]; + tccp=&tcp->tccps[compno]; + comp->dx=img->comps[compno].dx; + comp->dy=img->comps[compno].dy; + comp->numresolutions=tccp->numresolutions; + comp->resolutions=(pi_resolution_t*)malloc(comp->numresolutions*sizeof(pi_resolution_t)); + tcx0=int_ceildiv(pi->tx0, comp->dx); + tcy0=int_ceildiv(pi->ty0, comp->dy); + tcx1=int_ceildiv(pi->tx1, comp->dx); + tcy1=int_ceildiv(pi->ty1, comp->dy); + if (comp->numresolutions>maxres) { + maxres=comp->numresolutions; + } + for (resno=0; resnonumresolutions; resno++) { + int levelno; + int rx0, ry0, rx1, ry1; + int px0, py0, px1, py1; + pi_resolution_t *res=&comp->resolutions[resno]; + if (tccp->csty&J2K_CCP_CSTY_PRT) { + res->pdx=tccp->prcw[resno]; + res->pdy=tccp->prch[resno]; + } else { + res->pdx=15; + res->pdy=15; + } + levelno=comp->numresolutions-1-resno; + rx0=int_ceildivpow2(tcx0, levelno); + ry0=int_ceildivpow2(tcy0, levelno); + rx1=int_ceildivpow2(tcx1, levelno); + ry1=int_ceildivpow2(tcy1, levelno); + px0=int_floordivpow2(rx0, res->pdx)<pdx; + py0=int_floordivpow2(ry0, res->pdy)<pdy; + px1=int_ceildivpow2(rx1, res->pdx)<pdx; + py1=int_ceildivpow2(ry1, res->pdy)<pdy; + res->pw=(px1-px0)>>res->pdx; + res->ph=(py1-py0)>>res->pdy; + } + } + pi->first=1; + pi->poc.resno0=0; + pi->poc.compno0=0; + pi->poc.layno1=tcp->numlayers; + pi->poc.resno1=maxres; + pi->poc.compno1=img->numcomps; + pi->poc.prg=tcp->prg; + return pi; +} + +/// +/// Get next packet in layer=resolution-component-precinct order. +/// +int pi_next_lrcp(pi_iterator_t *pi) { + pi_comp_t *comp; + pi_resolution_t *res; + if (!pi->first) { + comp=&pi->comps[pi->compno]; + res=&comp->resolutions[pi->resno]; + goto skip; + } else { + pi->first=0; + } + for (pi->layno=0; pi->laynopoc.layno1; pi->layno++) { + for (pi->resno=pi->poc.resno0; pi->resnopoc.resno1; pi->resno++) { + for (pi->compno=pi->poc.compno0; pi->compnopoc.compno1; pi->compno++) { + comp=&pi->comps[pi->compno]; + if (pi->resno>=comp->numresolutions) { + continue; + } + res=&comp->resolutions[pi->resno]; + for (pi->precno=0; pi->precnopw*res->ph; pi->precno++) { + return 1; +skip: ; + } + } + } + } + return 0; +} + +/// +/// Get next packet in resolution-layer-component-precinct order. +/// +int pi_next_rlcp(pi_iterator_t *pi) { + pi_comp_t *comp; + pi_resolution_t *res; + if (!pi->first) { + comp=&pi->comps[pi->compno]; + res=&comp->resolutions[pi->resno]; + goto skip; + } else { + pi->first=0; + } + for (pi->resno=pi->poc.resno0; pi->resnopoc.resno1; pi->resno++) { + for (pi->layno=0; pi->laynopoc.layno1; pi->layno++) { + for (pi->compno=pi->poc.compno0; pi->compnopoc.compno1; pi->compno++) { + comp=&pi->comps[pi->compno]; + if (pi->resno>=comp->numresolutions) { + continue; + } + res=&comp->resolutions[pi->resno]; + for (pi->precno=0; pi->precnopw*res->ph; pi->precno++) { + return 1; +skip: ; + } + } + } + } + return 0; +} + +/// +/// Get next packet in resolution-precinct-component-layer order. +/// +int pi_next_rpcl(pi_iterator_t *pi) { + pi_comp_t *comp; + pi_resolution_t *res; + if (!pi->first) { + goto skip; + } else { + int compno, resno; + pi->first=0; + pi->dx=0; + pi->dy=0; + for (compno=0; compnonumcomps; compno++) { + comp=&pi->comps[compno]; + for (resno=0; resnonumresolutions; resno++) { + int dx, dy; + res=&comp->resolutions[resno]; + dx=comp->dx*(1<<(res->pdx+comp->numresolutions-1-resno)); + dy=comp->dy*(1<<(res->pdy+comp->numresolutions-1-resno)); + pi->dx=!pi->dx?dx:int_min(pi->dx, dx); + pi->dy=!pi->dy?dy:int_min(pi->dy, dy); + } + } + } + for (pi->resno=pi->poc.resno0; pi->resnopoc.resno1; pi->resno++) { + for (pi->y=pi->ty0; pi->yty1; pi->y+=pi->dy-(pi->y%pi->dy)) { + for (pi->x=pi->tx0; pi->xtx1; pi->x+=pi->dx-(pi->x%pi->dx)) { + for (pi->compno=pi->poc.compno0; pi->compnopoc.compno1; pi->compno++) { + int levelno; + int trx0, try0; + int rpx, rpy; + int prci, prcj; + comp=&pi->comps[pi->compno]; + if (pi->resno>=comp->numresolutions) { + continue; + } + res=&comp->resolutions[pi->resno]; + levelno=comp->numresolutions-1-pi->resno; + trx0=int_ceildiv(pi->tx0, comp->dx<ty0, comp->dy<pdx+levelno; + rpy=res->pdy+levelno; + if (!(pi->x%(comp->dx<x==pi->tx0&&(trx0<y%(comp->dy<y==pi->ty0&&(try0<x, comp->dx<pdx)-int_floordivpow2(trx0, res->pdx); + prcj=int_floordivpow2(int_ceildiv(pi->y, comp->dy<pdy)-int_floordivpow2(try0, res->pdy); + pi->precno=prci+prcj*res->pw; + for (pi->layno=0; pi->laynopoc.layno1; pi->layno++) { + return 1; +skip: ; + } + } + } + } + } + return 0; +} + +/// +/// Get next packet in precinct-component-resolution-layer order. +/// +int pi_next_pcrl(pi_iterator_t *pi) { + pi_comp_t *comp; + pi_resolution_t *res; + if (!pi->first) { + comp=&pi->comps[pi->compno]; + goto skip; + } else { + int compno, resno; + pi->first=0; + pi->dx=0; + pi->dy=0; + for (compno=0; compnonumcomps; compno++) { + comp=&pi->comps[compno]; + for (resno=0; resnonumresolutions; resno++) { + int dx, dy; + res=&comp->resolutions[resno]; + dx=comp->dx*(1<<(res->pdx+comp->numresolutions-1-resno)); + dy=comp->dy*(1<<(res->pdy+comp->numresolutions-1-resno)); + pi->dx=!pi->dx?dx:int_min(pi->dx, dx); + pi->dy=!pi->dy?dy:int_min(pi->dy, dy); + } + } + } + for (pi->y=pi->ty0; pi->yty1; pi->y+=pi->dy-(pi->y%pi->dy)) { + for (pi->x=pi->tx0; pi->xtx1; pi->x+=pi->dx-(pi->x%pi->dx)) { + for (pi->compno=pi->poc.compno0; pi->compnopoc.compno1; pi->compno++) { + comp=&pi->comps[pi->compno]; + for (pi->resno=pi->poc.resno0; pi->resnopoc.resno1, comp->numresolutions); pi->resno++) { + int levelno; + int trx0, try0; + int rpx, rpy; + int prci, prcj; + res=&comp->resolutions[pi->resno]; + levelno=comp->numresolutions-1-pi->resno; + trx0=int_ceildiv(pi->tx0, comp->dx<ty0, comp->dy<pdx+levelno; + rpy=res->pdy+levelno; + if (!(pi->x%(comp->dx<x==pi->tx0&&(trx0<y%(comp->dy<y==pi->ty0&&(try0<x, comp->dx<pdx)-int_floordivpow2(trx0, res->pdx); + prcj=int_floordivpow2(int_ceildiv(pi->y, comp->dy<pdy)-int_floordivpow2(try0, res->pdy); + pi->precno=prci+prcj*res->pw; + for (pi->layno=0; pi->laynopoc.layno1; pi->layno++) { + return 1; +skip: ; + } + } + } + } + } + return 0; +} + +/// +/// Get next packet in component-precinct-resolution-layer order. +/// +int pi_next_cprl(pi_iterator_t *pi) { + pi_comp_t *comp; + pi_resolution_t *res; + if (!pi->first) { + comp=&pi->comps[pi->compno]; + goto skip; + } else { + pi->first=0; + } + for (pi->compno=pi->poc.compno0; pi->compnopoc.compno1; pi->compno++) { + int resno; + comp=&pi->comps[pi->compno]; + pi->dx=0; + pi->dy=0; + for (resno=0; resnonumresolutions; resno++) { + int dx, dy; + res=&comp->resolutions[resno]; + dx=comp->dx*(1<<(res->pdx+comp->numresolutions-1-resno)); + dy=comp->dy*(1<<(res->pdy+comp->numresolutions-1-resno)); + pi->dx=!pi->dx?dx:int_min(pi->dx, dx); + pi->dy=!pi->dy?dy:int_min(pi->dy, dy); + } + for (pi->y=pi->ty0; pi->yty1; pi->y+=pi->dy-(pi->y%pi->dy)) { + for (pi->x=pi->tx0; pi->xtx1; pi->x+=pi->dx-(pi->x%pi->dx)) { + for (pi->resno=pi->poc.resno0; pi->resnopoc.resno1, comp->numresolutions); pi->resno++) { + int levelno; + int trx0, try0; + int rpx, rpy; + int prci, prcj; + res=&comp->resolutions[pi->resno]; + levelno=comp->numresolutions-1-pi->resno; + trx0=int_ceildiv(pi->tx0, comp->dx<ty0, comp->dy<pdx+levelno; + rpy=res->pdy+levelno; + if (!(pi->x%(comp->dx<x==pi->tx0&&(trx0<y%(comp->dy<y==pi->ty0&&(try0<x, comp->dx<pdx)-int_floordivpow2(trx0, res->pdx); + prcj=int_floordivpow2(int_ceildiv(pi->y, comp->dy<pdy)-int_floordivpow2(try0, res->pdy); + pi->precno=prci+prcj*res->pw; + for (pi->layno=0; pi->laynopoc.layno1; pi->layno++) { + return 1; +skip: ; + } + } + } + } + } + return 0; +} + +/// +/// Get next packet. +/// +int pi_next(pi_iterator_t *pi) { + switch (pi->poc.prg) { + case 0: + return pi_next_lrcp(pi); + case 1: + return pi_next_rlcp(pi); + case 2: + return pi_next_rpcl(pi); + case 3: + return pi_next_pcrl(pi); + case 4: + return pi_next_cprl(pi); + } + return 0; +} + +void pi_destroy(pi_iterator_t *pi) +{ + int i; + for (i=0;inumcomps;i++) { free(pi->comps[i].resolutions); pi->comps[i].resolutions = 0;} + free(pi->comps); pi->comps=0; + free(pi); +} diff --git a/SlnkDWFImpl/CxImage/j2k/pi.h b/SlnkDWFImpl/CxImage/j2k/pi.h new file mode 100644 index 0000000..702be52 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/pi.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __PI_H +#define __PI_H + +#include "j2k.h" +#include "tcd.h" + +typedef struct { + int pdx, pdy; + int pw, ph; +} pi_resolution_t; + +typedef struct { + int dx, dy; + int numresolutions; + pi_resolution_t *resolutions; +} pi_comp_t; + +typedef struct { + int compno, resno, precno, layno; + int first; + j2k_poc_t poc; + int numcomps; + pi_comp_t *comps; + int tx0, ty0, tx1, ty1; + int x, y, dx, dy; +} pi_iterator_t; + +pi_iterator_t *pi_create(j2k_image_t *img, j2k_cp_t *cp, int tileno); +int pi_next(pi_iterator_t *pi); +void pi_destroy(pi_iterator_t *pi); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/t1.c b/SlnkDWFImpl/CxImage/j2k/t1.c new file mode 100644 index 0000000..91a4da4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/t1.c @@ -0,0 +1,638 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "t1.h" +#include "j2k.h" +#include "mqc.h" +#include "int.h" +#include "mct.h" +#include "dwt.h" +#include "int.h" +#include "fix.h" +#include +#include + +#define T1_MAXCBLKW 64 +#define T1_MAXCBLKH 64 + +#define T1_SIG_NE 0x0001 +#define T1_SIG_SE 0x0002 +#define T1_SIG_SW 0x0004 +#define T1_SIG_NW 0x0008 +#define T1_SIG_N 0x0010 +#define T1_SIG_E 0x0020 +#define T1_SIG_S 0x0040 +#define T1_SIG_W 0x0080 +#define T1_SIG_OTH (T1_SIG_N|T1_SIG_NE|T1_SIG_E|T1_SIG_SE|T1_SIG_S|T1_SIG_SW|T1_SIG_W|T1_SIG_NW) +#define T1_SIG_PRIM (T1_SIG_N|T1_SIG_E|T1_SIG_S|T1_SIG_W) + +#define T1_SGN_N 0x0100 +#define T1_SGN_E 0x0200 +#define T1_SGN_S 0x0400 +#define T1_SGN_W 0x0800 +#define T1_SGN (T1_SGN_N|T1_SGN_E|T1_SGN_S|T1_SGN_W) + +#define T1_SIG 0x1000 +#define T1_REFINE 0x2000 +#define T1_VISIT 0x4000 + +#define T1_NUMCTXS_AGG 1 +#define T1_NUMCTXS_ZC 9 +#define T1_NUMCTXS_MAG 3 +#define T1_NUMCTXS_SC 5 +#define T1_NUMCTXS_UNI 1 + +#define T1_CTXNO_AGG 0 +#define T1_CTXNO_ZC (T1_CTXNO_AGG+T1_NUMCTXS_AGG) +#define T1_CTXNO_MAG (T1_CTXNO_ZC+T1_NUMCTXS_ZC) +#define T1_CTXNO_SC (T1_CTXNO_MAG+T1_NUMCTXS_MAG) +#define T1_CTXNO_UNI (T1_CTXNO_SC+T1_NUMCTXS_SC) +#define T1_NUMCTXS (T1_CTXNO_UNI+T1_NUMCTXS_UNI) + +#define T1_NMSEDEC_BITS 7 +#define T1_NMSEDEC_FRACBITS (T1_NMSEDEC_BITS-1) + +int t1_lut_ctxno_zc[1024]; +int t1_lut_ctxno_sc[256]; +int t1_lut_ctxno_mag[4096]; +int t1_lut_spb[256]; +int t1_lut_nmsedec_sig[1<>4]; +} + +int t1_getctxno_mag(int f) { + return t1_lut_ctxno_mag[(f&T1_SIG_OTH)|(((f&T1_REFINE)!=0)<<11)]; +} + +int t1_getspb(int f) { + return t1_lut_spb[(f&(T1_SIG_PRIM|T1_SGN))>>4]; +} + +int t1_getnmsedec_sig(int x, int bitpos) { + if (bitpos>T1_NMSEDEC_FRACBITS) { + return t1_lut_nmsedec_sig[(x>>(bitpos-T1_NMSEDEC_FRACBITS))&((1<T1_NMSEDEC_FRACBITS) { + return t1_lut_nmsedec_ref[(x>>(bitpos-T1_NMSEDEC_FRACBITS))&((1<>1; + oneplushalf=one|half; + for (k=0; k>1; + neghalf=bpno>0?-poshalf:-1; + for (k=0; k>1); + mqc_encode(runlen&1); + } else { + runlen=0; + } + for (j=k+runlen; j>1; + oneplushalf=one|half; + for (k=0; kx1-cblk->x0; + h=cblk->y1-cblk->y0; + + max=0; + for (j=0; jnumbps=max?(int_floorlog2(max)+1)-T1_NMSEDEC_FRACBITS:0; + + for (i=0; inumbps-1; + passtype=2; + + mqc_resetstates(); + mqc_setstate(T1_CTXNO_UNI, 0, 46); + mqc_setstate(T1_CTXNO_AGG, 0, 3); + mqc_setstate(T1_CTXNO_ZC, 0, 4); + mqc_init_enc(cblk->data); + + for (passno=0; bpno>=0; passno++) { + tcd_pass_t *pass=&cblk->passes[passno]; + switch (passtype) { + case 0: + t1_enc_sigpass(w, h, bpno, orient, &nmsedec); + break; + case 1: + t1_enc_refpass(w, h, bpno, &nmsedec); + break; + case 2: + t1_enc_clnpass(w, h, bpno, orient, &nmsedec); + break; + } + cumwmsedec+=t1_getwmsedec(nmsedec, compno, level, orient, bpno, qmfbid, stepsize); + pass->distortiondec=cumwmsedec; + pass->rate=mqc_numbytes()+3; // FIXME + if (++passtype==3) { + passtype=0; + bpno--; + } + } + mqc_flush(); + + cblk->totalpasses=passno; +} + +void t1_decode_cblk(tcd_cblk_t *cblk, int orient, int roishift, int cblksty) { + int i; + int w, h; + int bpno, passtype; + int segno, passno; + + for (i=0; ix1-cblk->x0; + h=cblk->y1-cblk->y0; + bpno=roishift+cblk->numbps-1; + passtype=2; + + mqc_resetstates(); + mqc_setstate(T1_CTXNO_UNI, 0, 46); + mqc_setstate(T1_CTXNO_AGG, 0, 3); + mqc_setstate(T1_CTXNO_ZC, 0, 4); + + for (segno=0; segnonumsegs; segno++) { + tcd_seg_t *seg=&cblk->segs[segno]; + //fprintf(stderr, "t1_decode_cblk: segno=%d, seg->len=%d, seg->numpasses=%d\n", segno, seg->len, seg->numpasses); + mqc_init_dec(seg->data, seg->len); + for (passno=0; passnonumpasses; passno++) { + switch (passtype) { + case 0: + t1_dec_sigpass(w, h, bpno, orient); + break; + case 1: + t1_dec_refpass(w, h, bpno); + break; + case 2: + t1_dec_clnpass(w, h, bpno, orient, cblksty&J2K_CCP_CBLKSTY_SEGSYM); + break; + } + if (++passtype==3) { + passtype=0; + bpno--; + } + } + } +} + +void t1_encode_cblks(tcd_tile_t *tile, j2k_tcp_t *tcp) { + int compno, resno, bandno, precno, cblkno; + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tile->comps[compno]; + for (resno=0; resnonumresolutions; resno++) { + tcd_resolution_t *res=&tilec->resolutions[resno]; + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + for (precno=0; precnopw*res->ph; precno++) { + tcd_precinct_t *prc=&band->precincts[precno]; + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + int x, y, i, j, orient; + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + if (band->bandno==0) { + x=res->x0+cblk->x0; + y=res->y0+cblk->y0; + } else if (band->bandno==1) { + x=res->x1-(band->x1-band->x0)+cblk->x0; + y=res->y0+cblk->y0; + } else if (band->bandno==2) { + x=res->x0+cblk->x0; + y=res->y1-(band->y1-band->y0)+cblk->y0; + } else if (band->bandno==3) { + x=res->x1-(band->x1-band->x0)+cblk->x0; + y=res->y1-(band->y1-band->y0)+cblk->y0; + } + if (tcp->tccps[compno].qmfbid==1) { + for (j=0; jy1-cblk->y0; j++) { + for (i=0; ix1-cblk->x0; i++) { + t1_data[j][i]=tilec->data[x+i+(y+j)*(tilec->x1-tilec->x0)]<tccps[compno].qmfbid==0) { + for (j=0; jy1-cblk->y0; j++) { + for (i=0; ix1-cblk->x0; i++) { + t1_data[j][i]=fix_mul(tilec->data[x+i+(y+j)*(tilec->x1-tilec->x0)], 8192*8192/band->stepsize)>>(13-T1_NMSEDEC_FRACBITS); + } + } + } + orient=band->bandno; // FIXME + if (orient==2) orient=1; + else if (orient==1) orient=2; + t1_encode_cblk(cblk, orient, compno, tilec->numresolutions-1-resno, tcp->tccps[compno].qmfbid, band->stepsize); + } + } + } + } + } +} + +void t1_decode_cblks(tcd_tile_t *tile, j2k_tcp_t *tcp) { + int compno, resno, bandno, precno, cblkno; + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tile->comps[compno]; + for (resno=0; resnonumresolutions; resno++) { + tcd_resolution_t *res=&tilec->resolutions[resno]; + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + for (precno=0; precnopw*res->ph; precno++) { + tcd_precinct_t *prc=&band->precincts[precno]; + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + int x, y, i, j, orient; + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + orient=band->bandno; // FIXME + if (orient==2) orient=1; + else if (orient==1) orient=2; + t1_decode_cblk(cblk, orient, tcp->tccps[compno].roishift, tcp->tccps[compno].cblksty); + if (band->bandno==0) { + x=cblk->x0-band->x0; + y=cblk->y0-band->y0; + } else if (band->bandno==1) { + tcd_resolution_t *pres=&tilec->resolutions[resno-1]; + x=pres->x1-pres->x0+cblk->x0-band->x0; + y=cblk->y0-band->y0; + } else if (band->bandno==2) { + tcd_resolution_t *pres=&tilec->resolutions[resno-1]; + x=cblk->x0-band->x0; + y=pres->y1-pres->y0+cblk->y0-band->y0; + } else if (band->bandno==3) { + tcd_resolution_t *pres=&tilec->resolutions[resno-1]; + x=pres->x1-pres->x0+cblk->x0-band->x0; + y=pres->y1-pres->y0+cblk->y0-band->y0; + } + if (tcp->tccps[compno].roishift) { + int thresh, val, mag; + thresh=1<tccps[compno].roishift; + for (j=0; jy1-cblk->y0; j++) { + for (i=0; ix1-cblk->x0; i++) { + val=t1_data[j][i]; + mag=int_abs(val); + if (mag>=thresh) { + mag>>=tcp->tccps[compno].roishift; + t1_data[j][i]=val<0?-mag:mag; + } + } + } + } + if (tcp->tccps[compno].qmfbid==1) { + for (j=0; jy1-cblk->y0; j++) { + for (i=0; ix1-cblk->x0; i++) { + tilec->data[x+i+(y+j)*(tilec->x1-tilec->x0)]=t1_data[j][i]; + } + } + } else if (tcp->tccps[compno].qmfbid==0) { + for (j=0; jy1-cblk->y0; j++) { + for (i=0; ix1-cblk->x0; i++) { + if (t1_data[j][i]==0) { + tilec->data[x+i+(y+j)*(tilec->x1-tilec->x0)]=0; + } else { + tilec->data[x+i+(y+j)*(tilec->x1-tilec->x0)]=fix_mul(t1_data[j][i]<<13, band->stepsize); + } + } + } + } + } + } + } + } + } +} + +int t1_init_ctxno_zc(int f, int orient) { + int h,v,d,n,t,hv;n=0;h=((f&T1_SIG_W)!=0)+((f&T1_SIG_E)!=0);v=((f&T1_SIG_N)!=0)+((f&T1_SIG_S)!=0);d=((f&T1_SIG_NW)!=0)+((f&T1_SIG_NE)!=0)+((f&T1_SIG_SE)!=0)+((f&T1_SIG_SW)!=0);switch(orient){case 2:t=h;h=v;v=t;case 0:case 1:if(!h){if(!v){if(!d){n=0;}else if(d==1){n=1;}else{n=2;}}else if(v==1){n=3;}else{n=4;}}else if(h==1){if(!v){if(!d){n=5;}else{n=6;}}else{n=7;}}else{n=8;}break;case 3:hv=h+v;if(!d){if(!hv){n=0;}else if(hv==1){n=1;}else{n=2;}}else if(d==1){if(!hv){n=3;}else if(hv==1){ n=4;}else{n=5;}}else if(d==2){if(!hv){n=6;}else{n=7;}}else{n=8;}break;}return T1_CTXNO_ZC+n; +} + +int t1_init_ctxno_sc(int f) { + int hc,vc,n;n=0;hc=int_min(((f&(T1_SIG_E|T1_SGN_E))==T1_SIG_E)+((f&(T1_SIG_W|T1_SGN_W))==T1_SIG_W),1)-int_min(((f&(T1_SIG_E|T1_SGN_E))==(T1_SIG_E|T1_SGN_E))+((f&(T1_SIG_W|T1_SGN_W))==(T1_SIG_W|T1_SGN_W)),1);vc=int_min(((f&(T1_SIG_N|T1_SGN_N))==T1_SIG_N)+((f&(T1_SIG_S|T1_SGN_S))==T1_SIG_S),1)-int_min(((f&(T1_SIG_N|T1_SGN_N))==(T1_SIG_N|T1_SGN_N))+((f&(T1_SIG_S|T1_SGN_S))==(T1_SIG_S|T1_SGN_S)),1);if(hc<0){hc=-hc;vc=-vc;}if(!hc){if(vc==-1){n=1;}else if(!vc){n=0;}else{n=1;}}else if(hc==1){if(vc==-1){n=2;}else if(!vc){n=3;}else{n=4;}}return T1_CTXNO_SC+n; +} + +int t1_init_ctxno_mag(int f) { + int n;if(!(f&T1_REFINE)){n=(f&(T1_SIG_OTH))?1:0;}else{n=2;}return T1_CTXNO_MAG+n; +} + +int t1_init_spb(int f) { + int hc,vc,n;hc=int_min(((f&(T1_SIG_E|T1_SGN_E))==T1_SIG_E)+((f&(T1_SIG_W|T1_SGN_W))==T1_SIG_W),1)-int_min(((f&(T1_SIG_E|T1_SGN_E))==(T1_SIG_E|T1_SGN_E))+((f&(T1_SIG_W|T1_SGN_W))==(T1_SIG_W|T1_SGN_W)),1);vc=int_min(((f&(T1_SIG_N|T1_SGN_N))==T1_SIG_N)+((f&(T1_SIG_S|T1_SGN_S))==T1_SIG_S),1)-int_min(((f&(T1_SIG_N|T1_SGN_N))==(T1_SIG_N|T1_SGN_N))+((f&(T1_SIG_S|T1_SGN_S))==(T1_SIG_S|T1_SGN_S)),1);if(!hc&&!vc){n=0;}else{n=(!(hc>0||(!hc&&vc>0)));}return n; +} + +void t1_init_luts() { + int i,j;double u,v,t;for(j=0;j<4;j++){for(i=0;i<256;++i){t1_lut_ctxno_zc[(j<<8)|i]=t1_init_ctxno_zc(i,j);}}for(i=0;i<256;i++){t1_lut_ctxno_sc[i]=t1_init_ctxno_sc(i<<4);}for(j=0;j<2;j++){for(i=0;i<2048;++i){t1_lut_ctxno_mag[(j<<11)+i]=t1_init_ctxno_mag((j?T1_REFINE:0)|i);}}for(i=0;i<256;++i){t1_lut_spb[i]=t1_init_spb(i<<4);} + // FIXME FIXME FIXME + //printf("nmsedec luts:\n"); + for (i=0; i<(1< +#include +#include +#include + +extern jmp_buf j2k_error; + +void t2_putcommacode(int n) +{ + while (--n>=0) { + bio_write(1, 1); + } + bio_write(0, 1); +} + +int t2_getcommacode() { + int n; + for (n=0; bio_read(1); n++) {} + return n; +} + +void t2_putnumpasses(int n) +{ + if (n==1) { + bio_write(0, 1); + } else if (n==2) { + bio_write(2, 2); + } else if (n<=5) { + bio_write(0xc|(n-3), 4); + } else if (n<=36) { + bio_write(0x1e0|(n-6), 9); + } else if (n<=164) { + bio_write(0xff80|(n-37), 16); + } +} + +int t2_getnumpasses() +{ + int n; + if (!bio_read(1)) return 1; + if (!bio_read(1)) return 2; + if ((n=bio_read(2))!=3) return 3+n; + if ((n=bio_read(5))!=31) return 6+n; + return 37+bio_read(7); +} + +int t2_encode_packet(tcd_tile_t *tile, j2k_tcp_t *tcp, int compno, int resno, int precno, int layno, unsigned char *dest, int len) { + int bandno, cblkno; + tcd_tilecomp_t *tilec=&tile->comps[compno]; + tcd_resolution_t *res=&tilec->resolutions[resno]; + unsigned char *c=dest; + if (!layno) { + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + tcd_precinct_t *prc=&band->precincts[precno]; + tgt_reset(prc->incltree); + tgt_reset(prc->imsbtree); + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + cblk->numpasses=0; + tgt_setvalue(prc->imsbtree, cblkno, band->numbps-cblk->numbps); + } + } + } + bio_init_enc(c, len); + bio_write(1, 1); + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + tcd_precinct_t *prc=&band->precincts[precno]; + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + tcd_layer_t *layer=&cblk->layers[layno]; + if (!cblk->numpasses && layer->numpasses) { + tgt_setvalue(prc->incltree, cblkno, layno); + } + } + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + tcd_layer_t *layer=&cblk->layers[layno]; + int increment; + if (!cblk->numpasses) { + tgt_encode(prc->incltree, cblkno, layno+1); + } else { + bio_write(layer->numpasses!=0, 1); + } + if (!layer->numpasses) { + continue; + } + if (!cblk->numpasses) { + cblk->numlenbits=3; + tgt_encode(prc->imsbtree, cblkno, 999); + } + t2_putnumpasses(layer->numpasses); + increment=int_max(0, int_floorlog2(layer->len)+1-(cblk->numlenbits+int_floorlog2(layer->numpasses))); + t2_putcommacode(increment); + cblk->numlenbits+=increment; + bio_write(layer->len, cblk->numlenbits+int_floorlog2(layer->numpasses)); + } + } + bio_flush(); + c+=bio_numbytes(); + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + tcd_precinct_t *prc=&band->precincts[precno]; + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + tcd_layer_t *layer=&cblk->layers[layno]; + if (!layer->numpasses) continue; + if (c+layer->len>dest+len) { + longjmp(j2k_error, 1); + } + memcpy(c, layer->data, layer->len); + cblk->numpasses+=layer->numpasses; + c+=layer->len; + } + } + return c-dest; +} + +void t2_init_seg(tcd_seg_t *seg, int cblksty) { + seg->numpasses=0; + seg->len=0; + seg->maxpasses=cblksty&J2K_CCP_CBLKSTY_TERMALL?1:100; +} + +int t2_decode_packet(unsigned char *src, int len, tcd_tile_t *tile, j2k_tcp_t *tcp, int compno, int resno, int precno, int layno) { + int bandno, cblkno; + tcd_tilecomp_t *tilec=&tile->comps[compno]; + tcd_resolution_t *res=&tilec->resolutions[resno]; + unsigned char *c=src; + int present; + if (layno==0) { + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + tcd_precinct_t *prc=&band->precincts[precno]; + tgt_reset(prc->incltree); + tgt_reset(prc->imsbtree); + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + cblk->numsegs=0; + } + } + } + if (tcp->csty&J2K_CP_CSTY_SOP) { + c+=6; + } + bio_init_dec(c, src+len-c); + present=bio_read(1); + if (!present) { + bio_inalign(); + c+=bio_numbytes(); + return c-src; + } + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + tcd_precinct_t *prc=&band->precincts[precno]; + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + int included, increment, n; + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + tcd_seg_t *seg; + if (!cblk->numsegs) { + included=tgt_decode(prc->incltree, cblkno, layno+1); + } else { + included=bio_read(1); + } + if (!included) { + cblk->numnewpasses=0; + continue; + } + if (!cblk->numsegs) { + int i, numimsbs; + for (i=0; !tgt_decode(prc->imsbtree, cblkno, i); i++) {} + numimsbs=i-1; + cblk->numbps=band->numbps-numimsbs; + cblk->numlenbits=3; + } + cblk->numnewpasses=t2_getnumpasses(); + increment=t2_getcommacode(); + cblk->numlenbits+=increment; + if (!cblk->numsegs) { + seg=&cblk->segs[0]; + t2_init_seg(seg, tcp->tccps[compno].cblksty); + } else { + seg=&cblk->segs[cblk->numsegs-1]; + if (seg->numpasses==seg->maxpasses) { + t2_init_seg(++seg, tcp->tccps[compno].cblksty); + } + } + n=cblk->numnewpasses; + do { + seg->numnewpasses=int_min(seg->maxpasses-seg->numpasses, n); + seg->newlen=bio_read(cblk->numlenbits+int_floorlog2(seg->numnewpasses)); + n-=seg->numnewpasses; + if (n>0) { + t2_init_seg(++seg, tcp->tccps[compno].cblksty); + } + } while (n>0); + } + } + + + bio_inalign(); + c+=bio_numbytes(); + if (tcp->csty&J2K_CP_CSTY_EPH) { + c+=2; + } + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + tcd_precinct_t *prc=&band->precincts[precno]; + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + tcd_seg_t *seg; + if (!cblk->numnewpasses) continue; + if (!cblk->numsegs) { + seg=&cblk->segs[cblk->numsegs++]; + cblk->len=0; + } else { + seg=&cblk->segs[cblk->numsegs-1]; + if (seg->numpasses==seg->maxpasses) { + seg++; + cblk->numsegs++; + } + } + do { + if (c+seg->newlen>src+len) longjmp(j2k_error, 1); + memcpy(cblk->data+cblk->len, c, seg->newlen); + if (seg->numpasses==0) { + seg->data=cblk->data+cblk->len; + } + c+=seg->newlen; + cblk->len+=seg->newlen; + seg->len+=seg->newlen; + seg->numpasses+=seg->numnewpasses; + cblk->numnewpasses-=seg->numnewpasses; + if (cblk->numnewpasses>0) { + seg++; + cblk->numsegs++; + } + } while (cblk->numnewpasses>0); + } + } + + + return c-src; +} + +int t2_encode_packets(j2k_image_t *img, j2k_cp_t *cp, int tileno, tcd_tile_t *tile, int maxlayers, unsigned char *dest, int len) { + unsigned char *c=dest; + pi_iterator_t *pi; + pi=pi_create(img, cp, tileno); + while (pi_next(pi)) { + if (pi->laynocompno, pi->resno, pi->precno, pi->layno); + c+=t2_encode_packet(tile, &cp->tcps[tileno], pi->compno, pi->resno, pi->precno, pi->layno, c, dest+len-c); + } + } + pi_destroy(pi); + return c-dest; +} + +int t2_decode_packets(unsigned char *src, int len, j2k_image_t *img, j2k_cp_t *cp, int tileno, tcd_tile_t *tile) { + unsigned char *c=src; + pi_iterator_t *pi; + pi=pi_create(img, cp, tileno); + while (pi_next(pi)) { + //fprintf(stderr, "compno=%d, resno=%d, precno=%d, layno=%d\n", pi->compno, pi->resno, pi->precno, pi->layno); + c+=t2_decode_packet(c, src+len-c, tile, &cp->tcps[tileno], pi->compno, pi->resno, pi->precno, pi->layno); + } + pi_destroy(pi); + return c-src; +} diff --git a/SlnkDWFImpl/CxImage/j2k/t2.h b/SlnkDWFImpl/CxImage/j2k/t2.h new file mode 100644 index 0000000..9bde25b --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/t2.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __T2_H +#define __T2_H + +#include "tcd.h" +#include "j2k.h" + +int t2_encode_packets(j2k_image_t *img, j2k_cp_t *cp, int tileno, tcd_tile_t *tile, int maxlayers, unsigned char *dest, int len); +int t2_decode_packets(unsigned char *src, int len, j2k_image_t *img, j2k_cp_t *cp, int tileno, tcd_tile_t *tile); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/tcd.c b/SlnkDWFImpl/CxImage/j2k/tcd.c new file mode 100644 index 0000000..ba4db8d --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/tcd.c @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "tcd.h" +#include "int.h" +#include "t1.h" +#include "t2.h" +#include "dwt.h" +#include "mct.h" +#include +#include +#include +#include +#include +#include +#include + +tcd_image_t tcd_image; + +j2k_image_t *tcd_img; +j2k_cp_t *tcd_cp; + +tcd_tile_t *tcd_tile; +j2k_tcp_t *tcd_tcp; +int tcd_tileno; + +extern jmp_buf j2k_error; + +#if J2K_DUMP_ENABLED +void tcd_dump(tcd_image_t *img) { + int tileno, compno, resno, bandno, precno, cblkno; + fprintf(stderr, "image {\n"); + fprintf(stderr, " tw=%d, th=%d\n", img->tw, img->th); + for (tileno=0; tilenotw*img->th; tileno++) { + tcd_tile_t *tile=&tcd_image.tiles[tileno]; + fprintf(stderr, " tile {\n"); + fprintf(stderr, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n", tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps); + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tile->comps[compno]; + fprintf(stderr, " tilec {\n"); + fprintf(stderr, " x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n", tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions); + for (resno=0; resnonumresolutions; resno++) { + tcd_resolution_t *res=&tilec->resolutions[resno]; + fprintf(stderr, " res {\n"); + fprintf(stderr, " x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n", res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands); + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + fprintf(stderr, " band {\n"); + fprintf(stderr, " x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%d, numbps=%d\n", band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps); + for (precno=0; precnopw*res->ph; precno++) { + tcd_precinct_t *prec=&band->precincts[precno]; + fprintf(stderr, " prec {\n"); + fprintf(stderr, " x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n", prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch); + for (cblkno=0; cblknocw*prec->ch; cblkno++) { + tcd_cblk_t *cblk=&prec->cblks[cblkno]; + fprintf(stderr, " cblk {\n"); + fprintf(stderr, " x0=%d, y0=%d, x1=%d, y1=%d\n", cblk->x0, cblk->y0, cblk->x1, cblk->y1); + fprintf(stderr, " }\n"); + } + fprintf(stderr, " }\n"); + } + fprintf(stderr, " }\n"); + } + fprintf(stderr, " }\n"); + } + fprintf(stderr, " }\n"); + } + fprintf(stderr, " }\n"); + } + fprintf(stderr, "}\n"); +} +#endif //J2K_DUMP_ENABLED + +void tcd_init(j2k_image_t *img, j2k_cp_t *cp) { + int tileno, compno, resno, bandno, precno, cblkno; + tcd_img=img; + tcd_cp=cp; + tcd_image.tw=cp->tw; + tcd_image.th=cp->th; + tcd_image.tiles=(tcd_tile_t*)malloc(cp->tw*cp->th*sizeof(tcd_tile_t)); + for (tileno=0; tilenotw*cp->th; tileno++) { + j2k_tcp_t *tcp=&cp->tcps[tileno]; + tcd_tile_t *tile=&tcd_image.tiles[tileno]; + int p=tileno%cp->tw; + int q=tileno/cp->tw; + tile->x0=int_max(cp->tx0+p*cp->tdx, img->x0); + tile->y0=int_max(cp->ty0+q*cp->tdy, img->y0); + tile->x1=int_min(cp->tx0+(p+1)*cp->tdx, img->x1); + tile->y1=int_min(cp->ty0+(q+1)*cp->tdy, img->y1); + + tile->numcomps=img->numcomps; + tile->comps=(tcd_tilecomp_t*)malloc(img->numcomps*sizeof(tcd_tilecomp_t)); + for (compno=0; compnonumcomps; compno++) { + j2k_tccp_t *tccp=&tcp->tccps[compno]; + tcd_tilecomp_t *tilec=&tile->comps[compno]; + tilec->x0=int_ceildiv(tile->x0, img->comps[compno].dx); + tilec->y0=int_ceildiv(tile->y0, img->comps[compno].dy); + tilec->x1=int_ceildiv(tile->x1, img->comps[compno].dx); + tilec->y1=int_ceildiv(tile->y1, img->comps[compno].dy); + tilec->data=(int*)malloc(sizeof(int)*(tilec->x1-tilec->x0)*(tilec->y1-tilec->y0)); + tilec->numresolutions=tccp->numresolutions; + tilec->resolutions=(tcd_resolution_t*)malloc(tilec->numresolutions*sizeof(tcd_resolution_t)); + for (resno=0; resnonumresolutions; resno++) { + int pdx, pdy; + int levelno=tilec->numresolutions-1-resno; + int tlprcxstart, tlprcystart, brprcxend, brprcyend; + int tlcbgxstart, tlcbgystart, brcbgxend, brcbgyend; + int cbgwidthexpn, cbgheightexpn; + int cblkwidthexpn, cblkheightexpn; + tcd_resolution_t *res=&tilec->resolutions[resno]; + res->x0=int_ceildivpow2(tilec->x0, levelno); + res->y0=int_ceildivpow2(tilec->y0, levelno); + res->x1=int_ceildivpow2(tilec->x1, levelno); + res->y1=int_ceildivpow2(tilec->y1, levelno); + res->numbands=resno==0?1:3; + + if (tccp->csty&J2K_CCP_CSTY_PRT) { + pdx=tccp->prcw[resno]; + pdy=tccp->prch[resno]; + } else { + pdx=15; + pdy=15; + } + + tlprcxstart=int_floordivpow2(res->x0, pdx)<y0, pdy)<x1, pdx)<y1, pdy)<pw=(brprcxend-tlprcxstart)>>pdx; + res->ph=(brprcyend-tlprcystart)>>pdy; + + if (resno==0) { + tlcbgxstart=tlprcxstart; + tlcbgystart=tlprcystart; + brcbgxend=brprcxend; + brcbgyend=brprcyend; + cbgwidthexpn=pdx; + cbgheightexpn=pdy; + } else { + tlcbgxstart=int_ceildivpow2(tlprcxstart, 1); + tlcbgystart=int_ceildivpow2(tlprcystart, 1); + brcbgxend=int_ceildivpow2(brprcxend, 1); + brcbgyend=int_ceildivpow2(brprcyend, 1); + cbgwidthexpn=pdx-1; + cbgheightexpn=pdy-1; + } + + cblkwidthexpn=int_min(tccp->cblkw, cbgwidthexpn); + cblkheightexpn=int_min(tccp->cblkh, cbgheightexpn); + + for (bandno=0; bandnonumbands; bandno++) { + int x0b, y0b; + int gain, numbps; + j2k_stepsize_t *ss; + tcd_band_t *band=&res->bands[bandno]; + band->bandno=resno==0?0:bandno+1; + x0b=(band->bandno==1)||(band->bandno==3)?1:0; + y0b=(band->bandno==2)||(band->bandno==3)?1:0; + + if (band->bandno==0) { + band->x0=int_ceildivpow2(tilec->x0, levelno); + band->y0=int_ceildivpow2(tilec->y0, levelno); + band->x1=int_ceildivpow2(tilec->x1, levelno); + band->y1=int_ceildivpow2(tilec->y1, levelno); + } else { + band->x0=int_ceildivpow2(tilec->x0-(1<y0=int_ceildivpow2(tilec->y0-(1<x1=int_ceildivpow2(tilec->x1-(1<y1=int_ceildivpow2(tilec->y1-(1<stepsizes[resno==0?0:3*(resno-1)+bandno+1]; + gain=tccp->qmfbid==0?dwt_getgain_real(band->bandno):dwt_getgain(band->bandno); + numbps=img->comps[compno].prec+gain; + band->stepsize=(int)floor((1.0+ss->mant/2048.0)*pow(2.0,numbps-ss->expn)*8192.0); + band->numbps=ss->expn+tccp->numgbits-1; // WHY -1 ? + + band->precincts=(tcd_precinct_t*)malloc(res->pw*res->ph*sizeof(tcd_precinct_t)); + + for (precno=0; precnopw*res->ph; precno++) { + int tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend; + int cbgxstart=tlcbgxstart+(precno%res->pw)*(1<pw)*(1<precincts[precno]; + prc->x0=int_max(cbgxstart, band->x0); + prc->y0=int_max(cbgystart, band->y0); + prc->x1=int_min(cbgxend, band->x1); + prc->y1=int_min(cbgyend, band->y1); + + tlcblkxstart=int_floordivpow2(prc->x0, cblkwidthexpn)<y0, cblkheightexpn)<x1, cblkwidthexpn)<y1, cblkheightexpn)<cw=(brcblkxend-tlcblkxstart)>>cblkwidthexpn; + prc->ch=(brcblkyend-tlcblkystart)>>cblkheightexpn; + + prc->cblks=(tcd_cblk_t*)malloc(prc->cw*prc->ch*sizeof(tcd_cblk_t)); + + prc->incltree=tgt_create(prc->cw, prc->ch); + prc->imsbtree=tgt_create(prc->cw, prc->ch); + + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + int cblkxstart=tlcblkxstart+(cblkno%prc->cw)*(1<cw)*(1<cblks[cblkno]; + cblk->x0=int_max(cblkxstart, prc->x0); + cblk->y0=int_max(cblkystart, prc->y0); + cblk->x1=int_min(cblkxend, prc->x1); + cblk->y1=int_min(cblkyend, prc->y1); + } + } + } + } + } + } +#if J2K_DUMP_ENABLED + tcd_dump(&tcd_image); +#endif //J2K_DUMP_ENABLED +} + +void tcd_makelayer(int layno, double thresh, int final) { + int compno, resno, bandno, precno, cblkno, passno; + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tcd_tile->comps[compno]; + for (resno=0; resnonumresolutions; resno++) { + tcd_resolution_t *res=&tilec->resolutions[resno]; + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + for (precno=0; precnopw*res->ph; precno++) { + tcd_precinct_t *prc=&band->precincts[precno]; + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + tcd_layer_t *layer=&cblk->layers[layno]; + int n; + if (layno==0) { + cblk->numpassesinlayers=0; + } + n=cblk->numpassesinlayers; + for (passno=cblk->numpassesinlayers; passnototalpasses; passno++) { + int dr; + double dd; + tcd_pass_t *pass=&cblk->passes[passno]; + if (n==0) { + dr=pass->rate; + dd=pass->distortiondec; + } else { + dr=pass->rate-cblk->passes[n-1].rate; + dd=pass->distortiondec-cblk->passes[n-1].distortiondec; + } + if (dr==0) { + if (dd!=0) { + n=passno+1; + } + continue; + } + if (dd/dr>thresh) { + n=passno+1; + } + } + layer->numpasses=n-cblk->numpassesinlayers; + if (!layer->numpasses) { + continue; + } + if (cblk->numpassesinlayers==0) { + layer->len=cblk->passes[n-1].rate; + layer->data=cblk->data; + } else { + layer->len=cblk->passes[n-1].rate-cblk->passes[cblk->numpassesinlayers-1].rate; + layer->data=cblk->data+cblk->passes[cblk->numpassesinlayers-1].rate; + } + if (final) { + cblk->numpassesinlayers=n; + } + } + } + } + } + } +} + +void tcd_rateallocate(unsigned char *dest, int len) { + int compno, resno, bandno, precno, cblkno, passno, layno; + double min, max; + min=DBL_MAX; + max=0; + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tcd_tile->comps[compno]; + for (resno=0; resnonumresolutions; resno++) { + tcd_resolution_t *res=&tilec->resolutions[resno]; + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + for (precno=0; precnopw*res->ph; precno++) { + tcd_precinct_t *prc=&band->precincts[precno]; + for (cblkno=0; cblknocw*prc->ch; cblkno++) { + tcd_cblk_t *cblk=&prc->cblks[cblkno]; + for (passno=0; passnototalpasses; passno++) { + tcd_pass_t *pass=&cblk->passes[passno]; + int dr; + double dd, rdslope; + if (passno==0) { + dr=pass->rate; + dd=pass->distortiondec; + } else { + dr=pass->rate-cblk->passes[passno-1].rate; + dd=pass->distortiondec-cblk->passes[passno-1].distortiondec; + } + if (dr==0) { + continue; + } + rdslope=dd/dr; + if (rdslopemax) { + max=rdslope; + } + } + } + } + } + } + } + for (layno=0; laynonumlayers; layno++) { + volatile double lo=min; + volatile double hi=max; + volatile int success=0; + volatile int maxlen=int_min(tcd_tcp->rates[layno], len); + volatile double goodthresh; + volatile int goodlen; + volatile jmp_buf oldenv; + volatile int i; + memcpy((void*)oldenv, j2k_error, sizeof(jmp_buf)); + for (i=0; i<32; i++) { + volatile double thresh=(lo+hi)/2; + int l; + tcd_makelayer(layno, thresh, 0); + if (setjmp(j2k_error)) { + lo=thresh; + continue; + } + l=t2_encode_packets(tcd_img, tcd_cp, tcd_tileno, tcd_tile, layno+1, dest, maxlen); + J2KDUMP2("rate alloc: len=%d, max=%d\n", l, maxlen); + hi=thresh; + success=1; + goodthresh=thresh; + goodlen=l; + } + memcpy(j2k_error, (void*)oldenv, sizeof(jmp_buf)); + if (!success) { + longjmp(j2k_error, 1); + } + tcd_makelayer(layno, goodthresh, 1); + } +} + +int tcd_encode_tile(int tileno, unsigned char *dest, int len) { + int compno; + int l; + clock_t time1, time2, time3, time4, time5, time6, time7; + tcd_tile_t *tile; + tcd_tileno=tileno; + tcd_tile=&tcd_image.tiles[tileno]; + tcd_tcp=&tcd_cp->tcps[tileno]; + tile=tcd_tile; + + time7=clock(); + + time1=clock(); + for (compno=0; compnonumcomps; compno++) { + int i, j; + int tw, w; + tcd_tilecomp_t *tilec=&tile->comps[compno]; + int adjust=tcd_img->comps[compno].sgnd?0:1<<(tcd_img->comps[compno].prec-1); + tw=tilec->x1-tilec->x0; + w=int_ceildiv(tcd_img->x1-tcd_img->x0, tcd_img->comps[compno].dx); + for (j=tilec->y0; jy1; j++) { + for (i=tilec->x0; ix1; i++) { + if (tcd_tcp->tccps[compno].qmfbid==1) { + tilec->data[i-tilec->x0+(j-tilec->y0)*tw]=tcd_img->comps[compno].data[i+j*w]-adjust; + } else if (tcd_tcp->tccps[compno].qmfbid==0) { + tilec->data[i-tilec->x0+(j-tilec->y0)*tw]=(tcd_img->comps[compno].data[i+j*w]-adjust)<<13; + } + } + } + } + time1=clock()-time1; + + time2=clock(); + if (tcd_tcp->mct) { + if (tcd_tcp->tccps[0].qmfbid==0) { + mct_encode_real(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, (tile->comps[0].x1-tile->comps[0].x0)*(tile->comps[0].y1-tile->comps[0].y0)); + } else { + mct_encode(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, (tile->comps[0].x1-tile->comps[0].x0)*(tile->comps[0].y1-tile->comps[0].y0)); + } + } + time2=clock()-time2; + + time3=clock(); + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tile->comps[compno]; + if (tcd_tcp->tccps[compno].qmfbid==1) { + dwt_encode(tilec->data, tilec->x1-tilec->x0, tilec->y1-tilec->y0, tilec->numresolutions-1); + } else if (tcd_tcp->tccps[compno].qmfbid==0) { + dwt_encode_real(tilec->data, tilec->x1-tilec->x0, tilec->y1-tilec->y0, tilec->numresolutions-1); + } + } + time3=clock()-time3; + + time4=clock(); + t1_init_luts(); + + t1_encode_cblks(tile, tcd_tcp); + time4=clock()-time4; + + time5=clock(); + tcd_rateallocate(dest, len); + time5=clock()-time5; + + time6=clock(); + l=t2_encode_packets(tcd_img, tcd_cp, tileno, tile, tcd_tcp->numlayers, dest, len); + time6=clock()-time6; + + time7=clock()-time7; +#if J2K_DUMP_ENABLED + printf("tile encoding times:\n"); + printf("img->tile: %d.%.3d s\n", time1/CLOCKS_PER_SEC, (time1%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("mct: %d.%.3d s\n", time2/CLOCKS_PER_SEC, (time2%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("dwt: %d.%.3d s\n", time3/CLOCKS_PER_SEC, (time3%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("tier 1: %d.%.3d s\n", time4/CLOCKS_PER_SEC, (time4%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("ratealloc: %d.%.3d s\n", time5/CLOCKS_PER_SEC, (time5%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("tier 2: %d.%.3d s\n", time6/CLOCKS_PER_SEC, (time6%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("total: %d.%.3d s\n", time7/CLOCKS_PER_SEC, (time7%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); +#endif //J2K_DUMP_ENABLED + + return l; +} + +int tcd_decode_tile(unsigned char *src, int len, int tileno) { + int l; + int compno; + int eof=0; + jmp_buf oldenv; + clock_t time1, time2, time3, time4, time5, time6; + + tcd_tile_t *tile; + tcd_tileno=tileno; + tcd_tile=&tcd_image.tiles[tileno]; + tcd_tcp=&tcd_cp->tcps[tileno]; + tile=tcd_tile; + + time6=clock(); + + time1=clock(); + memcpy(oldenv, j2k_error, sizeof(jmp_buf)); + if (setjmp(j2k_error)) { + eof=1; + J2KWARNING("tcd_decode: incomplete bistream\n") + } else { + l=t2_decode_packets(src, len, tcd_img, tcd_cp, tileno, tile); + } + memcpy(j2k_error, oldenv, sizeof(jmp_buf)); + time1=clock()-time1; + + time2=clock(); + t1_init_luts(); + t1_decode_cblks(tile, tcd_tcp); + time2=clock()-time2; + + time3=clock(); + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tile->comps[compno]; + if (tcd_tcp->tccps[compno].qmfbid==1) { + dwt_decode(tilec->data, tilec->x1-tilec->x0, tilec->y1-tilec->y0, tilec->numresolutions-1); + } else if (tcd_tcp->tccps[compno].qmfbid==0) { + dwt_decode_real(tilec->data, tilec->x1-tilec->x0, tilec->y1-tilec->y0, tilec->numresolutions-1); + } + } + time3=clock()-time3; + + time4=clock(); + if (tcd_tcp->mct) { + if (tcd_tcp->tccps[0].qmfbid==0) { + mct_decode_real(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, (tile->comps[0].x1-tile->comps[0].x0)*(tile->comps[0].y1-tile->comps[0].y0)); + } else { + mct_decode(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, (tile->comps[0].x1-tile->comps[0].x0)*(tile->comps[0].y1-tile->comps[0].y0)); + } + } + time4=clock()-time4; + + time5=clock(); + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tile->comps[compno]; + int adjust=tcd_img->comps[compno].sgnd?0:1<<(tcd_img->comps[compno].prec-1); + int min=tcd_img->comps[compno].sgnd?-(1<<(tcd_img->comps[compno].prec-1)):0; + int max=tcd_img->comps[compno].sgnd?(1<<(tcd_img->comps[compno].prec-1))-1:(1<comps[compno].prec)-1; + int tw=tilec->x1-tilec->x0; + int w=int_ceildiv(tcd_img->x1-tcd_img->x0, tcd_img->comps[compno].dx); + int i, j; + for (j=tilec->y0; jy1; j++) { + for (i=tilec->x0; ix1; i++) { + int v; + if (tcd_tcp->tccps[compno].qmfbid==1) { + v=tilec->data[i-tilec->x0+(j-tilec->y0)*tw]; + } else if (tcd_tcp->tccps[compno].qmfbid==0) { + v=tilec->data[i-tilec->x0+(j-tilec->y0)*tw]>>13; + } + v+=adjust; + tcd_img->comps[compno].data[i+j*w]=int_clamp(v, min, max); + } + } + } + time5=clock()-time5; + + time6=clock()-time6; + +#if J2K_DUMP_ENABLED + printf("tile decoding times:\n"); + printf("tier 2: %d.%.3d s\n", time1/CLOCKS_PER_SEC, (time1%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("tier 1: %d.%.3d s\n", time2/CLOCKS_PER_SEC, (time2%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("dwt: %d.%.3d s\n", time3/CLOCKS_PER_SEC, (time3%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("mct: %d.%.3d s\n", time4/CLOCKS_PER_SEC, (time4%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("tile->img: %d.%.3d s\n", time5/CLOCKS_PER_SEC, (time5%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); + printf("total: %d.%.3d s\n", time6/CLOCKS_PER_SEC, (time6%CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC); +#endif //J2K_DUMP_ENABLED + + if (eof) { + longjmp(j2k_error, 1); + } + return l; +} + +void tcd_destroy(j2k_image_t *img, j2k_cp_t *cp) +{ + int tileno, compno, resno, bandno, precno; + for (tileno=0; tilenotw*cp->th; tileno++) { + tcd_tile_t *tile=&tcd_image.tiles[tileno]; + for (compno=0; compnonumcomps; compno++) { + tcd_tilecomp_t *tilec=&tile->comps[compno]; + for (resno=0; resnonumresolutions; resno++) { + tcd_resolution_t *res=&tilec->resolutions[resno]; + for (bandno=0; bandnonumbands; bandno++) { + tcd_band_t *band=&res->bands[bandno]; + for (precno=0; precnopw*res->ph; precno++) { + tcd_precinct_t *prec=&band->precincts[precno]; + if (prec[precno].incltree) {tgt_destroy(prec[precno].incltree); prec[precno].incltree=0;} + if (prec[precno].imsbtree) {tgt_destroy(prec[precno].imsbtree); prec[precno].imsbtree=0;} + if (prec[precno].cblks) {free(prec[precno].cblks); prec[precno].cblks=0;} + } + if(band->precincts) {free(band->precincts); band->precincts=0;} + } + } + if (tilec->data) {free(tilec->data); tilec->data=0;} + if (tilec->resolutions) {free(tilec->resolutions); tilec->resolutions=0;} + } + if (tile->comps) {free(tile->comps); tile->comps=0;} + } + if (tcd_image.tiles) {free(tcd_image.tiles); tcd_image.tiles=0;} +} + diff --git a/SlnkDWFImpl/CxImage/j2k/tcd.h b/SlnkDWFImpl/CxImage/j2k/tcd.h new file mode 100644 index 0000000..9ca4f64 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/tcd.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 __TCD_H +#define __TCD_H + +#include "j2k.h" +#include "tgt.h" + +typedef struct { + int numpasses; + int len; + unsigned char *data; + int maxpasses; + int numnewpasses; + int newlen; +} tcd_seg_t; + +typedef struct { + int rate; + double distortiondec; +} tcd_pass_t; + +typedef struct { + int numpasses; + int len; + unsigned char *data; +} tcd_layer_t; + +typedef struct { + int x0, y0, x1, y1; + int numbps; + int numlenbits; + int len; + int numpasses; + int numnewpasses; + int numsegs; + tcd_seg_t segs[100]; + unsigned char data[8192]; + int numpassesinlayers; + tcd_layer_t layers[100]; + int totalpasses; + tcd_pass_t passes[100]; +} tcd_cblk_t; + +typedef struct { + int x0, y0, x1, y1; + int cw, ch; + tcd_cblk_t *cblks; + tgt_tree_t *incltree; + tgt_tree_t *imsbtree; +} tcd_precinct_t; + +typedef struct { + int x0, y0, x1, y1; + int bandno; + tcd_precinct_t *precincts; + int numbps; + int stepsize; +} tcd_band_t; + +typedef struct { + int x0, y0, x1, y1; + int pw, ph; + int numbands; + tcd_band_t bands[3]; +} tcd_resolution_t; + +typedef struct { + int x0, y0, x1, y1; + int numresolutions; + tcd_resolution_t *resolutions; + int *data; +} tcd_tilecomp_t; + +typedef struct { + int x0, y0, x1, y1; + int numcomps; + tcd_tilecomp_t *comps; +} tcd_tile_t; + +typedef struct { + int tw, th; + tcd_tile_t *tiles; +} tcd_image_t; + +void tcd_init(j2k_image_t *img, j2k_cp_t *cp); +void tcd_destroy(j2k_image_t *img, j2k_cp_t *cp); +int tcd_encode_tile(int tileno, unsigned char *dest, int len); +int tcd_decode_tile(unsigned char *src, int len, int tileno); + +#endif diff --git a/SlnkDWFImpl/CxImage/j2k/tgt.c b/SlnkDWFImpl/CxImage/j2k/tgt.c new file mode 100644 index 0000000..24a1d72 --- /dev/null +++ b/SlnkDWFImpl/CxImage/j2k/tgt.c @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2001-2002, David Janssens + * 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. 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. + * + * 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 "tgt.h" +#include "bio.h" +#include + +/// +/// Reset tag-tree. +/// +void tgt_reset(tgt_tree_t *tree) +{ + int i; + for (i=0; inumnodes; i++) { + tree->nodes[i].value=999; + tree->nodes[i].low=0; + tree->nodes[i].known=0; + } +} + +/// +/// Create tag-tree. +/// +tgt_tree_t *tgt_create(int numleafsh, int numleafsv) +{ + int nplh[32]; + int nplv[32]; + tgt_node_t *node; + tgt_node_t *parentnode; + tgt_node_t *parentnode0; + tgt_tree_t *tree; + int i, j, k; + int numlvls; + int n; + + tree=(tgt_tree_t*)malloc(sizeof(tgt_tree_t)); + tree->numleafsh=numleafsh; + tree->numleafsv=numleafsv; + + numlvls=0; + nplh[0]=numleafsh; + nplv[0]=numleafsv; + tree->numnodes=0; + do { + n=nplh[numlvls]*nplv[numlvls]; + nplh[numlvls+1]=(nplh[numlvls]+1)/2; + nplv[numlvls+1]=(nplv[numlvls]+1)/2; + tree->numnodes+=n; + ++numlvls; + } while (n>1); + + tree->nodes=(tgt_node_t*)malloc(tree->numnodes*sizeof(tgt_node_t)); + + node=tree->nodes; + parentnode=&tree->nodes[tree->numleafsh*tree->numleafsv]; + parentnode0=parentnode; + + for (i=0; i=0) { + node->parent=parentnode; + ++node; + if (--k >= 0) { + node->parent=parentnode; + ++node; + } + ++parentnode; + } + if ((j&1)||j==nplv[i]-1) { + parentnode0=parentnode; + } else { + parentnode=parentnode0; + parentnode0+=nplh[i]; + } + } + } + node->parent=0; + + tgt_reset(tree); + + return tree; +} + +/// +/// Destroy tag-tree. +/// +void tgt_destroy(tgt_tree_t *t) { + free(t->nodes); + free(t); +} + +/// +/// Set the value of a leaf of the tag-tree. +/// +void tgt_setvalue(tgt_tree_t *tree, int leafno, int value) { + tgt_node_t *node; + node=&tree->nodes[leafno]; + while (node && node->value>value) { + node->value=value; + node=node->parent; + } +} + +/// +/// Encode the value of a leaf of the tag-tree. +/// +void tgt_encode(tgt_tree_t *tree, int leafno, int threshold) { + tgt_node_t *stk[31]; + tgt_node_t **stkptr; + tgt_node_t *node; + int low; + + stkptr=stk; + node=&tree->nodes[leafno]; + while (node->parent) { + *stkptr++=node; + node=node->parent; + } + + low=0; + for (;;) { + if (low>node->low) { + node->low=low; + } else { + low=node->low; + } + while (low=node->value) { + if (!node->known) { + bio_write(1, 1); + node->known=1; + } + break; + } + bio_write(0, 1); + ++low; + } + node->low=low; + if (stkptr==stk) break; + node=*--stkptr; + } +} + +/// +/// Decode the value of a leaf of the tag-tree. +/// +int tgt_decode(tgt_tree_t *tree, int leafno, int threshold) +{ + tgt_node_t *stk[31]; + tgt_node_t **stkptr; + tgt_node_t *node; + int low; + + stkptr=stk; + node=&tree->nodes[leafno]; + while (node->parent) { + *stkptr++=node; + node=node->parent; + } + + low=0; + for (;;) { + if (low>node->low) { + node->low=low; + } else { + low=node->low; + } + while (lowvalue) { + if (bio_read(1)) { + node->value=low; + } else { + ++low; + } + } + node->low=low; + if (stkptr==stk) { + break; + } + node=*--stkptr; + } + + return (node->value +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static jas_cmprof_t *jas_cmprof_create(void); +static void jas_cmshapmatlut_cleanup(jas_cmshapmatlut_t *); +static jas_cmreal_t jas_cmshapmatlut_lookup(jas_cmshapmatlut_t *lut, jas_cmreal_t x); + +static void jas_cmpxform_destroy(jas_cmpxform_t *pxform); +static jas_cmpxform_t *jas_cmpxform_copy(jas_cmpxform_t *pxform); + +static void jas_cmshapmat_destroy(jas_cmpxform_t *pxform); +static int jas_cmshapmat_apply(jas_cmpxform_t *pxform, jas_cmreal_t *in, + jas_cmreal_t *out, int cnt); + +static int jas_cmputint(long **bufptr, int sgnd, int prec, long val); +static int jas_cmgetint(long **bufptr, int sgnd, int prec, long *val); +static int jas_cmpxformseq_append(jas_cmpxformseq_t *pxformseq, + jas_cmpxformseq_t *othpxformseq); +static int jas_cmpxformseq_appendcnvt(jas_cmpxformseq_t *pxformseq, + int, int); +static int jas_cmpxformseq_resize(jas_cmpxformseq_t *pxformseq, int n); + +static int mono(jas_iccprof_t *prof, int op, jas_cmpxformseq_t **pxformseq); +static int triclr(jas_iccprof_t *prof, int op, jas_cmpxformseq_t **retpxformseq); + +static void jas_cmpxformseq_destroy(jas_cmpxformseq_t *pxformseq); +static int jas_cmpxformseq_delete(jas_cmpxformseq_t *pxformseq, int i); +static jas_cmpxformseq_t *jas_cmpxformseq_create(void); +static jas_cmpxformseq_t *jas_cmpxformseq_copy(jas_cmpxformseq_t *pxformseq); +static int jas_cmshapmat_invmat(jas_cmreal_t out[3][4], jas_cmreal_t in[3][4]); +static int jas_cmpxformseq_insertpxform(jas_cmpxformseq_t *pxformseq, + int i, jas_cmpxform_t *pxform); + +#define SEQFWD(intent) (intent) +#define SEQREV(intent) (4 + (intent)) +#define SEQSIM(intent) (8 + (intent)) +#define SEQGAM 12 + +#define fwdpxformseq(prof, intent) \ + (((prof)->pxformseqs[SEQFWD(intent)]) ? \ + ((prof)->pxformseqs[SEQFWD(intent)]) : \ + ((prof)->pxformseqs[SEQFWD(0)])) + +#define revpxformseq(prof, intent) \ + (((prof)->pxformseqs[SEQREV(intent)]) ? \ + ((prof)->pxformseqs[SEQREV(intent)]) : \ + ((prof)->pxformseqs[SEQREV(0)])) + +#define simpxformseq(prof, intent) \ + (((prof)->pxformseqs[SEQSIM(intent)]) ? \ + ((prof)->pxformseqs[SEQSIM(intent)]) : \ + ((prof)->pxformseqs[SEQSIM(0)])) + +#define gampxformseq(prof) ((prof)->pxformseqs[SEQGAM]) + +static int icctoclrspc(int iccclrspc, int refflag); +static jas_cmpxform_t *jas_cmpxform_create0(void); +static jas_cmpxform_t *jas_cmpxform_createshapmat(void); +static void jas_cmshapmatlut_init(jas_cmshapmatlut_t *lut); +static int jas_cmshapmatlut_set(jas_cmshapmatlut_t *lut, jas_icccurv_t *curv); + +static jas_cmpxformops_t shapmat_ops = {jas_cmshapmat_destroy, jas_cmshapmat_apply, 0}; +static jas_cmprof_t *jas_cmprof_createsycc(void); + +/******************************************************************************\ +* Color profile class. +\******************************************************************************/ + +jas_cmprof_t *jas_cmprof_createfromclrspc(int clrspc) +{ + jas_iccprof_t *iccprof; + jas_cmprof_t *prof; + + iccprof = 0; + prof = 0; + switch (clrspc) { + case JAS_CLRSPC_SYCBCR: + if (!(prof = jas_cmprof_createsycc())) + goto error; + break; + default: + if (!(iccprof = jas_iccprof_createfromclrspc(clrspc))) + goto error; + if (!(prof = jas_cmprof_createfromiccprof(iccprof))) + goto error; + jas_iccprof_destroy(iccprof); + if (!jas_clrspc_isgeneric(clrspc)) + prof->clrspc = clrspc; + break; + } + return prof; +error: + if (iccprof) + jas_iccprof_destroy(iccprof); + return 0; +} + +static jas_cmprof_t *jas_cmprof_createsycc() +{ + jas_cmprof_t *prof; + jas_cmpxform_t *fwdpxform; + jas_cmpxform_t *revpxform; + jas_cmshapmat_t *fwdshapmat; + jas_cmshapmat_t *revshapmat; + int i; + int j; + + if (!(prof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB))) + goto error; + prof->clrspc = JAS_CLRSPC_SYCBCR; + assert(prof->numchans == 3 && prof->numrefchans == 3); + assert(prof->refclrspc == JAS_CLRSPC_CIEXYZ); + if (!(fwdpxform = jas_cmpxform_createshapmat())) + goto error; + fwdpxform->numinchans = 3; + fwdpxform->numoutchans = 3; + fwdshapmat = &fwdpxform->data.shapmat; + fwdshapmat->mono = 0; + fwdshapmat->order = 0; + fwdshapmat->useluts = 0; + fwdshapmat->usemat = 1; + fwdshapmat->mat[0][0] = 1.0; + fwdshapmat->mat[0][1] = 0.0; + fwdshapmat->mat[0][2] = 1.402; + fwdshapmat->mat[1][0] = 1.0; + fwdshapmat->mat[1][1] = -0.34413; + fwdshapmat->mat[1][2] = -0.71414; + fwdshapmat->mat[2][0] = 1.0; + fwdshapmat->mat[2][1] = 1.772; + fwdshapmat->mat[2][2] = 0.0; + fwdshapmat->mat[0][3] = -0.5 * (1.402); + fwdshapmat->mat[1][3] = -0.5 * (-0.34413 - 0.71414); + fwdshapmat->mat[2][3] = -0.5 * (1.772); + if (!(revpxform = jas_cmpxform_createshapmat())) + goto error; + revpxform->numinchans = 3; + revpxform->numoutchans = 3; + revshapmat = &revpxform->data.shapmat; + revshapmat->mono = 0; + revshapmat->order = 1; + revshapmat->useluts = 0; + revshapmat->usemat = 1; + jas_cmshapmat_invmat(revshapmat->mat, fwdshapmat->mat); + + for (i = 0; i < JAS_CMXFORM_NUMINTENTS; ++i) { + j = SEQFWD(i); + if (prof->pxformseqs[j]) { + if (jas_cmpxformseq_insertpxform(prof->pxformseqs[j], 0, + fwdpxform)) + goto error; + } + j = SEQREV(i); + if (prof->pxformseqs[j]) { + if (jas_cmpxformseq_insertpxform(prof->pxformseqs[j], + -1, revpxform)) + goto error; + } + } + + jas_cmpxform_destroy(fwdpxform); + jas_cmpxform_destroy(revpxform); + return prof; +error: + return 0; +} + +jas_cmprof_t *jas_cmprof_createfromiccprof(jas_iccprof_t *iccprof) +{ + jas_cmprof_t *prof; + jas_icchdr_t icchdr; + jas_cmpxformseq_t *fwdpxformseq; + jas_cmpxformseq_t *revpxformseq; + + if (!(prof = jas_cmprof_create())) + goto error; + jas_iccprof_gethdr(iccprof, &icchdr); + if (!(prof->iccprof = jas_iccprof_copy(iccprof))) + goto error; + prof->clrspc = icctoclrspc(icchdr.colorspc, 0); + prof->refclrspc = icctoclrspc(icchdr.refcolorspc, 1); + prof->numchans = jas_clrspc_numchans(prof->clrspc); + prof->numrefchans = jas_clrspc_numchans(prof->refclrspc); + + if (prof->numchans == 1) { + if (mono(prof->iccprof, 0, &fwdpxformseq)) + goto error; + if (mono(prof->iccprof, 1, &revpxformseq)) + goto error; + } else if (prof->numchans == 3) { + if (triclr(prof->iccprof, 0, &fwdpxformseq)) + goto error; + if (triclr(prof->iccprof, 1, &revpxformseq)) + goto error; + } + prof->pxformseqs[SEQFWD(0)] = fwdpxformseq; + prof->pxformseqs[SEQREV(0)] = revpxformseq; + +#if 0 + if (prof->numchans > 1) { + lut(prof->iccprof, 0, PER, &pxformseq); + pxformseqs_set(prof, SEQFWD(PER), pxformseq); + lut(prof->iccprof, 1, PER, &pxformseq); + pxformseqs_set(prof, SEQREV(PER), pxformseq); + lut(prof->iccprof, 0, CLR, &pxformseq); + pxformseqs_set(prof, SEQREV(CLR), pxformseq); + lut(prof->iccprof, 1, CLR, &pxformseq); + pxformseqs_set(prof, SEQREV(CLR), pxformseq); + lut(prof->iccprof, 0, SAT, &pxformseq); + pxformseqs_set(prof, SEQREV(SAT), pxformseq); + lut(prof->iccprof, 1, SAT, &pxformseq); + pxformseqs_set(prof, SEQREV(SAT), pxformseq); + } +#endif + + return prof; +error: + return 0; +} + +static jas_cmprof_t *jas_cmprof_create() +{ + int i; + jas_cmprof_t *prof; + if (!(prof = jas_malloc(sizeof(jas_cmprof_t)))) + return 0; + memset(prof, 0, sizeof(jas_cmprof_t)); + prof->iccprof = 0; + for (i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i) + prof->pxformseqs[i] = 0; + return prof; +} + +void jas_cmprof_destroy(jas_cmprof_t *prof) +{ + int i; + for (i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i) { + if (prof->pxformseqs[i]) { + jas_cmpxformseq_destroy(prof->pxformseqs[i]); + prof->pxformseqs[i] = 0; + } + } + if (prof->iccprof) + jas_iccprof_destroy(prof->iccprof); + jas_free(prof); +} + +jas_cmprof_t *jas_cmprof_copy(jas_cmprof_t *prof) +{ + jas_cmprof_t *newprof; + int i; + + if (!(newprof = jas_cmprof_create())) + goto error; + newprof->clrspc = prof->clrspc; + newprof->numchans = prof->numchans; + newprof->refclrspc = prof->refclrspc; + newprof->numrefchans = prof->numrefchans; + newprof->iccprof = jas_iccprof_copy(prof->iccprof); + for (i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i) { + if (prof->pxformseqs[i]) { + if (!(newprof->pxformseqs[i] = jas_cmpxformseq_copy(prof->pxformseqs[i]))) + goto error; + } + } + return newprof; +error: + return 0; +} + +/******************************************************************************\ +* Transform class. +\******************************************************************************/ + +jas_cmxform_t *jas_cmxform_create(jas_cmprof_t *inprof, jas_cmprof_t *outprof, + jas_cmprof_t *prfprof, int op, int intent, int optimize) +{ + jas_cmxform_t *xform; + jas_cmpxformseq_t *inpxformseq; + jas_cmpxformseq_t *outpxformseq; + jas_cmpxformseq_t *altoutpxformseq; + jas_cmpxformseq_t *prfpxformseq; + int prfintent; + + /* Avoid compiler warnings about unused parameters. */ + optimize = 0; + + prfintent = intent; + + if (!(xform = jas_malloc(sizeof(jas_cmxform_t)))) + goto error; + if (!(xform->pxformseq = jas_cmpxformseq_create())) + goto error; + + switch (op) { + case JAS_CMXFORM_OP_FWD: + inpxformseq = fwdpxformseq(inprof, intent); + outpxformseq = revpxformseq(outprof, intent); + if (!inpxformseq || !outpxformseq) + goto error; + if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) || + jas_cmpxformseq_appendcnvt(xform->pxformseq, + inprof->refclrspc, outprof->refclrspc) || + jas_cmpxformseq_append(xform->pxformseq, outpxformseq)) + goto error; + xform->numinchans = jas_clrspc_numchans(inprof->clrspc); + xform->numoutchans = jas_clrspc_numchans(outprof->clrspc); + break; + case JAS_CMXFORM_OP_REV: + outpxformseq = fwdpxformseq(outprof, intent); + inpxformseq = revpxformseq(inprof, intent); + if (!outpxformseq || !inpxformseq) + goto error; + if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq) || + jas_cmpxformseq_appendcnvt(xform->pxformseq, + outprof->refclrspc, inprof->refclrspc) || + jas_cmpxformseq_append(xform->pxformseq, inpxformseq)) + goto error; + xform->numinchans = jas_clrspc_numchans(outprof->clrspc); + xform->numoutchans = jas_clrspc_numchans(inprof->clrspc); + break; + case JAS_CMXFORM_OP_PROOF: + assert(prfprof); + inpxformseq = fwdpxformseq(inprof, intent); + prfpxformseq = fwdpxformseq(prfprof, prfintent); + if (!inpxformseq || !prfpxformseq) + goto error; + outpxformseq = simpxformseq(outprof, intent); + altoutpxformseq = 0; + if (!outpxformseq) { + outpxformseq = revpxformseq(outprof, intent); + altoutpxformseq = fwdpxformseq(outprof, intent); + if (!outpxformseq || !altoutpxformseq) + goto error; + } + if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) || + jas_cmpxformseq_appendcnvt(xform->pxformseq, + inprof->refclrspc, outprof->refclrspc)) + goto error; + if (altoutpxformseq) { + if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq) || + jas_cmpxformseq_append(xform->pxformseq, altoutpxformseq)) + goto error; + } else { + if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq)) + goto error; + } + if (jas_cmpxformseq_appendcnvt(xform->pxformseq, + outprof->refclrspc, inprof->refclrspc) || + jas_cmpxformseq_append(xform->pxformseq, prfpxformseq)) + goto error; + xform->numinchans = jas_clrspc_numchans(inprof->clrspc); + xform->numoutchans = jas_clrspc_numchans(prfprof->clrspc); + break; + case JAS_CMXFORM_OP_GAMUT: + inpxformseq = fwdpxformseq(inprof, intent); + outpxformseq = gampxformseq(outprof); + if (!inpxformseq || !outpxformseq) + goto error; + if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) || + jas_cmpxformseq_appendcnvt(xform->pxformseq, + inprof->refclrspc, outprof->refclrspc) || + jas_cmpxformseq_append(xform->pxformseq, outpxformseq)) + goto error; + xform->numinchans = jas_clrspc_numchans(inprof->clrspc); + xform->numoutchans = 1; + break; + } + return xform; +error: + return 0; +} + +#define APPLYBUFSIZ 2048 +int jas_cmxform_apply(jas_cmxform_t *xform, jas_cmpixmap_t *in, jas_cmpixmap_t *out) +{ + jas_cmcmptfmt_t *fmt; + jas_cmreal_t buf[2][APPLYBUFSIZ]; + jas_cmpxformseq_t *pxformseq; + int i; + int j; + int width; + int height; + int total; + int n; + jas_cmreal_t *inbuf; + jas_cmreal_t *outbuf; + jas_cmpxform_t *pxform; + long *dataptr; + int maxchans; + int bufmax; + int m; + int bias; + jas_cmreal_t scale; + long v; + jas_cmreal_t *bufptr; + + if (xform->numinchans > in->numcmpts || xform->numoutchans > out->numcmpts) + goto error; + + fmt = &in->cmptfmts[0]; + width = fmt->width; + height = fmt->height; + for (i = 1; i < xform->numinchans; ++i) { + fmt = &in->cmptfmts[i]; + if (fmt->width != width || fmt->height != height) { + goto error; + } + } + for (i = 0; i < xform->numoutchans; ++i) { + fmt = &out->cmptfmts[i]; + if (fmt->width != width || fmt->height != height) { + goto error; + } + } + + maxchans = 0; + pxformseq = xform->pxformseq; + for (i = 0; i < pxformseq->numpxforms; ++i) { + pxform = pxformseq->pxforms[i]; + if (pxform->numinchans > maxchans) { + maxchans = pxform->numinchans; + } + if (pxform->numoutchans > maxchans) { + maxchans = pxform->numoutchans; + } + } + bufmax = APPLYBUFSIZ / maxchans; + assert(bufmax > 0); + + total = width * height; + n = 0; + while (n < total) { + + inbuf = &buf[0][0]; + m = JAS_MIN(total - n, bufmax); + + for (i = 0; i < xform->numinchans; ++i) { + fmt = &in->cmptfmts[i]; + scale = (double)((1 << fmt->prec) - 1); + bias = fmt->sgnd ? (1 << (fmt->prec - 1)) : 0; + dataptr = &fmt->buf[n]; + bufptr = &inbuf[i]; + for (j = 0; j < m; ++j) { + if (jas_cmgetint(&dataptr, fmt->sgnd, fmt->prec, &v)) + goto error; + *bufptr = (v - bias) / scale; + bufptr += xform->numinchans; + } + } + + inbuf = &buf[0][0]; + outbuf = inbuf; + for (i = 0; i < pxformseq->numpxforms; ++i) { + pxform = pxformseq->pxforms[i]; + if (pxform->numoutchans > pxform->numinchans) { + outbuf = (inbuf == &buf[0][0]) ? &buf[1][0] : &buf[0][0]; + } else { + outbuf = inbuf; + } + if ((*pxform->ops->apply)(pxform, inbuf, outbuf, m)) + goto error; + inbuf = outbuf; + } + + for (i = 0; i < xform->numoutchans; ++i) { + fmt = &out->cmptfmts[i]; + scale = (double)((1 << fmt->prec) - 1); + bias = fmt->sgnd ? (1 << (fmt->prec - 1)) : 0; + bufptr = &outbuf[i]; + dataptr = &fmt->buf[n]; + for (j = 0; j < m; ++j) { + v = (long)((*bufptr) * scale + bias); + bufptr += xform->numoutchans; + if (jas_cmputint(&dataptr, fmt->sgnd, fmt->prec, v)) + goto error; + } + } + + n += m; + } + + return 0; +error: + return -1; +} + +void jas_cmxform_destroy(jas_cmxform_t *xform) +{ + if (xform->pxformseq) + jas_cmpxformseq_destroy(xform->pxformseq); + jas_free(xform); +} + +/******************************************************************************\ +* Primitive transform sequence class. +\******************************************************************************/ + +static jas_cmpxformseq_t *jas_cmpxformseq_create() +{ + jas_cmpxformseq_t *pxformseq; + pxformseq = 0; + if (!(pxformseq = jas_malloc(sizeof(jas_cmpxformseq_t)))) + goto error; + pxformseq->pxforms = 0; + pxformseq->numpxforms = 0; + pxformseq->maxpxforms = 0; + if (jas_cmpxformseq_resize(pxformseq, 16)) + goto error; + return pxformseq; +error: + if (pxformseq) + jas_cmpxformseq_destroy(pxformseq); + return 0; +} + +static jas_cmpxformseq_t *jas_cmpxformseq_copy(jas_cmpxformseq_t *pxformseq) +{ + jas_cmpxformseq_t *newpxformseq; + + if (!(newpxformseq = jas_cmpxformseq_create())) + goto error; + if (jas_cmpxformseq_append(newpxformseq, pxformseq)) + goto error; + return newpxformseq; +error: + return 0; +} + +static void jas_cmpxformseq_destroy(jas_cmpxformseq_t *pxformseq) +{ + while (pxformseq->numpxforms > 0) + jas_cmpxformseq_delete(pxformseq, pxformseq->numpxforms - 1); + if (pxformseq->pxforms) + jas_free(pxformseq->pxforms); + jas_free(pxformseq); +} + +static int jas_cmpxformseq_delete(jas_cmpxformseq_t *pxformseq, int i) +{ + assert(i >= 0 && i < pxformseq->numpxforms); + if (i != pxformseq->numpxforms - 1) + abort(); + jas_cmpxform_destroy(pxformseq->pxforms[i]); + pxformseq->pxforms[i] = 0; + --pxformseq->numpxforms; + return 0; +} + +static int jas_cmpxformseq_appendcnvt(jas_cmpxformseq_t *pxformseq, + int dstclrspc, int srcclrspc) +{ + if (dstclrspc == srcclrspc) + return 0; + abort(); + /* Avoid compiler warnings about unused parameters. */ + pxformseq = 0; + return -1; +} + +static int jas_cmpxformseq_insertpxform(jas_cmpxformseq_t *pxformseq, + int i, jas_cmpxform_t *pxform) +{ + jas_cmpxform_t *tmppxform; + int n; + if (i < 0) + i = pxformseq->numpxforms; + assert(i >= 0 && i <= pxformseq->numpxforms); + if (pxformseq->numpxforms >= pxformseq->maxpxforms) { + if (jas_cmpxformseq_resize(pxformseq, pxformseq->numpxforms + + 16)) + goto error; + } + assert(pxformseq->numpxforms < pxformseq->maxpxforms); + if (!(tmppxform = jas_cmpxform_copy(pxform))) + goto error; + n = pxformseq->numpxforms - i; + if (n > 0) { + memmove(&pxformseq->pxforms[i + 1], &pxformseq->pxforms[i], + n * sizeof(jas_cmpxform_t *)); + } + pxformseq->pxforms[i] = tmppxform; + ++pxformseq->numpxforms; + return 0; +error: + return -1; +} + +static int jas_cmpxformseq_append(jas_cmpxformseq_t *pxformseq, + jas_cmpxformseq_t *othpxformseq) +{ + int n; + int i; + jas_cmpxform_t *pxform; + jas_cmpxform_t *othpxform; + n = pxformseq->numpxforms + othpxformseq->numpxforms; + if (n > pxformseq->maxpxforms) { + if (jas_cmpxformseq_resize(pxformseq, n)) + goto error; + } + for (i = 0; i < othpxformseq->numpxforms; ++i) { + othpxform = othpxformseq->pxforms[i]; + if (!(pxform = jas_cmpxform_copy(othpxform))) + goto error; + pxformseq->pxforms[pxformseq->numpxforms] = pxform; + ++pxformseq->numpxforms; + } + return 0; +error: + return -1; +} + +static int jas_cmpxformseq_resize(jas_cmpxformseq_t *pxformseq, int n) +{ + jas_cmpxform_t **p; + assert(n >= pxformseq->numpxforms); + p = (!pxformseq->pxforms) ? jas_malloc(n * sizeof(jas_cmpxform_t *)) : + jas_realloc(pxformseq->pxforms, n * sizeof(jas_cmpxform_t *)); + if (!p) { + return -1; + } + pxformseq->pxforms = p; + pxformseq->maxpxforms = n; + return 0; +} + +/******************************************************************************\ +* Primitive transform class. +\******************************************************************************/ + +static jas_cmpxform_t *jas_cmpxform_create0() +{ + jas_cmpxform_t *pxform; + if (!(pxform = jas_malloc(sizeof(jas_cmpxform_t)))) + return 0; + memset(pxform, 0, sizeof(jas_cmpxform_t)); + pxform->refcnt = 0; + pxform->ops = 0; + return pxform; +} + +static void jas_cmpxform_destroy(jas_cmpxform_t *pxform) +{ + if (--pxform->refcnt <= 0) { + (*pxform->ops->destroy)(pxform); + jas_free(pxform); + } +} + +static jas_cmpxform_t *jas_cmpxform_copy(jas_cmpxform_t *pxform) +{ + ++pxform->refcnt; + return pxform; +} + +/******************************************************************************\ +* Shaper matrix class. +\******************************************************************************/ + +static jas_cmpxform_t *jas_cmpxform_createshapmat() +{ + int i; + int j; + jas_cmpxform_t *pxform; + jas_cmshapmat_t *shapmat; + if (!(pxform = jas_cmpxform_create0())) + return 0; + pxform->ops = &shapmat_ops; + shapmat = &pxform->data.shapmat; + shapmat->mono = 0; + shapmat->order = 0; + shapmat->useluts = 0; + shapmat->usemat = 0; + for (i = 0; i < 3; ++i) + jas_cmshapmatlut_init(&shapmat->luts[i]); + for (i = 0; i < 3; ++i) { + for (j = 0; j < 4; ++j) + shapmat->mat[i][j] = 0.0; + } + ++pxform->refcnt; + return pxform; +} + +static void jas_cmshapmat_destroy(jas_cmpxform_t *pxform) +{ + jas_cmshapmat_t *shapmat = &pxform->data.shapmat; + int i; + for (i = 0; i < 3; ++i) + jas_cmshapmatlut_cleanup(&shapmat->luts[i]); +} + +static int jas_cmshapmat_apply(jas_cmpxform_t *pxform, jas_cmreal_t *in, + jas_cmreal_t *out, int cnt) +{ + jas_cmshapmat_t *shapmat = &pxform->data.shapmat; + jas_cmreal_t *src; + jas_cmreal_t *dst; + jas_cmreal_t a0; + jas_cmreal_t a1; + jas_cmreal_t a2; + jas_cmreal_t b0; + jas_cmreal_t b1; + jas_cmreal_t b2; + src = in; + dst = out; + if (!shapmat->mono) { + while (--cnt >= 0) { + a0 = *src++; + a1 = *src++; + a2 = *src++; + if (!shapmat->order && shapmat->useluts) { + a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0); + a1 = jas_cmshapmatlut_lookup(&shapmat->luts[1], a1); + a2 = jas_cmshapmatlut_lookup(&shapmat->luts[2], a2); + } + if (shapmat->usemat) { + b0 = shapmat->mat[0][0] * a0 + + shapmat->mat[0][1] * a1 + + shapmat->mat[0][2] * a2 + + shapmat->mat[0][3]; + b1 = shapmat->mat[1][0] * a0 + + shapmat->mat[1][1] * a1 + + shapmat->mat[1][2] * a2 + + shapmat->mat[1][3]; + b2 = shapmat->mat[2][0] * a0 + + shapmat->mat[2][1] * a1 + + shapmat->mat[2][2] * a2 + + shapmat->mat[2][3]; + a0 = b0; + a1 = b1; + a2 = b2; + } + if (shapmat->order && shapmat->useluts) { + a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0); + a1 = jas_cmshapmatlut_lookup(&shapmat->luts[1], a1); + a2 = jas_cmshapmatlut_lookup(&shapmat->luts[2], a2); + } + *dst++ = a0; + *dst++ = a1; + *dst++ = a2; + } + } else { + if (!shapmat->order) { + while (--cnt >= 0) { + a0 = *src++; + if (shapmat->useluts) + a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0); + a2 = a0 * shapmat->mat[2][0]; + a1 = a0 * shapmat->mat[1][0]; + a0 = a0 * shapmat->mat[0][0]; + *dst++ = a0; + *dst++ = a1; + *dst++ = a2; + } + } else { +assert(0); + while (--cnt >= 0) { + a0 = *src++; + src++; + src++; + a0 = a0 * shapmat->mat[0][0]; + if (shapmat->useluts) + a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0); + *dst++ = a0; + } + } + } + + return 0; +} + +static void jas_cmshapmatlut_init(jas_cmshapmatlut_t *lut) +{ + lut->data = 0; + lut->size = 0; +} + +static void jas_cmshapmatlut_cleanup(jas_cmshapmatlut_t *lut) +{ + if (lut->data) { + jas_free(lut->data); + lut->data = 0; + } + lut->size = 0; +} + +static double gammafn(double x, double gamma) +{ + if (x == 0.0) + return 0.0; + return pow(x, gamma); +} + +static int jas_cmshapmatlut_set(jas_cmshapmatlut_t *lut, jas_icccurv_t *curv) +{ + jas_cmreal_t gamma; + int i; + gamma = 0; + jas_cmshapmatlut_cleanup(lut); + if (curv->numents == 0) { + lut->size = 2; + if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t)))) + goto error; + lut->data[0] = 0.0; + lut->data[1] = 1.0; + } else if (curv->numents == 1) { + lut->size = 256; + if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t)))) + goto error; + gamma = curv->ents[0] / 256.0; + for (i = 0; i < lut->size; ++i) { + lut->data[i] = gammafn(i / (double) (lut->size - 1), gamma); + } + } else { + lut->size = curv->numents; + if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t)))) + goto error; + for (i = 0; i < lut->size; ++i) { + lut->data[i] = curv->ents[i] / 65535.0; + } + } + return 0; +error: + return -1; +} + +static jas_cmreal_t jas_cmshapmatlut_lookup(jas_cmshapmatlut_t *lut, jas_cmreal_t x) +{ + jas_cmreal_t t; + int lo; + int hi; + t = x * (lut->size - 1); + lo = (int) floor(t); + if (lo < 0) + return lut->data[0]; + hi = (int) ceil(t); + if (hi >= lut->size) + return lut->data[lut->size - 1]; + return lut->data[lo] + (t - lo) * (lut->data[hi] - lut->data[lo]); +} + +static int jas_cmshapmatlut_invert(jas_cmshapmatlut_t *invlut, + jas_cmshapmatlut_t *lut, int n) +{ + int i; + int j; + int k; + jas_cmreal_t ax; + jas_cmreal_t ay; + jas_cmreal_t bx; + jas_cmreal_t by; + jas_cmreal_t sx; + jas_cmreal_t sy; + assert(n >= 2); + if (invlut->data) { + jas_free(invlut->data); + invlut->data = 0; + } + /* The sample values should be nondecreasing. */ + for (i = 1; i < lut->size; ++i) { + if (lut->data[i - 1] > lut->data[i]) { + assert(0); + return -1; + } + } + if (!(invlut->data = jas_malloc(n * sizeof(jas_cmreal_t)))) + return -1; + invlut->size = n; + for (i = 0; i < invlut->size; ++i) { + sy = ((double) i) / (invlut->size - 1); + sx = 1.0; + for (j = 0; j < lut->size; ++j) { + ay = lut->data[j]; + if (sy == ay) { + for (k = j + 1; k < lut->size; ++k) { + by = lut->data[k]; + if (by != sy) + break; +#if 0 +assert(0); +#endif + } + if (k < lut->size) { + --k; + ax = ((double) j) / (lut->size - 1); + bx = ((double) k) / (lut->size - 1); + sx = (ax + bx) / 2.0; + } + break; + } + if (j < lut->size - 1) { + by = lut->data[j + 1]; + if (sy > ay && sy < by) { + ax = ((double) j) / (lut->size - 1); + bx = ((double) j + 1) / (lut->size - 1); + sx = ax + + (sy - ay) / (by - ay) * (bx - ax); + break; + } + } + } + invlut->data[i] = sx; + } +#if 0 +for (i=0;isize;++i) + fprintf(stderr, "lut[%d]=%f ", i, lut->data[i]); +for (i=0;isize;++i) + fprintf(stderr, "invlut[%d]=%f ", i, invlut->data[i]); +#endif + return 0; +} + +static int jas_cmshapmat_invmat(jas_cmreal_t out[3][4], jas_cmreal_t in[3][4]) +{ + jas_cmreal_t d; + d = in[0][0] * (in[1][1] * in[2][2] - in[1][2] * in[2][1]) + - in[0][1] * (in[1][0] * in[2][2] - in[1][2] * in[2][0]) + + in[0][2] * (in[1][0] * in[2][1] - in[1][1] * in[2][0]); +#if 0 +fprintf(stderr, "delta=%f\n", d); +#endif + if (JAS_ABS(d) < 1e-6) + return -1; + out[0][0] = (in[1][1] * in[2][2] - in[1][2] * in[2][1]) / d; + out[1][0] = -(in[1][0] * in[2][2] - in[1][2] * in[2][0]) / d; + out[2][0] = (in[1][0] * in[2][1] - in[1][1] * in[2][0]) / d; + out[0][1] = -(in[0][1] * in[2][2] - in[0][2] * in[2][1]) / d; + out[1][1] = (in[0][0] * in[2][2] - in[0][2] * in[2][0]) / d; + out[2][1] = -(in[0][0] * in[2][1] - in[0][1] * in[2][0]) / d; + out[0][2] = (in[0][1] * in[1][2] - in[0][2] * in[1][1]) / d; + out[1][2] = -(in[0][0] * in[1][2] - in[1][0] * in[0][2]) / d; + out[2][2] = (in[0][0] * in[1][1] - in[0][1] * in[1][0]) / d; + out[0][3] = -in[0][3]; + out[1][3] = -in[1][3]; + out[2][3] = -in[2][3]; +#if 0 +fprintf(stderr, "[ %f %f %f %f ]\n[ %f %f %f %f ]\n[ %f %f %f %f ]\n", +in[0][0], in[0][1], in[0][2], in[0][3], +in[1][0], in[1][1], in[1][2], in[1][3], +in[2][0], in[2][1], in[2][2], in[2][3]); +fprintf(stderr, "[ %f %f %f %f ]\n[ %f %f %f %f ]\n[ %f %f %f %f ]\n", +out[0][0], out[0][1], out[0][2], out[0][3], +out[1][0], out[1][1], out[1][2], out[1][3], +out[2][0], out[2][1], out[2][2], out[2][3]); +#endif + return 0; +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static int icctoclrspc(int iccclrspc, int refflag) +{ + if (refflag) { + switch (iccclrspc) { + case JAS_ICC_COLORSPC_XYZ: + return JAS_CLRSPC_CIEXYZ; + case JAS_ICC_COLORSPC_LAB: + return JAS_CLRSPC_CIELAB; + default: + abort(); + break; + } + } else { + switch (iccclrspc) { + case JAS_ICC_COLORSPC_YCBCR: + return JAS_CLRSPC_GENYCBCR; + case JAS_ICC_COLORSPC_RGB: + return JAS_CLRSPC_GENRGB; + case JAS_ICC_COLORSPC_GRAY: + return JAS_CLRSPC_GENGRAY; + default: + abort(); + break; + } + } +} + +static int mono(jas_iccprof_t *iccprof, int op, jas_cmpxformseq_t **retpxformseq) +{ + jas_iccattrval_t *graytrc; + jas_cmshapmat_t *shapmat; + jas_cmpxform_t *pxform; + jas_cmpxformseq_t *pxformseq; + jas_cmshapmatlut_t lut; + + jas_cmshapmatlut_init(&lut); + if (!(graytrc = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRYTRC)) || + graytrc->type != JAS_ICC_TYPE_CURV) + goto error; + if (!(pxform = jas_cmpxform_createshapmat())) + goto error; + shapmat = &pxform->data.shapmat; + if (!(pxformseq = jas_cmpxformseq_create())) + goto error; + if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform)) + goto error; + + pxform->numinchans = 1; + pxform->numoutchans = 3; + + shapmat->mono = 1; + shapmat->useluts = 1; + shapmat->usemat = 1; + if (!op) { + shapmat->order = 0; + shapmat->mat[0][0] = 0.9642; + shapmat->mat[1][0] = 1.0; + shapmat->mat[2][0] = 0.8249; + if (jas_cmshapmatlut_set(&shapmat->luts[0], &graytrc->data.curv)) + goto error; + } else { + shapmat->order = 1; + shapmat->mat[0][0] = 1.0 / 0.9642; + shapmat->mat[1][0] = 1.0; + shapmat->mat[2][0] = 1.0 / 0.8249; + jas_cmshapmatlut_init(&lut); + if (jas_cmshapmatlut_set(&lut, &graytrc->data.curv)) + goto error; + if (jas_cmshapmatlut_invert(&shapmat->luts[0], &lut, lut.size)) + goto error; + jas_cmshapmatlut_cleanup(&lut); + } + jas_iccattrval_destroy(graytrc); + jas_cmpxform_destroy(pxform); + *retpxformseq = pxformseq; + return 0; +error: + return -1; +} + +static int triclr(jas_iccprof_t *iccprof, int op, jas_cmpxformseq_t **retpxformseq) +{ + int i; + jas_iccattrval_t *trcs[3]; + jas_iccattrval_t *cols[3]; + jas_cmshapmat_t *shapmat; + jas_cmpxform_t *pxform; + jas_cmpxformseq_t *pxformseq; + jas_cmreal_t mat[3][4]; + jas_cmshapmatlut_t lut; + jas_cmshapmatlut_init(&lut); + for (i = 0; i < 3; ++i) { + trcs[i] = 0; + cols[i] = 0; + } + if (!(trcs[0] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_REDTRC)) || + !(trcs[1] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRNTRC)) || + !(trcs[2] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_BLUTRC)) || + !(cols[0] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_REDMATCOL)) || + !(cols[1] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRNMATCOL)) || + !(cols[2] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_BLUMATCOL))) + goto error; + for (i = 0; i < 3; ++i) { + if (trcs[i]->type != JAS_ICC_TYPE_CURV || + cols[i]->type != JAS_ICC_TYPE_XYZ) + goto error; + } + if (!(pxform = jas_cmpxform_createshapmat())) + goto error; + pxform->numinchans = 3; + pxform->numoutchans = 3; + shapmat = &pxform->data.shapmat; + if (!(pxformseq = jas_cmpxformseq_create())) + goto error; + if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform)) + goto error; + shapmat->mono = 0; + shapmat->useluts = 1; + shapmat->usemat = 1; + if (!op) { + shapmat->order = 0; + for (i = 0; i < 3; ++i) { + shapmat->mat[0][i] = cols[i]->data.xyz.x / 65536.0; + shapmat->mat[1][i] = cols[i]->data.xyz.y / 65536.0; + shapmat->mat[2][i] = cols[i]->data.xyz.z / 65536.0; + } + for (i = 0; i < 3; ++i) + shapmat->mat[i][3] = 0.0; + for (i = 0; i < 3; ++i) { + if (jas_cmshapmatlut_set(&shapmat->luts[i], &trcs[i]->data.curv)) + goto error; + } + } else { + shapmat->order = 1; + for (i = 0; i < 3; ++i) { + mat[0][i] = cols[i]->data.xyz.x / 65536.0; + mat[1][i] = cols[i]->data.xyz.y / 65536.0; + mat[2][i] = cols[i]->data.xyz.z / 65536.0; + } + for (i = 0; i < 3; ++i) + mat[i][3] = 0.0; + if (jas_cmshapmat_invmat(shapmat->mat, mat)) + goto error; + for (i = 0; i < 3; ++i) { + jas_cmshapmatlut_init(&lut); + if (jas_cmshapmatlut_set(&lut, &trcs[i]->data.curv)) + goto error; + if (jas_cmshapmatlut_invert(&shapmat->luts[i], &lut, lut.size)) + goto error; + jas_cmshapmatlut_cleanup(&lut); + } + } + for (i = 0; i < 3; ++i) { + jas_iccattrval_destroy(trcs[i]); + jas_iccattrval_destroy(cols[i]); + } + jas_cmpxform_destroy(pxform); + *retpxformseq = pxformseq; + return 0; +error: + return -1; +} + +static int jas_cmgetint(long **bufptr, int sgnd, int prec, long *val) +{ + long v; + int m; + v = **bufptr; + if (sgnd) { + m = (1 << (prec - 1)); + if (v < -m || v >= m) + return -1; + } else { + if (v < 0 || v >= (1 << prec)) + return -1; + } + ++(*bufptr); + *val = v; + return 0; +} + +static int jas_cmputint(long **bufptr, int sgnd, int prec, long val) +{ + int m; + if (sgnd) { + m = (1 << (prec - 1)); + if (val < -m || val >= m) + return -1; + } else { + if (val < 0 || val >= (1 << prec)) + return -1; + } + **bufptr = val; + ++(*bufptr); + return 0; +} + +int jas_clrspc_numchans(int clrspc) +{ + switch (jas_clrspc_fam(clrspc)) { + case JAS_CLRSPC_FAM_XYZ: + case JAS_CLRSPC_FAM_LAB: + case JAS_CLRSPC_FAM_RGB: + case JAS_CLRSPC_FAM_YCBCR: + return 3; + break; + case JAS_CLRSPC_FAM_GRAY: + return 1; + break; + default: + abort(); + break; + } +} + +jas_iccprof_t *jas_iccprof_createfromcmprof(jas_cmprof_t *prof) +{ + return jas_iccprof_copy(prof->iccprof); +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_debug.c b/SlnkDWFImpl/CxImage/jasper/base/jas_debug.c new file mode 100644 index 0000000..24b97a3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_debug.c @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_debug.h" + +/******************************************************************************\ +* Local data. +\******************************************************************************/ + +static int jas_dbglevel = 0; +/* The debug level. */ + +/******************************************************************************\ +* Code for getting/setting the debug level. +\******************************************************************************/ + +/* Set the library debug level. */ +int jas_setdbglevel(int dbglevel) +{ + int olddbglevel; + + /* Save the old debug level. */ + olddbglevel = jas_dbglevel; + + /* Change the debug level. */ + jas_dbglevel = dbglevel; + + /* Return the old debug level. */ + return olddbglevel; +} + +/* Get the library debug level. */ +int jas_getdbglevel() +{ + return jas_dbglevel; +} + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +/* Perform formatted output to standard error. */ +int jas_eprintf(const char *fmt, ...) +{ + int ret; + va_list ap; + + va_start(ap, fmt); + ret = vfprintf(stderr, fmt, ap); + va_end(ap); + return ret; +} + +/* Dump memory to a stream. */ +int jas_memdump(FILE *out, void *data, size_t len) +{ + size_t i; + size_t j; + uchar *dp; + dp = data; + for (i = 0; i < len; i += 16) { + fprintf(out, "%04x:", i); + for (j = 0; j < 16; ++j) { + if (i + j < len) { + fprintf(out, " %02x", dp[i + j]); + } + } + fprintf(out, "\n"); + } + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_getopt.c b/SlnkDWFImpl/CxImage/jasper/base/jas_getopt.c new file mode 100644 index 0000000..8554609 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_getopt.c @@ -0,0 +1,217 @@ +/* + * Copyright (c) 1999-2000, Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Command Line Option Parsing Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#include "jasper/jas_getopt.h" +#include "jasper/jas_math.h" + +/******************************************************************************\ +* Global data. +\******************************************************************************/ + +int jas_optind = 0; +int jas_opterr = 1; +char *jas_optarg = 0; + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +static jas_opt_t *jas_optlookup(jas_opt_t *opts, char *name) +{ + jas_opt_t *opt; + + for (opt = opts; opt->id >= 0 && opt->name; ++opt) { + if (!strcmp(opt->name, name)) { + return opt; + } + } + return 0; +} + +int jas_getopt(int argc, char **argv, jas_opt_t *opts) +{ + char *cp; + int id; + int hasarg; + jas_opt_t *opt; + char *s; + + if (!jas_optind) { + jas_optind = JAS_MIN(1, argc); + } + while (jas_optind < argc) { + s = cp = argv[jas_optind]; + if (*cp == '-') { + /* We are processing an option. */ + ++jas_optind; + if (*++cp == '-') { + /* We are processing a long option. */ + ++cp; + if (*cp == '\0') { + /* This is the end of the options. */ + return JAS_GETOPT_EOF; + } + if (!(opt = jas_optlookup(opts, cp))) { + if (jas_opterr) { + fprintf(stderr, "unknown long option %s\n", s); + } + return JAS_GETOPT_ERR; + } + hasarg = (opt->flags & JAS_OPT_HASARG) != 0; + id = opt->id; + } else { + /* We are processing a short option. */ + if (strlen(cp) != 1 || + !(opt = jas_optlookup(opts, cp))) { + if (jas_opterr) { + fprintf(stderr, "unknown short option %s\n", s); + } + return JAS_GETOPT_ERR; + } + hasarg = (opt->flags & JAS_OPT_HASARG) != 0; + id = opt->id; + } + if (hasarg) { + /* The option has an argument. */ + if (jas_optind >= argc) { + if (jas_opterr) { + fprintf(stderr, "missing argument for option %s\n", s); + } + return JAS_GETOPT_ERR; + } + jas_optarg = argv[jas_optind]; + ++jas_optind; + } else { + /* The option does not have an argument. */ + jas_optarg = 0; + } + return id; + } else { + /* We are not processing an option. */ + return JAS_GETOPT_EOF; + } + } + return JAS_GETOPT_EOF; +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_icc.c b/SlnkDWFImpl/CxImage/jasper/base/jas_icc.c new file mode 100644 index 0000000..32a2ecc --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_icc.c @@ -0,0 +1,1770 @@ +/* + * Copyright (c) 2002-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define jas_iccputuint8(out, val) jas_iccputuint(out, 1, val) +#define jas_iccputuint16(out, val) jas_iccputuint(out, 2, val) +#define jas_iccputsint32(out, val) jas_iccputsint(out, 4, val) +#define jas_iccputuint32(out, val) jas_iccputuint(out, 4, val) +#define jas_iccputuint64(out, val) jas_iccputuint(out, 8, val) + +static jas_iccattrval_t *jas_iccattrval_create0(void); + +static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val); +static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val); +static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val); +static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val); +static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val); +static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val); +static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val); +static int jas_iccputsint(jas_stream_t *out, int n, longlong val); +static jas_iccprof_t *jas_iccprof_create(void); +static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr); +static int jas_iccprof_writehdr(jas_stream_t *out, jas_icchdr_t *hdr); +static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab); +static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab); +static int jas_iccattrtab_lookup(jas_iccattrtab_t *attrtab, jas_iccuint32_t name); +static jas_iccattrtab_t *jas_iccattrtab_copy(jas_iccattrtab_t *attrtab); +static jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t name); +static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time); +static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz); +static int jas_icctagtabent_cmp(const void *src, const void *dst); + +static void jas_icccurv_destroy(jas_iccattrval_t *attrval); +static int jas_icccurv_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval); +static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt); +static int jas_icccurv_getsize(jas_iccattrval_t *attrval); +static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out); +static void jas_icccurv_dump(jas_iccattrval_t *attrval, FILE *out); + +static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval); +static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval); +static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt); +static int jas_icctxtdesc_getsize(jas_iccattrval_t *attrval); +static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out); +static void jas_icctxtdesc_dump(jas_iccattrval_t *attrval, FILE *out); + +static void jas_icctxt_destroy(jas_iccattrval_t *attrval); +static int jas_icctxt_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval); +static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt); +static int jas_icctxt_getsize(jas_iccattrval_t *attrval); +static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out); +static void jas_icctxt_dump(jas_iccattrval_t *attrval, FILE *out); + +static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt); +static int jas_iccxyz_getsize(jas_iccattrval_t *attrval); +static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out); +static void jas_iccxyz_dump(jas_iccattrval_t *attrval, FILE *out); + +static jas_iccattrtab_t *jas_iccattrtab_create(void); +static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab); +static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, int maxents); +static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i, + jas_iccuint32_t name, jas_iccattrval_t *val); +static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, int i, + jas_iccuint32_t name, jas_iccattrval_t *val); +static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, int i); +static long jas_iccpadtomult(long x, long y); +static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, int i, + jas_iccattrname_t *name, jas_iccattrval_t **val); +static int jas_iccprof_puttagtab(jas_stream_t *out, jas_icctagtab_t *tagtab); + +static void jas_icclut16_destroy(jas_iccattrval_t *attrval); +static int jas_icclut16_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval); +static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt); +static int jas_icclut16_getsize(jas_iccattrval_t *attrval); +static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out); +static void jas_icclut16_dump(jas_iccattrval_t *attrval, FILE *out); + +static void jas_icclut8_destroy(jas_iccattrval_t *attrval); +static int jas_icclut8_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval); +static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt); +static int jas_icclut8_getsize(jas_iccattrval_t *attrval); +static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out); +static void jas_icclut8_dump(jas_iccattrval_t *attrval, FILE *out); + +static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *ctime); +static int jas_iccputxyz(jas_stream_t *out, jas_iccxyz_t *xyz); + +static long jas_iccpowi(int x, int n); + +static char *jas_iccsigtostr(int sig, char *buf); + + +jas_iccattrvalinfo_t jas_iccattrvalinfos[] = { + {JAS_ICC_TYPE_CURV, {jas_icccurv_destroy, jas_icccurv_copy, + jas_icccurv_input, jas_icccurv_output, jas_icccurv_getsize, + jas_icccurv_dump}}, + {JAS_ICC_TYPE_XYZ, {0, 0, jas_iccxyz_input, jas_iccxyz_output, + jas_iccxyz_getsize, jas_iccxyz_dump}}, + {JAS_ICC_TYPE_TXTDESC, {jas_icctxtdesc_destroy, + jas_icctxtdesc_copy, jas_icctxtdesc_input, jas_icctxtdesc_output, + jas_icctxtdesc_getsize, jas_icctxtdesc_dump}}, + {JAS_ICC_TYPE_TXT, {jas_icctxt_destroy, jas_icctxt_copy, + jas_icctxt_input, jas_icctxt_output, jas_icctxt_getsize, + jas_icctxt_dump}}, + {JAS_ICC_TYPE_LUT8, {jas_icclut8_destroy, jas_icclut8_copy, + jas_icclut8_input, jas_icclut8_output, jas_icclut8_getsize, + jas_icclut8_dump}}, + {JAS_ICC_TYPE_LUT16, {jas_icclut16_destroy, jas_icclut16_copy, + jas_icclut16_input, jas_icclut16_output, jas_icclut16_getsize, + jas_icclut16_dump}}, + {0, {0, 0, 0, 0, 0, 0}} +}; + +typedef struct { + jas_iccuint32_t tag; + char *name; +} jas_icctaginfo_t; + +/******************************************************************************\ +* profile class +\******************************************************************************/ + +static jas_iccprof_t *jas_iccprof_create() +{ + jas_iccprof_t *prof; + prof = 0; + if (!(prof = jas_malloc(sizeof(jas_iccprof_t)))) { + goto error; + } + if (!(prof->attrtab = jas_iccattrtab_create())) + goto error; + memset(&prof->hdr, 0, sizeof(jas_icchdr_t)); + prof->tagtab.numents = 0; + prof->tagtab.ents = 0; + return prof; +error: + if (prof) + jas_iccprof_destroy(prof); + return 0; +} + +jas_iccprof_t *jas_iccprof_copy(jas_iccprof_t *prof) +{ + jas_iccprof_t *newprof; + newprof = 0; + if (!(newprof = jas_iccprof_create())) + goto error; + newprof->hdr = prof->hdr; + newprof->tagtab.numents = 0; + newprof->tagtab.ents = 0; + assert(newprof->attrtab); + jas_iccattrtab_destroy(newprof->attrtab); + if (!(newprof->attrtab = jas_iccattrtab_copy(prof->attrtab))) + goto error; + return newprof; +error: + if (newprof) + jas_iccprof_destroy(newprof); + return 0; +} + +void jas_iccprof_destroy(jas_iccprof_t *prof) +{ + if (prof->attrtab) + jas_iccattrtab_destroy(prof->attrtab); + if (prof->tagtab.ents) + jas_free(prof->tagtab.ents); + jas_free(prof); +} + +void jas_iccprof_dump(jas_iccprof_t *prof, FILE *out) +{ + jas_iccattrtab_dump(prof->attrtab, out); +} + +jas_iccprof_t *jas_iccprof_load(jas_stream_t *in) +{ + jas_iccprof_t *prof; + int numtags; + long curoff; + long reloff; + long prevoff; + jas_iccsig_t type; + jas_iccattrval_t *attrval; + jas_iccattrval_t *prevattrval; + jas_icctagtabent_t *tagtabent; + jas_iccattrvalinfo_t *attrvalinfo; + int i; + int len; + + prof = 0; + attrval = 0; + + if (!(prof = jas_iccprof_create())) { + goto error; + } + + if (jas_iccprof_readhdr(in, &prof->hdr)) { + jas_eprintf("cannot get header\n"); + goto error; + } + if (jas_iccprof_gettagtab(in, &prof->tagtab)) { + jas_eprintf("cannot get tab table\n"); + goto error; + } + jas_iccprof_sorttagtab(&prof->tagtab); + + numtags = prof->tagtab.numents; + curoff = JAS_ICC_HDRLEN + 4 + 12 * numtags; + prevoff = 0; + prevattrval = 0; + for (i = 0; i < numtags; ++i) { + tagtabent = &prof->tagtab.ents[i]; + if (tagtabent->off == JAS_CAST(jas_iccuint32_t, prevoff)) { + if (prevattrval) { + if (!(attrval = jas_iccattrval_clone(prevattrval))) + goto error; + if (jas_iccprof_setattr(prof, tagtabent->tag, attrval)) + goto error; + jas_iccattrval_destroy(attrval); + } else { +#if 0 + jas_eprintf("warning: skipping unknown tag type\n"); +#endif + } + continue; + } + reloff = tagtabent->off - curoff; + if (reloff > 0) { + if (jas_stream_gobble(in, reloff) != reloff) + goto error; + curoff += reloff; + } else if (reloff < 0) { + /* This should never happen since we read the tagged + element data in a single pass. */ + abort(); + } + prevoff = curoff; + if (jas_iccgetuint32(in, &type)) { + goto error; + } + if (jas_stream_gobble(in, 4) != 4) { + goto error; + } + curoff += 8; + if (!(attrvalinfo = jas_iccattrvalinfo_lookup(type))) { +#if 0 + jas_eprintf("warning: skipping unknown tag type\n"); +#endif + prevattrval = 0; + continue; + } + if (!(attrval = jas_iccattrval_create(type))) { + goto error; + } + len = tagtabent->len - 8; + if ((*attrval->ops->input)(attrval, in, len)) { + goto error; + } + curoff += len; + if (jas_iccprof_setattr(prof, tagtabent->tag, attrval)) { + goto error; + } + prevattrval = attrval; /* This is correct, but slimey. */ + jas_iccattrval_destroy(attrval); + attrval = 0; + } + + return prof; + +error: + if (prof) + jas_iccprof_destroy(prof); + if (attrval) + jas_iccattrval_destroy(attrval); + return 0; +} + +int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out) +{ + long curoff; + long reloff; + long newoff; + int i; + int j; + jas_icctagtabent_t *tagtabent; + jas_icctagtabent_t *sharedtagtabent; + jas_icctagtabent_t *tmptagtabent; + jas_iccuint32_t attrname; + jas_iccattrval_t *attrval; + jas_icctagtab_t *tagtab; + + tagtab = &prof->tagtab; + if (!(tagtab->ents = jas_malloc(prof->attrtab->numattrs * + sizeof(jas_icctagtabent_t)))) + goto error; + tagtab->numents = prof->attrtab->numattrs; + curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents; + for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) { + tagtabent = &tagtab->ents[i]; + if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval)) + goto error; + assert(attrval->ops->output); + tagtabent->tag = attrname; + tagtabent->data = &attrval->data; + sharedtagtabent = 0; + for (j = 0; j < i; ++j) { + tmptagtabent = &tagtab->ents[j]; + if (tagtabent->data == tmptagtabent->data) { + sharedtagtabent = tmptagtabent; + break; + } + } + if (sharedtagtabent) { + tagtabent->off = sharedtagtabent->off; + tagtabent->len = sharedtagtabent->len; + tagtabent->first = sharedtagtabent; + } else { + tagtabent->off = curoff; + tagtabent->len = (*attrval->ops->getsize)(attrval) + 8; + tagtabent->first = 0; + if (i < JAS_CAST(int, tagtab->numents - 1)) { + curoff = jas_iccpadtomult(curoff + tagtabent->len, 4); + } else { + curoff += tagtabent->len; + } + } + jas_iccattrval_destroy(attrval); + } + prof->hdr.size = curoff; + if (jas_iccprof_writehdr(out, &prof->hdr)) + goto error; + if (jas_iccprof_puttagtab(out, &prof->tagtab)) + goto error; + curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents; + for (i = 0; i < JAS_CAST(int, tagtab->numents);) { + tagtabent = &tagtab->ents[i]; + assert(curoff == JAS_CAST(long, tagtabent->off)); + if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval)) + goto error; + if (jas_iccputuint32(out, attrval->type) || jas_stream_pad(out, + 4, 0) != 4) + goto error; + if ((*attrval->ops->output)(attrval, out)) + goto error; + jas_iccattrval_destroy(attrval); + curoff += tagtabent->len; + ++i; + while (i < JAS_CAST(int, tagtab->numents) && + tagtab->ents[i].first) + ++i; + newoff = (i < JAS_CAST(int, tagtab->numents)) ? + tagtab->ents[i].off : prof->hdr.size; + reloff = newoff - curoff; + assert(reloff >= 0); + if (reloff > 0) { + if (jas_stream_pad(out, reloff, 0) != reloff) + goto error; + curoff += reloff; + } + } + return 0; +error: + /* XXX - need to free some resources here */ + return -1; +} + +static int jas_iccprof_writehdr(jas_stream_t *out, jas_icchdr_t *hdr) +{ + if (jas_iccputuint32(out, hdr->size) || + jas_iccputuint32(out, hdr->cmmtype) || + jas_iccputuint32(out, hdr->version) || + jas_iccputuint32(out, hdr->clas) || + jas_iccputuint32(out, hdr->colorspc) || + jas_iccputuint32(out, hdr->refcolorspc) || + jas_iccputtime(out, &hdr->ctime) || + jas_iccputuint32(out, hdr->magic) || + jas_iccputuint32(out, hdr->platform) || + jas_iccputuint32(out, hdr->flags) || + jas_iccputuint32(out, hdr->maker) || + jas_iccputuint32(out, hdr->model) || + jas_iccputuint64(out, hdr->attr) || + jas_iccputuint32(out, hdr->intent) || + jas_iccputxyz(out, &hdr->illum) || + jas_iccputuint32(out, hdr->creator) || + jas_stream_pad(out, 44, 0) != 44) + return -1; + return 0; +} + +static int jas_iccprof_puttagtab(jas_stream_t *out, jas_icctagtab_t *tagtab) +{ + int i; + jas_icctagtabent_t *tagtabent; + if (jas_iccputuint32(out, tagtab->numents)) + goto error; + for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) { + tagtabent = &tagtab->ents[i]; + if (jas_iccputuint32(out, tagtabent->tag) || + jas_iccputuint32(out, tagtabent->off) || + jas_iccputuint32(out, tagtabent->len)) + goto error; + } + return 0; +error: + return -1; +} + +static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr) +{ + if (jas_iccgetuint32(in, &hdr->size) || + jas_iccgetuint32(in, &hdr->cmmtype) || + jas_iccgetuint32(in, &hdr->version) || + jas_iccgetuint32(in, &hdr->clas) || + jas_iccgetuint32(in, &hdr->colorspc) || + jas_iccgetuint32(in, &hdr->refcolorspc) || + jas_iccgettime(in, &hdr->ctime) || + jas_iccgetuint32(in, &hdr->magic) || + jas_iccgetuint32(in, &hdr->platform) || + jas_iccgetuint32(in, &hdr->flags) || + jas_iccgetuint32(in, &hdr->maker) || + jas_iccgetuint32(in, &hdr->model) || + jas_iccgetuint64(in, &hdr->attr) || + jas_iccgetuint32(in, &hdr->intent) || + jas_iccgetxyz(in, &hdr->illum) || + jas_iccgetuint32(in, &hdr->creator) || + jas_stream_gobble(in, 44) != 44) + return -1; + return 0; +} + +static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab) +{ + int i; + jas_icctagtabent_t *tagtabent; + + if (tagtab->ents) { + jas_free(tagtab->ents); + tagtab->ents = 0; + } + if (jas_iccgetuint32(in, &tagtab->numents)) + goto error; + if (!(tagtab->ents = jas_malloc(tagtab->numents * + sizeof(jas_icctagtabent_t)))) + goto error; + tagtabent = tagtab->ents; + for (i = 0; i < JAS_CAST(long, tagtab->numents); ++i) { + if (jas_iccgetuint32(in, &tagtabent->tag) || + jas_iccgetuint32(in, &tagtabent->off) || + jas_iccgetuint32(in, &tagtabent->len)) + goto error; + ++tagtabent; + } + return 0; +error: + if (tagtab->ents) { + jas_free(tagtab->ents); + tagtab->ents = 0; + } + return -1; +} + +jas_iccattrval_t *jas_iccprof_getattr(jas_iccprof_t *prof, + jas_iccattrname_t name) +{ + int i; + jas_iccattrval_t *attrval; + if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) < 0) + goto error; + if (!(attrval = jas_iccattrval_clone(prof->attrtab->attrs[i].val))) + goto error; + return attrval; +error: + return 0; +} + +int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name, + jas_iccattrval_t *val) +{ + int i; + if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) >= 0) { + if (val) { + if (jas_iccattrtab_replace(prof->attrtab, i, name, val)) + goto error; + } else { + jas_iccattrtab_delete(prof->attrtab, i); + } + } else { + if (val) { + if (jas_iccattrtab_add(prof->attrtab, -1, name, val)) + goto error; + } else { + /* NOP */ + } + } + return 0; +error: + return -1; +} + +int jas_iccprof_gethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr) +{ + *hdr = prof->hdr; + return 0; +} + +int jas_iccprof_sethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr) +{ + prof->hdr = *hdr; + return 0; +} + +static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab) +{ + qsort(tagtab->ents, tagtab->numents, sizeof(jas_icctagtabent_t), + jas_icctagtabent_cmp); +} + +static int jas_icctagtabent_cmp(const void *src, const void *dst) +{ + jas_icctagtabent_t *srctagtabent = JAS_CAST(jas_icctagtabent_t *, src); + jas_icctagtabent_t *dsttagtabent = JAS_CAST(jas_icctagtabent_t *, dst); + if (srctagtabent->off > dsttagtabent->off) { + return 1; + } else if (srctagtabent->off < dsttagtabent->off) { + return -1; + } + return 0; +} + +static jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t type) +{ + jas_iccattrvalinfo_t *info; + info = jas_iccattrvalinfos; + for (info = jas_iccattrvalinfos; info->type; ++info) { + if (info->type == type) { + return info; + } + } + return 0; +} + +static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time) +{ + if (jas_iccgetuint16(in, &time->year) || + jas_iccgetuint16(in, &time->month) || + jas_iccgetuint16(in, &time->day) || + jas_iccgetuint16(in, &time->hour) || + jas_iccgetuint16(in, &time->min) || + jas_iccgetuint16(in, &time->sec)) { + return -1; + } + return 0; +} + +static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz) +{ + if (jas_iccgetsint32(in, &xyz->x) || + jas_iccgetsint32(in, &xyz->y) || + jas_iccgetsint32(in, &xyz->z)) { + return -1; + } + return 0; +} + +static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *time) +{ + jas_iccputuint16(out, time->year); + jas_iccputuint16(out, time->month); + jas_iccputuint16(out, time->day); + jas_iccputuint16(out, time->hour); + jas_iccputuint16(out, time->min); + jas_iccputuint16(out, time->sec); + return 0; +} + +static int jas_iccputxyz(jas_stream_t *out, jas_iccxyz_t *xyz) +{ + jas_iccputuint32(out, xyz->x); + jas_iccputuint32(out, xyz->y); + jas_iccputuint32(out, xyz->z); + return 0; +} + +/******************************************************************************\ +* attribute table class +\******************************************************************************/ + +static jas_iccattrtab_t *jas_iccattrtab_create() +{ + jas_iccattrtab_t *tab; + tab = 0; + if (!(tab = jas_malloc(sizeof(jas_iccattrtab_t)))) + goto error; + tab->maxattrs = 0; + tab->numattrs = 0; + tab->attrs = 0; + if (jas_iccattrtab_resize(tab, 32)) + goto error; + return tab; +error: + if (tab) + jas_iccattrtab_destroy(tab); + return 0; +} + +static jas_iccattrtab_t *jas_iccattrtab_copy(jas_iccattrtab_t *attrtab) +{ + jas_iccattrtab_t *newattrtab; + int i; + if (!(newattrtab = jas_iccattrtab_create())) + goto error; + for (i = 0; i < attrtab->numattrs; ++i) { + if (jas_iccattrtab_add(newattrtab, i, attrtab->attrs[i].name, + attrtab->attrs[i].val)) + goto error; + } + return newattrtab; +error: + return 0; +} + +static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab) +{ + if (tab->attrs) { + while (tab->numattrs > 0) { + jas_iccattrtab_delete(tab, 0); + } + jas_free(tab->attrs); + } + jas_free(tab); +} + +void jas_iccattrtab_dump(jas_iccattrtab_t *attrtab, FILE *out) +{ + int i; + jas_iccattr_t *attr; + jas_iccattrval_t *attrval; + jas_iccattrvalinfo_t *info; + char buf[16]; + fprintf(out, "numattrs=%d\n", attrtab->numattrs); + fprintf(out, "---\n"); + for (i = 0; i < attrtab->numattrs; ++i) { + attr = &attrtab->attrs[i]; + attrval = attr->val; + info = jas_iccattrvalinfo_lookup(attrval->type); + if (!info) abort(); + fprintf(out, "attrno=%d; attrname=\"%s\"(0x%08x); attrtype=\"%s\"(0x%08x)\n", + i, + jas_iccsigtostr(attr->name, &buf[0]), + attr->name, + jas_iccsigtostr(attrval->type, &buf[8]), + attrval->type + ); + jas_iccattrval_dump(attrval, out); + fprintf(out, "---\n"); + } +} + +static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, int maxents) +{ + jas_iccattr_t *newattrs; + assert(maxents >= tab->numattrs); + newattrs = tab->attrs ? jas_realloc(tab->attrs, maxents * + sizeof(jas_iccattr_t)) : jas_malloc(maxents * sizeof(jas_iccattr_t)); + if (!newattrs) + return -1; + tab->attrs = newattrs; + tab->maxattrs = maxents; + return 0; +} + +static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i, + jas_iccuint32_t name, jas_iccattrval_t *val) +{ + int n; + jas_iccattr_t *attr; + jas_iccattrval_t *tmpattrval; + tmpattrval = 0; + if (i < 0) { + i = attrtab->numattrs; + } + assert(i >= 0 && i <= attrtab->numattrs); + if (attrtab->numattrs >= attrtab->maxattrs) { + if (jas_iccattrtab_resize(attrtab, attrtab->numattrs + 32)) { + goto error; + } + } + if (!(tmpattrval = jas_iccattrval_clone(val))) + goto error; + n = attrtab->numattrs - i; + if (n > 0) + memmove(&attrtab->attrs[i + 1], &attrtab->attrs[i], + n * sizeof(jas_iccattr_t)); + attr = &attrtab->attrs[i]; + attr->name = name; + attr->val = tmpattrval; + ++attrtab->numattrs; + return 0; +error: + if (tmpattrval) + jas_iccattrval_destroy(tmpattrval); + return -1; +} + +static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, int i, + jas_iccuint32_t name, jas_iccattrval_t *val) +{ + jas_iccattrval_t *newval; + jas_iccattr_t *attr; + if (!(newval = jas_iccattrval_clone(val))) + goto error; + attr = &attrtab->attrs[i]; + jas_iccattrval_destroy(attr->val); + attr->name = name; + attr->val = newval; + return 0; +error: + return -1; +} + +static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, int i) +{ + int n; + jas_iccattrval_destroy(attrtab->attrs[i].val); + if ((n = attrtab->numattrs - i - 1) > 0) + memmove(&attrtab->attrs[i], &attrtab->attrs[i + 1], + n * sizeof(jas_iccattr_t)); + --attrtab->numattrs; +} + +static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, int i, + jas_iccattrname_t *name, jas_iccattrval_t **val) +{ + jas_iccattr_t *attr; + if (i < 0 || i >= attrtab->numattrs) + goto error; + attr = &attrtab->attrs[i]; + *name = attr->name; + if (!(*val = jas_iccattrval_clone(attr->val))) + goto error; + return 0; +error: + return -1; +} + +static int jas_iccattrtab_lookup(jas_iccattrtab_t *attrtab, + jas_iccuint32_t name) +{ + int i; + jas_iccattr_t *attr; + for (i = 0; i < attrtab->numattrs; ++i) { + attr = &attrtab->attrs[i]; + if (attr->name == name) + return i; + } + return -1; +} + +/******************************************************************************\ +* attribute value class +\******************************************************************************/ + +jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type) +{ + jas_iccattrval_t *attrval; + jas_iccattrvalinfo_t *info; + + if (!(info = jas_iccattrvalinfo_lookup(type))) + goto error; + if (!(attrval = jas_iccattrval_create0())) + goto error; + attrval->ops = &info->ops; + attrval->type = type; + ++attrval->refcnt; + memset(&attrval->data, 0, sizeof(attrval->data)); + return attrval; +error: + return 0; +} + +jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval) +{ + ++attrval->refcnt; + return attrval; +} + +void jas_iccattrval_destroy(jas_iccattrval_t *attrval) +{ +#if 0 +fprintf(stderr, "refcnt=%d\n", attrval->refcnt); +#endif + if (--attrval->refcnt <= 0) { + if (attrval->ops->destroy) + (*attrval->ops->destroy)(attrval); + jas_free(attrval); + } +} + +void jas_iccattrval_dump(jas_iccattrval_t *attrval, FILE *out) +{ + char buf[8]; + jas_iccsigtostr(attrval->type, buf); + fprintf(out, "refcnt = %d; type = 0x%08x %s\n", attrval->refcnt, + attrval->type, jas_iccsigtostr(attrval->type, &buf[0])); + if (attrval->ops->dump) { + (*attrval->ops->dump)(attrval, out); + } +} + +int jas_iccattrval_allowmodify(jas_iccattrval_t **attrvalx) +{ + jas_iccattrval_t *newattrval; + jas_iccattrval_t *attrval = *attrvalx; + newattrval = 0; + if (attrval->refcnt > 1) { + if (!(newattrval = jas_iccattrval_create0())) + goto error; + newattrval->ops = attrval->ops; + newattrval->type = attrval->type; + ++newattrval->refcnt; + if (newattrval->ops->copy) { + if ((*newattrval->ops->copy)(newattrval, attrval)) + goto error; + } else { + memcpy(&newattrval->data, &attrval->data, + sizeof(newattrval->data)); + } + *attrvalx = newattrval; + } + return 0; +error: + if (newattrval) { + jas_free(newattrval); + } + return -1; +} + +static jas_iccattrval_t *jas_iccattrval_create0() +{ + jas_iccattrval_t *attrval; + if (!(attrval = jas_malloc(sizeof(jas_iccattrval_t)))) + return 0; + memset(attrval, 0, sizeof(jas_iccattrval_t)); + attrval->refcnt = 0; + attrval->ops = 0; + attrval->type = 0; + return attrval; +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int len) +{ + if (len != 4 * 3) abort(); + return jas_iccgetxyz(in, &attrval->data.xyz); +} + +static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out) +{ + jas_iccxyz_t *xyz = &attrval->data.xyz; + if (jas_iccputuint32(out, xyz->x) || + jas_iccputuint32(out, xyz->y) || + jas_iccputuint32(out, xyz->z)) + return -1; + return 0; +} + +static int jas_iccxyz_getsize(jas_iccattrval_t *attrval) +{ + /* Avoid compiler warnings about unused parameters. */ + attrval = 0; + + return 12; +} + +static void jas_iccxyz_dump(jas_iccattrval_t *attrval, FILE *out) +{ + jas_iccxyz_t *xyz = &attrval->data.xyz; + fprintf(out, "(%f, %f, %f)\n", xyz->x / 65536.0, xyz->y / 65536.0, xyz->z / 65536.0); +} + +/******************************************************************************\ +* attribute table class +\******************************************************************************/ + +static void jas_icccurv_destroy(jas_iccattrval_t *attrval) +{ + jas_icccurv_t *curv = &attrval->data.curv; + if (curv->ents) + jas_free(curv->ents); +} + +static int jas_icccurv_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval) +{ + /* Avoid compiler warnings about unused parameters. */ + attrval = 0; + othattrval = 0; + + /* Not yet implemented. */ + abort(); + return -1; +} + +static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt) +{ + jas_icccurv_t *curv = &attrval->data.curv; + unsigned int i; + + curv->numents = 0; + curv->ents = 0; + + if (jas_iccgetuint32(in, &curv->numents)) + goto error; + if (!(curv->ents = jas_malloc(curv->numents * sizeof(jas_iccuint16_t)))) + goto error; + for (i = 0; i < curv->numents; ++i) { + if (jas_iccgetuint16(in, &curv->ents[i])) + goto error; + } + + if (JAS_CAST(int, 4 + 2 * curv->numents) != cnt) + goto error; + return 0; + +error: + jas_icccurv_destroy(attrval); + return -1; +} + +static int jas_icccurv_getsize(jas_iccattrval_t *attrval) +{ + jas_icccurv_t *curv = &attrval->data.curv; + return 4 + 2 * curv->numents; +} + +static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out) +{ + jas_icccurv_t *curv = &attrval->data.curv; + unsigned int i; + + if (jas_iccputuint32(out, curv->numents)) + goto error; + for (i = 0; i < curv->numents; ++i) { + if (jas_iccputuint16(out, curv->ents[i])) + goto error; + } + return 0; +error: + return -1; +} + +static void jas_icccurv_dump(jas_iccattrval_t *attrval, FILE *out) +{ + int i; + jas_icccurv_t *curv = &attrval->data.curv; + fprintf(out, "number of entires = %d\n", curv->numents); + if (curv->numents == 1) { + fprintf(out, "gamma = %f\n", curv->ents[0] / 256.0); + } else { + for (i = 0; i < JAS_CAST(int, curv->numents); ++i) { + if (i < 3 || i >= JAS_CAST(int, curv->numents) - 3) { + fprintf(out, "entry[%d] = %f\n", i, curv->ents[i] / 65535.0); + } + } + } +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval) +{ + jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; + if (txtdesc->ascdata) + jas_free(txtdesc->ascdata); + if (txtdesc->ucdata) + jas_free(txtdesc->ucdata); +} + +static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval) +{ + jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; + + /* Avoid compiler warnings about unused parameters. */ + attrval = 0; + othattrval = 0; + txtdesc = 0; + + /* Not yet implemented. */ + abort(); + return -1; +} + +static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt) +{ + int n; + int c; + jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; + txtdesc->ascdata = 0; + txtdesc->ucdata = 0; + if (jas_iccgetuint32(in, &txtdesc->asclen)) + goto error; + if (!(txtdesc->ascdata = jas_malloc(txtdesc->asclen))) + goto error; + if (jas_stream_read(in, txtdesc->ascdata, txtdesc->asclen) != + JAS_CAST(int, txtdesc->asclen)) + goto error; + txtdesc->ascdata[txtdesc->asclen - 1] = '\0'; + if (jas_iccgetuint32(in, &txtdesc->uclangcode) || + jas_iccgetuint32(in, &txtdesc->uclen)) + goto error; + if (!(txtdesc->ucdata = jas_malloc(txtdesc->uclen * 2))) + goto error; + if (jas_stream_read(in, txtdesc->ucdata, txtdesc->uclen * 2) != + JAS_CAST(int, txtdesc->uclen * 2)) + goto error; + if (jas_iccgetuint16(in, &txtdesc->sccode)) + goto error; + if ((c = jas_stream_getc(in)) == EOF) + goto error; + txtdesc->maclen = c; + if (jas_stream_read(in, txtdesc->macdata, 67) != 67) + goto error; + txtdesc->asclen = strlen(txtdesc->ascdata) + 1; +#define WORKAROUND_BAD_PROFILES +#ifdef WORKAROUND_BAD_PROFILES + n = txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67; + if (n > cnt) { + return -1; + } + if (n < cnt) { + if (jas_stream_gobble(in, cnt - n) != cnt - n) + goto error; + } +#else + if (txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67 != cnt) + return -1; +#endif + return 0; +error: + jas_icctxtdesc_destroy(attrval); + return -1; +} + +static int jas_icctxtdesc_getsize(jas_iccattrval_t *attrval) +{ + jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; + return strlen(txtdesc->ascdata) + 1 + txtdesc->uclen * 2 + 15 + 67; +} + +static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out) +{ + jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; + if (jas_iccputuint32(out, txtdesc->asclen) || + jas_stream_puts(out, txtdesc->ascdata) || + jas_stream_putc(out, 0) == EOF || + jas_iccputuint32(out, txtdesc->uclangcode) || + jas_iccputuint32(out, txtdesc->uclen) || + jas_stream_write(out, txtdesc->ucdata, txtdesc->uclen * 2) != JAS_CAST(int, txtdesc->uclen * 2) || + jas_iccputuint16(out, txtdesc->sccode) || + jas_stream_putc(out, txtdesc->maclen) == EOF) + goto error; + if (txtdesc->maclen > 0) { + if (jas_stream_write(out, txtdesc->macdata, 67) != 67) + goto error; + } else { + if (jas_stream_pad(out, 67, 0) != 67) + goto error; + } + return 0; +error: + return -1; +} + +static void jas_icctxtdesc_dump(jas_iccattrval_t *attrval, FILE *out) +{ + jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; + fprintf(out, "ascii = \"%s\"\n", txtdesc->ascdata); + fprintf(out, "uclangcode = %d; uclen = %d\n", txtdesc->uclangcode, + txtdesc->uclen); + fprintf(out, "sccode = %d\n", txtdesc->sccode); + fprintf(out, "maclen = %d\n", txtdesc->maclen); +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static void jas_icctxt_destroy(jas_iccattrval_t *attrval) +{ + jas_icctxt_t *txt = &attrval->data.txt; + if (txt->string) + jas_free(txt->string); +} + +static int jas_icctxt_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval) +{ + jas_icctxt_t *txt = &attrval->data.txt; + jas_icctxt_t *othtxt = &othattrval->data.txt; + if (!(txt->string = strdup(othtxt->string))) + return -1; + return 0; +} + +static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt) +{ + jas_icctxt_t *txt = &attrval->data.txt; + txt->string = 0; + if (!(txt->string = jas_malloc(cnt))) + goto error; + if (jas_stream_read(in, txt->string, cnt) != cnt) + goto error; + txt->string[cnt - 1] = '\0'; + if (JAS_CAST(int, strlen(txt->string)) + 1 != cnt) + goto error; + return 0; +error: + if (txt->string) + jas_free(txt->string); + return -1; +} + +static int jas_icctxt_getsize(jas_iccattrval_t *attrval) +{ + jas_icctxt_t *txt = &attrval->data.txt; + return strlen(txt->string) + 1; +} + +static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out) +{ + jas_icctxt_t *txt = &attrval->data.txt; + if (jas_stream_puts(out, txt->string) || + jas_stream_putc(out, 0) == EOF) + return -1; + return 0; +} + +static void jas_icctxt_dump(jas_iccattrval_t *attrval, FILE *out) +{ + jas_icctxt_t *txt = &attrval->data.txt; + fprintf(out, "string = \"%s\"\n", txt->string); +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static void jas_icclut8_destroy(jas_iccattrval_t *attrval) +{ + jas_icclut8_t *lut8 = &attrval->data.lut8; + if (lut8->clut) + jas_free(lut8->clut); + if (lut8->intabs) + jas_free(lut8->intabs); + if (lut8->intabsbuf) + jas_free(lut8->intabsbuf); + if (lut8->outtabs) + jas_free(lut8->outtabs); + if (lut8->outtabsbuf) + jas_free(lut8->outtabsbuf); +} + +static int jas_icclut8_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval) +{ + jas_icclut8_t *lut8 = &attrval->data.lut8; + /* Avoid compiler warnings about unused parameters. */ + attrval = 0; + othattrval = 0; + lut8 = 0; + abort(); + return -1; +} + +static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt) +{ + int i; + int j; + int clutsize; + jas_icclut8_t *lut8 = &attrval->data.lut8; + lut8->clut = 0; + lut8->intabs = 0; + lut8->intabsbuf = 0; + lut8->outtabs = 0; + lut8->outtabsbuf = 0; + if (jas_iccgetuint8(in, &lut8->numinchans) || + jas_iccgetuint8(in, &lut8->numoutchans) || + jas_iccgetuint8(in, &lut8->clutlen) || + jas_stream_getc(in) == EOF) + goto error; + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + if (jas_iccgetsint32(in, &lut8->e[i][j])) + goto error; + } + } + if (jas_iccgetuint16(in, &lut8->numintabents) || + jas_iccgetuint16(in, &lut8->numouttabents)) + goto error; + clutsize = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; + if (!(lut8->clut = jas_malloc(clutsize * sizeof(jas_iccuint8_t))) || + !(lut8->intabsbuf = jas_malloc(lut8->numinchans * + lut8->numintabents * sizeof(jas_iccuint8_t))) || + !(lut8->intabs = jas_malloc(lut8->numinchans * + sizeof(jas_iccuint8_t *)))) + goto error; + for (i = 0; i < lut8->numinchans; ++i) + lut8->intabs[i] = &lut8->intabsbuf[i * lut8->numintabents]; + if (!(lut8->outtabsbuf = jas_malloc(lut8->numoutchans * + lut8->numouttabents * sizeof(jas_iccuint8_t))) || + !(lut8->outtabs = jas_malloc(lut8->numoutchans * + sizeof(jas_iccuint8_t *)))) + goto error; + for (i = 0; i < lut8->numoutchans; ++i) + lut8->outtabs[i] = &lut8->outtabsbuf[i * lut8->numouttabents]; + for (i = 0; i < lut8->numinchans; ++i) { + for (j = 0; j < JAS_CAST(int, lut8->numintabents); ++j) { + if (jas_iccgetuint8(in, &lut8->intabs[i][j])) + goto error; + } + } + for (i = 0; i < lut8->numoutchans; ++i) { + for (j = 0; j < JAS_CAST(int, lut8->numouttabents); ++j) { + if (jas_iccgetuint8(in, &lut8->outtabs[i][j])) + goto error; + } + } + for (i = 0; i < clutsize; ++i) { + if (jas_iccgetuint8(in, &lut8->clut[i])) + goto error; + } + if (JAS_CAST(int, 44 + lut8->numinchans * lut8->numintabents + + lut8->numoutchans * lut8->numouttabents + + jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans) != + cnt) + goto error; + return 0; +error: + jas_icclut8_destroy(attrval); + return -1; +} + +static int jas_icclut8_getsize(jas_iccattrval_t *attrval) +{ + jas_icclut8_t *lut8 = &attrval->data.lut8; + return 44 + lut8->numinchans * lut8->numintabents + + lut8->numoutchans * lut8->numouttabents + + jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; +} + +static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out) +{ + jas_icclut8_t *lut8 = &attrval->data.lut8; + int i; + int j; + int n; + lut8->clut = 0; + lut8->intabs = 0; + lut8->intabsbuf = 0; + lut8->outtabs = 0; + lut8->outtabsbuf = 0; + if (jas_stream_putc(out, lut8->numinchans) == EOF || + jas_stream_putc(out, lut8->numoutchans) == EOF || + jas_stream_putc(out, lut8->clutlen) == EOF || + jas_stream_putc(out, 0) == EOF) + goto error; + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + if (jas_iccputsint32(out, lut8->e[i][j])) + goto error; + } + } + if (jas_iccputuint16(out, lut8->numintabents) || + jas_iccputuint16(out, lut8->numouttabents)) + goto error; + n = lut8->numinchans * lut8->numintabents; + for (i = 0; i < n; ++i) { + if (jas_iccputuint8(out, lut8->intabsbuf[i])) + goto error; + } + n = lut8->numoutchans * lut8->numouttabents; + for (i = 0; i < n; ++i) { + if (jas_iccputuint8(out, lut8->outtabsbuf[i])) + goto error; + } + n = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; + for (i = 0; i < n; ++i) { + if (jas_iccputuint8(out, lut8->clut[i])) + goto error; + } + return 0; +error: + return -1; +} + +static void jas_icclut8_dump(jas_iccattrval_t *attrval, FILE *out) +{ + jas_icclut8_t *lut8 = &attrval->data.lut8; + int i; + int j; + fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n", + lut8->numinchans, lut8->numoutchans, lut8->clutlen); + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + fprintf(out, "e[%d][%d]=%f ", i, j, lut8->e[i][j] / 65536.0); + } + fprintf(out, "\n"); + } + fprintf(out, "numintabents=%d, numouttabents=%d\n", + lut8->numintabents, lut8->numouttabents); +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static void jas_icclut16_destroy(jas_iccattrval_t *attrval) +{ + jas_icclut16_t *lut16 = &attrval->data.lut16; + if (lut16->clut) + jas_free(lut16->clut); + if (lut16->intabs) + jas_free(lut16->intabs); + if (lut16->intabsbuf) + jas_free(lut16->intabsbuf); + if (lut16->outtabs) + jas_free(lut16->outtabs); + if (lut16->outtabsbuf) + jas_free(lut16->outtabsbuf); +} + +static int jas_icclut16_copy(jas_iccattrval_t *attrval, + jas_iccattrval_t *othattrval) +{ + /* Avoid compiler warnings about unused parameters. */ + attrval = 0; + othattrval = 0; + /* Not yet implemented. */ + abort(); + return -1; +} + +static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in, + int cnt) +{ + int i; + int j; + int clutsize; + jas_icclut16_t *lut16 = &attrval->data.lut16; + lut16->clut = 0; + lut16->intabs = 0; + lut16->intabsbuf = 0; + lut16->outtabs = 0; + lut16->outtabsbuf = 0; + if (jas_iccgetuint8(in, &lut16->numinchans) || + jas_iccgetuint8(in, &lut16->numoutchans) || + jas_iccgetuint8(in, &lut16->clutlen) || + jas_stream_getc(in) == EOF) + goto error; + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + if (jas_iccgetsint32(in, &lut16->e[i][j])) + goto error; + } + } + if (jas_iccgetuint16(in, &lut16->numintabents) || + jas_iccgetuint16(in, &lut16->numouttabents)) + goto error; + clutsize = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans; + if (!(lut16->clut = jas_malloc(clutsize * sizeof(jas_iccuint16_t))) || + !(lut16->intabsbuf = jas_malloc(lut16->numinchans * + lut16->numintabents * sizeof(jas_iccuint16_t))) || + !(lut16->intabs = jas_malloc(lut16->numinchans * + sizeof(jas_iccuint16_t *)))) + goto error; + for (i = 0; i < lut16->numinchans; ++i) + lut16->intabs[i] = &lut16->intabsbuf[i * lut16->numintabents]; + if (!(lut16->outtabsbuf = jas_malloc(lut16->numoutchans * + lut16->numouttabents * sizeof(jas_iccuint16_t))) || + !(lut16->outtabs = jas_malloc(lut16->numoutchans * + sizeof(jas_iccuint16_t *)))) + goto error; + for (i = 0; i < lut16->numoutchans; ++i) + lut16->outtabs[i] = &lut16->outtabsbuf[i * lut16->numouttabents]; + for (i = 0; i < lut16->numinchans; ++i) { + for (j = 0; j < JAS_CAST(int, lut16->numintabents); ++j) { + if (jas_iccgetuint16(in, &lut16->intabs[i][j])) + goto error; + } + } + for (i = 0; i < lut16->numoutchans; ++i) { + for (j = 0; j < JAS_CAST(int, lut16->numouttabents); ++j) { + if (jas_iccgetuint16(in, &lut16->outtabs[i][j])) + goto error; + } + } + for (i = 0; i < clutsize; ++i) { + if (jas_iccgetuint16(in, &lut16->clut[i])) + goto error; + } + if (JAS_CAST(int, 44 + 2 * (lut16->numinchans * lut16->numintabents + + lut16->numoutchans * lut16->numouttabents + + jas_iccpowi(lut16->clutlen, lut16->numinchans) * + lut16->numoutchans)) != cnt) + goto error; + return 0; +error: + jas_icclut16_destroy(attrval); + return -1; +} + +static int jas_icclut16_getsize(jas_iccattrval_t *attrval) +{ + jas_icclut16_t *lut16 = &attrval->data.lut16; + return 44 + 2 * (lut16->numinchans * lut16->numintabents + + lut16->numoutchans * lut16->numouttabents + + jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans); +} + +static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out) +{ + jas_icclut16_t *lut16 = &attrval->data.lut16; + int i; + int j; + int n; + if (jas_stream_putc(out, lut16->numinchans) == EOF || + jas_stream_putc(out, lut16->numoutchans) == EOF || + jas_stream_putc(out, lut16->clutlen) == EOF || + jas_stream_putc(out, 0) == EOF) + goto error; + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + if (jas_iccputsint32(out, lut16->e[i][j])) + goto error; + } + } + if (jas_iccputuint16(out, lut16->numintabents) || + jas_iccputuint16(out, lut16->numouttabents)) + goto error; + n = lut16->numinchans * lut16->numintabents; + for (i = 0; i < n; ++i) { + if (jas_iccputuint16(out, lut16->intabsbuf[i])) + goto error; + } + n = lut16->numoutchans * lut16->numouttabents; + for (i = 0; i < n; ++i) { + if (jas_iccputuint16(out, lut16->outtabsbuf[i])) + goto error; + } + n = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans; + for (i = 0; i < n; ++i) { + if (jas_iccputuint16(out, lut16->clut[i])) + goto error; + } + return 0; +error: + return -1; +} + +static void jas_icclut16_dump(jas_iccattrval_t *attrval, FILE *out) +{ + jas_icclut16_t *lut16 = &attrval->data.lut16; + int i; + int j; + fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n", + lut16->numinchans, lut16->numoutchans, lut16->clutlen); + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + fprintf(out, "e[%d][%d]=%f ", i, j, lut16->e[i][j] / 65536.0); + } + fprintf(out, "\n"); + } + fprintf(out, "numintabents=%d, numouttabents=%d\n", + lut16->numintabents, lut16->numouttabents); +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val) +{ + int i; + int c; + ulonglong v; + v = 0; + for (i = n; i > 0; --i) { + if ((c = jas_stream_getc(in)) == EOF) + return -1; + v = (v << 8) | c; + } + *val = v; + return 0; +} + +static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val) +{ + int c; + if ((c = jas_stream_getc(in)) == EOF) + return -1; + *val = c; + return 0; +} + +static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val) +{ + ulonglong tmp; + if (jas_iccgetuint(in, 2, &tmp)) + return -1; + *val = tmp; + return 0; +} + +static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val) +{ + ulonglong tmp; + if (jas_iccgetuint(in, 4, &tmp)) + return -1; + *val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) & + 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp); + return 0; +} + +static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val) +{ + ulonglong tmp; + if (jas_iccgetuint(in, 4, &tmp)) + return -1; + *val = tmp; + return 0; +} + +static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) +{ + ulonglong tmp; + if (jas_iccgetuint(in, 8, &tmp)) + return -1; + *val = tmp; + return 0; +} + +static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val) +{ + int i; + int c; + for (i = n; i > 0; --i) { + c = (val >> (8 * (i - 1))) & 0xff; + if (jas_stream_putc(out, c) == EOF) + return -1; + } + return 0; +} + +static int jas_iccputsint(jas_stream_t *out, int n, longlong val) +{ + ulonglong tmp; + tmp = (val < 0) ? (abort(), 0) : val; + return jas_iccputuint(out, n, tmp); +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static char *jas_iccsigtostr(int sig, char *buf) +{ + int n; + int c; + char *bufptr; + bufptr = buf; + for (n = 4; n > 0; --n) { + c = (sig >> 24) & 0xff; + if (isalpha(c) || isdigit(c)) { + *bufptr++ = c; + } + sig <<= 8; + } + *bufptr = '\0'; + return buf; +} + +static long jas_iccpadtomult(long x, long y) +{ + return ((x + y - 1) / y) * y; +} + +static long jas_iccpowi(int x, int n) +{ + long y; + y = 1; + while (--n >= 0) + y *= x; + return y; +} + + +jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len) +{ + jas_stream_t *in; + jas_iccprof_t *prof; + if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len))) + goto error; + if (!(prof = jas_iccprof_load(in))) + goto error; + jas_stream_close(in); + return prof; +error: + return 0; +} + +jas_iccprof_t *jas_iccprof_createfromclrspc(int clrspc) +{ + jas_iccprof_t *prof; + switch (clrspc) { + case JAS_CLRSPC_SRGB: + prof = jas_iccprof_createfrombuf(jas_iccprofdata_srgb, + jas_iccprofdata_srgblen); + break; + case JAS_CLRSPC_SGRAY: + prof = jas_iccprof_createfrombuf(jas_iccprofdata_sgray, + jas_iccprofdata_sgraylen); + break; + default: + prof = 0; + break; + } + return prof; +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_iccdata.c b/SlnkDWFImpl/CxImage/jasper/base/jas_iccdata.c new file mode 100644 index 0000000..ec57e9d --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_iccdata.c @@ -0,0 +1,566 @@ +/* + * Copyright (c) 2002-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#include +#include + +uchar jas_iccprofdata_srgb[] = +{ + 0x00, 0x00, 0x0c, 0x48, 0x4c, 0x69, 0x6e, 0x6f, + 0x02, 0x10, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, + 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, + 0x07, 0xce, 0x00, 0x02, 0x00, 0x09, 0x00, 0x06, + 0x00, 0x31, 0x00, 0x00, 0x61, 0x63, 0x73, 0x70, + 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, + 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, + 0x48, 0x50, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x11, 0x63, 0x70, 0x72, 0x74, + 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x33, + 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x84, + 0x00, 0x00, 0x00, 0x6c, 0x77, 0x74, 0x70, 0x74, + 0x00, 0x00, 0x01, 0xf0, 0x00, 0x00, 0x00, 0x14, + 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x02, 0x04, + 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, + 0x00, 0x00, 0x02, 0x18, 0x00, 0x00, 0x00, 0x14, + 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x02, 0x2c, + 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, + 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x14, + 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, + 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, + 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, + 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x4c, + 0x00, 0x00, 0x00, 0x86, 0x76, 0x69, 0x65, 0x77, + 0x00, 0x00, 0x03, 0xd4, 0x00, 0x00, 0x00, 0x24, + 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xf8, + 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, + 0x00, 0x00, 0x04, 0x0c, 0x00, 0x00, 0x00, 0x24, + 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x04, 0x30, + 0x00, 0x00, 0x00, 0x0c, 0x72, 0x54, 0x52, 0x43, + 0x00, 0x00, 0x04, 0x3c, 0x00, 0x00, 0x08, 0x0c, + 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x3c, + 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, + 0x00, 0x00, 0x04, 0x3c, 0x00, 0x00, 0x08, 0x0c, + 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, + 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, + 0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x31, 0x39, + 0x39, 0x38, 0x20, 0x48, 0x65, 0x77, 0x6c, 0x65, + 0x74, 0x74, 0x2d, 0x50, 0x61, 0x63, 0x6b, 0x61, + 0x72, 0x64, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x61, + 0x6e, 0x79, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, + 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, + 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, + 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x12, 0x73, 0x52, 0x47, + 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, + 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x6f, 0xa2, 0x00, 0x00, 0x38, 0xf5, + 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x99, + 0x00, 0x00, 0xb7, 0x85, 0x00, 0x00, 0x18, 0xda, + 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x24, 0xa0, 0x00, 0x00, 0x0f, 0x84, + 0x00, 0x00, 0xb6, 0xcf, 0x64, 0x65, 0x73, 0x63, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, + 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, + 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, + 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, + 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, + 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, + 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, + 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, + 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, + 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, + 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, + 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, + 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, + 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, + 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, + 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, + 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, + 0x52, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, + 0x65, 0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e, + 0x67, 0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, + 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x49, + 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, + 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x52, + 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, + 0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e, 0x67, + 0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, + 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x49, 0x45, + 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, + 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0xfe, + 0x00, 0x14, 0x5f, 0x2e, 0x00, 0x10, 0xcf, 0x14, + 0x00, 0x03, 0xed, 0xcc, 0x00, 0x04, 0x13, 0x0b, + 0x00, 0x03, 0x5c, 0x9e, 0x00, 0x00, 0x00, 0x01, + 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x4c, 0x09, 0x56, 0x00, 0x50, 0x00, 0x00, + 0x00, 0x57, 0x1f, 0xe7, 0x6d, 0x65, 0x61, 0x73, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, + 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x43, 0x52, 0x54, 0x20, 0x63, 0x75, 0x72, 0x76, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, + 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, + 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, + 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, + 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, + 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, + 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, + 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, + 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, + 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, + 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, + 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, + 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, + 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, + 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, + 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, + 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, + 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, + 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, + 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, + 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, + 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, + 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, + 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, + 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, + 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, + 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, + 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, + 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, + 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, + 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, + 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, + 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, + 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, + 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, + 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, + 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, + 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, + 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, + 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, + 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, + 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, + 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, + 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, + 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, + 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, + 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, + 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, + 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, + 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, + 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, + 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, + 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, + 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, + 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, + 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, + 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, + 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, + 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, + 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, + 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, + 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, + 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, + 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, + 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, + 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, + 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, + 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, + 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, + 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, + 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, + 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, + 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, + 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, + 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, + 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, + 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, + 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, + 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, + 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, + 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, + 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, + 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, + 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, + 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, + 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, + 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, + 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, + 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, + 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, + 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, + 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, + 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, + 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, + 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, + 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, + 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, + 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, + 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, + 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, + 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, + 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, + 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, + 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, + 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, + 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, + 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, + 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, + 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, + 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, + 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, + 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, + 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, + 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, + 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, + 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, + 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, + 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, + 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, + 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, + 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, + 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, + 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, + 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, + 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, + 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, + 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, + 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, + 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, + 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, + 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, + 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, + 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, + 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, + 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, + 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, + 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, + 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, + 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, + 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, + 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, + 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, + 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, + 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, + 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, + 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, + 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, + 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, + 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, + 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, + 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, + 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, + 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, + 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, + 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, + 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, + 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, + 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, + 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, + 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, + 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, + 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, + 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, + 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, + 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, + 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, + 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, + 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, + 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, + 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, + 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, + 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, + 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, + 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, + 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, + 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, + 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, + 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, + 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, + 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, + 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, + 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, + 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, + 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, + 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, + 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, + 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, + 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, + 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, + 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, + 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, + 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, + 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, + 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, + 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, + 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, + 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, + 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, + 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, + 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, + 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, + 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, + 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, + 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, + 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, + 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, + 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, + 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, + 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, + 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, + 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, + 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, + 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, + 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, + 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, + 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, + 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, + 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, + 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, + 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, + 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, + 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, + 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, + 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, + 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, + 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, + 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, + 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, + 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, + 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, + 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, + 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, + 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, + 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, + 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, + 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, + 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, + 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, + 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, + 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, + 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, + 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, + 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, + 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, + 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, + 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, + 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, + 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, + 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, + 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, + 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, + 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, + 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, + 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, + 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, + 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff +}; + +int jas_iccprofdata_srgblen = sizeof(jas_iccprofdata_srgb); + +uchar jas_iccprofdata_sgray[] = { + 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x20, 0x00, 0x00, 0x73, 0x63, 0x6e, 0x72, + 0x47, 0x52, 0x41, 0x59, 0x58, 0x59, 0x5a, 0x20, + 0x07, 0xd3, 0x00, 0x01, 0x00, 0x1f, 0x00, 0x0d, + 0x00, 0x35, 0x00, 0x21, 0x61, 0x63, 0x73, 0x70, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x4b, 0x4f, 0x44, 0x41, 0x73, 0x47, 0x72, 0x79, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, + 0x4a, 0x50, 0x45, 0x47, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x04, 0x64, 0x65, 0x73, 0x63, + 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x86, + 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0x3c, + 0x00, 0x00, 0x00, 0x2b, 0x77, 0x74, 0x70, 0x74, + 0x00, 0x00, 0x01, 0x68, 0x00, 0x00, 0x00, 0x14, + 0x6b, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x7c, + 0x00, 0x00, 0x00, 0x0e, 0x64, 0x65, 0x73, 0x63, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, + 0x52, 0x65, 0x73, 0x74, 0x72, 0x69, 0x63, 0x74, + 0x65, 0x64, 0x20, 0x49, 0x43, 0x43, 0x20, 0x70, + 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x64, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x62, 0x69, 0x6e, + 0x67, 0x20, 0x73, 0x52, 0x47, 0x42, 0x2d, 0x67, + 0x72, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, + 0x00, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x70, 0x79, + 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x32, 0x30, + 0x30, 0x33, 0x20, 0x73, 0x52, 0x47, 0x42, 0x2d, + 0x67, 0x72, 0x65, 0x79, 0x20, 0x52, 0x65, 0x66, + 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x00, 0x00, + 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xf3, 0x54, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x01, 0x16, 0xcf, 0x63, 0x75, 0x72, 0x76, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x01, 0xcd +}; + +int jas_iccprofdata_sgraylen = sizeof(jas_iccprofdata_sgray); diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_image.c b/SlnkDWFImpl/CxImage/jasper/base/jas_image.c new file mode 100644 index 0000000..055a7ec --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_image.c @@ -0,0 +1,1493 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Image Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include +#include + +#include "jasper/jas_math.h" +#include "jasper/jas_image.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_string.h" + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +#define FLOORDIV(x, y) ((x) / (y)) + +/******************************************************************************\ +* Local prototypes. +\******************************************************************************/ + +static jas_image_cmpt_t *jas_image_cmpt_create0(void); +static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt); +static jas_image_cmpt_t *jas_image_cmpt_create(uint_fast32_t tlx, uint_fast32_t tly, + uint_fast32_t hstep, uint_fast32_t vstep, uint_fast32_t width, uint_fast32_t + height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem); +static void jas_image_setbbox(jas_image_t *image); +static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt); +static int jas_image_growcmpts(jas_image_t *image, int maxcmpts); +static uint_fast32_t inttobits(jas_seqent_t v, int prec, bool sgnd); +static jas_seqent_t bitstoint(uint_fast32_t v, int prec, bool sgnd); +static int putint(jas_stream_t *out, int sgnd, int prec, long val); +static int getint(jas_stream_t *in, int sgnd, int prec, long *val); +static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx, + jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry); +static long uptomult(long x, long y); +static long downtomult(long x, long y); +static long convert(long val, int oldsgnd, int oldprec, int newsgnd, + int newprec); +static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx, + jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry); + +/******************************************************************************\ +* Global data. +\******************************************************************************/ + +static int jas_image_numfmts = 0; +static jas_image_fmtinfo_t jas_image_fmtinfos[JAS_IMAGE_MAXFMTS]; + +/******************************************************************************\ +* Create and destroy operations. +\******************************************************************************/ + +jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms, + int clrspc) +{ + jas_image_t *image; + uint_fast32_t rawsize; + uint_fast32_t inmem; + int cmptno; + jas_image_cmptparm_t *cmptparm; + + if (!(image = jas_image_create0())) { + return 0; + } + + image->clrspc_ = clrspc; + image->maxcmpts_ = numcmpts; + image->inmem_ = true; + + /* Allocate memory for the per-component information. */ + if (!(image->cmpts_ = jas_malloc(image->maxcmpts_ * + sizeof(jas_image_cmpt_t *)))) { + jas_image_destroy(image); + return 0; + } + /* Initialize in case of failure. */ + for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) { + image->cmpts_[cmptno] = 0; + } + + /* Compute the approximate raw size of the image. */ + rawsize = 0; + for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, + ++cmptparm) { + rawsize += cmptparm->width * cmptparm->height * + (cmptparm->prec + 7) / 8; + } + /* Decide whether to buffer the image data in memory, based on the + raw size of the image. */ + inmem = (rawsize < JAS_IMAGE_INMEMTHRESH); + + /* Create the individual image components. */ + for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, + ++cmptparm) { + if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx, + cmptparm->tly, cmptparm->hstep, cmptparm->vstep, + cmptparm->width, cmptparm->height, cmptparm->prec, + cmptparm->sgnd, inmem))) { + jas_image_destroy(image); + return 0; + } + ++image->numcmpts_; + } + + /* Determine the bounding box for all of the components on the + reference grid (i.e., the image area) */ + jas_image_setbbox(image); + + return image; +} + +jas_image_t *jas_image_create0() +{ + jas_image_t *image; + + if (!(image = jas_malloc(sizeof(jas_image_t)))) { + return 0; + } + + image->tlx_ = 0; + image->tly_ = 0; + image->brx_ = 0; + image->bry_ = 0; + image->clrspc_ = JAS_CLRSPC_UNKNOWN; + image->numcmpts_ = 0; + image->maxcmpts_ = 0; + image->cmpts_ = 0; + image->inmem_ = true; + image->cmprof_ = 0; + + return image; +} + +jas_image_t *jas_image_copy(jas_image_t *image) +{ + jas_image_t *newimage; + int cmptno; + + newimage = jas_image_create0(); + if (jas_image_growcmpts(newimage, image->numcmpts_)) { + goto error; + } + for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { + if (!(newimage->cmpts_[cmptno] = jas_image_cmpt_copy(image->cmpts_[cmptno]))) { + goto error; + } + ++newimage->numcmpts_; + } + + jas_image_setbbox(newimage); + + if (image->cmprof_) { + if (!(newimage->cmprof_ = jas_cmprof_copy(image->cmprof_))) + goto error; + } + + return newimage; +error: + if (newimage) { + jas_image_destroy(newimage); + } + return 0; +} + +static jas_image_cmpt_t *jas_image_cmpt_create0() +{ + jas_image_cmpt_t *cmpt; + if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { + return 0; + } + memset(cmpt, 0, sizeof(jas_image_cmpt_t)); + cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; + return cmpt; +} + +static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt) +{ + jas_image_cmpt_t *newcmpt; + + if (!(newcmpt = jas_image_cmpt_create0())) { + return 0; + } + newcmpt->tlx_ = cmpt->tlx_; + newcmpt->tly_ = cmpt->tly_; + newcmpt->hstep_ = cmpt->hstep_; + newcmpt->vstep_ = cmpt->vstep_; + newcmpt->width_ = cmpt->width_; + newcmpt->height_ = cmpt->height_; + newcmpt->prec_ = cmpt->prec_; + newcmpt->sgnd_ = cmpt->sgnd_; + newcmpt->cps_ = cmpt->cps_; + newcmpt->type_ = cmpt->type_; + if (!(newcmpt->stream_ = jas_stream_memopen(0, 0))) { + return 0; + } + if (jas_stream_seek(cmpt->stream_, 0, SEEK_SET)) { + return 0; + } + if (jas_stream_copy(newcmpt->stream_, cmpt->stream_, -1)) { + return 0; + } + if (jas_stream_seek(newcmpt->stream_, 0, SEEK_SET)) { + return 0; + } + return newcmpt; +} + +void jas_image_destroy(jas_image_t *image) +{ + int i; + + if (image->cmpts_) { + for (i = 0; i < image->numcmpts_; ++i) { + jas_image_cmpt_destroy(image->cmpts_[i]); + image->cmpts_[i] = 0; + } + jas_free(image->cmpts_); + } + if (image->cmprof_) + jas_cmprof_destroy(image->cmprof_); + jas_free(image); +} + +static jas_image_cmpt_t *jas_image_cmpt_create(uint_fast32_t tlx, uint_fast32_t tly, + uint_fast32_t hstep, uint_fast32_t vstep, uint_fast32_t width, uint_fast32_t + height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) +{ + jas_image_cmpt_t *cmpt; + long size; + + if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { + return 0; + } + + cmpt->tlx_ = tlx; + cmpt->tly_ = tly; + cmpt->hstep_ = hstep; + cmpt->vstep_ = vstep; + cmpt->width_ = width; + cmpt->height_ = height; + cmpt->prec_ = depth; + cmpt->sgnd_ = sgnd; + cmpt->stream_ = 0; + cmpt->cps_ = (depth + 7) / 8; + + size = cmpt->width_ * cmpt->height_ * cmpt->cps_; + cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) : jas_stream_tmpfile(); + if (!cmpt->stream_) { + jas_image_cmpt_destroy(cmpt); + return 0; + } + + /* Zero the component data. This isn't necessary, but it is + convenient for debugging purposes. */ + if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || + jas_stream_putc(cmpt->stream_, 0) == EOF || + jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { + jas_image_cmpt_destroy(cmpt); + return 0; + } + + return cmpt; +} + +static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt) +{ + if (cmpt->stream_) { + jas_stream_close(cmpt->stream_); + } + jas_free(cmpt); +} + +/******************************************************************************\ +* Load and save operations. +\******************************************************************************/ + +jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, char *optstr) +{ + jas_image_fmtinfo_t *fmtinfo; + jas_image_t *image; + + image = 0; + + /* If possible, try to determine the format of the input data. */ + if (fmt < 0) { + if ((fmt = jas_image_getfmt(in)) < 0) + goto error; + } + + /* Is it possible to decode an image represented in this format? */ + if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) + goto error; + if (!fmtinfo->ops.decode) + goto error; + + /* Decode the image. */ + if (!(image = (*fmtinfo->ops.decode)(in, optstr))) + goto error; + + /* Create a color profile if needed. */ + if (!jas_clrspc_isunknown(image->clrspc_) && + !jas_clrspc_isgeneric(image->clrspc_) && !image->cmprof_) { + if (!(image->cmprof_ = + jas_cmprof_createfromclrspc(jas_image_clrspc(image)))) + goto error; + } + + return image; +error: + if (image) + jas_image_destroy(image); + return 0; +} + +int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt, char *optstr) +{ + jas_image_fmtinfo_t *fmtinfo; + if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) { + return -1; + } + return (fmtinfo->ops.encode) ? (*fmtinfo->ops.encode)(image, out, + optstr) : (-1); +} + +/******************************************************************************\ +* Component read and write operations. +\******************************************************************************/ + +int jas_image_readcmpt(jas_image_t *image, int cmptno, jas_image_coord_t x, + jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, + jas_matrix_t *data) +{ + jas_image_cmpt_t *cmpt; + jas_image_coord_t i; + jas_image_coord_t j; + int k; + jas_seqent_t v; + int c; + jas_seqent_t *dr; + jas_seqent_t *d; + int drs; + + if (cmptno < 0 || cmptno >= image->numcmpts_) { + return -1; + } + + cmpt = image->cmpts_[cmptno]; + if (x >= cmpt->width_ || y >= cmpt->height_ || + x + width > cmpt->width_ || + y + height > cmpt->height_) { + return -1; + } + + if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) { + if (jas_matrix_resize(data, height, width)) { + return -1; + } + } + + dr = jas_matrix_getref(data, 0, 0); + drs = jas_matrix_rowstep(data); + for (i = 0; i < height; ++i, dr += drs) { + d = dr; + if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) + * cmpt->cps_, SEEK_SET) < 0) { + return -1; + } + for (j = width; j > 0; --j, ++d) { + v = 0; + for (k = cmpt->cps_; k > 0; --k) { + if ((c = jas_stream_getc(cmpt->stream_)) == EOF) { + return -1; + } + v = (v << 8) | (c & 0xff); + } + *d = bitstoint(v, cmpt->prec_, cmpt->sgnd_); + } + } + + return 0; +} + +int jas_image_writecmpt(jas_image_t *image, int cmptno, jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, + jas_image_coord_t height, jas_matrix_t *data) +{ + jas_image_cmpt_t *cmpt; + jas_image_coord_t i; + jas_image_coord_t j; + jas_seqent_t *d; + jas_seqent_t *dr; + int drs; + jas_seqent_t v; + int k; + int c; + + if (cmptno < 0 || cmptno >= image->numcmpts_) { + return -1; + } + + cmpt = image->cmpts_[cmptno]; + if (x >= cmpt->width_ || y >= cmpt->height_ || + x + width > cmpt->width_ || + y + height > cmpt->height_) { + return -1; + } + + if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) { + return -1; + } + + dr = jas_matrix_getref(data, 0, 0); + drs = jas_matrix_rowstep(data); + for (i = 0; i < height; ++i, dr += drs) { + d = dr; + if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) + * cmpt->cps_, SEEK_SET) < 0) { + return -1; + } + for (j = width; j > 0; --j, ++d) { + v = inttobits(*d, cmpt->prec_, cmpt->sgnd_); + for (k = cmpt->cps_; k > 0; --k) { + c = (v >> (8 * (cmpt->cps_ - 1))) & 0xff; + if (jas_stream_putc(cmpt->stream_, + (unsigned char) c) == EOF) { + return -1; + } + v <<= 8; + } + } + } + + return 0; +} + +/******************************************************************************\ +* File format operations. +\******************************************************************************/ + +void jas_image_clearfmts() +{ + int i; + jas_image_fmtinfo_t *fmtinfo; + for (i = 0; i < jas_image_numfmts; ++i) { + fmtinfo = &jas_image_fmtinfos[i]; + if (fmtinfo->name) { + jas_free(fmtinfo->name); + fmtinfo->name = 0; + } + if (fmtinfo->ext) { + jas_free(fmtinfo->ext); + fmtinfo->ext = 0; + } + if (fmtinfo->desc) { + jas_free(fmtinfo->desc); + fmtinfo->desc = 0; + } + } + jas_image_numfmts = 0; +} + +int jas_image_addfmt(int id, char *name, char *ext, char *desc, + jas_image_fmtops_t *ops) +{ + jas_image_fmtinfo_t *fmtinfo; + assert(id >= 0 && name && ext && ops); + if (jas_image_numfmts >= JAS_IMAGE_MAXFMTS) { + return -1; + } + fmtinfo = &jas_image_fmtinfos[jas_image_numfmts]; + fmtinfo->id = id; + if (!(fmtinfo->name = jas_strdup(name))) { + return -1; + } + if (!(fmtinfo->ext = jas_strdup(ext))) { + jas_free(fmtinfo->name); + return -1; + } + if (!(fmtinfo->desc = jas_strdup(desc))) { + jas_free(fmtinfo->name); + jas_free(fmtinfo->ext); + return -1; + } + fmtinfo->ops = *ops; + ++jas_image_numfmts; + return 0; +} + +int jas_image_strtofmt(char *name) +{ + jas_image_fmtinfo_t *fmtinfo; + if (!(fmtinfo = jas_image_lookupfmtbyname(name))) { + return -1; + } + return fmtinfo->id; +} + +char *jas_image_fmttostr(int fmt) +{ + jas_image_fmtinfo_t *fmtinfo; + if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) { + return 0; + } + return fmtinfo->name; +} + +int jas_image_getfmt(jas_stream_t *in) +{ + jas_image_fmtinfo_t *fmtinfo; + int found; + int i; + + /* Check for data in each of the supported formats. */ + found = 0; + for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, + ++fmtinfo) { + if (fmtinfo->ops.validate) { + /* Is the input data valid for this format? */ + if (!(*fmtinfo->ops.validate)(in)) { + found = 1; + break; + } + } + } + return found ? fmtinfo->id : (-1); +} + +int jas_image_fmtfromname(char *name) +{ + int i; + char *ext; + jas_image_fmtinfo_t *fmtinfo; + /* Get the file name extension. */ + if (!(ext = strrchr(name, '.'))) { + return -1; + } + ++ext; + /* Try to find a format that uses this extension. */ + for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, + ++fmtinfo) { + /* Do we have a match? */ + if (!strcmp(ext, fmtinfo->ext)) { + return fmtinfo->id; + } + } + return -1; +} + +/******************************************************************************\ +* Miscellaneous operations. +\******************************************************************************/ + +uint_fast32_t jas_image_rawsize(jas_image_t *image) +{ + uint_fast32_t rawsize; + int cmptno; + jas_image_cmpt_t *cmpt; + + rawsize = 0; + for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { + cmpt = image->cmpts_[cmptno]; + rawsize += (cmpt->width_ * cmpt->height_ * cmpt->prec_ + + 7) / 8; + } + return rawsize; +} + +void jas_image_delcmpt(jas_image_t *image, int cmptno) +{ + if (cmptno >= image->numcmpts_) { + return; + } + jas_image_cmpt_destroy(image->cmpts_[cmptno]); + if (cmptno < image->numcmpts_) { + memmove(&image->cmpts_[cmptno], &image->cmpts_[cmptno + 1], + (image->numcmpts_ - 1 - cmptno) * sizeof(jas_image_cmpt_t *)); + } + --image->numcmpts_; + + jas_image_setbbox(image); +} + +int jas_image_addcmpt(jas_image_t *image, int cmptno, + jas_image_cmptparm_t *cmptparm) +{ + jas_image_cmpt_t *newcmpt; + if (cmptno < 0) + cmptno = image->numcmpts_; + assert(cmptno >= 0 && cmptno <= image->numcmpts_); + if (image->numcmpts_ >= image->maxcmpts_) { + if (jas_image_growcmpts(image, image->maxcmpts_ + 128)) { + return -1; + } + } + if (!(newcmpt = jas_image_cmpt_create(cmptparm->tlx, + cmptparm->tly, cmptparm->hstep, cmptparm->vstep, + cmptparm->width, cmptparm->height, cmptparm->prec, + cmptparm->sgnd, 1))) { + return -1; + } + if (cmptno < image->numcmpts_) { + memmove(&image->cmpts_[cmptno + 1], &image->cmpts_[cmptno], + (image->numcmpts_ - cmptno) * sizeof(jas_image_cmpt_t *)); + } + image->cmpts_[cmptno] = newcmpt; + ++image->numcmpts_; + + jas_image_setbbox(image); + + return 0; +} + +jas_image_fmtinfo_t *jas_image_lookupfmtbyid(int id) +{ + int i; + jas_image_fmtinfo_t *fmtinfo; + + for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) { + if (fmtinfo->id == id) { + return fmtinfo; + } + } + return 0; +} + +jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name) +{ + int i; + jas_image_fmtinfo_t *fmtinfo; + + for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) { + if (!strcmp(fmtinfo->name, name)) { + return fmtinfo; + } + } + return 0; +} + + + + + +static uint_fast32_t inttobits(jas_seqent_t v, int prec, bool sgnd) +{ + uint_fast32_t ret; + ret = ((sgnd && v < 0) ? ((1 << prec) + v) : v) & JAS_ONES(prec); + return ret; +} + +static jas_seqent_t bitstoint(uint_fast32_t v, int prec, bool sgnd) +{ + jas_seqent_t ret; + v &= JAS_ONES(prec); + ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v; + return ret; +} + +static void jas_image_setbbox(jas_image_t *image) +{ + jas_image_cmpt_t *cmpt; + int cmptno; + int_fast32_t x; + int_fast32_t y; + + if (image->numcmpts_ > 0) { + /* Determine the bounding box for all of the components on the + reference grid (i.e., the image area) */ + cmpt = image->cmpts_[0]; + image->tlx_ = cmpt->tlx_; + image->tly_ = cmpt->tly_; + image->brx_ = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1; + image->bry_ = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1; + for (cmptno = 1; cmptno < image->numcmpts_; ++cmptno) { + cmpt = image->cmpts_[cmptno]; + if (image->tlx_ > cmpt->tlx_) { + image->tlx_ = cmpt->tlx_; + } + if (image->tly_ > cmpt->tly_) { + image->tly_ = cmpt->tly_; + } + x = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1; + if (image->brx_ < x) { + image->brx_ = x; + } + y = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1; + if (image->bry_ < y) { + image->bry_ = y; + } + } + } else { + image->tlx_ = 0; + image->tly_ = 0; + image->brx_ = 0; + image->bry_ = 0; + } +} + +static int jas_image_growcmpts(jas_image_t *image, int maxcmpts) +{ + jas_image_cmpt_t **newcmpts; + int cmptno; + + newcmpts = (!image->cmpts_) ? jas_malloc(maxcmpts * sizeof(jas_image_cmpt_t *)) : + jas_realloc(image->cmpts_, maxcmpts * sizeof(jas_image_cmpt_t *)); + if (!newcmpts) { + return -1; + } + image->cmpts_ = newcmpts; + image->maxcmpts_ = maxcmpts; + for (cmptno = image->numcmpts_; cmptno < image->maxcmpts_; ++cmptno) { + image->cmpts_[cmptno] = 0; + } + return 0; +} + +int jas_image_copycmpt(jas_image_t *dstimage, int dstcmptno, jas_image_t *srcimage, + int srccmptno) +{ + jas_image_cmpt_t *newcmpt; + if (dstimage->numcmpts_ >= dstimage->maxcmpts_) { + if (jas_image_growcmpts(dstimage, dstimage->maxcmpts_ + 128)) { + return -1; + } + } + if (!(newcmpt = jas_image_cmpt_copy(srcimage->cmpts_[srccmptno]))) { + return -1; + } + if (dstcmptno < dstimage->numcmpts_) { + memmove(&dstimage->cmpts_[dstcmptno + 1], &dstimage->cmpts_[dstcmptno], + (dstimage->numcmpts_ - dstcmptno) * sizeof(jas_image_cmpt_t *)); + } + dstimage->cmpts_[dstcmptno] = newcmpt; + ++dstimage->numcmpts_; + + jas_image_setbbox(dstimage); + return 0; +} + +void jas_image_dump(jas_image_t *image, FILE *out) +{ + long buf[1024]; + int cmptno; + int n; + int i; + int width; + int height; + jas_image_cmpt_t *cmpt; + for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { + cmpt = image->cmpts_[cmptno]; + fprintf(out, "prec=%d, sgnd=%d, cmpttype=%d\n", cmpt->prec_, + cmpt->sgnd_, cmpt->type_); + width = jas_image_cmptwidth(image, cmptno); + height = jas_image_cmptheight(image, cmptno); + n = JAS_MIN(16, width); + if (jas_image_readcmpt2(image, cmptno, 0, 0, n, 1, buf)) { + abort(); + } + for (i = 0; i < n; ++i) { + fprintf(out, " f(%d,%d)=%ld", i, 0, buf[i]); + } + fprintf(out, "\n"); + if (jas_image_readcmpt2(image, cmptno, width - n, height - 1, n, 1, buf)) { + abort(); + } + for (i = 0; i < n; ++i) { + fprintf(out, " f(%d,%d)=%ld", width - n + i, height - 1, buf[i]); + } + fprintf(out, "\n"); + } +} + +int jas_image_depalettize(jas_image_t *image, int cmptno, int numlutents, + int_fast32_t *lutents, int dtype, int newcmptno) +{ + jas_image_cmptparm_t cmptparms; + int_fast32_t v; + int i; + int j; + jas_image_cmpt_t *cmpt; + + cmpt = image->cmpts_[cmptno]; + cmptparms.tlx = cmpt->tlx_; + cmptparms.tly = cmpt->tly_; + cmptparms.hstep = cmpt->hstep_; + cmptparms.vstep = cmpt->vstep_; + cmptparms.width = cmpt->width_; + cmptparms.height = cmpt->height_; + cmptparms.prec = JAS_IMAGE_CDT_GETPREC(dtype); + cmptparms.sgnd = JAS_IMAGE_CDT_GETSGND(dtype); + + if (jas_image_addcmpt(image, newcmptno, &cmptparms)) { + return -1; + } + if (newcmptno <= cmptno) { + ++cmptno; + cmpt = image->cmpts_[cmptno]; + } + + for (j = 0; j < cmpt->height_; ++j) { + for (i = 0; i < cmpt->width_; ++i) { + v = jas_image_readcmptsample(image, cmptno, i, j); + if (v < 0) { + v = 0; + } else if (v >= numlutents) { + v = numlutents - 1; + } + jas_image_writecmptsample(image, newcmptno, i, j, + lutents[v]); + } + } + return 0; +} + +int jas_image_readcmptsample(jas_image_t *image, int cmptno, int x, int y) +{ + jas_image_cmpt_t *cmpt; + uint_fast32_t v; + int k; + int c; + + cmpt = image->cmpts_[cmptno]; + + if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_, + SEEK_SET) < 0) { + return -1; + } + v = 0; + for (k = cmpt->cps_; k > 0; --k) { + if ((c = jas_stream_getc(cmpt->stream_)) == EOF) { + return -1; + } + v = (v << 8) | (c & 0xff); + } + return bitstoint(v, cmpt->prec_, cmpt->sgnd_); +} + +void jas_image_writecmptsample(jas_image_t *image, int cmptno, int x, int y, + int_fast32_t v) +{ + jas_image_cmpt_t *cmpt; + uint_fast32_t t; + int k; + int c; + + cmpt = image->cmpts_[cmptno]; + + if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_, + SEEK_SET) < 0) { + return; + } + t = inttobits(v, cmpt->prec_, cmpt->sgnd_); + for (k = cmpt->cps_; k > 0; --k) { + c = (t >> (8 * (cmpt->cps_ - 1))) & 0xff; + if (jas_stream_putc(cmpt->stream_, (unsigned char) c) == EOF) { + return; + } + t <<= 8; + } +} + +int jas_image_getcmptbytype(jas_image_t *image, int ctype) +{ + int cmptno; + + for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { + if (image->cmpts_[cmptno]->type_ == ctype) { + return cmptno; + } + } + return -1; +} + + + + + + + + + + + + + + + + +/***********************************************/ +/***********************************************/ +/***********************************************/ +/***********************************************/ + +int jas_image_readcmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x, + jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, + long *buf) +{ + jas_image_cmpt_t *cmpt; + jas_image_coord_t i; + jas_image_coord_t j; + long v; + long *bufptr; + + if (cmptno < 0 || cmptno >= image->numcmpts_) + goto error; + cmpt = image->cmpts_[cmptno]; + if (x < 0 || x >= cmpt->width_ || y < 0 || y >= cmpt->height_ || + width < 0 || height < 0 || x + width > cmpt->width_ || + y + height > cmpt->height_) + goto error; + + bufptr = buf; + for (i = 0; i < height; ++i) { + if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) + * cmpt->cps_, SEEK_SET) < 0) + goto error; + for (j = 0; j < width; ++j) { + if (getint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, &v)) + goto error; + *bufptr++ = v; + } + } + + return 0; +error: + return -1; +} + +int jas_image_writecmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x, + jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, + long *buf) +{ + jas_image_cmpt_t *cmpt; + jas_image_coord_t i; + jas_image_coord_t j; + long v; + long *bufptr; + + if (cmptno < 0 || cmptno >= image->numcmpts_) + goto error; + cmpt = image->cmpts_[cmptno]; + if (x < 0 || x >= cmpt->width_ || y < 0 || y >= cmpt->height_ || + width < 0 || height < 0 || x + width > cmpt->width_ || + y + height > cmpt->height_) + goto error; + + bufptr = buf; + for (i = 0; i < height; ++i) { + if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) + * cmpt->cps_, SEEK_SET) < 0) + goto error; + for (j = 0; j < width; ++j) { + v = *bufptr++; + if (putint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, v)) + goto error; + } + } + + return 0; +error: + return -1; +} + +int jas_image_sampcmpt(jas_image_t *image, int cmptno, int newcmptno, + jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs, + jas_image_coord_t vs, int sgnd, int prec) +{ + jas_image_cmpt_t *oldcmpt; + jas_image_cmpt_t *newcmpt; + int width; + int height; + jas_image_coord_t tlx; + jas_image_coord_t tly; + jas_image_coord_t brx; + jas_image_coord_t bry; + int i; + int j; + jas_image_cmptparm_t cmptparm; + jas_image_coord_t ax; + jas_image_coord_t ay; + jas_image_coord_t bx; + jas_image_coord_t by; + jas_image_coord_t d0; + jas_image_coord_t d1; + jas_image_coord_t d2; + jas_image_coord_t d3; + jas_image_coord_t oldx; + jas_image_coord_t oldy; + jas_image_coord_t x; + jas_image_coord_t y; + long v; + jas_image_coord_t cmptbrx; + jas_image_coord_t cmptbry; + + assert(cmptno >= 0 && cmptno < image->numcmpts_); + oldcmpt = image->cmpts_[cmptno]; + assert(oldcmpt->tlx_ == 0 && oldcmpt->tly_ == 0); + jas_image_calcbbox2(image, &tlx, &tly, &brx, &bry); + width = FLOORDIV(brx - ho + hs, hs); + height = FLOORDIV(bry - vo + vs, vs); + cmptparm.tlx = ho; + cmptparm.tly = vo; + cmptparm.hstep = hs; + cmptparm.vstep = vs; + cmptparm.width = width; + cmptparm.height = height; + cmptparm.prec = prec; + cmptparm.sgnd = sgnd; + if (jas_image_addcmpt(image, newcmptno, &cmptparm)) + goto error; +cmptbrx = oldcmpt->tlx_ + (oldcmpt->width_ - 1) * oldcmpt->hstep_; +cmptbry = oldcmpt->tly_ + (oldcmpt->height_ - 1) * oldcmpt->vstep_; + newcmpt = image->cmpts_[newcmptno]; + jas_stream_rewind(newcmpt->stream_); + for (i = 0; i < height; ++i) { + y = newcmpt->tly_ + newcmpt->vstep_ * i; + for (j = 0; j < width; ++j) { + x = newcmpt->tlx_ + newcmpt->hstep_ * j; + ax = downtomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_; + ay = downtomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_; + bx = uptomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_; + if (bx > cmptbrx) + bx = cmptbrx; + by = uptomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_; + if (by > cmptbry) + by = cmptbry; + d0 = (ax - x) * (ax - x) + (ay - y) * (ay - y); + d1 = (bx - x) * (bx - x) + (ay - y) * (ay - y); + d2 = (bx - x) * (bx - x) + (by - y) * (by - y); + d3 = (ax - x) * (ax - x) + (by - y) * (by - y); + if (d0 <= d1 && d0 <= d2 && d0 <= d3) { + oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_; + } else if (d1 <= d0 && d1 <= d2 && d1 <= d3) { + oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_; + } else if (d2 <= d0 && d2 <= d1 && d1 <= d3) { + oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_; + } else { + oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_; + } + assert(oldx >= 0 && oldx < oldcmpt->width_ && + oldy >= 0 && oldy < oldcmpt->height_); + if (jas_stream_seek(oldcmpt->stream_, oldcmpt->cps_ * + (oldy * oldcmpt->width_ + oldx), SEEK_SET) < 0) + goto error; + if (getint(oldcmpt->stream_, oldcmpt->sgnd_, + oldcmpt->prec_, &v)) + goto error; + if (newcmpt->prec_ != oldcmpt->prec_ || + newcmpt->sgnd_ != oldcmpt->sgnd_) { + v = convert(v, oldcmpt->sgnd_, oldcmpt->prec_, + newcmpt->sgnd_, newcmpt->prec_); + } + if (putint(newcmpt->stream_, newcmpt->sgnd_, + newcmpt->prec_, v)) + goto error; + } + } + return 0; +error: + return -1; +} + +int jas_image_ishomosamp(jas_image_t *image) +{ + jas_image_coord_t hstep; + jas_image_coord_t vstep; + int result; + int i; + hstep = jas_image_cmpthstep(image, 0); + vstep = jas_image_cmptvstep(image, 0); + result = 1; + for (i = 0; i < image->numcmpts_; ++i) { + if (jas_image_cmpthstep(image, i) != hstep || + jas_image_cmptvstep(image, i) != vstep) { + result = 0; + break; + } + } + return result; +} + +/* Note: This function defines a bounding box differently. */ +static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx, + jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry) +{ + jas_image_cmpt_t *cmpt; + jas_image_coord_t tmptlx; + jas_image_coord_t tmptly; + jas_image_coord_t tmpbrx; + jas_image_coord_t tmpbry; + jas_image_coord_t t; + int i; + if (image->numcmpts_ > 0) { + cmpt = image->cmpts_[0]; + tmptlx = cmpt->tlx_; + tmptly = cmpt->tly_; + tmpbrx = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1); + tmpbry = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1); + for (i = 0; i < image->numcmpts_; ++i) { + cmpt = image->cmpts_[i]; + if (cmpt->tlx_ < tmptlx) + tmptlx = cmpt->tlx_; + if (cmpt->tly_ < tmptly) + tmptly = cmpt->tly_; + t = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1); + if (t > tmpbrx) + tmpbrx = t; + t = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1); + if (t > tmpbry) + tmpbry = t; + } + } else { + tmptlx = 0; + tmptly = 0; + tmpbrx = -1; + tmpbry = -1; + } + *tlx = tmptlx; + *tly = tmptly; + *brx = tmpbrx; + *bry = tmpbry; +} + + + +static int getint(jas_stream_t *in, int sgnd, int prec, long *val) +{ + long v; + int n; + int c; + n = (prec + 7) / 8; + v = 0; + while (--n >= 0) { + if ((c = jas_stream_getc(in)) == EOF) + return -1; + v = (v << 8) | c; + } + v &= ((1 << prec) - 1); + if (sgnd) { + /* XXX - Do something here. */ + abort(); + } else { + *val = v; + } + return 0; +} + +static int putint(jas_stream_t *out, int sgnd, int prec, long val) +{ + int n; + int c; + if (sgnd) { + /* XXX - Do something here. */ + abort(); + } + val &= (1 << prec) - 1; + n = (prec + 7) / 8; + while (--n >= 0) { + c = (val >> (n * 8)) & 0xff; + if (jas_stream_putc(out, c) != c) + return -1; + } + return 0; +} + +static long convert(long val, int oldsgnd, int oldprec, int newsgnd, + int newprec) +{ + if (newsgnd != oldsgnd) { + } + if (newprec != oldprec) { + if (newprec > oldprec) { + val <<= newprec - oldprec; + } else if (oldprec > newprec) { + val >>= oldprec - newprec; + } + } + return val; +} + +static long downtomult(long x, long y) +{ + assert(x >= 0); + return (x / y) * y; +} + +static long uptomult(long x, long y) +{ + assert(x >= 0); + return ((x + y - 1) / y) * y; +} + +jas_image_t *jas_image_chclrspc(jas_image_t *image, jas_cmprof_t *outprof, + int intent) +{ + jas_image_t *inimage; + int minhstep; + int minvstep; + int i; + int j; + int k; + int n; + int hstep; + int vstep; + int numinauxchans; + int numoutauxchans; + int numinclrchans; + int numoutclrchans; + int prec; + jas_image_t *outimage; + int cmpttype; + int numoutchans; + jas_cmprof_t *inprof; + jas_cmprof_t *tmpprof; + jas_image_cmptparm_t cmptparm; + int width; + int height; + jas_cmxform_t *xform; + jas_cmpixmap_t inpixmap; + jas_cmpixmap_t outpixmap; + jas_cmcmptfmt_t *incmptfmts; + jas_cmcmptfmt_t *outcmptfmts; + +#if 0 +fprintf(stderr, "IMAGE\n"); +jas_image_dump(image, stderr); +#endif + + if (!(inimage = jas_image_copy(image))) + goto error; + image = 0; + + if (!jas_image_ishomosamp(inimage)) { + minhstep = jas_image_cmpthstep(inimage, 0); + minvstep = jas_image_cmptvstep(inimage, 0); + for (i = 1; i < jas_image_numcmpts(inimage); ++i) { + hstep = jas_image_cmpthstep(inimage, i); + vstep = jas_image_cmptvstep(inimage, i); + if (hstep < minhstep) + minhstep = hstep; + if (vstep < minvstep) + minvstep = vstep; + } + n = jas_image_numcmpts(inimage); + for (i = 0; i < n; ++i) { + cmpttype = jas_image_cmpttype(inimage, i); + if (jas_image_sampcmpt(inimage, i, i + 1, 0, 0, minhstep, minvstep, jas_image_cmptsgnd(inimage, i), jas_image_cmptprec(inimage, i))) + goto error; + jas_image_setcmpttype(inimage, i + 1, cmpttype); + jas_image_delcmpt(inimage, i); + } + } + + width = jas_image_cmptwidth(inimage, 0); + height = jas_image_cmptheight(inimage, 0); + hstep = jas_image_cmpthstep(inimage, 0); + vstep = jas_image_cmptvstep(inimage, 0); + + inprof = jas_image_cmprof(inimage); + assert(inprof); + numinclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(inprof)); + numinauxchans = jas_image_numcmpts(inimage) - numinclrchans; + numoutclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(outprof)); + numoutauxchans = 0; + numoutchans = numoutclrchans + numoutauxchans; + prec = 8; + + if (!(outimage = jas_image_create0())) + goto error; + + /* Create a component for each of the colorants. */ + for (i = 0; i < numoutclrchans; ++i) { + cmptparm.tlx = 0; + cmptparm.tly = 0; + cmptparm.hstep = hstep; + cmptparm.vstep = vstep; + cmptparm.width = width; + cmptparm.height = height; + cmptparm.prec = prec; + cmptparm.sgnd = 0; + if (jas_image_addcmpt(outimage, -1, &cmptparm)) + goto error; + jas_image_setcmpttype(outimage, i, JAS_IMAGE_CT_COLOR(i)); + } +#if 0 + /* Copy the auxiliary components without modification. */ + for (i = 0; i < jas_image_numcmpts(inimage); ++i) { + if (!ISCOLOR(jas_image_cmpttype(inimage, i))) { + jas_image_copycmpt(outimage, -1, inimage, i); +/* XXX - need to specify laydown of component on ref. grid */ + } + } +#endif + + if (!(tmpprof = jas_cmprof_copy(outprof))) + goto error; + assert(!jas_image_cmprof(outimage)); + jas_image_setcmprof(outimage, tmpprof); + tmpprof = 0; + jas_image_setclrspc(outimage, jas_cmprof_clrspc(outprof)); + + if (!(xform = jas_cmxform_create(inprof, outprof, 0, JAS_CMXFORM_OP_FWD, intent, 0))) + goto error; + + inpixmap.numcmpts = numinclrchans; + incmptfmts = malloc(numinclrchans * sizeof(jas_cmcmptfmt_t)); + assert(incmptfmts); + inpixmap.cmptfmts = incmptfmts; + for (i = 0; i < numinclrchans; ++i) { + j = jas_image_getcmptbytype(inimage, JAS_IMAGE_CT_COLOR(i)); + assert(j >= 0); + if (!(incmptfmts[i].buf = malloc(width * sizeof(long)))) + goto error; + incmptfmts[i].prec = jas_image_cmptprec(inimage, j); + incmptfmts[i].sgnd = jas_image_cmptsgnd(inimage, j); + incmptfmts[i].width = width; + incmptfmts[i].height = 1; + } + + outpixmap.numcmpts = numoutclrchans; + outcmptfmts = malloc(numoutclrchans * sizeof(jas_cmcmptfmt_t)); + assert(outcmptfmts); + outpixmap.cmptfmts = outcmptfmts; + + for (i = 0; i < numoutclrchans; ++i) { + j = jas_image_getcmptbytype(outimage, JAS_IMAGE_CT_COLOR(i)); + assert(j >= 0); + if (!(outcmptfmts[i].buf = malloc(width * sizeof(long)))) + goto error; + outcmptfmts[i].prec = jas_image_cmptprec(outimage, j); + outcmptfmts[i].sgnd = jas_image_cmptsgnd(outimage, j); + outcmptfmts[i].width = width; + outcmptfmts[i].height = 1; + } + + for (i = 0; i < height; ++i) { + for (j = 0; j < numinclrchans; ++j) { + k = jas_image_getcmptbytype(inimage, JAS_IMAGE_CT_COLOR(j)); + if (jas_image_readcmpt2(inimage, k, 0, i, width, 1, incmptfmts[j].buf)) + goto error; + } + jas_cmxform_apply(xform, &inpixmap, &outpixmap); + for (j = 0; j < numoutclrchans; ++j) { + k = jas_image_getcmptbytype(outimage, JAS_IMAGE_CT_COLOR(j)); + if (jas_image_writecmpt2(outimage, k, 0, i, width, 1, outcmptfmts[j].buf)) + goto error; + } + } + + for (i = 0; i < numoutclrchans; ++i) + jas_free(outcmptfmts[i].buf); + jas_free(outcmptfmts); + for (i = 0; i < numinclrchans; ++i) + jas_free(incmptfmts[i].buf); + jas_free(incmptfmts); + jas_cmxform_destroy(xform); + jas_image_destroy(inimage); + +#if 0 +fprintf(stderr, "INIMAGE\n"); +jas_image_dump(inimage, stderr); +fprintf(stderr, "OUTIMAGE\n"); +jas_image_dump(outimage, stderr); +#endif + return outimage; +error: + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_init.c b/SlnkDWFImpl/CxImage/jasper/base/jas_init.c new file mode 100644 index 0000000..d6738c2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_init.c @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" +#include "jasper/jas_image.h" +#include "jasper/jas_init.h" + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +/* Initialize the image format table. */ +int jas_init() +{ + jas_image_fmtops_t fmtops; + int fmtid; + + fmtid = 0; + +#if !defined(EXCLUDE_MIF_SUPPORT) + fmtops.decode = mif_decode; + fmtops.encode = mif_encode; + fmtops.validate = mif_validate; + jas_image_addfmt(fmtid, "mif", "mif", "My Image Format (MIF)", &fmtops); + ++fmtid; +#endif + +#if !defined(EXCLUDE_PNM_SUPPORT) + fmtops.decode = pnm_decode; + fmtops.encode = pnm_encode; + fmtops.validate = pnm_validate; + jas_image_addfmt(fmtid, "pnm", "pnm", "Portable Graymap/Pixmap (PNM)", + &fmtops); + jas_image_addfmt(fmtid, "pnm", "pgm", "Portable Graymap/Pixmap (PNM)", + &fmtops); + jas_image_addfmt(fmtid, "pnm", "ppm", "Portable Graymap/Pixmap (PNM)", + &fmtops); + ++fmtid; +#endif + +#if !defined(EXCLUDE_BMP_SUPPORT) + fmtops.decode = bmp_decode; + fmtops.encode = bmp_encode; + fmtops.validate = bmp_validate; + jas_image_addfmt(fmtid, "bmp", "bmp", "Microsoft Bitmap (BMP)", &fmtops); + ++fmtid; +#endif + +#if !defined(EXCLUDE_RAS_SUPPORT) + fmtops.decode = ras_decode; + fmtops.encode = ras_encode; + fmtops.validate = ras_validate; + jas_image_addfmt(fmtid, "ras", "ras", "Sun Rasterfile (RAS)", &fmtops); + ++fmtid; +#endif + +#if !defined(EXCLUDE_JP2_SUPPORT) + fmtops.decode = jp2_decode; + fmtops.encode = jp2_encode; + fmtops.validate = jp2_validate; + jas_image_addfmt(fmtid, "jp2", "jp2", + "JPEG-2000 JP2 File Format Syntax (ISO/IEC 15444-1)", &fmtops); + ++fmtid; + fmtops.decode = jpc_decode; + fmtops.encode = jpc_encode; + fmtops.validate = jpc_validate; + jas_image_addfmt(fmtid, "jpc", "jpc", + "JPEG-2000 Code Stream Syntax (ISO/IEC 15444-1)", &fmtops); + ++fmtid; +#endif + +#if !defined(EXCLUDE_JPG_SUPPORT) + fmtops.decode = jpg_decode; + fmtops.encode = jpg_encode; + fmtops.validate = jpg_validate; + jas_image_addfmt(fmtid, "jpg", "jpg", "JPEG (ISO/IEC 10918-1)", &fmtops); + ++fmtid; +#endif + +#if !defined(EXCLUDE_PGX_SUPPORT) + fmtops.decode = pgx_decode; + fmtops.encode = pgx_encode; + fmtops.validate = pgx_validate; + jas_image_addfmt(fmtid, "pgx", "pgx", "JPEG-2000 VM Format (PGX)", &fmtops); + ++fmtid; +#endif + + /* We must not register the JasPer library exit handler until after + at least one memory allocation is performed. This is desirable + as it ensures that the JasPer exit handler is called before the + debug memory allocator exit handler. */ + atexit(jas_cleanup); + + return 0; +} + +void jas_cleanup() +{ + jas_image_clearfmts(); +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_malloc.c b/SlnkDWFImpl/CxImage/jasper/base/jas_malloc.c new file mode 100644 index 0000000..1d6d1db --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_malloc.c @@ -0,0 +1,167 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Memory Allocator + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +/* We need the prototype for memset. */ +#include + +#include "jasper/jas_malloc.h" + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +#if defined(DEBUG_MEMALLOC) +#include "../../../local/src/memalloc.c" +#endif + +#if !defined(DEBUG_MEMALLOC) + +void *jas_malloc(size_t size) +{ + return malloc(size); +} + +void jas_free(void *ptr) +{ + free(ptr); +} + +void *jas_realloc(void *ptr, size_t size) +{ + return realloc(ptr, size); +} + +void *jas_calloc(size_t nmemb, size_t size) +{ + void *ptr; + size_t n; + n = nmemb * size; + if (!(ptr = jas_malloc(n * sizeof(char)))) { + return 0; + } + memset(ptr, 0, n); + return ptr; +} + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_seq.c b/SlnkDWFImpl/CxImage/jasper/base/jas_seq.c new file mode 100644 index 0000000..1093551 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_seq.c @@ -0,0 +1,477 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Sequence/Matrix Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_seq.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" + +/******************************************************************************\ +* Constructors and destructors. +\******************************************************************************/ + +jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend) +{ + jas_matrix_t *matrix; + assert(xstart <= xend && ystart <= yend); + if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) { + return 0; + } + matrix->xstart_ = xstart; + matrix->ystart_ = ystart; + matrix->xend_ = xend; + matrix->yend_ = yend; + return matrix; +} + +jas_matrix_t *jas_matrix_create(int numrows, int numcols) +{ + jas_matrix_t *matrix; + int i; + + if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { + return 0; + } + matrix->flags_ = 0; + matrix->numrows_ = numrows; + matrix->numcols_ = numcols; + matrix->rows_ = 0; + matrix->maxrows_ = numrows; + matrix->data_ = 0; + matrix->datasize_ = numrows * numcols; + + if (matrix->maxrows_ > 0) { + if (!(matrix->rows_ = jas_malloc(matrix->maxrows_ * + sizeof(jas_seqent_t *)))) { + jas_matrix_destroy(matrix); + return 0; + } + } + + if (matrix->datasize_ > 0) { + if (!(matrix->data_ = jas_malloc(matrix->datasize_ * + sizeof(jas_seqent_t)))) { + jas_matrix_destroy(matrix); + return 0; + } + } + + for (i = 0; i < numrows; ++i) { + matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; + } + + for (i = 0; i < matrix->datasize_; ++i) { + matrix->data_[i] = 0; + } + + matrix->xstart_ = 0; + matrix->ystart_ = 0; + matrix->xend_ = matrix->numcols_; + matrix->yend_ = matrix->numrows_; + + return matrix; +} + +void jas_matrix_destroy(jas_matrix_t *matrix) +{ + if (matrix->data_) { + assert(!(matrix->flags_ & JAS_MATRIX_REF)); + jas_free(matrix->data_); + matrix->data_ = 0; + } + if (matrix->rows_) { + jas_free(matrix->rows_); + matrix->rows_ = 0; + } + jas_free(matrix); +} + +jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x) +{ + jas_matrix_t *y; + int i; + int j; + y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x), + jas_seq2d_yend(x)); + assert(y); + for (i = 0; i < x->numrows_; ++i) { + for (j = 0; j < x->numcols_; ++j) { + *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); + } + } + return y; +} + +jas_matrix_t *jas_matrix_copy(jas_matrix_t *x) +{ + jas_matrix_t *y; + int i; + int j; + y = jas_matrix_create(x->numrows_, x->numcols_); + for (i = 0; i < x->numrows_; ++i) { + for (j = 0; j < x->numcols_; ++j) { + *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); + } + } + return y; +} + +/******************************************************************************\ +* Bind operations. +\******************************************************************************/ + +void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart, int ystart, + int xend, int yend) +{ + jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_, + yend - s1->ystart_ - 1, xend - s1->xstart_ - 1); +} + +void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0, + int r1, int c1) +{ + int i; + + if (mat0->data_) { + if (!(mat0->flags_ & JAS_MATRIX_REF)) { + jas_free(mat0->data_); + } + mat0->data_ = 0; + mat0->datasize_ = 0; + } + if (mat0->rows_) { + jas_free(mat0->rows_); + mat0->rows_ = 0; + } + mat0->flags_ |= JAS_MATRIX_REF; + mat0->numrows_ = r1 - r0 + 1; + mat0->numcols_ = c1 - c0 + 1; + mat0->maxrows_ = mat0->numrows_; + mat0->rows_ = jas_malloc(mat0->maxrows_ * sizeof(jas_seqent_t *)); + for (i = 0; i < mat0->numrows_; ++i) { + mat0->rows_[i] = mat1->rows_[r0 + i] + c0; + } + + mat0->xstart_ = mat1->xstart_ + c0; + mat0->ystart_ = mat1->ystart_ + r0; + mat0->xend_ = mat0->xstart_ + mat0->numcols_; + mat0->yend_ = mat0->ystart_ + mat0->numrows_; +} + +/******************************************************************************\ +* Arithmetic operations. +\******************************************************************************/ + +int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1) +{ + int i; + int j; + + if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ != + mat1->numcols_) { + return 1; + } + for (i = 0; i < mat0->numrows_; i++) { + for (j = 0; j < mat0->numcols_; j++) { + if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) { + return 1; + } + } + } + return 0; +} + +void jas_matrix_divpow2(jas_matrix_t *matrix, int n) +{ + int i; + int j; + jas_seqent_t *rowstart; + int rowstep; + jas_seqent_t *data; + + rowstep = jas_matrix_rowstep(matrix); + for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, + rowstart += rowstep) { + for (j = matrix->numcols_, data = rowstart; j > 0; --j, + ++data) { + *data = (*data >= 0) ? ((*data) >> n) : + (-((-(*data)) >> n)); + } + } +} + +void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval, jas_seqent_t maxval) +{ + int i; + int j; + jas_seqent_t v; + jas_seqent_t *rowstart; + jas_seqent_t *data; + int rowstep; + + rowstep = jas_matrix_rowstep(matrix); + for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, + rowstart += rowstep) { + data = rowstart; + for (j = matrix->numcols_, data = rowstart; j > 0; --j, + ++data) { + v = *data; + if (v < minval) { + *data = minval; + } else if (v > maxval) { + *data = maxval; + } + } + } +} + +void jas_matrix_asr(jas_matrix_t *matrix, int n) +{ + int i; + int j; + jas_seqent_t *rowstart; + int rowstep; + jas_seqent_t *data; + + assert(n >= 0); + rowstep = jas_matrix_rowstep(matrix); + for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, + rowstart += rowstep) { + for (j = matrix->numcols_, data = rowstart; j > 0; --j, + ++data) { + *data >>= n; + } + } +} + +void jas_matrix_asl(jas_matrix_t *matrix, int n) +{ + int i; + int j; + jas_seqent_t *rowstart; + int rowstep; + jas_seqent_t *data; + + rowstep = jas_matrix_rowstep(matrix); + for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, + rowstart += rowstep) { + for (j = matrix->numcols_, data = rowstart; j > 0; --j, + ++data) { + *data <<= n; + } + } +} + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols) +{ + int size; + int i; + + size = numrows * numcols; + if (size > matrix->datasize_ || numrows > matrix->maxrows_) { + return -1; + } + + matrix->numrows_ = numrows; + matrix->numcols_ = numcols; + + for (i = 0; i < numrows; ++i) { + matrix->rows_[i] = &matrix->data_[numcols * i]; + } + + return 0; +} + +int jas_matrix_output(jas_matrix_t *matrix, FILE *out) +{ + int i; + int j; + jas_seqent_t x; + + fprintf(out, "%d %d\n", jas_matrix_numrows(matrix), jas_matrix_numcols(matrix)); + for (i = 0; i < jas_matrix_numrows(matrix); ++i) { + for (j = 0; j < jas_matrix_numcols(matrix); ++j) { + x = jas_matrix_get(matrix, i, j); + fprintf(out, "%ld", JAS_CAST(long, x)); + if (j < jas_matrix_numcols(matrix) - 1) { + fprintf(out, " "); + } + } + fprintf(out, "\n"); + } + return 0; +} + +void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val) +{ + int i; + int j; + jas_seqent_t *rowstart; + int rowstep; + jas_seqent_t *data; + + rowstep = jas_matrix_rowstep(matrix); + for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, + rowstart += rowstep) { + for (j = matrix->numcols_, data = rowstart; j > 0; --j, + ++data) { + *data = val; + } + } +} + +#if 0 +jas_matrix_t *jas_matrix_input(FILE *in) +{ + jas_matrix_t *matrix; + int i; + int j; + long x; + int numrows; + int numcols; + + if (fscanf(in, "%d %d", &numrows, &numcols) != 2) + return 0; + if (!(matrix = jas_matrix_create(numrows, numcols))) + return 0; + + /* Get matrix data. */ + for (i = 0; i < jas_matrix_numrows(matrix); i++) { + for (j = 0; j < jas_matrix_numcols(matrix); j++) { + if (fscanf(in, "%ld", &x) != 1) { + jas_matrix_destroy(matrix); + return 0; + } + jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x)); + } + } + + return matrix; +} +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_stream.c b/SlnkDWFImpl/CxImage/jasper/base/jas_stream.c new file mode 100644 index 0000000..1641b2e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_stream.c @@ -0,0 +1,1197 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * I/O Stream Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include +#include +#include +#if defined(HAVE_UNISTD_H) +#include +#endif +#if defined(WIN32) || defined(HAVE_IO_H) +#include +#endif + +#include "jasper/jas_types.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" + +/******************************************************************************\ +* Local function prototypes. +\******************************************************************************/ + +static int jas_strtoopenmode(const char *s); +static void jas_stream_destroy(jas_stream_t *stream); +static jas_stream_t *jas_stream_create(void); +static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, + int bufsize); + +static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt); +static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt); +static long mem_seek(jas_stream_obj_t *obj, long offset, int origin); +static int mem_close(jas_stream_obj_t *obj); + +static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt); +static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt); +static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin); +static int sfile_close(jas_stream_obj_t *obj); + +static int file_read(jas_stream_obj_t *obj, char *buf, int cnt); +static int file_write(jas_stream_obj_t *obj, char *buf, int cnt); +static long file_seek(jas_stream_obj_t *obj, long offset, int origin); +static int file_close(jas_stream_obj_t *obj); + +/******************************************************************************\ +* Local data. +\******************************************************************************/ + +static jas_stream_ops_t jas_stream_fileops = { + file_read, + file_write, + file_seek, + file_close +}; + +static jas_stream_ops_t jas_stream_sfileops = { + sfile_read, + sfile_write, + sfile_seek, + sfile_close +}; + +static jas_stream_ops_t jas_stream_memops = { + mem_read, + mem_write, + mem_seek, + mem_close +}; + +/******************************************************************************\ +* Code for opening and closing streams. +\******************************************************************************/ + +static jas_stream_t *jas_stream_create() +{ + jas_stream_t *stream; + + if (!(stream = jas_malloc(sizeof(jas_stream_t)))) { + return 0; + } + stream->openmode_ = 0; + stream->bufmode_ = 0; + stream->flags_ = 0; + stream->bufbase_ = 0; + stream->bufstart_ = 0; + stream->bufsize_ = 0; + stream->ptr_ = 0; + stream->cnt_ = 0; + stream->ops_ = 0; + stream->obj_ = 0; + stream->rwcnt_ = 0; + stream->rwlimit_ = -1; + + return stream; +} + +jas_stream_t *jas_stream_memopen(char *buf, int bufsize) +{ + jas_stream_t *stream; + jas_stream_memobj_t *obj; + + if (!(stream = jas_stream_create())) { + return 0; + } + + /* A stream associated with a memory buffer is always opened + for both reading and writing in binary mode. */ + stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; + + /* Since the stream data is already resident in memory, buffering + is not necessary. */ + /* But... It still may be faster to use buffering anyways. */ + jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); + + /* Select the operations for a memory stream. */ + stream->ops_ = &jas_stream_memops; + + /* Allocate memory for the underlying memory stream object. */ + if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) { + jas_stream_destroy(stream); + return 0; + } + stream->obj_ = (void *) obj; + + /* Initialize a few important members of the memory stream object. */ + obj->myalloc_ = 0; + obj->buf_ = 0; + + /* If the buffer size specified is nonpositive, then the buffer + is allocated internally and automatically grown as needed. */ + if (bufsize <= 0) { + obj->bufsize_ = 1024; + obj->growable_ = 1; + } else { + obj->bufsize_ = bufsize; + obj->growable_ = 0; + } + if (buf) { + obj->buf_ = (unsigned char *) buf; + } else { + obj->buf_ = jas_malloc(obj->bufsize_ * sizeof(char)); + obj->myalloc_ = 1; + } + if (!obj->buf_) { + jas_stream_close(stream); + return 0; + } + + if (bufsize > 0 && buf) { + /* If a buffer was supplied by the caller and its length is positive, + make the associated buffer data appear in the stream initially. */ + obj->len_ = bufsize; + } else { + /* The stream is initially empty. */ + obj->len_ = 0; + } + obj->pos_ = 0; + + return stream; +} + +jas_stream_t *jas_stream_fopen(const char *filename, const char *mode) +{ + jas_stream_t *stream; + jas_stream_fileobj_t *obj; + int openflags; + + /* Allocate a stream object. */ + if (!(stream = jas_stream_create())) { + return 0; + } + + /* Parse the mode string. */ + stream->openmode_ = jas_strtoopenmode(mode); + + /* Determine the correct flags to use for opening the file. */ + if ((stream->openmode_ & JAS_STREAM_READ) && + (stream->openmode_ & JAS_STREAM_WRITE)) { + openflags = O_RDWR; + } else if (stream->openmode_ & JAS_STREAM_READ) { + openflags = O_RDONLY; + } else if (stream->openmode_ & JAS_STREAM_WRITE) { + openflags = O_WRONLY; + } else { + openflags = 0; + } + if (stream->openmode_ & JAS_STREAM_APPEND) { + openflags |= O_APPEND; + } + if (stream->openmode_ & JAS_STREAM_BINARY) { + openflags |= O_BINARY; + } + if (stream->openmode_ & JAS_STREAM_CREATE) { + openflags |= O_CREAT | O_TRUNC; + } + + /* Allocate space for the underlying file stream object. */ + if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { + jas_stream_destroy(stream); + return 0; + } + obj->fd = -1; + obj->flags = 0; + obj->pathname[0] = '\0'; + stream->obj_ = (void *) obj; + + /* Select the operations for a file stream object. */ + stream->ops_ = &jas_stream_fileops; + + /* Open the underlying file. */ + if ((obj->fd = open(filename, openflags, JAS_STREAM_PERMS)) < 0) { + jas_stream_destroy(stream); + return 0; + } + + /* By default, use full buffering for this type of stream. */ + jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); + + return stream; +} + +jas_stream_t *jas_stream_freopen(const char *path, const char *mode, FILE *fp) +{ + jas_stream_t *stream; + int openflags; + + /* Eliminate compiler warning about unused variable. */ + path = 0; + + /* Allocate a stream object. */ + if (!(stream = jas_stream_create())) { + return 0; + } + + /* Parse the mode string. */ + stream->openmode_ = jas_strtoopenmode(mode); + + /* Determine the correct flags to use for opening the file. */ + if ((stream->openmode_ & JAS_STREAM_READ) && + (stream->openmode_ & JAS_STREAM_WRITE)) { + openflags = O_RDWR; + } else if (stream->openmode_ & JAS_STREAM_READ) { + openflags = O_RDONLY; + } else if (stream->openmode_ & JAS_STREAM_WRITE) { + openflags = O_WRONLY; + } else { + openflags = 0; + } + if (stream->openmode_ & JAS_STREAM_APPEND) { + openflags |= O_APPEND; + } + if (stream->openmode_ & JAS_STREAM_BINARY) { + openflags |= O_BINARY; + } + if (stream->openmode_ & JAS_STREAM_CREATE) { + openflags |= O_CREAT | O_TRUNC; + } + + stream->obj_ = JAS_CAST(void *, fp); + + /* Select the operations for a file stream object. */ + stream->ops_ = &jas_stream_sfileops; + + /* By default, use full buffering for this type of stream. */ + jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); + + return stream; +} + +jas_stream_t *jas_stream_tmpfile() +{ + jas_stream_t *stream; + jas_stream_fileobj_t *obj; + + if (!(stream = jas_stream_create())) { + return 0; + } + + /* A temporary file stream is always opened for both reading and + writing in binary mode. */ + stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; + + /* Allocate memory for the underlying temporary file object. */ + if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { + jas_stream_destroy(stream); + return 0; + } + obj->fd = -1; + obj->flags = 0; + obj->pathname[0] = '\0'; + stream->obj_ = obj; + + /* Choose a file name. */ + tmpnam(obj->pathname); + + /* Open the underlying file. */ + if ((obj->fd = open(obj->pathname, O_CREAT | O_EXCL | O_RDWR | O_TRUNC | O_BINARY, + JAS_STREAM_PERMS)) < 0) { + jas_stream_destroy(stream); + return 0; + } + + /* Unlink the file so that it will disappear if the program + terminates abnormally. */ + /* Under UNIX, one can unlink an open file and continue to do I/O + on it. Not all operating systems support this functionality, however. + For example, under Microsoft Windows the unlink operation will fail, + since the file is open. */ + if (unlink(obj->pathname)) { + /* We will try unlinking the file again after it is closed. */ + obj->flags |= JAS_STREAM_FILEOBJ_DELONCLOSE; + } + + /* Use full buffering. */ + jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); + + stream->ops_ = &jas_stream_fileops; + + return stream; +} + +jas_stream_t *jas_stream_fdopen(int fd, const char *mode) +{ + jas_stream_t *stream; + jas_stream_fileobj_t *obj; + + /* Allocate a stream object. */ + if (!(stream = jas_stream_create())) { + return 0; + } + + /* Parse the mode string. */ + stream->openmode_ = jas_strtoopenmode(mode); + +#if defined(WIN32) + /* Argh!!! Someone ought to banish text mode (i.e., O_TEXT) to the + greatest depths of purgatory! */ + /* Ensure that the file descriptor is in binary mode, if the caller + has specified the binary mode flag. Arguably, the caller ought to + take care of this, but text mode is a ugly wart anyways, so we save + the caller some grief by handling this within the stream library. */ + /* This ugliness is mainly for the benefit of those who run the + JasPer software under Windows from shells that insist on opening + files in text mode. For example, in the Cygwin environment, + shells often open files in text mode when I/O redirection is + used. Grr... */ + if (stream->openmode_ & JAS_STREAM_BINARY) { + setmode(fd, O_BINARY); + } +#endif + + /* Allocate space for the underlying file stream object. */ + if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { + jas_stream_destroy(stream); + return 0; + } + obj->fd = fd; + obj->flags = 0; + obj->pathname[0] = '\0'; + stream->obj_ = (void *) obj; + + /* Do not close the underlying file descriptor when the stream is + closed. */ + obj->flags |= JAS_STREAM_FILEOBJ_NOCLOSE; + + /* By default, use full buffering for this type of stream. */ + jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); + + /* Select the operations for a file stream object. */ + stream->ops_ = &jas_stream_fileops; + + return stream; +} + +static void jas_stream_destroy(jas_stream_t *stream) +{ + /* If the memory for the buffer was allocated with malloc, free + this memory. */ + if ((stream->bufmode_ & JAS_STREAM_FREEBUF) && stream->bufbase_) { + jas_free(stream->bufbase_); + stream->bufbase_ = 0; + } + jas_free(stream); +} + +int jas_stream_close(jas_stream_t *stream) +{ + /* Flush buffer if necessary. */ + jas_stream_flush(stream); + + /* Close the underlying stream object. */ + (*stream->ops_->close_)(stream->obj_); + + jas_stream_destroy(stream); + + return 0; +} + +/******************************************************************************\ +* Code for reading and writing streams. +\******************************************************************************/ + +int jas_stream_getc_func(jas_stream_t *stream) +{ + assert(stream->ptr_ - stream->bufbase_ <= stream->bufsize_ + + JAS_STREAM_MAXPUTBACK); + return jas_stream_getc_macro(stream); +} + +int jas_stream_putc_func(jas_stream_t *stream, int c) +{ + assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_); + return jas_stream_putc_macro(stream, c); +} + +int jas_stream_ungetc(jas_stream_t *stream, int c) +{ + if (!stream->ptr_ || stream->ptr_ == stream->bufbase_) { + return -1; + } + + /* Reset the EOF indicator (since we now have at least one character + to read). */ + stream->flags_ &= ~JAS_STREAM_EOF; + + --stream->rwcnt_; + --stream->ptr_; + ++stream->cnt_; + *stream->ptr_ = c; + return 0; +} + +int jas_stream_read(jas_stream_t *stream, void *buf, int cnt) +{ + int n; + int c; + char *bufptr; + + bufptr = buf; + + n = 0; + while (n < cnt) { + if ((c = jas_stream_getc(stream)) == EOF) { + return n; + } + *bufptr++ = c; + ++n; + } + + return n; +} + +int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) +{ + int n; + const char *bufptr; + + bufptr = buf; + + n = 0; + while (n < cnt) { + if (jas_stream_putc(stream, *bufptr) == EOF) { + return n; + } + ++bufptr; + ++n; + } + + return n; +} + +/* Note: This function uses a fixed size buffer. Therefore, it cannot + handle invocations that will produce more output than can be held + by the buffer. */ +int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...) +{ + va_list ap; + char buf[4096]; + int ret; + + va_start(ap, fmt); + ret = vsprintf(buf, fmt, ap); + jas_stream_puts(stream, buf); + va_end(ap); + return ret; +} + +int jas_stream_puts(jas_stream_t *stream, const char *s) +{ + while (*s != '\0') { + if (jas_stream_putc_macro(stream, *s) == EOF) { + return -1; + } + ++s; + } + return 0; +} + +char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize) +{ + int c; + char *bufptr; + assert(bufsize > 0); + + bufptr = buf; + while (bufsize > 1) { + if ((c = jas_stream_getc(stream)) == EOF) { + break; + } + *bufptr++ = c; + --bufsize; + if (c == '\n') { + break; + } + } + *bufptr = '\0'; + return buf; +} + +int jas_stream_gobble(jas_stream_t *stream, int n) +{ + int m; + m = n; + for (m = n; m > 0; --m) { + if (jas_stream_getc(stream) == EOF) { + return n - m; + } + } + return n; +} + +int jas_stream_pad(jas_stream_t *stream, int n, int c) +{ + int m; + m = n; + for (m = n; m > 0; --m) { + if (jas_stream_putc(stream, c) == EOF) + return n - m; + } + return n; +} + +/******************************************************************************\ +* Code for getting and setting the stream position. +\******************************************************************************/ + +int jas_stream_isseekable(jas_stream_t *stream) +{ + if (stream->ops_ == &jas_stream_memops) { + return 1; + } else if (stream->ops_ == &jas_stream_fileops) { + if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) { + return 0; + } + return 1; + } else { + return 0; + } +} + +int jas_stream_rewind(jas_stream_t *stream) +{ + return jas_stream_seek(stream, 0, SEEK_SET); +} + +long jas_stream_seek(jas_stream_t *stream, long offset, int origin) +{ + long newpos; + + /* The buffer cannot be in use for both reading and writing. */ + assert(!((stream->bufmode_ & JAS_STREAM_RDBUF) && (stream->bufmode_ & + JAS_STREAM_WRBUF))); + + /* Reset the EOF indicator (since we may not be at the EOF anymore). */ + stream->flags_ &= ~JAS_STREAM_EOF; + + if (stream->bufmode_ & JAS_STREAM_RDBUF) { + if (origin == SEEK_CUR) { + offset -= stream->cnt_; + } + } else if (stream->bufmode_ & JAS_STREAM_WRBUF) { + if (jas_stream_flush(stream)) { + return -1; + } + } + stream->cnt_ = 0; + stream->ptr_ = stream->bufstart_; + stream->bufmode_ &= ~(JAS_STREAM_RDBUF | JAS_STREAM_WRBUF); + + if ((newpos = (*stream->ops_->seek_)(stream->obj_, offset, origin)) + < 0) { + return -1; + } + + return newpos; +} + +long jas_stream_tell(jas_stream_t *stream) +{ + int adjust; + int offset; + + if (stream->bufmode_ & JAS_STREAM_RDBUF) { + adjust = -stream->cnt_; + } else if (stream->bufmode_ & JAS_STREAM_WRBUF) { + adjust = stream->ptr_ - stream->bufstart_; + } else { + adjust = 0; + } + + if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR)) < 0) { + return -1; + } + + return offset + adjust; +} + +/******************************************************************************\ +* Buffer initialization code. +\******************************************************************************/ + +static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, + int bufsize) +{ + /* If this function is being called, the buffer should not have been + initialized yet. */ + assert(!stream->bufbase_); + + if (bufmode != JAS_STREAM_UNBUF) { + /* The full- or line-buffered mode is being employed. */ + if (!buf) { + /* The caller has not specified a buffer to employ, so allocate + one. */ + if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE + + JAS_STREAM_MAXPUTBACK))) { + stream->bufmode_ |= JAS_STREAM_FREEBUF; + stream->bufsize_ = JAS_STREAM_BUFSIZE; + } else { + /* The buffer allocation has failed. Resort to unbuffered + operation. */ + stream->bufbase_ = stream->tinybuf_; + stream->bufsize_ = 1; + } + } else { + /* The caller has specified a buffer to employ. */ + /* The buffer must be large enough to accommodate maximum + putback. */ + assert(bufsize > JAS_STREAM_MAXPUTBACK); + stream->bufbase_ = JAS_CAST(uchar *, buf); + stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK; + } + } else { + /* The unbuffered mode is being employed. */ + /* A buffer should not have been supplied by the caller. */ + assert(!buf); + /* Use a trivial one-character buffer. */ + stream->bufbase_ = stream->tinybuf_; + stream->bufsize_ = 1; + } + stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK]; + stream->ptr_ = stream->bufstart_; + stream->cnt_ = 0; + stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK; +} + +/******************************************************************************\ +* Buffer filling and flushing code. +\******************************************************************************/ + +int jas_stream_flush(jas_stream_t *stream) +{ + if (stream->bufmode_ & JAS_STREAM_RDBUF) { + return 0; + } + return jas_stream_flushbuf(stream, EOF); +} + +int jas_stream_fillbuf(jas_stream_t *stream, int getflag) +{ + int c; + + /* The stream must not be in an error or EOF state. */ + if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) { + return EOF; + } + + /* The stream must be open for reading. */ + if ((stream->openmode_ & JAS_STREAM_READ) == 0) { + return EOF; + } + + /* Make a half-hearted attempt to confirm that the buffer is not + currently being used for writing. This check is not intended + to be foolproof! */ + assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0); + + assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_); + + /* Mark the buffer as being used for reading. */ + stream->bufmode_ |= JAS_STREAM_RDBUF; + + /* Read new data into the buffer. */ + stream->ptr_ = stream->bufstart_; + if ((stream->cnt_ = (*stream->ops_->read_)(stream->obj_, + (char *) stream->bufstart_, stream->bufsize_)) <= 0) { + if (stream->cnt_ < 0) { + stream->flags_ |= JAS_STREAM_ERR; + } else { + stream->flags_ |= JAS_STREAM_EOF; + } + stream->cnt_ = 0; + return EOF; + } + + assert(stream->cnt_ > 0); + /* Get or peek at the first character in the buffer. */ + c = (getflag) ? jas_stream_getc2(stream) : (*stream->ptr_); + + return c; +} + +int jas_stream_flushbuf(jas_stream_t *stream, int c) +{ + int len; + int n; + + /* The stream should not be in an error or EOF state. */ + if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) { + return EOF; + } + + /* The stream must be open for writing. */ + if ((stream->openmode_ & (JAS_STREAM_WRITE | JAS_STREAM_APPEND)) == 0) { + return EOF; + } + + /* The buffer should not currently be in use for reading. */ + assert(!(stream->bufmode_ & JAS_STREAM_RDBUF)); + + /* Note: Do not use the quantity stream->cnt to determine the number + of characters in the buffer! Depending on how this function was + called, the stream->cnt value may be "off-by-one". */ + len = stream->ptr_ - stream->bufstart_; + if (len > 0) { + n = (*stream->ops_->write_)(stream->obj_, (char *) + stream->bufstart_, len); + if (n != len) { + stream->flags_ |= JAS_STREAM_ERR; + return EOF; + } + } + stream->cnt_ = stream->bufsize_; + stream->ptr_ = stream->bufstart_; + + stream->bufmode_ |= JAS_STREAM_WRBUF; + + if (c != EOF) { + assert(stream->cnt_ > 0); + return jas_stream_putc2(stream, c); + } + + return 0; +} + +/******************************************************************************\ +* Miscellaneous code. +\******************************************************************************/ + +static int jas_strtoopenmode(const char *s) +{ + int openmode = 0; + while (*s != '\0') { + switch (*s) { + case 'r': + openmode |= JAS_STREAM_READ; + break; + case 'w': + openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE; + break; + case 'b': + openmode |= JAS_STREAM_BINARY; + break; + case 'a': + openmode |= JAS_STREAM_APPEND; + break; + case '+': + openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE; + break; + default: + break; + } + ++s; + } + return openmode; +} + +int jas_stream_copy(jas_stream_t *out, jas_stream_t *in, int n) +{ + int all; + int c; + int m; + + all = (n < 0) ? 1 : 0; + + m = n; + while (all || m > 0) { + if ((c = jas_stream_getc_macro(in)) == EOF) { + /* The next character of input could not be read. */ + /* Return with an error if an I/O error occured + (not including EOF) or if an explicit copy count + was specified. */ + return (!all || jas_stream_error(in)) ? (-1) : 0; + } + if (jas_stream_putc_macro(out, c) == EOF) { + return -1; + } + --m; + } + return 0; +} + +long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt) +{ + int old; + + old = stream->rwcnt_; + stream->rwcnt_ = rwcnt; + return old; +} + +int jas_stream_display(jas_stream_t *stream, FILE *fp, int n) +{ + unsigned char buf[16]; + int i; + int j; + int m; + int c; + int display; + int cnt; + + cnt = n - (n % 16); + display = 1; + + for (i = 0; i < n; i += 16) { + if (n > 16 && i > 0) { + display = (i >= cnt) ? 1 : 0; + } + if (display) { + fprintf(fp, "%08x:", i); + } + m = JAS_MIN(n - i, 16); + for (j = 0; j < m; ++j) { + if ((c = jas_stream_getc(stream)) == EOF) { + abort(); + return -1; + } + buf[j] = c; + } + if (display) { + for (j = 0; j < m; ++j) { + fprintf(fp, " %02x", buf[j]); + } + fputc(' ', fp); + for (; j < 16; ++j) { + fprintf(fp, " "); + } + for (j = 0; j < m; ++j) { + if (isprint(buf[j])) { + fputc(buf[j], fp); + } else { + fputc(' ', fp); + } + } + fprintf(fp, "\n"); + } + + + } + return 0; +} + +long jas_stream_length(jas_stream_t *stream) +{ + long oldpos; + long pos; + if ((oldpos = jas_stream_tell(stream)) < 0) { + return -1; + } + if (jas_stream_seek(stream, 0, SEEK_END) < 0) { + return -1; + } + if ((pos = jas_stream_tell(stream)) < 0) { + return -1; + } + if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) { + return -1; + } + return pos; +} + +/******************************************************************************\ +* Memory stream object. +\******************************************************************************/ + +static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt) +{ + int n; + jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; + n = m->len_ - m->pos_; + cnt = JAS_MIN(n, cnt); + memcpy(buf, &m->buf_[m->pos_], cnt); + m->pos_ += cnt; + return cnt; +} + +static int mem_resize(jas_stream_memobj_t *m, int bufsize) +{ + unsigned char *buf; + + assert(m->buf_); + if (!(buf = jas_realloc(m->buf_, bufsize * sizeof(unsigned char)))) { + return -1; + } + m->buf_ = buf; + m->bufsize_ = bufsize; + return 0; +} + +static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt) +{ + int n; + int ret; + jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; + long newbufsize; + long newpos; + + newpos = m->pos_ + cnt; + if (newpos > m->bufsize_ && m->growable_) { + newbufsize = m->bufsize_; + while (newbufsize < newpos) { + newbufsize <<= 1; + assert(newbufsize >= 0); + } + if (mem_resize(m, newbufsize)) { + return -1; + } + } + if (m->pos_ > m->len_) { + /* The current position is beyond the end of the file, so + pad the file to the current position with zeros. */ + n = JAS_MIN(m->pos_, m->bufsize_) - m->len_; + if (n > 0) { + memset(&m->buf_[m->len_], 0, n); + m->len_ += n; + } + if (m->pos_ != m->len_) { + /* The buffer is not big enough. */ + return 0; + } + } + n = m->bufsize_ - m->pos_; + ret = JAS_MIN(n, cnt); + if (ret > 0) { + memcpy(&m->buf_[m->pos_], buf, ret); + m->pos_ += ret; + } + if (m->pos_ > m->len_) { + m->len_ = m->pos_; + } +assert(ret == cnt); + return ret; +} + +static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) +{ + jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; + long newpos; + + switch (origin) { + case SEEK_SET: + newpos = offset; + break; + case SEEK_END: + newpos = m->len_ - offset; + break; + case SEEK_CUR: + newpos = m->pos_ + offset; + break; + default: + abort(); + break; + } + if (newpos < 0) { + return -1; + } + m->pos_ = newpos; + + return m->pos_; +} + +static int mem_close(jas_stream_obj_t *obj) +{ + jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; + if (m->myalloc_ && m->buf_) { + jas_free(m->buf_); + m->buf_ = 0; + } + jas_free(obj); + return 0; +} + +/******************************************************************************\ +* File stream object. +\******************************************************************************/ + +static int file_read(jas_stream_obj_t *obj, char *buf, int cnt) +{ + jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); + return read(fileobj->fd, buf, cnt); +} + +static int file_write(jas_stream_obj_t *obj, char *buf, int cnt) +{ + jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); + return write(fileobj->fd, buf, cnt); +} + +static long file_seek(jas_stream_obj_t *obj, long offset, int origin) +{ + jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); + return lseek(fileobj->fd, offset, origin); +} + +static int file_close(jas_stream_obj_t *obj) +{ + jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); + int ret; + ret = close(fileobj->fd); + if (fileobj->flags & JAS_STREAM_FILEOBJ_DELONCLOSE) { + unlink(fileobj->pathname); + } + jas_free(fileobj); + return ret; +} + +/******************************************************************************\ +* Stdio file stream object. +\******************************************************************************/ + +static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt) +{ + FILE *fp; + fp = JAS_CAST(FILE *, obj); + return fread(buf, 1, cnt, fp); +} + +static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt) +{ + FILE *fp; + fp = JAS_CAST(FILE *, obj); + return fwrite(buf, 1, cnt, fp); +} + +static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin) +{ + FILE *fp; + fp = JAS_CAST(FILE *, obj); + return fseek(fp, offset, origin); +} + +static int sfile_close(jas_stream_obj_t *obj) +{ + FILE *fp; + fp = JAS_CAST(FILE *, obj); + return fclose(fp); +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_string.c b/SlnkDWFImpl/CxImage/jasper/base/jas_string.c new file mode 100644 index 0000000..594faa1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_string.c @@ -0,0 +1,145 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * String Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes +\******************************************************************************/ + +#include + +#include "jasper/jas_malloc.h" +#include "jasper/jas_string.h" + +/******************************************************************************\ +* Miscellaneous Functions +\******************************************************************************/ + +/* This function is equivalent to the popular but non-standard (and + not-always-available) strdup function. */ + +char *jas_strdup(const char *s) +{ + int n; + char *p; + n = strlen(s) + 1; + if (!(p = jas_malloc(n * sizeof(char)))) { + return 0; + } + strcpy(p, s); + return p; +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_tvp.c b/SlnkDWFImpl/CxImage/jasper/base/jas_tvp.c new file mode 100644 index 0000000..ebf3206 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_tvp.c @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tag-Value Parser Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include + +#include "jasper/jas_malloc.h" +#include "jasper/jas_string.h" +#include "jasper/jas_tvp.h" + +/******************************************************************************\ +* Macros. +\******************************************************************************/ + +/* Is the specified character valid for a tag name? */ +#define JAS_TVP_ISTAG(x) \ + (isalpha(x) || (x) == '_' || isdigit(x)) + +/******************************************************************************\ +* Code for creating and destroying a tag-value parser. +\******************************************************************************/ + +jas_tvparser_t *jas_tvparser_create(const char *s) +{ + jas_tvparser_t *tvp; + if (!(tvp = jas_malloc(sizeof(jas_tvparser_t)))) { + return 0; + } + if (!(tvp->buf = jas_strdup(s))) { + jas_tvparser_destroy(tvp); + return 0; + } + tvp->pos = tvp->buf; + tvp->tag = 0; + tvp->val = 0; + return tvp; +} + +void jas_tvparser_destroy(jas_tvparser_t *tvp) +{ + if (tvp->buf) { + jas_free(tvp->buf); + } + jas_free(tvp); +} + +/******************************************************************************\ +* Main parsing code. +\******************************************************************************/ + +/* Get the next tag-value pair. */ +int jas_tvparser_next(jas_tvparser_t *tvp) +{ + char *p; + char *tag; + char *val; + + /* Skip any leading whitespace. */ + p = tvp->pos; + while (*p != '\0' && isspace(*p)) { + ++p; + } + + /* Has the end of the input data been reached? */ + if (*p == '\0') { + /* No more tags are present. */ + tvp->pos = p; + return 1; + } + + /* Does the tag name begin with a valid character? */ + if (!JAS_TVP_ISTAG(*p)) { + return -1; + } + + /* Remember where the tag name begins. */ + tag = p; + + /* Find the end of the tag name. */ + while (*p != '\0' && JAS_TVP_ISTAG(*p)) { + ++p; + } + + /* Has the end of the input data been reached? */ + if (*p == '\0') { + /* The value field is empty. */ + tvp->tag = tag; + tvp->val = ""; + tvp->pos = p; + return 0; + } + + /* Is a value field not present? */ + if (*p != '=') { + if (*p != '\0' && !isspace(*p)) { + return -1; + } + *p++ = '\0'; + tvp->tag = tag; + tvp->val = ""; + tvp->pos = p; + return 0; + } + + *p++ = '\0'; + + val = p; + while (*p != '\0' && !isspace(*p)) { + ++p; + } + + if (*p != '\0') { + *p++ = '\0'; + } + + tvp->pos = p; + tvp->tag = tag; + tvp->val = val; + + return 0; +} + +/******************************************************************************\ +* Code for querying the current tag/value. +\******************************************************************************/ + +/* Get the current tag. */ +char *jas_tvparser_gettag(jas_tvparser_t *tvp) +{ + return tvp->tag; +} + +/* Get the current value. */ +char *jas_tvparser_getval(jas_tvparser_t *tvp) +{ + return tvp->val; +} + +/******************************************************************************\ +* Miscellaneous code. +\******************************************************************************/ + +/* Lookup a tag by name. */ +jas_taginfo_t *jas_taginfos_lookup(jas_taginfo_t *taginfos, const char *name) +{ + jas_taginfo_t *taginfo; + taginfo = taginfos; + while (taginfo->id >= 0) { + if (!strcmp(taginfo->name, name)) { + return taginfo; + } + ++taginfo; + } + return 0; +} + +/* This function is simply for convenience. */ +/* One can avoid testing for the special case of a null pointer, by + using this function. This function never returns a null pointer. */ +jas_taginfo_t *jas_taginfo_nonull(jas_taginfo_t *taginfo) +{ + static jas_taginfo_t invalidtaginfo = { + -1, 0 + }; + + return taginfo ? taginfo : &invalidtaginfo; +} diff --git a/SlnkDWFImpl/CxImage/jasper/base/jas_version.c b/SlnkDWFImpl/CxImage/jasper/base/jas_version.c new file mode 100644 index 0000000..7f907c6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/base/jas_version.c @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#include "jasper/jas_version.h" + +const char *jas_getversion() +{ + return JAS_VERSION; +} diff --git a/SlnkDWFImpl/CxImage/jasper/bmp/.gitignore b/SlnkDWFImpl/CxImage/jasper/bmp/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/bmp/bmp_cod.c b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_cod.c new file mode 100644 index 0000000..8546dbf --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_cod.c @@ -0,0 +1,184 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Windows Bitmap File Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_image.h" +#include "jasper/jas_malloc.h" + +#include "bmp_cod.h" + +/******************************************************************************\ +* Constructors and destructors. +\******************************************************************************/ + +bmp_info_t *bmp_info_create() +{ + bmp_info_t *info; + if (!(info = jas_malloc(sizeof(bmp_info_t)))) { + return 0; + } + info->palents = 0; + return info; +} + +void bmp_info_destroy(bmp_info_t *info) +{ + if (info->palents) { + jas_free(info->palents); + } + jas_free(info); +} + +/******************************************************************************\ +* Miscellaneous functions. +\******************************************************************************/ + +int bmp_isgrayscalepal(bmp_palent_t *palents, int numpalents) +{ + bmp_palent_t *palent; + int i; + + for (i = numpalents, palent = palents; i > 0; --i, ++palent) { + if (palent->red != palent->grn || palent->red != palent->blu) { + return 0; + } + } + return 1; +} + +int bmp_numcmpts(bmp_info_t *info) +{ + int numcmpts; + + if (info->depth == 24) { + numcmpts = 3; + } else if (info->depth == 8) { + numcmpts = bmp_isgrayscalepal(info->palents, info->numcolors) ? + 1 : 3; + } else { + numcmpts = 0; + abort(); + } + return numcmpts; +} diff --git a/SlnkDWFImpl/CxImage/jasper/bmp/bmp_cod.h b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_cod.h new file mode 100644 index 0000000..79c3f40 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_cod.h @@ -0,0 +1,264 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Windows Bitmap File Library + * + * $Id$ + */ + +#ifndef BMP_COD_H +#define BMP_COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" + +/******************************************************************************\ +* Constants and macros. +\******************************************************************************/ + +#define BMP_MAGIC 0x4d42 +/* The signature for a BMP file. */ + +#define BMP_HDRLEN 14 +/* The nominal header length. */ + +#define BMP_INFOLEN 40 +/* The nominal info length. */ + +#define BMP_PALLEN(info) ((info)->numcolors * 4) +/* The length of the palette. */ + +#define BMP_HASPAL(info) ((info)->numcolors > 0) +/* Is this a palettized image? */ + +/* Encoding types. */ +#define BMP_ENC_RGB 0 /* No special encoding. */ +#define BMP_ENC_RLE8 1 /* Run length encoding. */ +#define BMP_ENC_RLE4 2 /* Run length encoding. */ + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* BMP header. */ +typedef struct { + + int_fast16_t magic; + /* The signature (a.k.a. the magic number). */ + + int_fast32_t siz; + /* The size of the file in 32-bit words. */ + + int_fast16_t reserved1; + /* Ask Bill Gates what this is all about. */ + + int_fast16_t reserved2; + /* Ditto. */ + + int_fast32_t off; + /* The offset of the bitmap data from the bitmap file header in bytes. */ + +} bmp_hdr_t; + +/* Palette entry. */ +typedef struct { + + int_fast16_t red; + /* The red component. */ + + int_fast16_t grn; + /* The green component. */ + + int_fast16_t blu; + /* The blue component. */ + + int_fast16_t res; + /* Reserved. */ + +} bmp_palent_t; + +/* BMP info. */ +typedef struct { + + int_fast32_t len; + /* The length of the bitmap information header in bytes. */ + + int_fast32_t width; + /* The width of the bitmap in pixels. */ + + int_fast32_t height; + /* The height of the bitmap in pixels. */ + + int_fast8_t topdown; + /* The bitmap data is specified in top-down order. */ + + int_fast16_t numplanes; + /* The number of planes. This must be set to a value of one. */ + + int_fast16_t depth; + /* The number of bits per pixel. */ + + int_fast32_t enctype; + /* The type of compression used. */ + + int_fast32_t siz; + /* The size of the image in bytes. */ + + int_fast32_t hres; + /* The horizontal resolution in pixels/metre. */ + + int_fast32_t vres; + /* The vertical resolution in pixels/metre. */ + + int_fast32_t numcolors; + /* The number of color indices used by the bitmap. */ + + int_fast32_t mincolors; + /* The number of color indices important for displaying the bitmap. */ + + bmp_palent_t *palents; + /* The colors should be listed in order of importance. */ + +} bmp_info_t; + +/******************************************************************************\ +* Functions and macros. +\******************************************************************************/ + +#define bmp_issupported(hdr, info) \ + ((hdr)->magic == BMP_MAGIC && !(hdr)->reserved1 && \ + !(hdr)->reserved2 && (info)->numplanes == 1 && \ + ((info)->depth == 8 || (info)->depth == 24) && \ + (info)->enctype == BMP_ENC_RGB) +/* Is this type of BMP file supported? */ + +#define bmp_haspal(info) \ + ((info)->depth == 8) +/* Is there a palette? */ + +int bmp_numcmpts(bmp_info_t *info); +/* Get the number of components. */ + +bmp_info_t *bmp_info_create(void); +/* Create BMP information. */ + +void bmp_info_destroy(bmp_info_t *info); +/* Destroy BMP information. */ + +int bmp_isgrayscalepal(bmp_palent_t *palents, int numpalents); +/* Does the specified palette correspond to a grayscale image? */ + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/bmp/bmp_dec.c b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_dec.c new file mode 100644 index 0000000..3cbbfc7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_dec.c @@ -0,0 +1,512 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Windows Bitmap File Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_malloc.h" + +#include "bmp_cod.h" + +/******************************************************************************\ +* Local prototypes. +\******************************************************************************/ + +static int bmp_gethdr(jas_stream_t *in, bmp_hdr_t *hdr); +static bmp_info_t *bmp_getinfo(jas_stream_t *in); +static int bmp_getdata(jas_stream_t *in, bmp_info_t *info, jas_image_t *image); +static int bmp_getint16(jas_stream_t *in, int_fast16_t *val); +static int bmp_getint32(jas_stream_t *in, int_fast32_t *val); +static int bmp_gobble(jas_stream_t *in, long n); + +/******************************************************************************\ +* Interface functions. +\******************************************************************************/ + +jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) +{ + jas_image_t *image; + bmp_hdr_t hdr; + bmp_info_t *info; + uint_fast16_t cmptno; + jas_image_cmptparm_t cmptparms[3]; + jas_image_cmptparm_t *cmptparm; + uint_fast16_t numcmpts; + long n; + + if (optstr) { + fprintf(stderr, "warning: ignoring BMP decoder options\n"); + } + + fprintf(stderr, + "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" + "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" + "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" + "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" + ); + + /* Read the bitmap header. */ + if (bmp_gethdr(in, &hdr)) { + fprintf(stderr, "cannot get header\n"); + return 0; + } + + /* Read the bitmap information. */ + if (!(info = bmp_getinfo(in))) { + fprintf(stderr, "cannot get info\n"); + return 0; + } + + /* Ensure that we support this type of BMP file. */ + if (!bmp_issupported(&hdr, info)) { + fprintf(stderr, "error: unsupported BMP encoding\n"); + bmp_info_destroy(info); + return 0; + } + + /* Skip over any useless data between the end of the palette + and start of the bitmap data. */ + if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { + fprintf(stderr, "error: possibly bad bitmap offset?\n"); + return 0; + } + if (n > 0) { + fprintf(stderr, "skipping unknown data in BMP file\n"); + if (bmp_gobble(in, n)) { + bmp_info_destroy(info); + return 0; + } + } + + /* Get the number of components. */ + numcmpts = bmp_numcmpts(info); + + for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, + ++cmptparm) { + cmptparm->tlx = 0; + cmptparm->tly = 0; + cmptparm->hstep = 1; + cmptparm->vstep = 1; + cmptparm->width = info->width; + cmptparm->height = info->height; + cmptparm->prec = 8; + cmptparm->sgnd = false; + } + + /* Create image object. */ + if (!(image = jas_image_create(numcmpts, cmptparms, + JAS_CLRSPC_UNKNOWN))) { + bmp_info_destroy(info); + return 0; + } + + if (numcmpts == 3) { + jas_image_setclrspc(image, JAS_CLRSPC_SRGB); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); + jas_image_setcmpttype(image, 1, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); + jas_image_setcmpttype(image, 2, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); + } else { + jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); + } + + /* Read the bitmap data. */ + if (bmp_getdata(in, info, image)) { + bmp_info_destroy(info); + jas_image_destroy(image); + return 0; + } + + bmp_info_destroy(info); + + return image; +} + +int bmp_validate(jas_stream_t *in) +{ + int n; + int i; + uchar buf[2]; + + assert(JAS_STREAM_MAXPUTBACK >= 2); + + /* Read the first two characters that constitute the signature. */ + if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) { + return -1; + } + /* Put the characters read back onto the stream. */ + for (i = n - 1; i >= 0; --i) { + if (jas_stream_ungetc(in, buf[i]) == EOF) { + return -1; + } + } + /* Did we read enough characters? */ + if (n < 2) { + return -1; + } + /* Is the signature correct for the BMP format? */ + if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) { + return 0; + } + return -1; +} + +/******************************************************************************\ +* Code for aggregate types. +\******************************************************************************/ + +static int bmp_gethdr(jas_stream_t *in, bmp_hdr_t *hdr) +{ + if (bmp_getint16(in, &hdr->magic) || hdr->magic != BMP_MAGIC || + bmp_getint32(in, &hdr->siz) || bmp_getint16(in, &hdr->reserved1) || + bmp_getint16(in, &hdr->reserved2) || bmp_getint32(in, &hdr->off)) { + return -1; + } + return 0; +} + +static bmp_info_t *bmp_getinfo(jas_stream_t *in) +{ + bmp_info_t *info; + int i; + bmp_palent_t *palent; + + if (!(info = bmp_info_create())) { + return 0; + } + + if (bmp_getint32(in, &info->len) || info->len != 40 || + bmp_getint32(in, &info->width) || bmp_getint32(in, &info->height) || + bmp_getint16(in, &info->numplanes) || + bmp_getint16(in, &info->depth) || bmp_getint32(in, &info->enctype) || + bmp_getint32(in, &info->siz) || + bmp_getint32(in, &info->hres) || bmp_getint32(in, &info->vres) || + bmp_getint32(in, &info->numcolors) || + bmp_getint32(in, &info->mincolors)) { + bmp_info_destroy(info); + return 0; + } + + if (info->height < 0) { + info->topdown = 1; + info->height = -info->height; + } else { + info->topdown = 0; + } + + if (info->width <= 0 || info->height <= 0 || info->numplanes <= 0 || + info->depth <= 0 || info->numcolors < 0 || info->mincolors < 0) { + bmp_info_destroy(info); + return 0; + } + + if (info->enctype != BMP_ENC_RGB) { + fprintf(stderr, "unsupported BMP encoding\n"); + bmp_info_destroy(info); + return 0; + } + + if (info->numcolors > 0) { + if (!(info->palents = jas_malloc(info->numcolors * + sizeof(bmp_palent_t)))) { + bmp_info_destroy(info); + return 0; + } + } else { + info->palents = 0; + } + + for (i = 0; i < info->numcolors; ++i) { + palent = &info->palents[i]; + if ((palent->blu = jas_stream_getc(in)) == EOF || + (palent->grn = jas_stream_getc(in)) == EOF || + (palent->red = jas_stream_getc(in)) == EOF || + (palent->res = jas_stream_getc(in)) == EOF) { + bmp_info_destroy(info); + return 0; + } + } + + return info; +} + +static int bmp_getdata(jas_stream_t *in, bmp_info_t *info, jas_image_t *image) +{ + int i; + int j; + int y; + jas_matrix_t *cmpts[3]; + int numpad; + int red; + int grn; + int blu; + int ret; + int numcmpts; + int cmptno; + int ind; + bmp_palent_t *palent; + int mxind; + int haspal; + + assert(info->depth == 8 || info->depth == 24); + assert(info->enctype == BMP_ENC_RGB); + + numcmpts = bmp_numcmpts(info); + haspal = bmp_haspal(info); + + ret = 0; + for (i = 0; i < numcmpts; ++i) { + cmpts[i] = 0; + } + + /* Create temporary matrices to hold component data. */ + for (i = 0; i < numcmpts; ++i) { + if (!(cmpts[i] = jas_matrix_create(1, info->width))) { + ret = -1; + goto bmp_getdata_done; + } + } + + /* Calculate number of padding bytes per row of image data. */ + numpad = (numcmpts * info->width) % 4; + if (numpad) { + numpad = 4 - numpad; + } + + mxind = (1 << info->depth) - 1; + for (i = 0; i < info->height; ++i) { + for (j = 0; j < info->width; ++j) { + if (haspal) { + if ((ind = jas_stream_getc(in)) == EOF) { + ret = -1; + goto bmp_getdata_done; + } + if (ind > mxind) { + ret = -1; + goto bmp_getdata_done; + } + if (ind < info->numcolors) { + palent = &info->palents[ind]; + red = palent->red; + grn = palent->grn; + blu = palent->blu; + } else { + red = ind; + grn = ind; + blu = ind; + } + } else { + if ((blu = jas_stream_getc(in)) == EOF || + (grn = jas_stream_getc(in)) == EOF || + (red = jas_stream_getc(in)) == EOF) { + ret = -1; + goto bmp_getdata_done; + } + } + if (numcmpts == 3) { + jas_matrix_setv(cmpts[0], j, red); + jas_matrix_setv(cmpts[1], j, grn); + jas_matrix_setv(cmpts[2], j, blu); + } else { + jas_matrix_setv(cmpts[0], j, red); + } + } + for (j = numpad; j > 0; --j) { + if (jas_stream_getc(in) == EOF) { + ret = -1; + goto bmp_getdata_done; + } + } + for (cmptno = 0; cmptno < numcmpts; ++cmptno) { + y = info->topdown ? i : (info->height - 1 - i); + if (jas_image_writecmpt(image, cmptno, 0, y, info->width, + 1, cmpts[cmptno])) { + ret = -1; + goto bmp_getdata_done; + } + } + } + +bmp_getdata_done: + /* Destroy the temporary matrices. */ + for (i = 0; i < numcmpts; ++i) { + if (cmpts[i]) { + jas_matrix_destroy(cmpts[i]); + } + } + + return ret; +} + +/******************************************************************************\ +* Code for primitive types. +\******************************************************************************/ + +static int bmp_getint16(jas_stream_t *in, int_fast16_t *val) +{ + int lo; + int hi; + if ((lo = jas_stream_getc(in)) == EOF || (hi = jas_stream_getc(in)) == EOF) { + return -1; + } + if (val) { + *val = (hi << 8) | lo; + } + return 0; +} + +static int bmp_getint32(jas_stream_t *in, int_fast32_t *val) +{ + int n; + uint_fast32_t v; + int c; + for (n = 4, v = 0;;) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v |= (c << 24); + if (--n <= 0) { + break; + } + v >>= 8; + } + if (val) { + *val = v; + } + return 0; +} + +static int bmp_gobble(jas_stream_t *in, long n) +{ + while (--n >= 0) { + if (jas_stream_getc(in) == EOF) { + return -1; + } + } + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/bmp/bmp_enc.c b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_enc.c new file mode 100644 index 0000000..c89b063 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_enc.c @@ -0,0 +1,444 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Windows Bitmap File Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_debug.h" + +#include "bmp_enc.h" +#include "bmp_cod.h" + +/******************************************************************************\ +* Local prototypes. +\******************************************************************************/ + +static int bmp_puthdr(jas_stream_t *out, bmp_hdr_t *hdr); +static int bmp_putinfo(jas_stream_t *out, bmp_info_t *info); +static int bmp_putdata(jas_stream_t *out, bmp_info_t *info, jas_image_t *image, int *cmpts); +static int bmp_putint16(jas_stream_t *in, int_fast16_t val); +static int bmp_putint32(jas_stream_t *out, int_fast32_t val); + +/******************************************************************************\ +* Interface functions. +\******************************************************************************/ + +int bmp_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + jas_image_coord_t width; + jas_image_coord_t height; + int depth; + int cmptno; + bmp_hdr_t hdr; + bmp_info_t *info; + int_fast32_t datalen; + int numpad; + bmp_enc_t encbuf; + bmp_enc_t *enc = &encbuf; + jas_clrspc_t clrspc; + + if (optstr) { + fprintf(stderr, "warning: ignoring BMP encoder options\n"); + } + + clrspc = jas_image_clrspc(image); + switch (jas_clrspc_fam(clrspc)) { + case JAS_CLRSPC_FAM_RGB: + if (clrspc != JAS_CLRSPC_SRGB) + jas_eprintf("warning: inaccurate color\n"); + break; + case JAS_CLRSPC_FAM_GRAY: + if (clrspc != JAS_CLRSPC_SGRAY) + jas_eprintf("warning: inaccurate color\n"); + break; + default: + jas_eprintf("error: BMP format does not support color space\n"); + return -1; + break; + } + + switch (jas_clrspc_fam(clrspc)) { + case JAS_CLRSPC_FAM_RGB: + enc->numcmpts = 3; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 || + (enc->cmpts[1] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 || + (enc->cmpts[2] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) { + jas_eprintf("error: missing color component\n"); + return -1; + } + break; + case JAS_CLRSPC_FAM_GRAY: + enc->numcmpts = 1; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) { + jas_eprintf("error: missing color component\n"); + return -1; + } + break; + default: + abort(); + break; + } + + width = jas_image_cmptwidth(image, enc->cmpts[0]); + height = jas_image_cmptheight(image, enc->cmpts[0]); + depth = jas_image_cmptprec(image, enc->cmpts[0]); + + /* Check to ensure that the image to be saved can actually be represented + using the BMP format. */ + for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) { + if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width || + jas_image_cmptheight(image, enc->cmpts[cmptno]) != height || + jas_image_cmptprec(image, enc->cmpts[cmptno]) != depth || + jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != false || + jas_image_cmpttlx(image, enc->cmpts[cmptno]) != 0 || + jas_image_cmpttly(image, enc->cmpts[cmptno]) != 0) { + fprintf(stderr, "The BMP format cannot be used to represent an image with this geometry.\n"); + return -1; + } + } + + /* The component depths must be 1, 4, or 8. */ + if (depth != 1 && depth != 4 && depth != 8) { + return -1; + } + + numpad = (width * enc->numcmpts) % 4; + if (numpad) { + numpad = 4 - numpad; + } + datalen = (enc->numcmpts * width + numpad) * height; + + if (!(info = bmp_info_create())) { + return -1; + } + info->len = BMP_INFOLEN; + info->width = width; + info->height = height; + info->numplanes = 1; + info->depth = enc->numcmpts * depth; + info->enctype = BMP_ENC_RGB; + info->siz = datalen; + info->hres = 0; + info->vres = 0; + info->numcolors = (enc->numcmpts == 1) ? 256 : 0; + info->mincolors = 0; + + hdr.magic = BMP_MAGIC; + hdr.siz = BMP_HDRLEN + BMP_INFOLEN + 0 + datalen; + hdr.off = BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info); + + /* Write the bitmap header. */ + if (bmp_puthdr(out, &hdr)) { + return -1; + } + + /* Write the bitmap information. */ + if (bmp_putinfo(out, info)) { + return -1; + } + + /* Write the bitmap data. */ + if (bmp_putdata(out, info, image, enc->cmpts)) { + return -1; + } + + bmp_info_destroy(info); + + return 0; +} + +/******************************************************************************\ +* Code for aggregate types. +\******************************************************************************/ + +static int bmp_puthdr(jas_stream_t *out, bmp_hdr_t *hdr) +{ + assert(hdr->magic == BMP_MAGIC); + if (bmp_putint16(out, hdr->magic) || bmp_putint32(out, hdr->siz) || + bmp_putint32(out, 0) || bmp_putint32(out, hdr->off)) { + return -1; + } + return 0; +} + +static int bmp_putinfo(jas_stream_t *out, bmp_info_t *info) +{ + int i; + + info->len = 40; + if (bmp_putint32(out, info->len) || + bmp_putint32(out, info->width) || + bmp_putint32(out, info->height) || + bmp_putint16(out, info->numplanes) || + bmp_putint16(out, info->depth) || + bmp_putint32(out, info->enctype) || + bmp_putint32(out, info->siz) || + bmp_putint32(out, info->hres) || + bmp_putint32(out, info->vres) || + bmp_putint32(out, info->numcolors) || + bmp_putint32(out, info->mincolors)) { + return -1; + } + + for (i = 0; i < info->numcolors; ++i) + { + if (jas_stream_putc(out, i) == EOF || + jas_stream_putc(out, i) == EOF || + jas_stream_putc(out, i) == EOF || + jas_stream_putc(out, 0) == EOF) + { + return -1; + } + } + + return 0; +} + +static int bmp_putdata(jas_stream_t *out, bmp_info_t *info, jas_image_t *image, + int *cmpts) +{ + int i; + int j; + jas_matrix_t *bufs[3]; + int numpad; + unsigned char red; + unsigned char grn; + unsigned char blu; + int ret; + int numcmpts; + int v; + int cmptno; + + numcmpts = (info->depth == 24) ? 3:1; + + /* We do not support palettized images. */ + if (BMP_HASPAL(info) && numcmpts == 3) { + fprintf(stderr, "no palettized image support for BMP format\n"); + return -1; + } + + ret = 0; + for (i = 0; i < numcmpts; ++i) { + bufs[i] = 0; + } + + /* Create temporary matrices to hold component data. */ + for (i = 0; i < numcmpts; ++i) { + if (!(bufs[i] = jas_matrix_create(1, info->width))) { + ret = -1; + goto bmp_putdata_done; + } + } + + /* Calculate number of padding bytes per row of image data. */ + numpad = (numcmpts * info->width) % 4; + if (numpad) { + numpad = 4 - numpad; + } + + /* Put the image data. */ + for (i = info->height - 1; i >= 0; --i) { + for (cmptno = 0; cmptno < numcmpts; ++cmptno) { + if (jas_image_readcmpt(image, cmptno, 0, i, info->width, + 1, bufs[cmpts[cmptno]])) { + ret = -1; + goto bmp_putdata_done; + } + } + for (j = 0; j < info->width; ++j) { + if (numcmpts == 3) { + red = (jas_matrix_getv(bufs[0], j)); + grn = (jas_matrix_getv(bufs[1], j)); + blu = (jas_matrix_getv(bufs[2], j)); + if (jas_stream_putc(out, blu) == EOF || + jas_stream_putc(out, grn) == EOF || + jas_stream_putc(out, red) == EOF) { + ret = -1; + goto bmp_putdata_done; + } + } else if (numcmpts == 1) { + v = (jas_matrix_getv(bufs[cmpts[0]], j)); + if (jas_stream_putc(out, v) == EOF) { + ret = -1; + goto bmp_putdata_done; + } + } else { + abort(); + } + } + for (j = numpad; j > 0; --j) { + if (jas_stream_putc(out, 0) == EOF) { + ret = -1; + goto bmp_putdata_done; + } + } + } + +bmp_putdata_done: + /* Destroy the temporary matrices. */ + for (i = 0; i < numcmpts; ++i) { + if (bufs[i]) { + jas_matrix_destroy(bufs[i]); + } + } + + return ret; +} + +/******************************************************************************\ +* Code for primitive types. +\******************************************************************************/ + +static int bmp_putint16(jas_stream_t *in, int_fast16_t val) +{ + if (jas_stream_putc(in, val & 0xff) == EOF || jas_stream_putc(in, (val >> 8) & + 0xff) == EOF) { + return -1; + } + return 0; +} + +static int bmp_putint32(jas_stream_t *out, int_fast32_t val) +{ + int n; + int_fast32_t v; + + /* This code needs to be changed if we want to handle negative values. */ + assert(val >= 0); + v = val; + for (n = 4;;) { + if (jas_stream_putc(out, v & 0xff) == EOF) { + return -1; + } + if (--n <= 0) { + break; + } + v >>= 8; + } + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/bmp/bmp_enc.h b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_enc.h new file mode 100644 index 0000000..0590a59 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/bmp/bmp_enc.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef BMP_ENC_H +#define BMP_ENC_H + +typedef struct { + + int numcmpts; + int cmpts[4]; + +} bmp_enc_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/.gitignore b/SlnkDWFImpl/CxImage/jasper/include/jasper/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_cm.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_cm.h new file mode 100644 index 0000000..dd642a4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_cm.h @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2002-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Color Management + * + * $Id$ + */ + +#ifndef JAS_CM_H +#define JAS_CM_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef int jas_clrspc_t; + +/* transform operations */ +#define JAS_CMXFORM_OP_FWD 0 +#define JAS_CMXFORM_OP_REV 1 +#define JAS_CMXFORM_OP_PROOF 2 +#define JAS_CMXFORM_OP_GAMUT 3 + +/* rendering intents */ +#define JAS_CMXFORM_INTENT_PER 0 +#define JAS_CMXFORM_INTENT_RELCLR 1 +#define JAS_CMXFORM_INTENT_ABSCLR 2 +#define JAS_CMXFORM_INTENT_SAT 3 +#define JAS_CMXFORM_NUMINTENTS 4 + +#define JAS_CMXFORM_OPTM_SPEED 0 +#define JAS_CMXFORM_OPTM_SIZE 1 +#define JAS_CMXFORM_OPTM_ACC 2 + + +#define jas_clrspc_create(fam, mbr) (((fam) << 8) | (mbr)) +#define jas_clrspc_fam(clrspc) ((clrspc) >> 8) +#define jas_clrspc_mbr(clrspc) ((clrspc) & 0xff) +#define jas_clrspc_isgeneric(clrspc) (!jas_clrspc_mbr(clrspc)) +#define jas_clrspc_isunknown(clrspc) ((clrspc) & JAS_CLRSPC_UNKNOWNMASK) + +#define JAS_CLRSPC_UNKNOWNMASK 0x4000 + +/* color space families */ +#define JAS_CLRSPC_FAM_UNKNOWN 0 +#define JAS_CLRSPC_FAM_XYZ 1 +#define JAS_CLRSPC_FAM_LAB 2 +#define JAS_CLRSPC_FAM_GRAY 3 +#define JAS_CLRSPC_FAM_RGB 4 +#define JAS_CLRSPC_FAM_YCBCR 5 + +/* specific color spaces */ +#define JAS_CLRSPC_UNKNOWN JAS_CLRSPC_UNKNOWNMASK +#define JAS_CLRSPC_CIEXYZ jas_clrspc_create(JAS_CLRSPC_FAM_XYZ, 1) +#define JAS_CLRSPC_CIELAB jas_clrspc_create(JAS_CLRSPC_FAM_LAB, 1) +#define JAS_CLRSPC_SGRAY jas_clrspc_create(JAS_CLRSPC_FAM_GRAY, 1) +#define JAS_CLRSPC_SRGB jas_clrspc_create(JAS_CLRSPC_FAM_RGB, 1) +#define JAS_CLRSPC_SYCBCR jas_clrspc_create(JAS_CLRSPC_FAM_YCBCR, 1) + +/* generic color spaces */ +#define JAS_CLRSPC_GENRGB jas_clrspc_create(JAS_CLRSPC_FAM_RGB, 0) +#define JAS_CLRSPC_GENGRAY jas_clrspc_create(JAS_CLRSPC_FAM_GRAY, 0) +#define JAS_CLRSPC_GENYCBCR jas_clrspc_create(JAS_CLRSPC_FAM_YCBCR, 0) + +#define JAS_CLRSPC_CHANIND_YCBCR_Y 0 +#define JAS_CLRSPC_CHANIND_YCBCR_CB 1 +#define JAS_CLRSPC_CHANIND_YCBCR_CR 2 + +#define JAS_CLRSPC_CHANIND_RGB_R 0 +#define JAS_CLRSPC_CHANIND_RGB_G 1 +#define JAS_CLRSPC_CHANIND_RGB_B 2 + +#define JAS_CLRSPC_CHANIND_GRAY_Y 0 + +typedef double jas_cmreal_t; + +struct jas_cmpxform_s; + +typedef struct { + long *buf; + int prec; + int sgnd; + int width; + int height; +} jas_cmcmptfmt_t; + +typedef struct { + int numcmpts; + jas_cmcmptfmt_t *cmptfmts; +} jas_cmpixmap_t; + +typedef struct { + void (*destroy)(struct jas_cmpxform_s *pxform); + int (*apply)(struct jas_cmpxform_s *pxform, jas_cmreal_t *in, jas_cmreal_t *out, int cnt); + void (*dump)(struct jas_cmpxform_s *pxform); +} jas_cmpxformops_t; + +typedef struct { + jas_cmreal_t *data; + int size; +} jas_cmshapmatlut_t; + +typedef struct { + int mono; + int order; + int useluts; + int usemat; + jas_cmshapmatlut_t luts[3]; + jas_cmreal_t mat[3][4]; +} jas_cmshapmat_t; + +typedef struct { + int order; +} jas_cmshaplut_t; + +typedef struct { + int inclrspc; + int outclrspc; +} jas_cmclrspcconv_t; + +#define jas_align_t double + +typedef struct jas_cmpxform_s { + int refcnt; + jas_cmpxformops_t *ops; + int numinchans; + int numoutchans; + union { + jas_align_t dummy; + jas_cmshapmat_t shapmat; + jas_cmshaplut_t shaplut; + jas_cmclrspcconv_t clrspcconv; + } data; +} jas_cmpxform_t; + +typedef struct { + int numpxforms; + int maxpxforms; + jas_cmpxform_t **pxforms; +} jas_cmpxformseq_t; + +typedef struct { + int numinchans; + int numoutchans; + jas_cmpxformseq_t *pxformseq; +} jas_cmxform_t; + +#define JAS_CMPROF_TYPE_DEV 1 +#define JAS_CMPROF_TYPE_CLRSPC 2 + +#define JAS_CMPROF_NUMPXFORMSEQS 13 + +typedef struct { + int clrspc; + int numchans; + int refclrspc; + int numrefchans; + jas_iccprof_t *iccprof; + jas_cmpxformseq_t *pxformseqs[JAS_CMPROF_NUMPXFORMSEQS]; +} jas_cmprof_t; + +/* Create a profile. */ + +/* Destroy a profile. */ +void jas_cmprof_destroy(jas_cmprof_t *prof); + +#if 0 +typedef int_fast32_t jas_cmattrname_t; +typedef int_fast32_t jas_cmattrval_t; +typedef int_fast32_t jas_cmattrtype_t; +/* Load a profile. */ +int jas_cmprof_load(jas_cmprof_t *prof, jas_stream_t *in, int fmt); +/* Save a profile. */ +int jas_cmprof_save(jas_cmprof_t *prof, jas_stream_t *out, int fmt); +/* Set an attribute of a profile. */ +int jas_cm_prof_setattr(jas_cm_prof_t *prof, jas_cm_attrname_t name, void *val); +/* Get an attribute of a profile. */ +void *jas_cm_prof_getattr(jas_cm_prof_t *prof, jas_cm_attrname_t name); +#endif + +jas_cmxform_t *jas_cmxform_create(jas_cmprof_t *inprof, jas_cmprof_t *outprof, + jas_cmprof_t *proofprof, int op, int intent, int optimize); + +void jas_cmxform_destroy(jas_cmxform_t *xform); + +/* Apply a transform to data. */ +int jas_cmxform_apply(jas_cmxform_t *xform, jas_cmpixmap_t *in, + jas_cmpixmap_t *out); + +int jas_cxform_optimize(jas_cmxform_t *xform, int optimize); + +int jas_clrspc_numchans(int clrspc); +jas_cmprof_t *jas_cmprof_createfromiccprof(jas_iccprof_t *iccprof); +jas_cmprof_t *jas_cmprof_createfromclrspc(int clrspc); +jas_iccprof_t *jas_iccprof_createfromcmprof(jas_cmprof_t *prof); + +#define jas_cmprof_clrspc(prof) ((prof)->clrspc) +jas_cmprof_t *jas_cmprof_copy(jas_cmprof_t *prof); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config.h new file mode 100644 index 0000000..9036ce1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config.h @@ -0,0 +1,231 @@ +/* src/libjasper/include/jasper/jas_config.h. Generated automatically by configure. */ +/* src/libjasper/include/jasper/jas_config.h.in. Generated automatically from configure.in by autoheader. */ + +/* + * Copyright (c) 2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JAS_CONFIG_H +#define JAS_CONFIG_H + +/* This identifies the version of JasPer. */ +#define JAS_VERSION "1.700.2" + +/* The preprocessor symbol JAS_WIN_MSVC_BUILD should not be defined + unless the JasPer software is being built under Microsoft Windows + using Microsoft Visual C. */ +#ifndef JAS_WIN_MSVC_BUILD + +/* Define to empty if the keyword does not work. */ +/* #undef const */ + +/* Define if you don't have vprintf but do have _doprnt. */ +/* #undef HAVE_DOPRNT */ + +/* Define if you have the vprintf function. */ +#define HAVE_VPRINTF 1 + +/* Define as __inline if that's what the C compiler calls it. */ +/* #undef inline */ + +/* Define to `unsigned' if doesn't define. */ +/* #undef size_t */ + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define if your processor stores words with the most significant + byte first (like Motorola and SPARC, unlike Intel and VAX). */ +/* #undef WORDS_BIGENDIAN */ + +/* Define if the X Window System is missing or not being used. */ +/* #undef X_DISPLAY_MISSING */ + +#define JAS_CONFIGURE 1 +#define JAS_VERSION "1.700.2" +/* #undef DEBUG_MEMALLOC */ +/* #undef DEBUG_OVERFLOW */ +/* #undef ushort */ +/* #undef uint */ +#define uchar unsigned char +#define longlong long long +#define ulonglong unsigned long long +/* #undef ssize_t */ + +/* The number of bytes in a int. */ +#define SIZEOF_INT 4 + +/* The number of bytes in a long. */ +#define SIZEOF_LONG 4 + +/* The number of bytes in a long long. */ +#define SIZEOF_LONG_LONG 8 + +/* The number of bytes in a short. */ +#define SIZEOF_SHORT 2 + +/* The number of bytes in a unsigned int. */ +#define SIZEOF_UNSIGNED_INT 4 + +/* The number of bytes in a unsigned long. */ +#define SIZEOF_UNSIGNED_LONG 4 + +/* The number of bytes in a unsigned long long. */ +#define SIZEOF_UNSIGNED_LONG_LONG 8 + +/* The number of bytes in a unsigned short. */ +#define SIZEOF_UNSIGNED_SHORT 2 + +/* Define if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define if you have the header file. */ +/* #undef HAVE_IO_H */ + +/* Define if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define if you have the header file. */ +#define HAVE_STDBOOL_H 1 + +/* Define if you have the header file. */ +#define HAVE_STDDEF_H 1 + +/* Define if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define if you have the header file. */ +/* #undef HAVE_WINDOWS_H */ + +/* Define if you have the m library (-lm). */ +#define HAVE_LIBM 1 + +/* Name of package */ +#define PACKAGE "jasper" + +/* Version number of package */ +#define VERSION "1.700.2" + +#else +#include +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config.h.in b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config.h.in new file mode 100644 index 0000000..66b0a8a --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config.h.in @@ -0,0 +1,230 @@ +/* src/libjasper/include/jasper/jas_config.h.in. Generated automatically from configure.in by autoheader. */ + +/* + * Copyright (c) 2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JAS_CONFIG_H +#define JAS_CONFIG_H + +/* This identifies the version of JasPer. */ +#undef JAS_VERSION + +/* The preprocessor symbol JAS_WIN_MSVC_BUILD should not be defined + unless the JasPer software is being built under Microsoft Windows + using Microsoft Visual C. */ +#ifndef JAS_WIN_MSVC_BUILD + +/* Define to empty if the keyword does not work. */ +#undef const + +/* Define if you don't have vprintf but do have _doprnt. */ +#undef HAVE_DOPRNT + +/* Define if you have the vprintf function. */ +#undef HAVE_VPRINTF + +/* Define as __inline if that's what the C compiler calls it. */ +#undef inline + +/* Define to `unsigned' if doesn't define. */ +#undef size_t + +/* Define if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Define if your processor stores words with the most significant + byte first (like Motorola and SPARC, unlike Intel and VAX). */ +#undef WORDS_BIGENDIAN + +/* Define if the X Window System is missing or not being used. */ +#undef X_DISPLAY_MISSING + +#undef JAS_CONFIGURE +#undef JAS_VERSION +#undef DEBUG_MEMALLOC +#undef DEBUG_OVERFLOW +#undef ushort +#undef uint +#undef uchar +#undef longlong +#undef ulonglong +#undef ssize_t + +/* The number of bytes in a int. */ +#undef SIZEOF_INT + +/* The number of bytes in a long. */ +#undef SIZEOF_LONG + +/* The number of bytes in a long long. */ +#undef SIZEOF_LONG_LONG + +/* The number of bytes in a short. */ +#undef SIZEOF_SHORT + +/* The number of bytes in a unsigned int. */ +#undef SIZEOF_UNSIGNED_INT + +/* The number of bytes in a unsigned long. */ +#undef SIZEOF_UNSIGNED_LONG + +/* The number of bytes in a unsigned long long. */ +#undef SIZEOF_UNSIGNED_LONG_LONG + +/* The number of bytes in a unsigned short. */ +#undef SIZEOF_UNSIGNED_SHORT + +/* Define if you have the header file. */ +#undef HAVE_DLFCN_H + +/* Define if you have the header file. */ +#undef HAVE_FCNTL_H + +/* Define if you have the header file. */ +#undef HAVE_IO_H + +/* Define if you have the header file. */ +#undef HAVE_LIMITS_H + +/* Define if you have the header file. */ +#undef HAVE_STDBOOL_H + +/* Define if you have the header file. */ +#undef HAVE_STDDEF_H + +/* Define if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Define if you have the header file. */ +#undef HAVE_WINDOWS_H + +/* Define if you have the m library (-lm). */ +#undef HAVE_LIBM + +/* Name of package */ +#undef PACKAGE + +/* Version number of package */ +#undef VERSION + +#else +#include +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config2.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config2.h new file mode 100644 index 0000000..b2986f9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_config2.h @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2002-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JAS_CONFIG2_H +#define JAS_CONFIG2_H + +/* + * Configuration for Microsoft Windows and Microsoft Visual C. + * + * We are not using a configure-based build. + * Try to compensate for this here, by specifying the preprocessor symbols + * normally defined by configure. + */ + +#define uchar unsigned char +#define ushort unsigned short +#define uint unsigned int +#define ulong unsigned long +#define longlong long long +#define ulonglong unsigned long long +/*#define ssize_t int*/ + +#define HAVE_FCNTL_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_IO_H 1 +#define HAVE_WINDOWS_H 1 +#define HAVE_SYS_TYPES_H 1 + +#if !defined(HAVE_STDLIB_H) + #define HAVE_STDLIB_H 1 +#endif + +#if !defined(HAVE_STDDEF_H) + #define HAVE_STDDEF_H 1 +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_debug.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_debug.h new file mode 100644 index 0000000..fd8c22b --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_debug.h @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Debugging-Related Code + * + * $Id$ + */ + +#ifndef JAS_DEBUG_H +#define JAS_DEBUG_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include +#include "jasper/jas_types.h" +#include "jasper/jas_debug.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Macros and functions. +\******************************************************************************/ + +/* Output debugging information to standard error provided that the debug + level is set sufficiently high. */ +#if defined(DEBUG) +#define JAS_DBGLOG(n, x) \ + ((jas_getdbglevel() >= (n)) ? (jas_eprintf x) : 0) +#else +#define JAS_DBGLOG(n, x) +#endif + +/* Get the library debug level. */ +int jas_getdbglevel(void); + +/* Set the library debug level. */ +int jas_setdbglevel(int dbglevel); + +/* Perform formatted output to standard error. */ +int jas_eprintf(const char *fmt, ...); + +/* Dump memory to a stream. */ +int jas_memdump(FILE *out, void *data, size_t len); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_fix.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_fix.h new file mode 100644 index 0000000..3171725 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_fix.h @@ -0,0 +1,407 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Fixed-Point Number Class + * + * $Id$ + */ + +#ifndef JAS_FIX_H +#define JAS_FIX_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* The representation of the value zero. */ +#define JAS_FIX_ZERO(fix_t, fracbits) \ + JAS_CAST(fix_t, 0) + +/* The representation of the value one. */ +#define JAS_FIX_ONE(fix_t, fracbits) \ + (JAS_CAST(fix_t, 1) << (fracbits)) + +/* The representation of the value one half. */ +#define JAS_FIX_HALF(fix_t, fracbits) \ + (JAS_CAST(fix_t, 1) << ((fracbits) - 1)) + +/******************************************************************************\ +* Conversion operations. +\******************************************************************************/ + +/* Convert an int to a fixed-point number. */ +#define JAS_INTTOFIX(fix_t, fracbits, x) \ + JAS_CAST(fix_t, (x) << (fracbits)) + +/* Convert a fixed-point number to an int. */ +#define JAS_FIXTOINT(fix_t, fracbits, x) \ + JAS_CAST(int, (x) >> (fracbits)) + +/* Convert a fixed-point number to a double. */ +#define JAS_FIXTODBL(fix_t, fracbits, x) \ + (JAS_CAST(double, x) / (JAS_CAST(fix_t, 1) << (fracbits))) + +/* Convert a double to a fixed-point number. */ +#define JAS_DBLTOFIX(fix_t, fracbits, x) \ + JAS_CAST(fix_t, ((x) * JAS_CAST(double, JAS_CAST(fix_t, 1) << (fracbits)))) + +/******************************************************************************\ +* Basic arithmetic operations. +* All other arithmetic operations are synthesized from these basic operations. +* There are three macros for each type of arithmetic operation. +* One macro always performs overflow/underflow checking, one never performs +* overflow/underflow checking, and one is generic with its behavior +* depending on compile-time flags. +* Only the generic macros should be invoked directly by application code. +\******************************************************************************/ + +/* Calculate the sum of two fixed-point numbers. */ +#if !defined(DEBUG_OVERFLOW) +#define JAS_FIX_ADD JAS_FIX_ADD_FAST +#else +#define JAS_FIX_ADD JAS_FIX_ADD_OFLOW +#endif + +/* Calculate the sum of two fixed-point numbers without overflow checking. */ +#define JAS_FIX_ADD_FAST(fix_t, fracbits, x, y) ((x) + (y)) + +/* Calculate the sum of two fixed-point numbers with overflow checking. */ +#define JAS_FIX_ADD_OFLOW(fix_t, fracbits, x, y) \ + ((x) >= 0) ? \ + (((y) >= 0) ? ((x) + (y) >= 0 || JAS_FIX_OFLOW(), (x) + (y)) : \ + ((x) + (y))) : \ + (((y) >= 0) ? ((x) + (y)) : ((x) + (y) < 0 || JAS_FIX_OFLOW(), \ + (x) + (y))) + +/* Calculate the product of two fixed-point numbers. */ +#if !defined(DEBUG_OVERFLOW) +#define JAS_FIX_MUL JAS_FIX_MUL_FAST +#else +#define JAS_FIX_MUL JAS_FIX_MUL_OFLOW +#endif + +/* Calculate the product of two fixed-point numbers without overflow + checking. */ +#define JAS_FIX_MUL_FAST(fix_t, fracbits, bigfix_t, x, y) \ + JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y)) >> \ + (fracbits)) + +/* Calculate the product of two fixed-point numbers with overflow + checking. */ +#define JAS_FIX_MUL_OFLOW(fix_t, fracbits, bigfix_t, x, y) \ + ((JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> (fracbits)) == \ + JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \ + (fracbits))) ? \ + JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \ + (fracbits))) : JAS_FIX_OFLOW()) + +/* Calculate the product of a fixed-point number and an int. */ +#if !defined(DEBUG_OVERFLOW) +#define JAS_FIX_MULBYINT JAS_FIX_MULBYINT_FAST +#else +#define JAS_FIX_MULBYINT JAS_FIX_MULBYINT_OFLOW +#endif + +/* Calculate the product of a fixed-point number and an int without overflow + checking. */ +#define JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y) \ + JAS_CAST(fix_t, ((x) * (y))) + +/* Calculate the product of a fixed-point number and an int with overflow + checking. */ +#define JAS_FIX_MULBYINT_OFLOW(fix_t, fracbits, x, y) \ + JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y) + +/* Calculate the quotient of two fixed-point numbers. */ +#if !defined(DEBUG_OVERFLOW) +#define JAS_FIX_DIV JAS_FIX_DIV_FAST +#else +#define JAS_FIX_DIV JAS_FIX_DIV_UFLOW +#endif + +/* Calculate the quotient of two fixed-point numbers without underflow + checking. */ +#define JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y) \ + JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) << (fracbits)) / (y)) + +/* Calculate the quotient of two fixed-point numbers with underflow + checking. */ +#define JAS_FIX_DIV_UFLOW(fix_t, fracbits, bigfix_t, x, y) \ + JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y) + +/* Negate a fixed-point number. */ +#if !defined(DEBUG_OVERFLOW) +#define JAS_FIX_NEG JAS_FIX_NEG_FAST +#else +#define JAS_FIX_NEG JAS_FIX_NEG_OFLOW +#endif + +/* Negate a fixed-point number without overflow checking. */ +#define JAS_FIX_NEG_FAST(fix_t, fracbits, x) \ + (-(x)) + +/* Negate a fixed-point number with overflow checking. */ +/* Yes, overflow is actually possible for two's complement representations, + although highly unlikely to occur. */ +#define JAS_FIX_NEG_OFLOW(fix_t, fracbits, x) \ + (((x) < 0) ? (-(x) > 0 || JAS_FIX_OFLOW(), -(x)) : (-(x))) + +/* Perform an arithmetic shift left of a fixed-point number. */ +#if !defined(DEBUG_OVERFLOW) +#define JAS_FIX_ASL JAS_FIX_ASL_FAST +#else +#define JAS_FIX_ASL JAS_FIX_ASL_OFLOW +#endif + +/* Perform an arithmetic shift left of a fixed-point number without overflow + checking. */ +#define JAS_FIX_ASL_FAST(fix_t, fracbits, x, n) \ + ((x) << (n)) + +/* Perform an arithmetic shift left of a fixed-point number with overflow + checking. */ +#define JAS_FIX_ASL_OFLOW(fix_t, fracbits, x, n) \ + ((((x) << (n)) >> (n)) == (x) || JAS_FIX_OFLOW(), (x) << (n)) + +/* Perform an arithmetic shift right of a fixed-point number. */ +#if !defined(DEBUG_OVERFLOW) +#define JAS_FIX_ASR JAS_FIX_ASR_FAST +#else +#define JAS_FIX_ASR JAS_FIX_ASR_UFLOW +#endif + +/* Perform an arithmetic shift right of a fixed-point number without underflow + checking. */ +#define JAS_FIX_ASR_FAST(fix_t, fracbits, x, n) \ + ((x) >> (n)) + +/* Perform an arithmetic shift right of a fixed-point number with underflow + checking. */ +#define JAS_FIX_ASR_UFLOW(fix_t, fracbits, x, n) \ + JAS_FIX_ASR_FAST(fix_t, fracbits, x, n) + +/******************************************************************************\ +* Other basic arithmetic operations. +\******************************************************************************/ + +/* Calculate the difference between two fixed-point numbers. */ +#define JAS_FIX_SUB(fix_t, fracbits, x, y) \ + JAS_FIX_ADD(fix_t, fracbits, x, JAS_FIX_NEG(fix_t, fracbits, y)) + +/* Add one fixed-point number to another. */ +#define JAS_FIX_PLUSEQ(fix_t, fracbits, x, y) \ + ((x) = JAS_FIX_ADD(fix_t, fracbits, x, y)) + +/* Subtract one fixed-point number from another. */ +#define JAS_FIX_MINUSEQ(fix_t, fracbits, x, y) \ + ((x) = JAS_FIX_SUB(fix_t, fracbits, x, y)) + +/* Multiply one fixed-point number by another. */ +#define JAS_FIX_MULEQ(fix_t, fracbits, bigfix_t, x, y) \ + ((x) = JAS_FIX_MUL(fix_t, fracbits, bigfix_t, x, y)) + +/******************************************************************************\ +* Miscellaneous operations. +\******************************************************************************/ + +/* Calculate the absolute value of a fixed-point number. */ +#define JAS_FIX_ABS(fix_t, fracbits, x) \ + (((x) >= 0) ? (x) : (JAS_FIX_NEG(fix_t, fracbits, x))) + +/* Is a fixed-point number an integer? */ +#define JAS_FIX_ISINT(fix_t, fracbits, x) \ + (JAS_FIX_FLOOR(fix_t, fracbits, x) == (x)) + +/* Get the sign of a fixed-point number. */ +#define JAS_FIX_SGN(fix_t, fracbits, x) \ + ((x) >= 0 ? 1 : (-1)) + +/******************************************************************************\ +* Relational operations. +\******************************************************************************/ + +/* Compare two fixed-point numbers. */ +#define JAS_FIX_CMP(fix_t, fracbits, x, y) \ + ((x) > (y) ? 1 : (((x) == (y)) ? 0 : (-1))) + +/* Less than. */ +#define JAS_FIX_LT(fix_t, fracbits, x, y) \ + ((x) < (y)) + +/* Less than or equal. */ +#define JAS_FIX_LTE(fix_t, fracbits, x, y) \ + ((x) <= (y)) + +/* Greater than. */ +#define JAS_FIX_GT(fix_t, fracbits, x, y) \ + ((x) > (y)) + +/* Greater than or equal. */ +#define JAS_FIX_GTE(fix_t, fracbits, x, y) \ + ((x) >= (y)) + +/******************************************************************************\ +* Rounding functions. +\******************************************************************************/ + +/* Round a fixed-point number to the nearest integer. */ +#define JAS_FIX_ROUND(fix_t, fracbits, x) \ + (((x) < 0) ? JAS_FIX_FLOOR(fix_t, fracbits, JAS_FIX_ADD(fix_t, fracbits, \ + (x), JAS_FIX_HALF(fix_t, fracbits))) : \ + JAS_FIX_NEG(fix_t, fracbits, JAS_FIX_FLOOR(fix_t, fracbits, \ + JAS_FIX_ADD(fix_t, fracbits, (-(x)), JAS_FIX_HALF(fix_t, fracbits))))) + +/* Round a fixed-point number to the nearest integer in the direction of + negative infinity (i.e., the floor function). */ +#define JAS_FIX_FLOOR(fix_t, fracbits, x) \ + ((x) & (~((JAS_CAST(fix_t, 1) << (fracbits)) - 1))) + +/* Round a fixed-point number to the nearest integer in the direction + of zero. */ +#define JAS_FIX_TRUNC(fix_t, fracbits, x) \ + (((x) >= 0) ? JAS_FIX_FLOOR(fix_t, fracbits, x) : \ + JAS_FIX_CEIL(fix_t, fracbits, x)) + +/******************************************************************************\ +* The below macros are for internal library use only. Do not invoke them +* directly in application code. +\******************************************************************************/ + +/* Handle overflow. */ +#define JAS_FIX_OFLOW() \ + fprintf(stderr, "overflow error: file %s, line %d\n", __FILE__, __LINE__) + +/* Handle underflow. */ +#define JAS_FIX_UFLOW() \ + fprintf(stderr, "underflow error: file %s, line %d\n", __FILE__, __LINE__) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_getopt.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_getopt.h new file mode 100644 index 0000000..76e150e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_getopt.h @@ -0,0 +1,180 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Command Line Option Parsing Code + * + * $Id$ + */ + +#ifndef JAS_GETOPT_H +#define JAS_GETOPT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +#define JAS_GETOPT_EOF (-1) +#define JAS_GETOPT_ERR '?' + +/* option flags. */ +#define JAS_OPT_HASARG 0x01 /* option has argument */ + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* Command line option type. */ +typedef struct { + + int id; + /* The unique identifier for this option. */ + + char *name; + /* The name of this option. */ + + int flags; + /* option flags. */ + +} jas_opt_t; + +/******************************************************************************\ +* External data. +\******************************************************************************/ + +/* The current option index. */ +extern int jas_optind; + +/* The current option argument. */ +extern char *jas_optarg; + +/* The debug level. */ +extern int jas_opterr; + +/******************************************************************************\ +* Prototypes. +\******************************************************************************/ + +/* Get the next option. */ +int jas_getopt(int argc, char **argv, jas_opt_t *opts); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_icc.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_icc.h new file mode 100644 index 0000000..e0ee932 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_icc.h @@ -0,0 +1,456 @@ +/* + * Copyright (c) 2002-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JAS_ICC_H +#define JAS_ICC_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Profile file signature. */ +#define JAS_ICC_MAGIC 0x61637370 + +#define JAS_ICC_HDRLEN 128 + +/* Profile/device class signatures. */ +#define JAS_ICC_CLAS_IN 0x73636e72 /* input device */ +#define JAS_ICC_CLAS_DPY 0x6d6e7472 /* display device */ +#define JAS_ICC_CLAS_OUT 0x70727472 /* output device */ +#define JAS_ICC_CLAS_LNK 0x6c696e6b /* device link */ +#define JAS_ICC_CLAS_CNV 0x73706163 /* color space conversion */ +#define JAS_ICC_CLAS_ABS 0x61627374 /* abstract */ +#define JAS_ICC_CLAS_NAM 0x6e6d636c /* named color */ + +/* Color space signatures. */ +#define JAS_ICC_COLORSPC_XYZ 0x58595a20 /* XYZ */ +#define JAS_ICC_COLORSPC_LAB 0x4c616220 /* LAB */ +#define JAS_ICC_COLORSPC_LUV 0x4c757620 /* LUV */ +#define JAS_ICC_COLORSPC_YCBCR 0x59436272 /* YCbCr */ +#define JAS_ICC_COLORSPC_YXY 0x59787920 /* Yxy */ +#define JAS_ICC_COLORSPC_RGB 0x52474220 /* RGB */ +#define JAS_ICC_COLORSPC_GRAY 0x47524159 /* Gray */ +#define JAS_ICC_COLORSPC_HSV 0x48535620 /* HSV */ +#define JAS_ICC_COLORSPC_HLS 0x484c5320 /* HLS */ +#define JAS_ICC_COLORSPC_CMYK 0x434d594b /* CMYK */ +#define JAS_ICC_COLORSPC_CMY 0x434d5920 /* CMY */ +#define JAS_ICC_COLORSPC_2 0x32434c52 /* 2 channel color */ +#define JAS_ICC_COLORSPC_3 0x33434c52 /* 3 channel color */ +#define JAS_ICC_COLORSPC_4 0x34434c52 /* 4 channel color */ +#define JAS_ICC_COLORSPC_5 0x35434c52 /* 5 channel color */ +#define JAS_ICC_COLORSPC_6 0x36434c52 /* 6 channel color */ +#define JAS_ICC_COLORSPC_7 0x37434c52 /* 7 channel color */ +#define JAS_ICC_COLORSPC_8 0x38434c52 /* 8 channel color */ +#define JAS_ICC_COLORSPC_9 0x39434c52 /* 9 channel color */ +#define JAS_ICC_COLORSPC_10 0x41434c52 /* 10 channel color */ +#define JAS_ICC_COLORSPC_11 0x42434c52 /* 11 channel color */ +#define JAS_ICC_COLORSPC_12 0x43434c52 /* 12 channel color */ +#define JAS_ICC_COLORSPC_13 0x44434c52 /* 13 channel color */ +#define JAS_ICC_COLORSPC_14 0x45434c52 /* 14 channel color */ +#define JAS_ICC_COLORSPC_15 0x46434c52 /* 15 channel color */ + +/* Profile connection color space (PCS) signatures. */ +#define JAS_ICC_REFCOLORSPC_XYZ 0x58595a20 /* CIE XYZ */ +#define JAS_ICC_REFCOLORSPC_LAB 0x4c616220 /* CIE Lab */ + +/* Primary platform signatures. */ +#define JAS_ICC_PLATFORM_APPL 0x4150504c /* Apple Computer */ +#define JAS_ICC_PLATFORM_MSFT 0x4d534654 /* Microsoft */ +#define JAS_ICC_PLATFORM_SGI 0x53474920 /* Silicon Graphics */ +#define JAS_ICC_PLATFORM_SUNW 0x53554e57 /* Sun Microsystems */ +#define JAS_ICC_PLATFORM_TGNT 0x54474e54 /* Taligent */ + +/* Profile flags. */ +#define JAS_ICC_FLAGS_EMBED 0x01 /* embedded */ +#define JAS_ICC_FLAGS_NOSEP 0x02 /* no separate use */ + +/* Attributes. */ +#define JAS_ICC_ATTR_TRANS 0x01 /* transparent */ +#define JAS_ICC_ATTR_MATTE 0x02 /* matte */ + +/* Rendering intents. */ +#define JAS_ICC_INTENT_PER 0 /* perceptual */ +#define JAS_ICC_INTENT_REL 1 /* relative colorimetric */ +#define JAS_ICC_INTENT_SAT 2 /* saturation */ +#define JAS_ICC_INTENT_ABS 3 /* absolute colorimetric */ + +/* Tag signatures. */ +#define JAS_ICC_TAG_ATOB0 0x41324230 /* */ +#define JAS_ICC_TAG_ATOB1 0x41324231 /* */ +#define JAS_ICC_TAG_ATOB2 0x41324232 /* */ +#define JAS_ICC_TAG_BLUMATCOL 0x6258595a /* */ +#define JAS_ICC_TAG_BLUTRC 0x62545243 /* */ +#define JAS_ICC_TAG_BTOA0 0x42324130 /* */ +#define JAS_ICC_TAG_BTOA1 0x42324131 /* */ +#define JAS_ICC_TAG_BTOA2 0x42324132 /* */ +#define JAS_ICC_TAG_CALTIME 0x63616c74 /* */ +#define JAS_ICC_TAG_CHARTARGET 0x74617267 /* */ +#define JAS_ICC_TAG_CPYRT 0x63707274 /* */ +#define JAS_ICC_TAG_CRDINFO 0x63726469 /* */ +#define JAS_ICC_TAG_DEVMAKERDESC 0x646d6e64 /* */ +#define JAS_ICC_TAG_DEVMODELDESC 0x646d6464 /* */ +#define JAS_ICC_TAG_DEVSET 0x64657673 /* */ +#define JAS_ICC_TAG_GAMUT 0x67616d74 /* */ +#define JAS_ICC_TAG_GRYTRC 0x6b545243 /* */ +#define JAS_ICC_TAG_GRNMATCOL 0x6758595a /* */ +#define JAS_ICC_TAG_GRNTRC 0x67545243 /* */ +#define JAS_ICC_TAG_LUM 0x6c756d69 /* */ +#define JAS_ICC_TAG_MEASURE 0x6d656173 /* */ +#define JAS_ICC_TAG_MEDIABLKPT 0x626b7074 /* */ +#define JAS_ICC_TAG_MEDIAWHIPT 0x77747074 /* */ +#define JAS_ICC_TAG_NAMCOLR 0x6e636f6c /* */ +#define JAS_ICC_TAG_NAMCOLR2 0x6e636c32 /* */ +#define JAS_ICC_TAG_OUTRESP 0x72657370 /* */ +#define JAS_ICC_TAG_PREVIEW0 0x70726530 /* */ +#define JAS_ICC_TAG_PREVIEW1 0x70726531 /* */ +#define JAS_ICC_TAG_PREVIEW2 0x70726532 /* */ +#define JAS_ICC_TAG_PROFDESC 0x64657363 /* */ +#define JAS_ICC_TAG_PROFSEQDESC 0x70736571 /* */ +#define JAS_ICC_TAG_PSDCRD0 0x70736430 /* */ +#define JAS_ICC_TAG_PSCRDD1 0x70736431 /* */ +#define JAS_ICC_TAG_PSCRDD2 0x70736432 /* */ +#define JAS_ICC_TAG_PSCRDD3 0x70736433 /* */ +#define JAS_ICC_TAG_PS2CSA 0x70733273 /* */ +#define JAS_ICC_TAG_PS2RENINTENT 0x70733269 /* */ +#define JAS_ICC_TAG_REDMATCOL 0x7258595a /* */ +#define JAS_ICC_TAG_REDTRC 0x72545243 /* */ +#define JAS_ICC_TAG_SCRNGDES 0x73637264 /* */ +#define JAS_ICC_TAG_SCRNG 0x7363726e /* */ +#define JAS_ICC_TAG_TECH 0x74656368 /* */ +#define JAS_ICC_TAG_UCRBG 0x62666420 /* */ +#define JAS_ICC_TAG_VIEWCONDDESC 0x76756564 /* */ +#define JAS_ICC_TAG_VIEWCOND 0x76696577 /* */ + +/* Type signatures. */ +#define JAS_ICC_TYPE_CRDINFO 0x63726469 /* CRD information */ +#define JAS_ICC_TYPE_CURV 0x63757276 /* curve */ +#define JAS_ICC_TYPE_DATA 0x64617461 /* data */ +#define JAS_ICC_TYPE_TIME 0x6474696d /* date/time */ +#define JAS_ICC_TYPE_DEVSET 0x64657673 /* device settings */ +#define JAS_ICC_TYPE_LUT16 0x6d667432 /* */ +#define JAS_ICC_TYPE_LUT8 0x6d667431 /* */ +#define JAS_ICC_TYPE_MEASURE 0x6d656173 /* */ +#define JAS_ICC_TYPE_NAMCOLR 0x6e636f6c /* */ +#define JAS_ICC_TYPE_NAMCOLR2 0x6e636c32 /* */ +#define JAS_ICC_TYPE_PROFSEQDESC 0x70736571 /* profile sequence description */ +#define JAS_ICC_TYPE_RESPCURVSET16 0x72637332 /* response curve set 16 */ +#define JAS_ICC_TYPE_SF32 0x73663332 /* signed 32-bit fixed-point */ +#define JAS_ICC_TYPE_SCRNG 0x7363726e /* screening */ +#define JAS_ICC_TYPE_SIG 0x73696720 /* signature */ +#define JAS_ICC_TYPE_TXTDESC 0x64657363 /* text description */ +#define JAS_ICC_TYPE_TXT 0x74657874 /* text */ +#define JAS_ICC_TYPE_UF32 0x75663332 /* unsigned 32-bit fixed-point */ +#define JAS_ICC_TYPE_UCRBG 0x62666420 /* */ +#define JAS_ICC_TYPE_UI16 0x75693136 /* */ +#define JAS_ICC_TYPE_UI32 0x75693332 /* */ +#define JAS_ICC_TYPE_UI8 0x75693038 /* */ +#define JAS_ICC_TYPE_UI64 0x75693634 /* */ +#define JAS_ICC_TYPE_VIEWCOND 0x76696577 /* */ +#define JAS_ICC_TYPE_XYZ 0x58595a20 /* XYZ */ + +typedef uint_fast8_t jas_iccuint8_t; +typedef uint_fast16_t jas_iccuint16_t; +typedef uint_fast32_t jas_iccuint32_t; +typedef int_fast32_t jas_iccsint32_t; +typedef int_fast32_t jas_iccs15fixed16_t; +typedef uint_fast32_t jas_iccu16fixed16_t; +typedef uint_fast64_t jas_iccuint64_t; +typedef uint_fast32_t jas_iccsig_t; + +typedef jas_iccsig_t jas_icctagsig_t; +typedef jas_iccsig_t jas_icctagtype_t; +typedef jas_iccsig_t jas_iccattrname_t; + +/* Date/time type. */ +typedef struct { + jas_iccuint16_t year; + jas_iccuint16_t month; + jas_iccuint16_t day; + jas_iccuint16_t hour; + jas_iccuint16_t min; + jas_iccuint16_t sec; +} jas_icctime_t; + +/* XYZ type. */ +typedef struct { + jas_iccs15fixed16_t x; + jas_iccs15fixed16_t y; + jas_iccs15fixed16_t z; +} jas_iccxyz_t; + +/* Curve type. */ +typedef struct { + jas_iccuint32_t numents; + jas_iccuint16_t *ents; +} jas_icccurv_t; + +/* Text description type. */ +typedef struct { + jas_iccuint32_t asclen; + char *ascdata; /* ASCII invariant description */ + jas_iccuint32_t uclangcode; /* Unicode language code */ + jas_iccuint32_t uclen; /* Unicode localizable description count */ + uchar *ucdata; /* Unicode localizable description */ + jas_iccuint16_t sccode; /* ScriptCode code */ + jas_iccuint8_t maclen; /* Localizable Macintosh description count */ + uchar macdata[69]; /* Localizable Macintosh description */ +} jas_icctxtdesc_t; + +/* Text type. */ +typedef struct { + char *string; /* ASCII character string */ +} jas_icctxt_t; + +typedef struct { + jas_iccuint8_t numinchans; + jas_iccuint8_t numoutchans; + jas_iccsint32_t e[3][3]; + jas_iccuint8_t clutlen; + jas_iccuint8_t *clut; + jas_iccuint16_t numintabents; + jas_iccuint8_t **intabs; + jas_iccuint8_t *intabsbuf; + jas_iccuint16_t numouttabents; + jas_iccuint8_t **outtabs; + jas_iccuint8_t *outtabsbuf; +} jas_icclut8_t; + +typedef struct { + jas_iccuint8_t numinchans; + jas_iccuint8_t numoutchans; + jas_iccsint32_t e[3][3]; + jas_iccuint8_t clutlen; + jas_iccuint16_t *clut; + jas_iccuint16_t numintabents; + jas_iccuint16_t **intabs; + jas_iccuint16_t *intabsbuf; + jas_iccuint16_t numouttabents; + jas_iccuint16_t **outtabs; + jas_iccuint16_t *outtabsbuf; +} jas_icclut16_t; + +struct jas_iccattrval_s; + +typedef struct { + void (*destroy)(struct jas_iccattrval_s *); + int (*copy)(struct jas_iccattrval_s *, struct jas_iccattrval_s *); + int (*input)(struct jas_iccattrval_s *, jas_stream_t *, int); + int (*output)(struct jas_iccattrval_s *, jas_stream_t *); + int (*getsize)(struct jas_iccattrval_s *); + void (*dump)(struct jas_iccattrval_s *, FILE *); +} jas_iccattrvalops_t; + +/* Attribute value type (type and value information). */ +typedef struct jas_iccattrval_s { + int refcnt; /* reference count */ + jas_iccsig_t type; /* type */ + jas_iccattrvalops_t *ops; /* type-dependent operations */ + union { + jas_iccxyz_t xyz; + jas_icccurv_t curv; + jas_icctxtdesc_t txtdesc; + jas_icctxt_t txt; + jas_icclut8_t lut8; + jas_icclut16_t lut16; + } data; /* value */ +} jas_iccattrval_t; + +/* Header type. */ +typedef struct { + jas_iccuint32_t size; /* profile size */ + jas_iccsig_t cmmtype; /* CMM type signature */ + jas_iccuint32_t version; /* profile version */ + jas_iccsig_t clas; /* profile/device class signature */ + jas_iccsig_t colorspc; /* color space of data */ + jas_iccsig_t refcolorspc; /* profile connection space */ + jas_icctime_t ctime; /* creation time */ + jas_iccsig_t magic; /* profile file signature */ + jas_iccsig_t platform; /* primary platform */ + jas_iccuint32_t flags; /* profile flags */ + jas_iccsig_t maker; /* device manufacturer signature */ + jas_iccsig_t model; /* device model signature */ + jas_iccuint64_t attr; /* device setup attributes */ + jas_iccsig_t intent; /* rendering intent */ + jas_iccxyz_t illum; /* illuminant */ + jas_iccsig_t creator; /* profile creator signature */ +} jas_icchdr_t; + +typedef struct { + jas_iccsig_t name; + jas_iccattrval_t *val; +} jas_iccattr_t; + +typedef struct { + int numattrs; + int maxattrs; + jas_iccattr_t *attrs; +} jas_iccattrtab_t; + +typedef struct jas_icctagtabent_s { + jas_iccuint32_t tag; + jas_iccuint32_t off; + jas_iccuint32_t len; + void *data; + struct jas_icctagtabent_s *first; +} jas_icctagtabent_t; + +typedef struct { + jas_iccuint32_t numents; + jas_icctagtabent_t *ents; +} jas_icctagtab_t; + +/* ICC profile type. */ +typedef struct { + jas_icchdr_t hdr; + jas_icctagtab_t tagtab; + jas_iccattrtab_t *attrtab; +} jas_iccprof_t; + +typedef struct { + jas_iccuint32_t type; + jas_iccattrvalops_t ops; +} jas_iccattrvalinfo_t; + +jas_iccprof_t *jas_iccprof_load(jas_stream_t *in); +int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out); +void jas_iccprof_destroy(jas_iccprof_t *prof); +jas_iccattrval_t *jas_iccprof_getattr(jas_iccprof_t *prof, + jas_iccattrname_t name); +int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name, + jas_iccattrval_t *val); +void jas_iccprof_dump(jas_iccprof_t *prof, FILE *out); +jas_iccprof_t *jas_iccprof_copy(jas_iccprof_t *prof); +int jas_iccprof_gethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr); +int jas_iccprof_sethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr); + +void jas_iccattrval_destroy(jas_iccattrval_t *attrval); +void jas_iccattrval_dump(jas_iccattrval_t *attrval, FILE *out); +int jas_iccattrval_allowmodify(jas_iccattrval_t **attrval); +jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval); +jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type); + +void jas_iccattrtab_dump(jas_iccattrtab_t *attrtab, FILE *out); + +extern uchar jas_iccprofdata_srgb[]; +extern int jas_iccprofdata_srgblen; +extern uchar jas_iccprofdata_sgray[]; +extern int jas_iccprofdata_sgraylen; +jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len); +jas_iccprof_t *jas_iccprof_createfromclrspc(int clrspc); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_image.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_image.h new file mode 100644 index 0000000..38a4b76 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_image.h @@ -0,0 +1,613 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Image Class + * + * $Id$ + */ + +#ifndef JAS_IMAGE_H +#define JAS_IMAGE_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* + * Miscellaneous constants. + */ + +/* The threshold at which image data is no longer stored in memory. */ +#define JAS_IMAGE_INMEMTHRESH (512 * 1024 * 1024) + +/* + * Component types + */ + +#define JAS_IMAGE_CT_UNKNOWN 0x10000 +#define JAS_IMAGE_CT_COLOR(n) ((n) & 0x7fff) +#define JAS_IMAGE_CT_OPACITY 0x08000 + +#define JAS_IMAGE_CT_RGB_R 0 +#define JAS_IMAGE_CT_RGB_G 1 +#define JAS_IMAGE_CT_RGB_B 2 + +#define JAS_IMAGE_CT_YCBCR_Y 0 +#define JAS_IMAGE_CT_YCBCR_CB 1 +#define JAS_IMAGE_CT_YCBCR_CR 2 + +#define JAS_IMAGE_CT_GRAY_Y 0 + +/******************************************************************************\ +* Simple types. +\******************************************************************************/ + +/* Image coordinate. */ +typedef int_fast32_t jas_image_coord_t; + +/* Color space (e.g., RGB, YCbCr). */ +typedef int_fast16_t jas_image_colorspc_t; + +/* Component type (e.g., color, opacity). */ +typedef int_fast32_t jas_image_cmpttype_t; + +/* Component sample data format (e.g., real/integer, signedness, precision). */ +typedef int_fast16_t jas_image_smpltype_t; + +/******************************************************************************\ +* Image class and supporting classes. +\******************************************************************************/ + +/* Image component class. */ + +typedef struct { + + jas_image_coord_t tlx_; + /* The x-coordinate of the top-left corner of the component. */ + + jas_image_coord_t tly_; + /* The y-coordinate of the top-left corner of the component. */ + + jas_image_coord_t hstep_; + /* The horizontal sampling period in units of the reference grid. */ + + jas_image_coord_t vstep_; + /* The vertical sampling period in units of the reference grid. */ + + jas_image_coord_t width_; + /* The component width in samples. */ + + jas_image_coord_t height_; + /* The component height in samples. */ + +#ifdef FIX_ME + int smpltype_; +#else + int prec_; + /* The precision of the sample data (i.e., the number of bits per + sample). If the samples are signed values, this quantity + includes the sign bit. */ + + int sgnd_; + /* The signedness of the sample data. */ +#endif + + jas_stream_t *stream_; + /* The stream containing the component data. */ + + int cps_; + /* The number of characters per sample in the stream. */ + + jas_image_cmpttype_t type_; + /* The type of component (e.g., opacity, red, green, blue, luma). */ + +} jas_image_cmpt_t; + +/* Image class. */ + +typedef struct { + + jas_image_coord_t tlx_; + /* The x-coordinate of the top-left corner of the image bounding box. */ + + jas_image_coord_t tly_; + /* The y-coordinate of the top-left corner of the image bounding box. */ + + jas_image_coord_t brx_; + /* The x-coordinate of the bottom-right corner of the image bounding + box (plus one). */ + + jas_image_coord_t bry_; + /* The y-coordinate of the bottom-right corner of the image bounding + box (plus one). */ + + int numcmpts_; + /* The number of components. */ + + int maxcmpts_; + /* The maximum number of components that this image can have (i.e., the + allocated size of the components array). */ + + jas_image_cmpt_t **cmpts_; + /* Per-component information. */ + + jas_clrspc_t clrspc_; + + jas_cmprof_t *cmprof_; + + bool inmem_; + +} jas_image_t; + +/* Component parameters class. */ +/* This data type exists solely/mainly for the purposes of the + jas_image_create function. */ + +typedef struct { + + jas_image_coord_t tlx; + /* The x-coordinate of the top-left corner of the component. */ + + jas_image_coord_t tly; + /* The y-coordinate of the top-left corner of the component. */ + + jas_image_coord_t hstep; + /* The horizontal sampling period in units of the reference grid. */ + + jas_image_coord_t vstep; + /* The vertical sampling period in units of the reference grid. */ + + jas_image_coord_t width; + /* The width of the component in samples. */ + + jas_image_coord_t height; + /* The height of the component in samples. */ + +#ifdef FIX_ME + int smpltype; +#else + int prec; + /* The precision of the component sample data. */ + + int sgnd; + /* The signedness of the component sample data. */ +#endif + +} jas_image_cmptparm_t; + +/******************************************************************************\ +* File format related classes. +\******************************************************************************/ + +#define JAS_IMAGE_MAXFMTS 32 +/* The maximum number of image data formats supported. */ + +/* Image format-dependent operations. */ + +typedef struct { + + jas_image_t *(*decode)(jas_stream_t *in, char *opts); + /* Decode image data from a stream. */ + + int (*encode)(jas_image_t *image, jas_stream_t *out, char *opts); + /* Encode image data to a stream. */ + + int (*validate)(jas_stream_t *in); + /* Determine if stream data is in a particular format. */ + +} jas_image_fmtops_t; + +/* Image format information. */ + +typedef struct { + + int id; + /* The ID for this format. */ + + char *name; + /* The name by which this format is identified. */ + + char *ext; + /* The file name extension associated with this format. */ + + char *desc; + /* A brief description of the format. */ + + jas_image_fmtops_t ops; + /* The operations for this format. */ + +} jas_image_fmtinfo_t; + +/******************************************************************************\ +* Image operations. +\******************************************************************************/ + +/* Create an image. */ +jas_image_t *jas_image_create(int numcmpts, + jas_image_cmptparm_t *cmptparms, jas_clrspc_t clrspc); + +/* Create an "empty" image. */ +jas_image_t *jas_image_create0(void); + +/* Clone an image. */ +jas_image_t *jas_image_copy(jas_image_t *image); + +/* Deallocate any resources associated with an image. */ +void jas_image_destroy(jas_image_t *image); + +/* Get the width of the image in units of the image reference grid. */ +#define jas_image_width(image) \ + ((image)->brx_ - (image)->tlx_) + +/* Get the height of the image in units of the image reference grid. */ +#define jas_image_height(image) \ + ((image)->bry_ - (image)->tly_) + +/* Get the x-coordinate of the top-left corner of the image bounding box + on the reference grid. */ +#define jas_image_tlx(image) \ + ((image)->tlx_) + +/* Get the y-coordinate of the top-left corner of the image bounding box + on the reference grid. */ +#define jas_image_tly(image) \ + ((image)->tly_) + +/* Get the x-coordinate of the bottom-right corner of the image bounding box + on the reference grid (plus one). */ +#define jas_image_brx(image) \ + ((image)->brx_) + +/* Get the y-coordinate of the bottom-right corner of the image bounding box + on the reference grid (plus one). */ +#define jas_image_bry(image) \ + ((image)->bry_) + +/* Get the number of image components. */ +#define jas_image_numcmpts(image) \ + ((image)->numcmpts_) + +/* Get the color model used by the image. */ +#define jas_image_clrspc(image) \ + ((image)->clrspc_) + +/* Set the color model for an image. */ +#define jas_image_setclrspc(image, clrspc) \ + ((image)->clrspc_ = (clrspc)) + +#define jas_image_cmpttype(image, cmptno) \ + ((image)->cmpts_[(cmptno)]->type_) +#define jas_image_setcmpttype(image, cmptno, type) \ + ((image)->cmpts_[(cmptno)]->type_ = (type)) + +/* Get the width of a component. */ +#define jas_image_cmptwidth(image, cmptno) \ + ((image)->cmpts_[cmptno]->width_) + +/* Get the height of a component. */ +#define jas_image_cmptheight(image, cmptno) \ + ((image)->cmpts_[cmptno]->height_) + +/* Get the signedness of the sample data for a component. */ +#define jas_image_cmptsgnd(image, cmptno) \ + ((image)->cmpts_[cmptno]->sgnd_) + +/* Get the precision of the sample data for a component. */ +#define jas_image_cmptprec(image, cmptno) \ + ((image)->cmpts_[cmptno]->prec_) + +/* Get the horizontal subsampling factor for a component. */ +#define jas_image_cmpthstep(image, cmptno) \ + ((image)->cmpts_[cmptno]->hstep_) + +/* Get the vertical subsampling factor for a component. */ +#define jas_image_cmptvstep(image, cmptno) \ + ((image)->cmpts_[cmptno]->vstep_) + +/* Get the x-coordinate of the top-left corner of a component. */ +#define jas_image_cmpttlx(image, cmptno) \ + ((image)->cmpts_[cmptno]->tlx_) + +/* Get the y-coordinate of the top-left corner of a component. */ +#define jas_image_cmpttly(image, cmptno) \ + ((image)->cmpts_[cmptno]->tly_) + +/* Get the x-coordinate of the bottom-right corner of a component + (plus "one"). */ +#define jas_image_cmptbrx(image, cmptno) \ + ((image)->cmpts_[cmptno]->tlx_ + (image)->cmpts_[cmptno]->width_ * \ + (image)->cmpts_[cmptno]->hstep_) + +/* Get the y-coordinate of the bottom-right corner of a component + (plus "one"). */ +#define jas_image_cmptbry(image, cmptno) \ + ((image)->cmpts_[cmptno]->tly_ + (image)->cmpts_[cmptno]->height_ * \ + (image)->cmpts_[cmptno]->vstep_) + +/* Get the raw size of an image (i.e., the nominal size of the image without + any compression. */ +uint_fast32_t jas_image_rawsize(jas_image_t *image); + +/* Create an image from a stream in some specified format. */ +jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, char *optstr); + +/* Write an image to a stream in a specified format. */ +int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt, + char *optstr); + +/* Read a rectangular region of an image component. */ +/* The position and size of the rectangular region to be read is specified +relative to the component's coordinate system. */ +int jas_image_readcmpt(jas_image_t *image, int cmptno, + jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, + jas_matrix_t *data); + +/* Write a rectangular region of an image component. */ +int jas_image_writecmpt(jas_image_t *image, int cmptno, + jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, + jas_matrix_t *data); + +/* Delete a component from an image. */ +void jas_image_delcmpt(jas_image_t *image, int cmptno); + +/* Add a component to an image. */ +int jas_image_addcmpt(jas_image_t *image, int cmptno, + jas_image_cmptparm_t *cmptparm); + +/* Copy a component from one image to another. */ +int jas_image_copycmpt(jas_image_t *dstimage, int dstcmptno, + jas_image_t *srcimage, int srccmptno); + +#define JAS_IMAGE_CDT_GETSGND(dtype) (((dtype) >> 7) & 1) +#define JAS_IMAGE_CDT_SETSGND(dtype) (((dtype) & 1) << 7) +#define JAS_IMAGE_CDT_GETPREC(dtype) ((dtype) & 0x7f) +#define JAS_IMAGE_CDT_SETPREC(dtype) ((dtype) & 0x7f) + +#define jas_image_cmptdtype(image, cmptno) \ + (JAS_IMAGE_CDT_SETSGND((image)->cmpts_[cmptno]->sgnd_) | JAS_IMAGE_CDT_SETPREC((image)->cmpts_[cmptno]->prec_)) + +int jas_image_depalettize(jas_image_t *image, int cmptno, int numlutents, + int_fast32_t *lutents, int dtype, int newcmptno); + +int jas_image_readcmptsample(jas_image_t *image, int cmptno, int x, int y); +void jas_image_writecmptsample(jas_image_t *image, int cmptno, int x, int y, + int_fast32_t v); + +int jas_image_getcmptbytype(jas_image_t *image, int ctype); + +/******************************************************************************\ +* Image format-related operations. +\******************************************************************************/ + +/* Clear the table of image formats. */ +void jas_image_clearfmts(void); + +/* Add entry to table of image formats. */ +int jas_image_addfmt(int id, char *name, char *ext, char *desc, + jas_image_fmtops_t *ops); + +/* Get the ID for the image format with the specified name. */ +int jas_image_strtofmt(char *s); + +/* Get the name of the image format with the specified ID. */ +char *jas_image_fmttostr(int fmt); + +/* Lookup image format information by the format ID. */ +jas_image_fmtinfo_t *jas_image_lookupfmtbyid(int id); + +/* Lookup image format information by the format name. */ +jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name); + +/* Guess the format of an image file based on its name. */ +int jas_image_fmtfromname(char *filename); + +/* Get the format of image data in a stream. */ +int jas_image_getfmt(jas_stream_t *in); + + +#define jas_image_cmprof(image) ((image)->cmprof_) +int jas_image_ishomosamp(jas_image_t *image); +int jas_image_sampcmpt(jas_image_t *image, int cmptno, int newcmptno, + jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs, + jas_image_coord_t vs, int sgnd, int prec); +int jas_image_writecmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x, + jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, + long *buf); +int jas_image_readcmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x, + jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, + long *buf); + +#define jas_image_setcmprof(image, cmprof) ((image)->cmprof_ = cmprof) +jas_image_t *jas_image_chclrspc(jas_image_t *image, jas_cmprof_t *outprof, + int intent); +void jas_image_dump(jas_image_t *image, FILE *out); + +/******************************************************************************\ +* Image format-dependent operations. +\******************************************************************************/ + +#if !defined(EXCLUDE_JPG_SUPPORT) +/* Format-dependent operations for JPG support. */ +jas_image_t *jpg_decode(jas_stream_t *in, char *optstr); +int jpg_encode(jas_image_t *image, jas_stream_t *out, char *optstr); +int jpg_validate(jas_stream_t *in); +#endif + +#if !defined(EXCLUDE_MIF_SUPPORT) +/* Format-dependent operations for MIF support. */ +jas_image_t *mif_decode(jas_stream_t *in, char *optstr); +int mif_encode(jas_image_t *image, jas_stream_t *out, char *optstr); +int mif_validate(jas_stream_t *in); +#endif + +#if !defined(EXCLUDE_PNM_SUPPORT) +/* Format-dependent operations for PNM support. */ +jas_image_t *pnm_decode(jas_stream_t *in, char *optstr); +int pnm_encode(jas_image_t *image, jas_stream_t *out, char *optstr); +int pnm_validate(jas_stream_t *in); +#endif + +#if !defined(EXCLUDE_RAS_SUPPORT) +/* Format-dependent operations for Sun Rasterfile support. */ +jas_image_t *ras_decode(jas_stream_t *in, char *optstr); +int ras_encode(jas_image_t *image, jas_stream_t *out, char *optstr); +int ras_validate(jas_stream_t *in); +#endif + +#if !defined(EXCLUDE_BMP_SUPPORT) +/* Format-dependent operations for BMP support. */ +jas_image_t *bmp_decode(jas_stream_t *in, char *optstr); +int bmp_encode(jas_image_t *image, jas_stream_t *out, char *optstr); +int bmp_validate(jas_stream_t *in); +#endif + +#if !defined(EXCLUDE_JP2_SUPPORT) +/* Format-dependent operations for JP2 support. */ +jas_image_t *jp2_decode(jas_stream_t *in, char *optstr); +int jp2_encode(jas_image_t *image, jas_stream_t *out, char *optstr); +int jp2_validate(jas_stream_t *in); +#endif + +#if !defined(EXCLUDE_JPC_SUPPORT) +/* Format-dependent operations for JPEG-2000 code stream support. */ +jas_image_t *jpc_decode(jas_stream_t *in, char *optstr); +int jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr); +int jpc_validate(jas_stream_t *in); +#endif + +#if !defined(EXCLUDE_PGX_SUPPORT) +/* Format-dependent operations for PGX support. */ +jas_image_t *pgx_decode(jas_stream_t *in, char *optstr); +int pgx_encode(jas_image_t *image, jas_stream_t *out, char *optstr); +int pgx_validate(jas_stream_t *in); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_init.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_init.h new file mode 100644 index 0000000..abfb0ed --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_init.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JAS_INIT_H +#define JAS_INIT_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +int jas_init(void); + +void jas_cleanup(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_malloc.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_malloc.h new file mode 100644 index 0000000..2b4f67f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_malloc.h @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Memory Allocator + * + * $Id$ + */ + +#ifndef JAS_MALLOC_H +#define JAS_MALLOC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Hack follows... +\******************************************************************************/ + +#if defined(DEBUG_MEMALLOC) +/* This is somewhat of a hack, but it's a useful hack. :-) */ +/* Use my own custom memory allocator for debugging. */ +#include "../../../../local/src/memalloc.h" +#define jas_malloc MEMALLOC +#define jas_free MEMFREE +#define jas_realloc MEMREALLOC +#define jas_calloc MEMCALLOC +#endif + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +#if !defined(DEBUG_MEMALLOC) + +/* Allocate memory. */ +void *jas_malloc(size_t size); + +/* Free memory. */ +void jas_free(void *ptr); + +/* Resize a block of allocated memory. */ +void *jas_realloc(void *ptr, size_t size); + +/* Allocate a block of memory and initialize the contents to zero. */ +void *jas_calloc(size_t nmemb, size_t size); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_math.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_math.h new file mode 100644 index 0000000..72bd03d --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_math.h @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Math-Related Code + * + * $Id$ + */ + +#ifndef JAS_MATH_H +#define JAS_MATH_H + +/******************************************************************************\ +* Includes +\******************************************************************************/ + +#include + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Macros +\******************************************************************************/ + +/* Compute the absolute value. */ +#define JAS_ABS(x) \ + (((x) >= 0) ? (x) : (-(x))) + +/* Compute the minimum of two values. */ +#define JAS_MIN(x, y) \ + (((x) < (y)) ? (x) : (y)) + +/* Compute the maximum of two values. */ +#define JAS_MAX(x, y) \ + (((x) > (y)) ? (x) : (y)) + +/* Compute the remainder from division (where division is defined such + that the remainder is always nonnegative). */ +#define JAS_MOD(x, y) \ + (((x) < 0) ? (((-x) % (y)) ? ((y) - ((-(x)) % (y))) : (0)) : ((x) % (y))) + +/* Compute the integer with the specified number of least significant bits + set to one. */ +#define JAS_ONES(n) \ + ((1 << (n)) - 1) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_seq.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_seq.h new file mode 100644 index 0000000..6870ee4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_seq.h @@ -0,0 +1,348 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Sequence/Matrix Library + * + * $Id$ + */ + +#ifndef JAS_SEQ_H +#define JAS_SEQ_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* This matrix is a reference to another matrix. */ +#define JAS_MATRIX_REF 0x0001 + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* An element in a sequence. */ +typedef int_fast32_t jas_seqent_t; + +/* An element in a matrix. */ +typedef int_fast32_t jas_matent_t; + +/* Matrix. */ + +typedef struct { + + /* Additional state information. */ + int flags_; + + /* The starting horizontal index. */ + int_fast32_t xstart_; + + /* The starting vertical index. */ + int_fast32_t ystart_; + + /* The ending horizontal index. */ + int_fast32_t xend_; + + /* The ending vertical index. */ + int_fast32_t yend_; + + /* The number of rows in the matrix. */ + int_fast32_t numrows_; + + /* The number of columns in the matrix. */ + int_fast32_t numcols_; + + /* Pointers to the start of each row. */ + jas_seqent_t **rows_; + + /* The allocated size of the rows array. */ + int_fast32_t maxrows_; + + /* The matrix data buffer. */ + jas_seqent_t *data_; + + /* The allocated size of the data array. */ + int_fast32_t datasize_; + +} jas_matrix_t; + +typedef jas_matrix_t jas_seq2d_t; +typedef jas_matrix_t jas_seq_t; + +/******************************************************************************\ +* Functions/macros for matrix class. +\******************************************************************************/ + +/* Get the number of rows. */ +#define jas_matrix_numrows(matrix) \ + ((matrix)->numrows_) + +/* Get the number of columns. */ +#define jas_matrix_numcols(matrix) \ + ((matrix)->numcols_) + +/* Get a matrix element. */ +#define jas_matrix_get(matrix, i, j) \ + ((matrix)->rows_[i][j]) + +/* Set a matrix element. */ +#define jas_matrix_set(matrix, i, j, v) \ + ((matrix)->rows_[i][j] = (v)) + +/* Get an element from a matrix that is known to be a row or column vector. */ +#define jas_matrix_getv(matrix, i) \ + (((matrix)->numrows_ == 1) ? ((matrix)->rows_[0][i]) : \ + ((matrix)->rows_[i][0])) + +/* Set an element in a matrix that is known to be a row or column vector. */ +#define jas_matrix_setv(matrix, i, v) \ + (((matrix)->numrows_ == 1) ? ((matrix)->rows_[0][i] = (v)) : \ + ((matrix)->rows_[i][0] = (v))) + +/* Get the address of an element in a matrix. */ +#define jas_matrix_getref(matrix, i, j) \ + (&(matrix)->rows_[i][j]) + +#define jas_matrix_getvref(matrix, i) \ + (((matrix)->numrows_ > 1) ? jas_matrix_getref(matrix, i, 0) : jas_matrix_getref(matrix, 0, i)) + +#define jas_matrix_length(matrix) \ + (max((matrix)->numrows_, (matrix)->numcols_)) + +/* Create a matrix with the specified dimensions. */ +jas_matrix_t *jas_matrix_create(int numrows, int numcols); + +/* Destroy a matrix. */ +void jas_matrix_destroy(jas_matrix_t *matrix); + +/* Resize a matrix. The previous contents of the matrix are lost. */ +int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols); + +int jas_matrix_output(jas_matrix_t *matrix, FILE *out); + +/* Create a matrix that references part of another matrix. */ +void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0, + int r1, int c1); + +/* Create a matrix that is a reference to a row of another matrix. */ +#define jas_matrix_bindrow(mat0, mat1, r) \ + (jas_matrix_bindsub((mat0), (mat1), (r), 0, (r), (mat1)->numcols_ - 1)) + +/* Create a matrix that is a reference to a column of another matrix. */ +#define jas_matrix_bindcol(mat0, mat1, c) \ + (jas_matrix_bindsub((mat0), (mat1), 0, (c), (mat1)->numrows_ - 1, (c))) + +/* Clip the values of matrix elements to the specified range. */ +void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval, + jas_seqent_t maxval); + +/* Arithmetic shift left of all elements in a matrix. */ +void jas_matrix_asl(jas_matrix_t *matrix, int n); + +/* Arithmetic shift right of all elements in a matrix. */ +void jas_matrix_asr(jas_matrix_t *matrix, int n); + +/* Almost-but-not-quite arithmetic shift right of all elements in a matrix. */ +void jas_matrix_divpow2(jas_matrix_t *matrix, int n); + +/* Set all elements of a matrix to the specified value. */ +void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val); + +/* The spacing between rows of a matrix. */ +#define jas_matrix_rowstep(matrix) \ + (((matrix)->numrows_ > 1) ? ((matrix)->rows_[1] - (matrix)->rows_[0]) : (0)) + +/* The spacing between columns of a matrix. */ +#define jas_matrix_step(matrix) \ + (((matrix)->numrows_ > 1) ? (jas_matrix_rowstep(matrix)) : (1)) + +/* Compare two matrices for equality. */ +int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1); + +jas_matrix_t *jas_matrix_copy(jas_matrix_t *x); + +/******************************************************************************\ +* Functions/macros for 2-D sequence class. +\******************************************************************************/ + +jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x); + +jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend); + +#define jas_seq2d_destroy(s) \ + jas_matrix_destroy(s) + +#define jas_seq2d_xstart(s) \ + ((s)->xstart_) +#define jas_seq2d_ystart(s) \ + ((s)->ystart_) +#define jas_seq2d_xend(s) \ + ((s)->xend_) +#define jas_seq2d_yend(s) \ + ((s)->yend_) +#define jas_seq2d_getref(s, x, y) \ + (jas_matrix_getref(s, (y) - (s)->ystart_, (x) - (s)->xstart_)) +#define jas_seq2d_get(s, x, y) \ + (jas_matrix_get(s, (y) - (s)->ystart_, (x) - (s)->xstart_)) +#define jas_seq2d_rowstep(s) \ + jas_matrix_rowstep(s) +#define jas_seq2d_width(s) \ + ((s)->xend_ - (s)->xstart_) +#define jas_seq2d_height(s) \ + ((s)->yend_ - (s)->ystart_) +#define jas_seq2d_setshift(s, x, y) \ + ((s)->xstart_ = (x), (s)->ystart_ = (y), \ + (s)->xend_ = (s)->xstart_ + (s)->numcols_, \ + (s)->yend_ = (s)->ystart_ + (s)->numrows_) + +void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart, + int ystart, int xend, int yend); + +/******************************************************************************\ +* Functions/macros for 1-D sequence class. +\******************************************************************************/ + +#define jas_seq_create(start, end) \ + (jas_seq2d_create(start, 0, end, 1)) + +#define jas_seq_destroy(seq) \ + (jas_seq2d_destroy(seq)) + +#define jas_seq_set(seq, i, v) \ + ((seq)->rows_[0][(i) - (seq)->xstart_] = (v)) +#define jas_seq_getref(seq, i) \ + (&(seq)->rows_[0][(i) - (seq)->xstart_]) +#define jas_seq_get(seq, i) \ + ((seq)->rows_[0][(i) - (seq)->xstart_]) +#define jas_seq_start(seq) \ + ((seq)->xstart_) +#define jas_seq_end(seq) \ + ((seq)->xend_) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_stream.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_stream.h new file mode 100644 index 0000000..e86a77d --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_stream.h @@ -0,0 +1,511 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * I/O Stream Class + * + * $Id$ + */ + +#ifndef JAS_STREAM_H +#define JAS_STREAM_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include +#include +#include +#if defined(HAVE_UNISTD_H) +#include +#endif +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* On most UNIX systems, we probably need to define O_BINARY ourselves. */ +#ifndef O_BINARY +#define O_BINARY 0 +#endif + +/* + * Stream open flags. + */ + +/* The stream was opened for reading. */ +#define JAS_STREAM_READ 0x0001 +/* The stream was opened for writing. */ +#define JAS_STREAM_WRITE 0x0002 +/* The stream was opened for appending. */ +#define JAS_STREAM_APPEND 0x0004 +/* The stream was opened in binary mode. */ +#define JAS_STREAM_BINARY 0x0008 +/* The stream should be created/truncated. */ +#define JAS_STREAM_CREATE 0x0010 + + +/* + * Stream buffering flags. + */ + +/* The stream is unbuffered. */ +#define JAS_STREAM_UNBUF 0x0000 +/* The stream is line buffered. */ +#define JAS_STREAM_LINEBUF 0x0001 +/* The stream is fully buffered. */ +#define JAS_STREAM_FULLBUF 0x0002 +/* The buffering mode mask. */ +#define JAS_STREAM_BUFMODEMASK 0x000f + +/* The memory associated with the buffer needs to be deallocated when the + stream is destroyed. */ +#define JAS_STREAM_FREEBUF 0x0008 +/* The buffer is currently being used for reading. */ +#define JAS_STREAM_RDBUF 0x0010 +/* The buffer is currently being used for writing. */ +#define JAS_STREAM_WRBUF 0x0020 + +/* + * Stream error flags. + */ + +/* The end-of-file has been encountered (on reading). */ +#define JAS_STREAM_EOF 0x0001 +/* An I/O error has been encountered on the stream. */ +#define JAS_STREAM_ERR 0x0002 +/* The read/write limit has been exceeded. */ +#define JAS_STREAM_RWLIMIT 0x0004 +/* The error mask. */ +#define JAS_STREAM_ERRMASK \ + (JAS_STREAM_EOF | JAS_STREAM_ERR | JAS_STREAM_RWLIMIT) + +/* + * Other miscellaneous constants. + */ + +/* The default buffer size (for fully-buffered operation). */ +#define JAS_STREAM_BUFSIZE 8192 +/* The default permission mask for file creation. */ +#define JAS_STREAM_PERMS 0666 + +/* The maximum number of characters that can always be put back on a stream. */ +#define JAS_STREAM_MAXPUTBACK 16 + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* + * Generic file object. + */ + +typedef void jas_stream_obj_t; + +/* + * Generic file object operations. + */ + +typedef struct { + + /* Read characters from a file object. */ + int (*read_)(jas_stream_obj_t *obj, char *buf, int cnt); + + /* Write characters to a file object. */ + int (*write_)(jas_stream_obj_t *obj, char *buf, int cnt); + + /* Set the position for a file object. */ + long (*seek_)(jas_stream_obj_t *obj, long offset, int origin); + + /* Close a file object. */ + int (*close_)(jas_stream_obj_t *obj); + +} jas_stream_ops_t; + +/* + * Stream object. + */ + +typedef struct { + + /* The mode in which the stream was opened. */ + int openmode_; + + /* The buffering mode. */ + int bufmode_; + + /* The stream status. */ + int flags_; + + /* The start of the buffer area to use for reading/writing. */ + uchar *bufbase_; + + /* The start of the buffer area excluding the extra initial space for + character putback. */ + uchar *bufstart_; + + /* The buffer size. */ + int bufsize_; + + /* The current position in the buffer. */ + uchar *ptr_; + + /* The number of characters that must be read/written before + the buffer needs to be filled/flushed. */ + int cnt_; + + /* A trivial buffer to be used for unbuffered operation. */ + uchar tinybuf_[JAS_STREAM_MAXPUTBACK + 1]; + + /* The operations for the underlying stream file object. */ + jas_stream_ops_t *ops_; + + /* The underlying stream file object. */ + jas_stream_obj_t *obj_; + + /* The number of characters read/written. */ + long rwcnt_; + + /* The maximum number of characters that may be read/written. */ + long rwlimit_; + +} jas_stream_t; + +/* + * Regular file object. + */ + +/* + * File descriptor file object. + */ +typedef struct { + int fd; + int flags; + char pathname[L_tmpnam + 1]; +} jas_stream_fileobj_t; + +#define JAS_STREAM_FILEOBJ_DELONCLOSE 0x01 +#define JAS_STREAM_FILEOBJ_NOCLOSE 0x02 + +/* + * Memory file object. + */ + +typedef struct { + + /* The data associated with this file. */ + uchar *buf_; + + /* The allocated size of the buffer for holding file data. */ + int bufsize_; + + /* The length of the file. */ + int_fast32_t len_; + + /* The seek position. */ + int_fast32_t pos_; + + /* Is the buffer growable? */ + int growable_; + + /* Was the buffer allocated internally? */ + int myalloc_; + +} jas_stream_memobj_t; + +/******************************************************************************\ +* Macros/functions for opening and closing streams. +\******************************************************************************/ + +/* Open a file as a stream. */ +jas_stream_t *jas_stream_fopen(const char *filename, const char *mode); + +/* Open a memory buffer as a stream. */ +jas_stream_t *jas_stream_memopen(char *buf, int bufsize); + +/* Open a file descriptor as a stream. */ +jas_stream_t *jas_stream_fdopen(int fd, const char *mode); + +/* Open a stdio stream as a stream. */ +jas_stream_t *jas_stream_freopen(const char *path, const char *mode, FILE *fp); + +/* Open a temporary file as a stream. */ +jas_stream_t *jas_stream_tmpfile(void); + +/* Close a stream. */ +int jas_stream_close(jas_stream_t *stream); + +/******************************************************************************\ +* Macros/functions for getting/setting the stream state. +\******************************************************************************/ + +/* Get the EOF indicator for a stream. */ +#define jas_stream_eof(stream) \ + (((stream)->flags_ & JAS_STREAM_EOF) != 0) + +/* Get the error indicator for a stream. */ +#define jas_stream_error(stream) \ + (((stream)->flags_ & JAS_STREAM_ERR) != 0) + +/* Clear the error indicator for a stream. */ +#define jas_stream_clearerr(stream) \ + ((stream)->flags_ &= ~(JAS_STREAM_ERR | JAS_STREAM_EOF)) + +/* Get the read/write limit for a stream. */ +#define jas_stream_getrwlimit(stream) \ + (((const jas_stream_t *)(stream))->rwlimit_) + +/* Set the read/write limit for a stream. */ +int jas_stream_setrwlimit(jas_stream_t *stream, long rwlimit); + +/* Get the read/write count for a stream. */ +#define jas_stream_getrwcount(stream) \ + (((const jas_stream_t *)(stream))->rwcnt_) + +/* Set the read/write count for a stream. */ +long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt); + +/******************************************************************************\ +* Macros/functions for I/O. +\******************************************************************************/ + +/* Read a character from a stream. */ +#if defined(DEBUG) +#define jas_stream_getc(stream) jas_stream_getc_func(stream) +#else +#define jas_stream_getc(stream) jas_stream_getc_macro(stream) +#endif + +/* Write a character to a stream. */ +#if defined(DEBUG) +#define jas_stream_putc(stream, c) jas_stream_putc_func(stream, c) +#else +#define jas_stream_putc(stream, c) jas_stream_putc_macro(stream, c) +#endif + +/* Read characters from a stream into a buffer. */ +int jas_stream_read(jas_stream_t *stream, void *buf, int cnt); + +/* Write characters from a buffer to a stream. */ +int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt); + +/* Write formatted output to a stream. */ +int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...); + +/* Write a string to a stream. */ +int jas_stream_puts(jas_stream_t *stream, const char *s); + +/* Read a line of input from a stream. */ +char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize); + +/* Look at the next character to be read from a stream without actually + removing it from the stream. */ +#define jas_stream_peekc(stream) \ + (((stream)->cnt_ <= 0) ? jas_stream_fillbuf(stream, 0) : \ + ((int)(*(stream)->ptr_))) + +/* Put a character back on a stream. */ +int jas_stream_ungetc(jas_stream_t *stream, int c); + +/******************************************************************************\ +* Macros/functions for getting/setting the stream position. +\******************************************************************************/ + +/* Is it possible to seek on this stream? */ +int jas_stream_isseekable(jas_stream_t *stream); + +/* Set the current position within the stream. */ +long jas_stream_seek(jas_stream_t *stream, long offset, int origin); + +/* Get the current position within the stream. */ +long jas_stream_tell(jas_stream_t *stream); + +/* Seek to the beginning of a stream. */ +int jas_stream_rewind(jas_stream_t *stream); + +/******************************************************************************\ +* Macros/functions for flushing. +\******************************************************************************/ + +/* Flush any pending output to a stream. */ +int jas_stream_flush(jas_stream_t *stream); + +/******************************************************************************\ +* Miscellaneous macros/functions. +\******************************************************************************/ + +/* Copy data from one stream to another. */ +int jas_stream_copy(jas_stream_t *dst, jas_stream_t *src, int n); + +/* Display stream contents (for debugging purposes). */ +int jas_stream_display(jas_stream_t *stream, FILE *fp, int n); + +/* Consume (i.e., discard) characters from stream. */ +int jas_stream_gobble(jas_stream_t *stream, int n); + +/* Write a character multiple times to a stream. */ +int jas_stream_pad(jas_stream_t *stream, int n, int c); + +/* Get the size of the file associated with the specified stream. + The specified stream must be seekable. */ +long jas_stream_length(jas_stream_t *stream); + +/******************************************************************************\ +* Internal functions. +\******************************************************************************/ + +/* The following functions are for internal use only! If you call them +directly, you will die a horrible, miserable, and painful death! */ + +/* Read a character from a stream. */ +#define jas_stream_getc_macro(stream) \ + ((!((stream)->flags_ & (JAS_STREAM_ERR | JAS_STREAM_EOF | \ + JAS_STREAM_RWLIMIT))) ? \ + (((stream)->rwlimit_ >= 0 && (stream)->rwcnt_ >= (stream)->rwlimit_) ? \ + (stream->flags_ |= JAS_STREAM_RWLIMIT, EOF) : \ + jas_stream_getc2(stream)) : EOF) +#define jas_stream_getc2(stream) \ + ((--(stream)->cnt_ < 0) ? jas_stream_fillbuf(stream, 1) : \ + (++(stream)->rwcnt_, (int)(*(stream)->ptr_++))) + +/* Write a character to a stream. */ +#define jas_stream_putc_macro(stream, c) \ + ((!((stream)->flags_ & (JAS_STREAM_ERR | JAS_STREAM_EOF | \ + JAS_STREAM_RWLIMIT))) ? \ + (((stream)->rwlimit_ >= 0 && (stream)->rwcnt_ >= (stream)->rwlimit_) ? \ + (stream->flags_ |= JAS_STREAM_RWLIMIT, EOF) : \ + jas_stream_putc2(stream, c)) : EOF) +#define jas_stream_putc2(stream, c) \ + (((stream)->bufmode_ |= JAS_STREAM_WRBUF, --(stream)->cnt_ < 0) ? \ + jas_stream_flushbuf((stream), (uchar)(c)) : \ + (++(stream)->rwcnt_, (int)(*(stream)->ptr_++ = (c)))) + +/* These prototypes need to be here for the sake of the stream_getc and +stream_putc macros. */ +int jas_stream_fillbuf(jas_stream_t *stream, int getflag); +int jas_stream_flushbuf(jas_stream_t *stream, int c); +int jas_stream_getc_func(jas_stream_t *stream); +int jas_stream_putc_func(jas_stream_t *stream, int c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_string.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_string.h new file mode 100644 index 0000000..a901ec2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_string.h @@ -0,0 +1,144 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * String Library + * + * $Id$ + */ + +#ifndef JAS_STRING_H +#define JAS_STRING_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Copy a string (a la strdup). */ +char *jas_strdup(const char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_tvp.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_tvp.h new file mode 100644 index 0000000..f5fd782 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_tvp.h @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tag/Value Parser + * + * $Id$ + */ + +#ifndef JAS_TVP_H +#define JAS_TVP_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* Tag information type. */ + +typedef struct { + + int id; + /* The ID for the tag. */ + + char *name; + /* The name of the tag. */ + +} jas_taginfo_t; + +/* Tag-value parser type. */ + +typedef struct { + + char *buf; + /* The parsing buffer. */ + + char *tag; + /* The current tag name. */ + + char *val; + /* The current value. */ + + char *pos; + /* The current position in the parsing buffer. */ + +} jas_tvparser_t; + +/******************************************************************************\ +* Tag information functions. +\******************************************************************************/ + +/* Lookup a tag by name. */ +jas_taginfo_t *jas_taginfos_lookup(jas_taginfo_t *taginfos, const char *name); + +/* This function returns a pointer to the specified taginfo object if it + exists (i.e., the pointer is nonnull); otherwise, a pointer to a dummy + object is returned. This is useful in some situations to avoid checking + for a null pointer. */ +jas_taginfo_t *jas_taginfo_nonull(jas_taginfo_t *taginfo); + +/******************************************************************************\ +* Tag-value parser functions. +\******************************************************************************/ + +/* Create a tag-value parser for the specified string. */ +jas_tvparser_t *jas_tvparser_create(const char *s); + +/* Destroy a tag-value parser. */ +void jas_tvparser_destroy(jas_tvparser_t *tvparser); + +/* Get the next tag-value pair. */ +int jas_tvparser_next(jas_tvparser_t *tvparser); + +/* Get the tag name for the current tag-value pair. */ +char *jas_tvparser_gettag(jas_tvparser_t *tvparser); + +/* Get the value for the current tag-value pair. */ +char *jas_tvparser_getval(jas_tvparser_t *tvparser); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_types.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_types.h new file mode 100644 index 0000000..3034ae0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_types.h @@ -0,0 +1,259 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Primitive Types + * + * $Id$ + */ + +#ifndef JAS_TYPES_H +#define JAS_TYPES_H + +#include + +#if !defined(JAS_CONFIGURE) + +#if defined(WIN32) || defined(HAVE_WINDOWS_H) +/* + We are dealing with Microsoft Windows and most likely Microsoft + Visual C (MSVC). (Heaven help us.) Sadly, MSVC does not correctly + define some of the standard types specified in ISO/IEC 9899:1999. + In particular, it does not define the "long long" and "unsigned long + long" types. So, we work around this problem by using the "INT64" + and "UINT64" types that are defined in the header file "windows.h". + */ +#include +#undef longlong +#define longlong INT64 +#undef ulonglong +#define ulonglong UINT64 +#endif + +#endif + +#if defined(HAVE_STDLIB_H) +#include +#endif +#if defined(HAVE_STDDEF_H) +#include +#endif +#if defined(HAVE_SYS_TYPES_H) +#include +#endif + +#if defined(HAVE_STDBOOL_H) +/* + * The C language implementation does correctly provide the standard header + * file "stdbool.h". + */ +#include +#else + +#ifndef __cplusplus +/* + * The C language implementation does not provide the standard header file + * "stdbool.h" as required by ISO/IEC 9899:1999. Try to compensate for this + * braindamage below. + */ +#if !defined(bool) +#define bool int +#endif +#if !defined(true) +#define true 1 +#endif +#if !defined(false) +#define false 0 +#endif +#endif + +#endif + +#if defined(HAVE_STDINT_H) +/* + * The C language implementation does correctly provide the standard header + * file "stdint.h". + */ +#include +#else +/* + * The C language implementation does not provide the standard header file + * "stdint.h" as required by ISO/IEC 9899:1999. Try to compensate for this + * braindamage below. + */ +#include +/**********/ +#if !defined(INT_FAST8_MIN) +typedef signed char int_fast8_t; +#define INT_FAST8_MIN (-127) +#define INT_FAST8_MAX 128 +#endif +/**********/ +#if !defined(UINT_FAST8_MIN) +typedef unsigned char uint_fast8_t; +#define UINT_FAST8_MIN 0 +#define UINT_FAST8_MAX 255 +#endif +/**********/ +#if !defined(INT_FAST16_MIN) +typedef short int_fast16_t; +#define INT_FAST16_MIN SHRT_MIN +#define INT_FAST16_MAX SHRT_MAX +#endif +/**********/ +#if !defined(UINT_FAST16_MIN) +typedef unsigned short uint_fast16_t; +#define UINT_FAST16_MIN USHRT_MIN +#define UINT_FAST16_MAX USHRT_MAX +#endif +/**********/ +#if !defined(INT_FAST32_MIN) +typedef int int_fast32_t; +#define INT_FAST32_MIN INT_MIN +#define INT_FAST32_MAX INT_MAX +#endif +/**********/ +#if !defined(UINT_FAST32_MIN) +typedef unsigned int uint_fast32_t; +#define UINT_FAST32_MIN UINT_MIN +#define UINT_FAST32_MAX UINT_MAX +#endif +/**********/ +#if !defined(INT_FAST64_MIN) +typedef longlong int_fast64_t; +#define INT_FAST64_MIN LLONG_MIN +#define INT_FAST64_MAX LLONG_MAX +#endif +/**********/ +#if !defined(UINT_FAST64_MIN) +typedef ulonglong uint_fast64_t; +#define UINT_FAST64_MIN ULLONG_MIN +#define UINT_FAST64_MAX ULLONG_MAX +#endif +/**********/ +#endif + +/* The below macro is intended to be used for type casts. By using this + macro, type casts can be easily located in the source code with + tools like "grep". */ +#define JAS_CAST(t, e) \ + ((t) (e)) + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_version.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_version.h new file mode 100644 index 0000000..f83b76c --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jas_version.h @@ -0,0 +1,169 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * $Id$ + */ + +#ifndef JAS_VERSION_H +#define JAS_VERSION_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************\ +* Constants and types. +\******************************************************************************/ + +#if !defined(JAS_VERSION) +/* The version information below should match that specified in + the "configure.in" file! */ +#define JAS_VERSION "unknown" +#endif + +#define JAS_COPYRIGHT \ + "Copyright (c) 1999-2000 Image Power, Inc. and the University of\n" \ + " British Columbia.\n" \ + "Copyright (c) 2001-2003 Michael David Adams.\n" \ + "All rights reserved.\n" + +#define JAS_NOTES \ + "For more information about this software, please visit the following\n" \ + "web sites/pages:\n" \ + " http://www.ece.uvic.ca/~mdadams/jasper\n" \ + " http://www.jpeg.org/software\n" \ + "To be added to the (moderated) JasPer software announcements\n" \ + "mailing list, send an email to:\n" \ + " jasper-announce-subscribe@yahoogroups.com\n" \ + "To be added to the (unmoderated) JasPer software discussion\n" \ + "mailing list, send an email to:\n" \ + " jasper-discussion-subscribe@yahoogroups.com\n" \ + "Please send any bug reports to:\n" \ + " mdadams@ieee.org\n" + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +const char *jas_getversion(void); +/* Get the version information for the JasPer library. */ +/* Note: Since libjasper can be built as a shared library, the version + returned by this function may not necessarily correspond to JAS_VERSION. */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/jasper.h b/SlnkDWFImpl/CxImage/jasper/include/jasper/jasper.h new file mode 100644 index 0000000..3ca30d6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/jasper.h @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JAS_JASPER_H +#define JAS_JASPER_H + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/include/jasper/stamp-h.in b/SlnkDWFImpl/CxImage/jasper/include/jasper/stamp-h.in new file mode 100644 index 0000000..7354eae --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/include/jasper/stamp-h.in @@ -0,0 +1 @@ +timestamp diff --git a/SlnkDWFImpl/CxImage/jasper/jasper.dsp b/SlnkDWFImpl/CxImage/jasper/jasper.dsp new file mode 100644 index 0000000..9d9d0cf --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jasper.dsp @@ -0,0 +1,426 @@ +# Microsoft Developer Studio Project File - Name="jasper" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=jasper - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "jasper.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "jasper.mak" CFG="jasper - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "jasper - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "jasper - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "jasper - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W2 /GX /O2 /I ".\include" /D "NDEBUG" /D "WIN32" /D "_MBCS" /D "_LIB" /D "JAS_WIN_MSVC_BUILD" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "jasper - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W2 /Gm /GX /ZI /Od /I ".\include" /D "_DEBUG" /D "WIN32" /D "_MBCS" /D "_LIB" /D "JAS_WIN_MSVC_BUILD" /FD /GZ /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "jasper - Win32 Release" +# Name "jasper - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\bmp\bmp_cod.c +# End Source File +# Begin Source File + +SOURCE=.\bmp\bmp_dec.c +# End Source File +# Begin Source File + +SOURCE=.\bmp\bmp_enc.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_cm.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_debug.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_getopt.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_icc.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_iccdata.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_image.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_init.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_malloc.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_seq.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_stream.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_string.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_tvp.c +# End Source File +# Begin Source File + +SOURCE=.\base\jas_version.c +# End Source File +# Begin Source File + +SOURCE=.\jp2\jp2_cod.c +# End Source File +# Begin Source File + +SOURCE=.\jp2\jp2_dec.c +# End Source File +# Begin Source File + +SOURCE=.\jp2\jp2_enc.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_bs.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_cs.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_dec.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_enc.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_math.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_mct.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_mqcod.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_mqdec.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_mqenc.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_qmfb.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t1cod.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t1dec.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t1enc.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t2cod.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t2dec.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t2enc.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_tagtree.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_tsfb.c +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_util.c +# End Source File +# Begin Source File + +SOURCE=.\jpg\jpg_dummy.c +# End Source File +# Begin Source File + +SOURCE=.\jpg\jpg_val.c +# End Source File +# Begin Source File + +SOURCE=.\mif\mif_cod.c +# End Source File +# Begin Source File + +SOURCE=.\pgx\pgx_cod.c +# End Source File +# Begin Source File + +SOURCE=.\pgx\pgx_dec.c +# End Source File +# Begin Source File + +SOURCE=.\pgx\pgx_enc.c +# End Source File +# Begin Source File + +SOURCE=.\pnm\pnm_cod.c +# End Source File +# Begin Source File + +SOURCE=.\pnm\pnm_dec.c +# End Source File +# Begin Source File + +SOURCE=.\pnm\pnm_enc.c +# End Source File +# Begin Source File + +SOURCE=.\ras\ras_cod.c +# End Source File +# Begin Source File + +SOURCE=.\ras\ras_dec.c +# End Source File +# Begin Source File + +SOURCE=.\ras\ras_enc.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\bmp\bmp_cod.h +# End Source File +# Begin Source File + +SOURCE=.\include\jasper\jas_cm.h +# End Source File +# Begin Source File + +SOURCE=.\include\jasper\jas_icc.h +# End Source File +# Begin Source File + +SOURCE=.\include\jasper\jas_image.h +# End Source File +# Begin Source File + +SOURCE=.\jp2\jp2_cod.h +# End Source File +# Begin Source File + +SOURCE=.\jp2\jp2_dec.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_bs.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_cod.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_cs.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_dec.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_enc.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_fix.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_flt.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_math.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_mct.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_mqcod.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_mqdec.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_mqenc.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_qmfb.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t1cod.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t1dec.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t1enc.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t2cod.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t2dec.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_t2enc.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_tagtree.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_tsfb.h +# End Source File +# Begin Source File + +SOURCE=.\jpc\jpc_util.h +# End Source File +# Begin Source File + +SOURCE=.\jpg\jpg_cod.h +# End Source File +# Begin Source File + +SOURCE=.\mif\mif_cod.h +# End Source File +# Begin Source File + +SOURCE=.\pgx\pgx_cod.h +# End Source File +# Begin Source File + +SOURCE=.\pnm\pnm_cod.h +# End Source File +# Begin Source File + +SOURCE=.\ras\ras_cod.h +# End Source File +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/jasper/jasper.dsw b/SlnkDWFImpl/CxImage/jasper/jasper.dsw new file mode 100644 index 0000000..7d0b96e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jasper.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "jasper"=".\jasper.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/jasper/jasper.vcproj b/SlnkDWFImpl/CxImage/jasper/jasper.vcproj new file mode 100644 index 0000000..d5bd62c --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jasper.vcproj @@ -0,0 +1,1415 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/jasper/jasper.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/jasper/jasper.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..f57b253 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jasper.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/jasper/jp2/.gitignore b/SlnkDWFImpl/CxImage/jasper/jp2/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/jp2/jp2_cod.c b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_cod.c new file mode 100644 index 0000000..c48c227 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_cod.c @@ -0,0 +1,949 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * JP2 Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#include "jasper/jas_stream.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_debug.h" + +#include "jp2_cod.h" + +/******************************************************************************\ +* Function prototypes. +\******************************************************************************/ + +#define ONES(n) ((1 << (n)) - 1) + +jp2_boxinfo_t *jp2_boxinfolookup(int type); + +static int jp2_getuint8(jas_stream_t *in, uint_fast8_t *val); +static int jp2_getuint16(jas_stream_t *in, uint_fast16_t *val); +static int jp2_getuint32(jas_stream_t *in, uint_fast32_t *val); +static int jp2_getuint64(jas_stream_t *in, uint_fast64_t *val); +static int jp2_putuint8(jas_stream_t *out, uint_fast8_t val); +static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val); +static int jp2_putuint32(jas_stream_t *out, uint_fast32_t val); +static int jp2_putuint64(jas_stream_t *out, uint_fast64_t val); + +static int jp2_getint(jas_stream_t *in, int s, int n, int_fast32_t *val); + +jp2_box_t *jp2_box_get(jas_stream_t *in); +void jp2_box_dump(jp2_box_t *box, FILE *out); + +static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in); +static int jp2_jp_putdata(jp2_box_t *box, jas_stream_t *out); +static int jp2_ftyp_getdata(jp2_box_t *box, jas_stream_t *in); +static int jp2_ftyp_putdata(jp2_box_t *box, jas_stream_t *out); +static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in); +static int jp2_ihdr_putdata(jp2_box_t *box, jas_stream_t *out); +static void jp2_bpcc_destroy(jp2_box_t *box); +static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in); +static int jp2_bpcc_putdata(jp2_box_t *box, jas_stream_t *out); +static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in); +static int jp2_colr_putdata(jp2_box_t *box, jas_stream_t *out); +static void jp2_colr_dumpdata(jp2_box_t *box, FILE *out); +static void jp2_colr_destroy(jp2_box_t *box); +static void jp2_cdef_destroy(jp2_box_t *box); +static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in); +static int jp2_cdef_putdata(jp2_box_t *box, jas_stream_t *out); +static void jp2_cdef_dumpdata(jp2_box_t *box, FILE *out); +static void jp2_cmap_destroy(jp2_box_t *box); +static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in); +static int jp2_cmap_putdata(jp2_box_t *box, jas_stream_t *out); +static void jp2_cmap_dumpdata(jp2_box_t *box, FILE *out); +static void jp2_pclr_destroy(jp2_box_t *box); +static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in); +static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out); +static void jp2_pclr_dumpdata(jp2_box_t *box, FILE *out); + +/******************************************************************************\ +* Local data. +\******************************************************************************/ + +jp2_boxinfo_t jp2_boxinfos[] = { + {JP2_BOX_JP, "JP", 0, + {0, 0, jp2_jp_getdata, jp2_jp_putdata, 0}}, + {JP2_BOX_FTYP, "FTYP", 0, + {0, 0, jp2_ftyp_getdata, jp2_ftyp_putdata, 0}}, + {JP2_BOX_JP2H, "JP2H", JP2_BOX_SUPER, + {0, 0, 0, 0, 0}}, + {JP2_BOX_IHDR, "IHDR", 0, + {0, 0, jp2_ihdr_getdata, jp2_ihdr_putdata, 0}}, + {JP2_BOX_BPCC, "BPCC", 0, + {0, jp2_bpcc_destroy, jp2_bpcc_getdata, jp2_bpcc_putdata, 0}}, + {JP2_BOX_COLR, "COLR", 0, + {0, jp2_colr_destroy, jp2_colr_getdata, jp2_colr_putdata, jp2_colr_dumpdata}}, + {JP2_BOX_PCLR, "PCLR", 0, + {0, jp2_pclr_destroy, jp2_pclr_getdata, jp2_pclr_putdata, jp2_pclr_dumpdata}}, + {JP2_BOX_CMAP, "CMAP", 0, + {0, jp2_cmap_destroy, jp2_cmap_getdata, jp2_cmap_putdata, jp2_cmap_dumpdata}}, + {JP2_BOX_CDEF, "CDEF", 0, + {0, jp2_cdef_destroy, jp2_cdef_getdata, jp2_cdef_putdata, jp2_cdef_dumpdata}}, + {JP2_BOX_RES, "RES", JP2_BOX_SUPER, + {0, 0, 0, 0, 0}}, + {JP2_BOX_RESC, "RESC", 0, + {0, 0, 0, 0, 0}}, + {JP2_BOX_RESD, "RESD", 0, + {0, 0, 0, 0, 0}}, + {JP2_BOX_JP2C, "JP2C", JP2_BOX_NODATA, + {0, 0, 0, 0, 0}}, + {JP2_BOX_JP2I, "JP2I", 0, + {0, 0, 0, 0, 0}}, + {JP2_BOX_XML, "XML", 0, + {0, 0, 0, 0, 0}}, + {JP2_BOX_UUID, "UUID", 0, + {0, 0, 0, 0, 0}}, + {JP2_BOX_UINF, "UINF", JP2_BOX_SUPER, + {0, 0, 0, 0, 0}}, + {JP2_BOX_ULST, "ULST", 0, + {0, 0, 0, 0, 0}}, + {JP2_BOX_URL, "URL", 0, + {0, 0, 0, 0, 0}}, + {0, 0, 0, {0, 0, 0, 0, 0}}, +}; + +jp2_boxinfo_t jp2_boxinfo_unk = { + 0, "Unknown", 0, {0, 0, 0, 0, 0} +}; + +/******************************************************************************\ +* Box constructor. +\******************************************************************************/ + +jp2_box_t *jp2_box_create(int type) +{ + jp2_box_t *box; + jp2_boxinfo_t *boxinfo; + + if (!(box = jas_malloc(sizeof(jp2_box_t)))) { + return 0; + } + memset(box, 0, sizeof(jp2_box_t)); + box->type = type; + box->len = 0; + if (!(boxinfo = jp2_boxinfolookup(type))) { + return 0; + } + box->info = boxinfo; + box->ops = &boxinfo->ops; + return box; +} + +/******************************************************************************\ +* Box destructor. +\******************************************************************************/ + +void jp2_box_destroy(jp2_box_t *box) +{ + if (box->ops->destroy) { + (*box->ops->destroy)(box); + } + jas_free(box); +} + +static void jp2_bpcc_destroy(jp2_box_t *box) +{ + jp2_bpcc_t *bpcc = &box->data.bpcc; + if (bpcc->bpcs) { + jas_free(bpcc->bpcs); + bpcc->bpcs = 0; + } +} + +static void jp2_cdef_destroy(jp2_box_t *box) +{ + jp2_cdef_t *cdef = &box->data.cdef; + if (cdef->ents) { + jas_free(cdef->ents); + cdef->ents = 0; + } +} + +/******************************************************************************\ +* Box input. +\******************************************************************************/ + +jp2_box_t *jp2_box_get(jas_stream_t *in) +{ + jp2_box_t *box; + jp2_boxinfo_t *boxinfo; + jas_stream_t *tmpstream; + uint_fast32_t len; + uint_fast64_t extlen; + bool dataflag; + + box = 0; + tmpstream = 0; + + if (!(box = jas_malloc(sizeof(jp2_box_t)))) { + goto error; + } + box->ops = &jp2_boxinfo_unk.ops; + if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { + goto error; + } + boxinfo = jp2_boxinfolookup(box->type); + box->info = boxinfo; + box->ops = &boxinfo->ops; + box->len = len; + if (box->len == 1) { + if (jp2_getuint64(in, &extlen)) { + goto error; + } + box->len = extlen; + } + if (box->len != 0 && box->len < 8) { + goto error; + } + + dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); + + if (dataflag) { + if (!(tmpstream = jas_stream_memopen(0, 0))) { + goto error; + } + if (jas_stream_copy(tmpstream, in, box->len - JP2_BOX_HDRLEN)) { + goto error; + } + jas_stream_rewind(tmpstream); + + if (box->ops->getdata) { + if ((*box->ops->getdata)(box, tmpstream)) { + goto error; + } + } + jas_stream_close(tmpstream); + } + +#if 0 + jp2_box_dump(box, stderr); +#endif + + return box; + abort(); + +error: + if (box) { + jp2_box_destroy(box); + } + if (tmpstream) { + jas_stream_close(tmpstream); + } + return 0; +} + +void jp2_box_dump(jp2_box_t *box, FILE *out) +{ + jp2_boxinfo_t *boxinfo; + boxinfo = jp2_boxinfolookup(box->type); + assert(boxinfo); + + fprintf(out, "JP2 box: "); + fprintf(out, "type=%c%s%c (0x%08x); length=%d\n", '"', boxinfo->name, + '"', box->type, box->len); + if (box->ops->dumpdata) { + (*box->ops->dumpdata)(box, out); + } +} + +static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in) +{ + jp2_jp_t *jp = &box->data.jp; + if (jp2_getuint32(in, &jp->magic)) { + return -1; + } + return 0; +} + +static int jp2_ftyp_getdata(jp2_box_t *box, jas_stream_t *in) +{ + jp2_ftyp_t *ftyp = &box->data.ftyp; + unsigned int i; + if (jp2_getuint32(in, &ftyp->majver) || jp2_getuint32(in, &ftyp->minver)) { + return -1; + } + ftyp->numcompatcodes = ((box->len - JP2_BOX_HDRLEN) - 8) / 4; + if (ftyp->numcompatcodes > JP2_FTYP_MAXCOMPATCODES) { + return -1; + } + for (i = 0; i < ftyp->numcompatcodes; ++i) { + if (jp2_getuint32(in, &ftyp->compatcodes[i])) { + return -1; + } + } + return 0; +} + +static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in) +{ + jp2_ihdr_t *ihdr = &box->data.ihdr; + if (jp2_getuint32(in, &ihdr->height) || jp2_getuint32(in, &ihdr->width) || + jp2_getuint16(in, &ihdr->numcmpts) || jp2_getuint8(in, &ihdr->bpc) || + jp2_getuint8(in, &ihdr->comptype) || jp2_getuint8(in, &ihdr->csunk) || + jp2_getuint8(in, &ihdr->ipr)) { + return -1; + } + return 0; +} + +static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in) +{ + jp2_bpcc_t *bpcc = &box->data.bpcc; + unsigned int i; + bpcc->numcmpts = box->len - JP2_BOX_HDRLEN; + if (!(bpcc->bpcs = jas_malloc(bpcc->numcmpts * sizeof(uint_fast8_t)))) { + return -1; + } + for (i = 0; i < bpcc->numcmpts; ++i) { + if (jp2_getuint8(in, &bpcc->bpcs[i])) { + return -1; + } + } + return 0; +} + +static void jp2_colr_dumpdata(jp2_box_t *box, FILE *out) +{ + jp2_colr_t *colr = &box->data.colr; + fprintf(out, "method=%d; pri=%d; approx=%d\n", (int)colr->method, (int)colr->pri, (int)colr->approx); + switch (colr->method) { + case JP2_COLR_ENUM: + fprintf(out, "csid=%d\n", (int)colr->csid); + break; + case JP2_COLR_ICC: + jas_memdump(out, colr->iccp, colr->iccplen); + break; + } +} + +static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in) +{ + jp2_colr_t *colr = &box->data.colr; + colr->csid = 0; + colr->iccp = 0; + colr->iccplen = 0; + + if (jp2_getuint8(in, &colr->method) || jp2_getuint8(in, &colr->pri) || + jp2_getuint8(in, &colr->approx)) { + return -1; + } + switch (colr->method) { + case JP2_COLR_ENUM: + if (jp2_getuint32(in, &colr->csid)) { + return -1; + } + break; + case JP2_COLR_ICC: + colr->iccplen = box->len - JP2_BOX_HDRLEN - 3; + if (!(colr->iccp = jas_malloc(colr->iccplen * sizeof(uint_fast8_t)))) { + return -1; + } + if (jas_stream_read(in, colr->iccp, colr->iccplen) != colr->iccplen) { + return -1; + } + break; + } + return 0; +} + +static void jp2_cdef_dumpdata(jp2_box_t *box, FILE *out) +{ + jp2_cdef_t *cdef = &box->data.cdef; + unsigned int i; + for (i = 0; i < cdef->numchans; ++i) { + fprintf(out, "channo=%d; type=%d; assoc=%d\n", + cdef->ents[i].channo, cdef->ents[i].type, cdef->ents[i].assoc); + } +} + +static void jp2_colr_destroy(jp2_box_t *box) +{ + jp2_colr_t *colr = &box->data.colr; + if (colr->iccp) { + jas_free(colr->iccp); + } +} + +static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in) +{ + jp2_cdef_t *cdef = &box->data.cdef; + jp2_cdefchan_t *chan; + unsigned int channo; + if (jp2_getuint16(in, &cdef->numchans)) { + return -1; + } + if (!(cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t)))) { + return -1; + } + for (channo = 0; channo < cdef->numchans; ++channo) { + chan = &cdef->ents[channo]; + if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) || + jp2_getuint16(in, &chan->assoc)) { + return -1; + } + } + return 0; +} + +/******************************************************************************\ +* Box output. +\******************************************************************************/ + +int jp2_box_put(jp2_box_t *box, jas_stream_t *out) +{ + jas_stream_t *tmpstream; + bool extlen; + bool dataflag; + + tmpstream = 0; + + dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); + + if (dataflag) { + tmpstream = jas_stream_memopen(0, 0); + if (box->ops->putdata) { + if ((*box->ops->putdata)(box, tmpstream)) { + goto error; + } + } + box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN; + jas_stream_rewind(tmpstream); + } + extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0; + if (jp2_putuint32(out, extlen ? 1 : box->len)) { + goto error; + } + if (jp2_putuint32(out, box->type)) { + goto error; + } + if (extlen) { + if (jp2_putuint64(out, box->len)) { + goto error; + } + } + + if (dataflag) { + if (jas_stream_copy(out, tmpstream, box->len - JP2_BOX_HDRLEN)) { + goto error; + } + jas_stream_close(tmpstream); + } + + return 0; + abort(); + +error: + + if (tmpstream) { + jas_stream_close(tmpstream); + } + return -1; +} + +static int jp2_jp_putdata(jp2_box_t *box, jas_stream_t *out) +{ + jp2_jp_t *jp = &box->data.jp; + if (jp2_putuint32(out, jp->magic)) { + return -1; + } + return 0; +} + +static int jp2_ftyp_putdata(jp2_box_t *box, jas_stream_t *out) +{ + jp2_ftyp_t *ftyp = &box->data.ftyp; + unsigned int i; + if (jp2_putuint32(out, ftyp->majver) || jp2_putuint32(out, ftyp->minver)) { + return -1; + } + for (i = 0; i < ftyp->numcompatcodes; ++i) { + if (jp2_putuint32(out, ftyp->compatcodes[i])) { + return -1; + } + } + return 0; +} + +static int jp2_ihdr_putdata(jp2_box_t *box, jas_stream_t *out) +{ + jp2_ihdr_t *ihdr = &box->data.ihdr; + if (jp2_putuint32(out, ihdr->height) || jp2_putuint32(out, ihdr->width) || + jp2_putuint16(out, ihdr->numcmpts) || jp2_putuint8(out, ihdr->bpc) || + jp2_putuint8(out, ihdr->comptype) || jp2_putuint8(out, ihdr->csunk) || + jp2_putuint8(out, ihdr->ipr)) { + return -1; + } + return 0; +} + +static int jp2_bpcc_putdata(jp2_box_t *box, jas_stream_t *out) +{ + jp2_bpcc_t *bpcc = &box->data.bpcc; + unsigned int i; + for (i = 0; i < bpcc->numcmpts; ++i) { + if (jp2_putuint8(out, bpcc->bpcs[i])) { + return -1; + } + } + return 0; +} + +static int jp2_colr_putdata(jp2_box_t *box, jas_stream_t *out) +{ + jp2_colr_t *colr = &box->data.colr; + if (jp2_putuint8(out, colr->method) || jp2_putuint8(out, colr->pri) || + jp2_putuint8(out, colr->approx)) { + return -1; + } + switch (colr->method) { + case JP2_COLR_ENUM: + if (jp2_putuint32(out, colr->csid)) { + return -1; + } + break; + case JP2_COLR_ICC: + if (jas_stream_write(out, colr->iccp, + JAS_CAST(int, colr->iccplen)) != JAS_CAST(int, colr->iccplen)) + return -1; + break; + } + return 0; +} + +static int jp2_cdef_putdata(jp2_box_t *box, jas_stream_t *out) +{ + jp2_cdef_t *cdef = &box->data.cdef; + unsigned int i; + jp2_cdefchan_t *ent; + + if (jp2_putuint16(out, cdef->numchans)) { + return -1; + } + + for (i = 0; i < cdef->numchans; ++i) { + ent = &cdef->ents[i]; + if (jp2_putuint16(out, ent->channo) || + jp2_putuint16(out, ent->type) || + jp2_putuint16(out, ent->assoc)) { + return -1; + } + } + return 0; +} + +/******************************************************************************\ +* Input operations for primitive types. +\******************************************************************************/ + +static int jp2_getuint8(jas_stream_t *in, uint_fast8_t *val) +{ + int c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + if (val) { + *val = c; + } + return 0; +} + +static int jp2_getuint16(jas_stream_t *in, uint_fast16_t *val) +{ + uint_fast16_t v; + int c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + if (val) { + *val = v; + } + return 0; +} + +static int jp2_getuint32(jas_stream_t *in, uint_fast32_t *val) +{ + uint_fast32_t v; + int c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + if (val) { + *val = v; + } + return 0; +} + +static int jp2_getuint64(jas_stream_t *in, uint_fast64_t *val) +{ + in = 0; + val = 0; + abort(); +} + +/******************************************************************************\ +* Output operations for primitive types. +\******************************************************************************/ + +static int jp2_putuint8(jas_stream_t *out, uint_fast8_t val) +{ + if (jas_stream_putc(out, val & 0xff) == EOF) { + return -1; + } + return 0; +} + +static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val) +{ + if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF || + jas_stream_putc(out, val & 0xff) == EOF) { + return -1; + } + return 0; +} + +static int jp2_putuint32(jas_stream_t *out, uint_fast32_t val) +{ + if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF || + jas_stream_putc(out, (val >> 16) & 0xff) == EOF || + jas_stream_putc(out, (val >> 8) & 0xff) == EOF || + jas_stream_putc(out, val & 0xff) == EOF) { + return -1; + } + return 0; +} + +static int jp2_putuint64(jas_stream_t *out, uint_fast64_t val) +{ + if (jp2_putuint32(out, (val >> 32) & 0xffffffffUL) || + jp2_putuint32(out, val & 0xffffffffUL)) { + return -1; + } + return 0; +} + +/******************************************************************************\ +* Miscellaneous code. +\******************************************************************************/ + +jp2_boxinfo_t *jp2_boxinfolookup(int type) +{ + jp2_boxinfo_t *boxinfo; + for (boxinfo = jp2_boxinfos; boxinfo->name; ++boxinfo) { + if (boxinfo->type == type) { + return boxinfo; + } + } + return &jp2_boxinfo_unk; +} + + + + + +static void jp2_cmap_destroy(jp2_box_t *box) +{ + jp2_cmap_t *cmap = &box->data.cmap; + if (cmap->ents) { + jas_free(cmap->ents); + } +} + +static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in) +{ + jp2_cmap_t *cmap = &box->data.cmap; + jp2_cmapent_t *ent; + unsigned int i; + + cmap->numchans = (box->len - JP2_BOX_HDRLEN) / 4; + if (!(cmap->ents = jas_malloc(cmap->numchans * sizeof(jp2_cmapent_t)))) { + return -1; + } + for (i = 0; i < cmap->numchans; ++i) { + ent = &cmap->ents[i]; + if (jp2_getuint16(in, &ent->cmptno) || + jp2_getuint8(in, &ent->map) || + jp2_getuint8(in, &ent->pcol)) { + return -1; + } + } + + return 0; +} + +static int jp2_cmap_putdata(jp2_box_t *box, jas_stream_t *out) +{ + /* Eliminate compiler warning about unused variables. */ + box = 0; + out = 0; + + return -1; +} + +static void jp2_cmap_dumpdata(jp2_box_t *box, FILE *out) +{ + jp2_cmap_t *cmap = &box->data.cmap; + unsigned int i; + jp2_cmapent_t *ent; + fprintf(out, "numchans = %d\n", (int) cmap->numchans); + for (i = 0; i < cmap->numchans; ++i) { + ent = &cmap->ents[i]; + fprintf(out, "cmptno=%d; map=%d; pcol=%d\n", + (int) ent->cmptno, (int) ent->map, (int) ent->pcol); + } +} + +static void jp2_pclr_destroy(jp2_box_t *box) +{ + jp2_pclr_t *pclr = &box->data.pclr; + if (pclr->lutdata) { + jas_free(pclr->lutdata); + } + if (pclr->bpc) + jas_free(pclr->bpc); +} + +static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in) +{ + jp2_pclr_t *pclr = &box->data.pclr; + int lutsize; + unsigned int i; + unsigned int j; + int_fast32_t x; + + pclr->lutdata = 0; + + if (jp2_getuint16(in, &pclr->numlutents) || + jp2_getuint8(in, &pclr->numchans)) { + return -1; + } + lutsize = pclr->numlutents * pclr->numchans; + if (!(pclr->lutdata = jas_malloc(lutsize * sizeof(int_fast32_t)))) { + return -1; + } + if (!(pclr->bpc = jas_malloc(pclr->numchans * sizeof(uint_fast8_t)))) { + return -1; + } + for (i = 0; i < pclr->numchans; ++i) { + if (jp2_getuint8(in, &pclr->bpc[i])) { + return -1; + } + } + for (i = 0; i < pclr->numlutents; ++i) { + for (j = 0; j < pclr->numchans; ++j) { + if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0, + (pclr->bpc[j] & 0x7f) + 1, &x)) { + return -1; + } + pclr->lutdata[i * pclr->numchans + j] = x; + } + } + return 0; +} + +static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out) +{ +#if 0 + jp2_pclr_t *pclr = &box->data.pclr; +#endif +/* Eliminate warning about unused variable. */ +box = 0; +out = 0; + return -1; +} + +static void jp2_pclr_dumpdata(jp2_box_t *box, FILE *out) +{ + jp2_pclr_t *pclr = &box->data.pclr; + unsigned int i; + int j; + fprintf(out, "numents=%d; numchans=%d\n", (int) pclr->numlutents, + (int) pclr->numchans); + for (i = 0; i < pclr->numlutents; ++i) { + for (j = 0; j < pclr->numchans; ++j) { + fprintf(out, "LUT[%d][%d]=%d\n", i, j, pclr->lutdata[i * pclr->numchans + j]); + } + } +} + +static int jp2_getint(jas_stream_t *in, int s, int n, int_fast32_t *val) +{ + int c; + int i; + uint_fast32_t v; + int m; + + m = (n + 7) / 8; + + v = 0; + for (i = 0; i < m; ++i) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + } + v &= ONES(n); + if (s) { + int sb; + sb = v & (1 << (8 * m - 1)); + *val = ((~v) + 1) & ONES(8 * m); + if (sb) { + *val = -*val; + } + } else { + *val = v; + } + + return 0; +} + +jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo) +{ + unsigned int i; + jp2_cdefchan_t *cdefent; + for (i = 0; i < cdef->numchans; ++i) { + cdefent = &cdef->ents[i]; + if (cdefent->channo == JAS_CAST(unsigned int, channo)) { + return cdefent; + } + } + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jp2/jp2_cod.h b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_cod.h new file mode 100644 index 0000000..bf4a040 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_cod.h @@ -0,0 +1,348 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * JP2 Library + * + * $Id$ + */ + +#ifndef JP2_COD_H +#define JP2_COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" + +/******************************************************************************\ +* Macros. +\******************************************************************************/ + +#define JP2_SPTOBPC(s, p) \ + ((((p) - 1) & 0x7f) | (((s) & 1) << 7)) + +/******************************************************************************\ +* Box class. +\******************************************************************************/ + +#define JP2_BOX_HDRLEN 8 + +/* Box types. */ +#define JP2_BOX_JP 0x6a502020 /* Signature */ +#define JP2_BOX_FTYP 0x66747970 /* File Type */ +#define JP2_BOX_JP2H 0x6a703268 /* JP2 Header */ +#define JP2_BOX_IHDR 0x69686472 /* Image Header */ +#define JP2_BOX_BPCC 0x62706363 /* Bits Per Component */ +#define JP2_BOX_COLR 0x636f6c72 /* Color Specification */ +#define JP2_BOX_PCLR 0x70636c72 /* Palette */ +#define JP2_BOX_CMAP 0x636d6170 /* Component Mapping */ +#define JP2_BOX_CDEF 0x63646566 /* Channel Definition */ +#define JP2_BOX_RES 0x72657320 /* Resolution */ +#define JP2_BOX_RESC 0x72657363 /* Capture Resolution */ +#define JP2_BOX_RESD 0x72657364 /* Default Display Resolution */ +#define JP2_BOX_JP2C 0x6a703263 /* Contiguous Code Stream */ +#define JP2_BOX_JP2I 0x6a703269 /* Intellectual Property */ +#define JP2_BOX_XML 0x786d6c20 /* XML */ +#define JP2_BOX_UUID 0x75756964 /* UUID */ +#define JP2_BOX_UINF 0x75696e66 /* UUID Info */ +#define JP2_BOX_ULST 0x75637374 /* UUID List */ +#define JP2_BOX_URL 0x75726c20 /* URL */ + +#define JP2_BOX_SUPER 0x01 +#define JP2_BOX_NODATA 0x02 + +/* JP box data. */ + +#define JP2_JP_MAGIC 0x0d0a870a +#define JP2_JP_LEN 12 + +typedef struct { + uint_fast32_t magic; +} jp2_jp_t; + +/* FTYP box data. */ + +#define JP2_FTYP_MAXCOMPATCODES 32 +#define JP2_FTYP_MAJVER 0x6a703220 +#define JP2_FTYP_MINVER 0 +#define JP2_FTYP_COMPATCODE JP2_FTYP_MAJVER + +typedef struct { + uint_fast32_t majver; + uint_fast32_t minver; + uint_fast32_t numcompatcodes; + uint_fast32_t compatcodes[JP2_FTYP_MAXCOMPATCODES]; +} jp2_ftyp_t; + +/* IHDR box data. */ + +#define JP2_IHDR_COMPTYPE 7 +#define JP2_IHDR_BPCNULL 255 + +typedef struct { + uint_fast32_t width; + uint_fast32_t height; + uint_fast16_t numcmpts; + uint_fast8_t bpc; + uint_fast8_t comptype; + uint_fast8_t csunk; + uint_fast8_t ipr; +} jp2_ihdr_t; + +/* BPCC box data. */ + +typedef struct { + uint_fast16_t numcmpts; + uint_fast8_t *bpcs; +} jp2_bpcc_t; + +/* COLR box data. */ + +#define JP2_COLR_ENUM 1 +#define JP2_COLR_ICC 2 +#define JP2_COLR_PRI 0 + +#define JP2_COLR_SRGB 16 +#define JP2_COLR_SGRAY 17 +#define JP2_COLR_SYCC 18 + +typedef struct { + uint_fast8_t method; + uint_fast8_t pri; + uint_fast8_t approx; + uint_fast32_t csid; + uint_fast8_t *iccp; + int iccplen; + /* XXX - Someday we ought to add ICC profile data here. */ +} jp2_colr_t; + +/* PCLR box data. */ + +typedef struct { + uint_fast16_t numlutents; + uint_fast8_t numchans; + int_fast32_t *lutdata; + uint_fast8_t *bpc; +} jp2_pclr_t; + +/* CDEF box per-channel data. */ + +#define JP2_CDEF_RGB_R 1 +#define JP2_CDEF_RGB_G 2 +#define JP2_CDEF_RGB_B 3 + +#define JP2_CDEF_YCBCR_Y 1 +#define JP2_CDEF_YCBCR_CB 2 +#define JP2_CDEF_YCBCR_CR 3 + +#define JP2_CDEF_GRAY_Y 1 + +#define JP2_CDEF_TYPE_COLOR 0 +#define JP2_CDEF_TYPE_OPACITY 1 +#define JP2_CDEF_TYPE_UNSPEC 65535 +#define JP2_CDEF_ASOC_ALL 0 +#define JP2_CDEF_ASOC_NONE 65535 + +typedef struct { + uint_fast16_t channo; + uint_fast16_t type; + uint_fast16_t assoc; +} jp2_cdefchan_t; + +/* CDEF box data. */ + +typedef struct { + uint_fast16_t numchans; + jp2_cdefchan_t *ents; +} jp2_cdef_t; + +typedef struct { + uint_fast16_t cmptno; + uint_fast8_t map; + uint_fast8_t pcol; +} jp2_cmapent_t; + +typedef struct { + uint_fast16_t numchans; + jp2_cmapent_t *ents; +} jp2_cmap_t; + +#define JP2_CMAP_DIRECT 0 +#define JP2_CMAP_PALETTE 1 + +/* Generic box. */ + +struct jp2_boxops_s; +typedef struct { + + struct jp2_boxops_s *ops; + struct jp2_boxinfo_s *info; + + uint_fast32_t type; + uint_fast32_t len; + + union { + jp2_jp_t jp; + jp2_ftyp_t ftyp; + jp2_ihdr_t ihdr; + jp2_bpcc_t bpcc; + jp2_colr_t colr; + jp2_pclr_t pclr; + jp2_cdef_t cdef; + jp2_cmap_t cmap; + } data; + +} jp2_box_t; + +typedef struct jp2_boxops_s { + void (*init)(jp2_box_t *box); + void (*destroy)(jp2_box_t *box); + int (*getdata)(jp2_box_t *box, jas_stream_t *in); + int (*putdata)(jp2_box_t *box, jas_stream_t *out); + void (*dumpdata)(jp2_box_t *box, FILE *out); +} jp2_boxops_t; + +/******************************************************************************\ +* +\******************************************************************************/ + +typedef struct jp2_boxinfo_s { + int type; + char *name; + int flags; + jp2_boxops_t ops; +} jp2_boxinfo_t; + +/******************************************************************************\ +* Box class. +\******************************************************************************/ + +jp2_box_t *jp2_box_create(int type); +void jp2_box_destroy(jp2_box_t *box); +jp2_box_t *jp2_box_get(jas_stream_t *in); +int jp2_box_put(jp2_box_t *box, jas_stream_t *out); + +#define JP2_DTYPETOBPC(dtype) \ + ((JAS_IMAGE_CDT_GETSGND(dtype) << 7) | (JAS_IMAGE_CDT_GETPREC(dtype) - 1)) +#define JP2_BPCTODTYPE(bpc) \ + (JAS_IMAGE_CDT_SETSGND(bpc >> 7) | JAS_IMAGE_CDT_SETPREC((bpc & 0x7f) + 1)) + +#define ICC_CS_RGB 0x52474220 +#define ICC_CS_YCBCR 0x59436272 +#define ICC_CS_GRAY 0x47524159 + +jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo); + + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jp2/jp2_dec.c b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_dec.c new file mode 100644 index 0000000..b1d86ff --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_dec.c @@ -0,0 +1,652 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * JP2 Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_image.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_math.h" +#include "jasper/jas_debug.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_version.h" + +#include "jp2_cod.h" +#include "jp2_dec.h" + +#define JP2_VALIDATELEN (JAS_MIN(JP2_JP_LEN + 16, JAS_STREAM_MAXPUTBACK)) + +static jp2_dec_t *jp2_dec_create(void); +static void jp2_dec_destroy(jp2_dec_t *dec); +static int jp2_getcs(jp2_colr_t *colr); +static int fromiccpcs(int cs); +static int jp2_getct(int colorspace, int type, int assoc); + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +jas_image_t *jp2_decode(jas_stream_t *in, char *optstr) +{ + jp2_box_t *box; + int found; + jas_image_t *image; + jp2_dec_t *dec; + bool samedtype; + int dtype; + unsigned int i; + jp2_cmap_t *cmapd; + jp2_pclr_t *pclrd; + jp2_cdef_t *cdefd; + unsigned int channo; + int newcmptno; + int_fast32_t *lutents; +#if 0 + jp2_cdefchan_t *cdefent; + int cmptno; +#endif + jp2_cmapent_t *cmapent; + jas_icchdr_t icchdr; + jas_iccprof_t *iccprof; + + dec = 0; + box = 0; + image = 0; + + if (!(dec = jp2_dec_create())) { + goto error; + } + + /* Get the first box. This should be a JP box. */ + if (!(box = jp2_box_get(in))) { + jas_eprintf("error: cannot get box\n"); + goto error; + } + if (box->type != JP2_BOX_JP) { + jas_eprintf("error: expecting signature box\n"); + goto error; + } + if (box->data.jp.magic != JP2_JP_MAGIC) { + jas_eprintf("incorrect magic number\n"); + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Get the second box. This should be a FTYP box. */ + if (!(box = jp2_box_get(in))) { + goto error; + } + if (box->type != JP2_BOX_FTYP) { + jas_eprintf("expecting file type box\n"); + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Get more boxes... */ + found = 0; + while ((box = jp2_box_get(in))) { + if (jas_getdbglevel() >= 1) { + fprintf(stderr, "box type %s\n", box->info->name); + } + switch (box->type) { + case JP2_BOX_JP2C: + found = 1; + break; + case JP2_BOX_IHDR: + if (!dec->ihdr) { + dec->ihdr = box; + box = 0; + } + break; + case JP2_BOX_BPCC: + if (!dec->bpcc) { + dec->bpcc = box; + box = 0; + } + break; + case JP2_BOX_CDEF: + if (!dec->cdef) { + dec->cdef = box; + box = 0; + } + break; + case JP2_BOX_PCLR: + if (!dec->pclr) { + dec->pclr = box; + box = 0; + } + break; + case JP2_BOX_CMAP: + if (!dec->cmap) { + dec->cmap = box; + box = 0; + } + break; + case JP2_BOX_COLR: + if (!dec->colr) { + dec->colr = box; + box = 0; + } + break; + } + if (box) { + jp2_box_destroy(box); + box = 0; + } + if (found) { + break; + } + } + + if (!found) { + jas_eprintf("error: no code stream found\n"); + goto error; + } + + if (!(dec->image = jpc_decode(in, optstr))) { + jas_eprintf("error: cannot decode code stream\n"); + goto error; + } + + /* An IHDR box must be present. */ + if (!dec->ihdr) { + jas_eprintf("error: missing IHDR box\n"); + goto error; + } + + /* Does the number of components indicated in the IHDR box match + the value specified in the code stream? */ + if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(uint, jas_image_numcmpts(dec->image))) { + jas_eprintf("warning: number of components mismatch\n"); + } + + /* At least one component must be present. */ + if (!jas_image_numcmpts(dec->image)) { + jas_eprintf("error: no components\n"); + goto error; + } + + /* Determine if all components have the same data type. */ + samedtype = true; + dtype = jas_image_cmptdtype(dec->image, 0); + for (i = 1; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) { + if (jas_image_cmptdtype(dec->image, i) != dtype) { + samedtype = false; + break; + } + } + + /* Is the component data type indicated in the IHDR box consistent + with the data in the code stream? */ + if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || + (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { + jas_eprintf("warning: component data type mismatch\n"); + } + + /* Is the compression type supported? */ + if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { + jas_eprintf("error: unsupported compression type\n"); + goto error; + } + + if (dec->bpcc) { + /* Is the number of components indicated in the BPCC box + consistent with the code stream data? */ + if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(uint, jas_image_numcmpts( + dec->image))) { + jas_eprintf("warning: number of components mismatch\n"); + } + /* Is the component data type information indicated in the BPCC + box consistent with the code stream data? */ + if (!samedtype) { + for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) { + if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { + jas_eprintf("warning: component data type mismatch\n"); + } + } + } else { + jas_eprintf("warning: superfluous BPCC box\n"); + } + } + + /* A COLR box must be present. */ + if (!dec->colr) { + jas_eprintf("error: no COLR box\n"); + goto error; + } + + switch (dec->colr->data.colr.method) { + case JP2_COLR_ENUM: + jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); + break; + case JP2_COLR_ICC: + iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, + dec->colr->data.colr.iccplen); + assert(iccprof); + jas_iccprof_gethdr(iccprof, &icchdr); + jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc); + jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); + dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); + assert(dec->image->cmprof_); + jas_iccprof_destroy(iccprof); + break; + } + + /* If a CMAP box is present, a PCLR box must also be present. */ + if (dec->cmap && !dec->pclr) { + jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n"); + jp2_box_destroy(dec->cmap); + dec->cmap = 0; + } + + /* If a CMAP box is not present, a PCLR box must not be present. */ + if (!dec->cmap && dec->pclr) { + jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n"); + jp2_box_destroy(dec->pclr); + dec->pclr = 0; + } + + /* Determine the number of channels (which is essentially the number + of components after any palette mappings have been applied). */ + dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(uint, jas_image_numcmpts(dec->image)); + + /* Perform a basic sanity check on the CMAP box if present. */ + if (dec->cmap) { + for (i = 0; i < dec->numchans; ++i) { + /* Is the component number reasonable? */ + if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(uint, jas_image_numcmpts(dec->image))) { + jas_eprintf("error: invalid component number in CMAP box\n"); + goto error; + } + /* Is the LUT index reasonable? */ + if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) { + jas_eprintf("error: invalid CMAP LUT index\n"); + goto error; + } + } + } + + /* Allocate space for the channel-number to component-number LUT. */ + if (!(dec->chantocmptlut = jas_malloc(dec->numchans * sizeof(uint_fast16_t)))) { + jas_eprintf("error: no memory\n"); + goto error; + } + + if (!dec->cmap) { + for (i = 0; i < dec->numchans; ++i) { + dec->chantocmptlut[i] = i; + } + } else { + cmapd = &dec->cmap->data.cmap; + pclrd = &dec->pclr->data.pclr; + cdefd = &dec->cdef->data.cdef; + for (channo = 0; channo < cmapd->numchans; ++channo) { + cmapent = &cmapd->ents[channo]; + if (cmapent->map == JP2_CMAP_DIRECT) { + dec->chantocmptlut[channo] = channo; + } else if (cmapent->map == JP2_CMAP_PALETTE) { + lutents = jas_malloc(pclrd->numlutents * sizeof(int_fast32_t)); + for (i = 0; i < pclrd->numlutents; ++i) { + lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; + } + newcmptno = jas_image_numcmpts(dec->image); + jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); + dec->chantocmptlut[channo] = newcmptno; + jas_free(lutents); +#if 0 + if (dec->cdef) { + cdefent = jp2_cdef_lookup(cdefd, channo); + if (!cdefent) { + abort(); + } + jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); + } else { + jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); + } +#endif + } + } + } + + /* Mark all components as being of unknown type. */ + + for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) { + jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); + } + + /* Determine the type of each component. */ + if (dec->cdef) { + for (i = 0; i < dec->numchans; ++i) { + jas_image_setcmpttype(dec->image, + dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], + jp2_getct(jas_image_clrspc(dec->image), + dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc)); + } + } else { + for (i = 0; i < dec->numchans; ++i) { + jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], + jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); + } + } + + /* Delete any components that are not of interest. */ + for (i = jas_image_numcmpts(dec->image); i > 0; --i) { + if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { + jas_image_delcmpt(dec->image, i - 1); + } + } + + /* Ensure that some components survived. */ + if (!jas_image_numcmpts(dec->image)) { + jas_eprintf("error: no components\n"); + goto error; + } +#if 0 +fprintf(stderr, "no of components is %d\n", jas_image_numcmpts(dec->image)); +#endif + + /* Prevent the image from being destroyed later. */ + image = dec->image; + dec->image = 0; + + jp2_dec_destroy(dec); + + return image; + +error: + if (box) { + jp2_box_destroy(box); + } + if (dec) { + jp2_dec_destroy(dec); + } + return 0; +} + +int jp2_validate(jas_stream_t *in) +{ + char buf[JP2_VALIDATELEN]; + int i; + int n; +#if 0 + jas_stream_t *tmpstream; + jp2_box_t *box; +#endif + + assert(JAS_STREAM_MAXPUTBACK >= JP2_VALIDATELEN); + + /* Read the validation data (i.e., the data used for detecting + the format). */ + if ((n = jas_stream_read(in, buf, JP2_VALIDATELEN)) < 0) { + return -1; + } + + /* Put the validation data back onto the stream, so that the + stream position will not be changed. */ + for (i = n - 1; i >= 0; --i) { + if (jas_stream_ungetc(in, buf[i]) == EOF) { + return -1; + } + } + + /* Did we read enough data? */ + if (n < JP2_VALIDATELEN) { + return -1; + } + + /* Is the box type correct? */ + if (((buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7]) != + JP2_BOX_JP) + { + return -1; + } + + return 0; +} + +static jp2_dec_t *jp2_dec_create(void) +{ + jp2_dec_t *dec; + + if (!(dec = jas_malloc(sizeof(jp2_dec_t)))) { + return 0; + } + dec->ihdr = 0; + dec->bpcc = 0; + dec->cdef = 0; + dec->pclr = 0; + dec->image = 0; + dec->chantocmptlut = 0; + dec->cmap = 0; + dec->colr = 0; + return dec; +} + +static void jp2_dec_destroy(jp2_dec_t *dec) +{ + if (dec->ihdr) { + jp2_box_destroy(dec->ihdr); + } + if (dec->bpcc) { + jp2_box_destroy(dec->bpcc); + } + if (dec->cdef) { + jp2_box_destroy(dec->cdef); + } + if (dec->pclr) { + jp2_box_destroy(dec->pclr); + } + if (dec->image) { + jas_image_destroy(dec->image); + } + if (dec->cmap) { + jp2_box_destroy(dec->cmap); + } + if (dec->colr) { + jp2_box_destroy(dec->colr); + } + if (dec->chantocmptlut) { + jas_free(dec->chantocmptlut); + } + jas_free(dec); +} + +static int jp2_getct(int colorspace, int type, int assoc) +{ + if (type == 1 && assoc == 0) { + return JAS_IMAGE_CT_OPACITY; + } + if (type == 0 && assoc >= 1 && assoc <= 65534) { + switch (colorspace) { + case JAS_CLRSPC_FAM_RGB: + switch (assoc) { + case JP2_CDEF_RGB_R: + return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R); + break; + case JP2_CDEF_RGB_G: + return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G); + break; + case JP2_CDEF_RGB_B: + return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B); + break; + } + break; + case JAS_CLRSPC_FAM_YCBCR: + switch (assoc) { + case JP2_CDEF_YCBCR_Y: + return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y); + break; + case JP2_CDEF_YCBCR_CB: + return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB); + break; + case JP2_CDEF_YCBCR_CR: + return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR); + break; + } + break; + case JAS_CLRSPC_FAM_GRAY: + switch (assoc) { + case JP2_CDEF_GRAY_Y: + return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y); + break; + } + break; + default: + return JAS_IMAGE_CT_COLOR(assoc - 1); + break; + } + } + return JAS_IMAGE_CT_UNKNOWN; +} + +static int jp2_getcs(jp2_colr_t *colr) +{ + if (colr->method == JP2_COLR_ENUM) { + switch (colr->csid) { + case JP2_COLR_SRGB: + return JAS_CLRSPC_SRGB; + break; + case JP2_COLR_SYCC: + return JAS_CLRSPC_SYCBCR; + break; + case JP2_COLR_SGRAY: + return JAS_CLRSPC_SGRAY; + break; + } + } + return JAS_CLRSPC_UNKNOWN; +} + +static int fromiccpcs(int cs) +{ + switch (cs) { + case ICC_CS_RGB: + return JAS_CLRSPC_GENRGB; + break; + case ICC_CS_YCBCR: + return JAS_CLRSPC_GENYCBCR; + break; + case ICC_CS_GRAY: + return JAS_CLRSPC_GENGRAY; + break; + } + return JAS_CLRSPC_UNKNOWN; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jp2/jp2_dec.h b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_dec.h new file mode 100644 index 0000000..00f735e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_dec.h @@ -0,0 +1,134 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JP2_DEC_H +#define JP2_DEC_H + +#include "jasper/jas_image.h" +#include "jasper/jas_stream.h" +#include "jp2_cod.h" + +typedef struct { + + jp2_box_t *pclr; + jp2_box_t *cdef; + jp2_box_t *ihdr; + jp2_box_t *bpcc; + jp2_box_t *cmap; + jp2_box_t *colr; + jas_image_t *image; + uint_fast16_t numchans; + uint_fast16_t *chantocmptlut; + +} jp2_dec_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jp2/jp2_enc.c b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_enc.c new file mode 100644 index 0000000..708e4a4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jp2/jp2_enc.c @@ -0,0 +1,485 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * JP2 Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include "jasper/jas_malloc.h" +#include "jasper/jas_image.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_cm.h" +#include "jasper/jas_icc.h" +#include "jp2_cod.h" + +static uint_fast32_t jp2_gettypeasoc(int colorspace, int ctype); +static int clrspctojp2(jas_clrspc_t clrspc); + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +int jp2_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + jp2_box_t *box; + jp2_ftyp_t *ftyp; + jp2_ihdr_t *ihdr; + jas_stream_t *tmpstream; + int allcmptssame; + jp2_bpcc_t *bpcc; + long len; + uint_fast16_t cmptno; + jp2_colr_t *colr; + char buf[4096]; + uint_fast32_t overhead; + jp2_cdefchan_t *cdefchanent; + jp2_cdef_t *cdef; + int i; + uint_fast32_t typeasoc; +jas_iccprof_t *iccprof; +jas_stream_t *iccstream; +int pos; +int needcdef; +int prec; +int sgnd; + + box = 0; + tmpstream = 0; + + allcmptssame = 1; + sgnd = jas_image_cmptsgnd(image, 0); + prec = jas_image_cmptprec(image, 0); + for (i = 1; i < jas_image_numcmpts(image); ++i) { + if (jas_image_cmptsgnd(image, i) != sgnd || + jas_image_cmptprec(image, i) != prec) { + allcmptssame = 0; + break; + } + } + + /* Output the signature box. */ + + if (!(box = jp2_box_create(JP2_BOX_JP))) { + goto error; + } + box->data.jp.magic = JP2_JP_MAGIC; + if (jp2_box_put(box, out)) { + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Output the file type box. */ + + if (!(box = jp2_box_create(JP2_BOX_FTYP))) { + goto error; + } + ftyp = &box->data.ftyp; + ftyp->majver = JP2_FTYP_MAJVER; + ftyp->minver = JP2_FTYP_MINVER; + ftyp->numcompatcodes = 1; + ftyp->compatcodes[0] = JP2_FTYP_COMPATCODE; + if (jp2_box_put(box, out)) { + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* + * Generate the data portion of the JP2 header box. + * We cannot simply output the header for this box + * since we do not yet know the correct value for the length + * field. + */ + + if (!(tmpstream = jas_stream_memopen(0, 0))) { + goto error; + } + + /* Generate image header box. */ + + if (!(box = jp2_box_create(JP2_BOX_IHDR))) { + goto error; + } + ihdr = &box->data.ihdr; + ihdr->width = jas_image_width(image); + ihdr->height = jas_image_height(image); + ihdr->numcmpts = jas_image_numcmpts(image); + ihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0), + jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL; + ihdr->comptype = JP2_IHDR_COMPTYPE; + ihdr->csunk = 0; + ihdr->ipr = 0; + if (jp2_box_put(box, tmpstream)) { + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Generate bits per component box. */ + + if (!allcmptssame) { + if (!(box = jp2_box_create(JP2_BOX_BPCC))) { + goto error; + } + bpcc = &box->data.bpcc; + bpcc->numcmpts = jas_image_numcmpts(image); + if (!(bpcc->bpcs = jas_malloc(bpcc->numcmpts * + sizeof(uint_fast8_t)))) { + goto error; + } + for (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) { + bpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image, + cmptno), jas_image_cmptprec(image, cmptno)); + } + if (jp2_box_put(box, tmpstream)) { + goto error; + } + jp2_box_destroy(box); + box = 0; + } + + /* Generate color specification box. */ + + if (!(box = jp2_box_create(JP2_BOX_COLR))) { + goto error; + } + colr = &box->data.colr; + switch (jas_image_clrspc(image)) { + case JAS_CLRSPC_SRGB: + case JAS_CLRSPC_SYCBCR: + case JAS_CLRSPC_SGRAY: + colr->method = JP2_COLR_ENUM; + colr->csid = clrspctojp2(jas_image_clrspc(image)); + colr->pri = JP2_COLR_PRI; + colr->approx = 0; + break; + default: + colr->method = JP2_COLR_ICC; + colr->pri = JP2_COLR_PRI; + colr->approx = 0; + iccprof = jas_iccprof_createfromcmprof(jas_image_cmprof(image)); + assert(iccprof); + iccstream = jas_stream_memopen(0, 0); + assert(iccstream); + if (jas_iccprof_save(iccprof, iccstream)) + abort(); + if ((pos = jas_stream_tell(iccstream)) < 0) + abort(); + colr->iccplen = pos; + colr->iccp = jas_malloc(pos); + assert(colr->iccp); + jas_stream_rewind(iccstream); + if (jas_stream_read(iccstream, colr->iccp, colr->iccplen) != colr->iccplen) + abort(); + jas_stream_close(iccstream); + jas_iccprof_destroy(iccprof); + break; + } + if (jp2_box_put(box, tmpstream)) { + goto error; + } + jp2_box_destroy(box); + box = 0; + + needcdef = 1; + switch (jas_clrspc_fam(jas_image_clrspc(image))) { + case JAS_CLRSPC_FAM_RGB: + if (jas_image_cmpttype(image, 0) == + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) && + jas_image_cmpttype(image, 1) == + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) && + jas_image_cmpttype(image, 2) == + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)) + needcdef = 0; + break; + case JAS_CLRSPC_FAM_YCBCR: + if (jas_image_cmpttype(image, 0) == + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) && + jas_image_cmpttype(image, 1) == + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) && + jas_image_cmpttype(image, 2) == + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR)) + needcdef = 0; + break; + case JAS_CLRSPC_FAM_GRAY: + if (jas_image_cmpttype(image, 0) == + JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y)) + needcdef = 0; + break; + default: + abort(); + break; + } + + if (needcdef) { + if (!(box = jp2_box_create(JP2_BOX_CDEF))) { + goto error; + } + cdef = &box->data.cdef; + cdef->numchans = jas_image_numcmpts(image); + cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t)); + for (i = 0; i < jas_image_numcmpts(image); ++i) { + cdefchanent = &cdef->ents[i]; + cdefchanent->channo = i; + typeasoc = jp2_gettypeasoc(jas_image_clrspc(image), jas_image_cmpttype(image, i)); + cdefchanent->type = typeasoc >> 16; + cdefchanent->assoc = typeasoc & 0x7fff; + } + if (jp2_box_put(box, tmpstream)) { + goto error; + } + jp2_box_destroy(box); + box = 0; + } + + /* Determine the total length of the JP2 header box. */ + + len = jas_stream_tell(tmpstream); + jas_stream_rewind(tmpstream); + + /* + * Output the JP2 header box and all of the boxes which it contains. + */ + + if (!(box = jp2_box_create(JP2_BOX_JP2H))) { + goto error; + } + box->len = len + JP2_BOX_HDRLEN; + if (jp2_box_put(box, out)) { + goto error; + } + jp2_box_destroy(box); + box = 0; + + if (jas_stream_copy(out, tmpstream, len)) { + goto error; + } + + jas_stream_close(tmpstream); + tmpstream = 0; + + /* + * Output the contiguous code stream box. + */ + + if (!(box = jp2_box_create(JP2_BOX_JP2C))) { + goto error; + } + box->len = 0; + if (jp2_box_put(box, out)) { + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Output the JPEG-2000 code stream. */ + + overhead = jas_stream_getrwcount(out); + sprintf(buf, "%s\n_jp2overhead=%lu\n", (optstr ? optstr : ""), + (unsigned long) overhead); + + if (jpc_encode(image, out, buf)) { + goto error; + } + + return 0; + abort(); + +error: + + if (box) { + jp2_box_destroy(box); + } + if (tmpstream) { + jas_stream_close(tmpstream); + } + return -1; +} + +static uint_fast32_t jp2_gettypeasoc(int colorspace, int ctype) +{ + int type; + int asoc; + + if (ctype & JAS_IMAGE_CT_OPACITY) { + type = JP2_CDEF_TYPE_OPACITY; + asoc = JP2_CDEF_ASOC_ALL; + goto done; + } + + type = JP2_CDEF_TYPE_UNSPEC; + asoc = JP2_CDEF_ASOC_NONE; + switch (jas_clrspc_fam(colorspace)) { + case JAS_CLRSPC_FAM_RGB: + switch (JAS_IMAGE_CT_COLOR(ctype)) { + case JAS_IMAGE_CT_RGB_R: + type = JP2_CDEF_TYPE_COLOR; + asoc = JP2_CDEF_RGB_R; + break; + case JAS_IMAGE_CT_RGB_G: + type = JP2_CDEF_TYPE_COLOR; + asoc = JP2_CDEF_RGB_G; + break; + case JAS_IMAGE_CT_RGB_B: + type = JP2_CDEF_TYPE_COLOR; + asoc = JP2_CDEF_RGB_B; + break; + } + break; + case JAS_CLRSPC_FAM_YCBCR: + switch (JAS_IMAGE_CT_COLOR(ctype)) { + case JAS_IMAGE_CT_YCBCR_Y: + type = JP2_CDEF_TYPE_COLOR; + asoc = JP2_CDEF_YCBCR_Y; + break; + case JAS_IMAGE_CT_YCBCR_CB: + type = JP2_CDEF_TYPE_COLOR; + asoc = JP2_CDEF_YCBCR_CB; + break; + case JAS_IMAGE_CT_YCBCR_CR: + type = JP2_CDEF_TYPE_COLOR; + asoc = JP2_CDEF_YCBCR_CR; + break; + } + break; + case JAS_CLRSPC_FAM_GRAY: + type = JP2_CDEF_TYPE_COLOR; + asoc = JP2_CDEF_GRAY_Y; + break; + } + +done: + return (type << 16) | asoc; +} + +static int clrspctojp2(jas_clrspc_t clrspc) +{ + switch (clrspc) { + case JAS_CLRSPC_SRGB: + return JP2_COLR_SRGB; + case JAS_CLRSPC_SYCBCR: + return JP2_COLR_SYCC; + case JAS_CLRSPC_SGRAY: + return JP2_COLR_SGRAY; + default: + abort(); + break; + } +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/.gitignore b/SlnkDWFImpl/CxImage/jasper/jpc/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_bs.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_bs.c new file mode 100644 index 0000000..7110b91 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_bs.c @@ -0,0 +1,486 @@ +/* + * Copyright (c) 1999-2000, Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Bit Stream Class + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" +#include "jasper/jas_debug.h" + +#include "jpc_bs.h" + +/******************************************************************************\ +* Local function prototypes. +\******************************************************************************/ + +static jpc_bitstream_t *jpc_bitstream_alloc(void); + +/******************************************************************************\ +* Code for opening and closing bit streams. +\******************************************************************************/ + +/* Open a bit stream from a stream. */ +jpc_bitstream_t *jpc_bitstream_sopen(jas_stream_t *stream, char *mode) +{ + jpc_bitstream_t *bitstream; + + /* Ensure that the open mode is valid. */ + assert(!strcmp(mode, "r") || !strcmp(mode, "w") || !strcmp(mode, "r+") + || !strcmp(mode, "w+")); + + if (!(bitstream = jpc_bitstream_alloc())) { + return 0; + } + + /* By default, do not close the underlying (character) stream, upon + the close of the bit stream. */ + bitstream->flags_ = JPC_BITSTREAM_NOCLOSE; + + bitstream->stream_ = stream; + bitstream->openmode_ = (mode[0] == 'w') ? JPC_BITSTREAM_WRITE : + JPC_BITSTREAM_READ; + + /* Mark the data buffer as empty. */ + bitstream->cnt_ = (bitstream->openmode_ == JPC_BITSTREAM_READ) ? 0 : 8; + bitstream->buf_ = 0; + + return bitstream; +} + +/* Close a bit stream. */ +int jpc_bitstream_close(jpc_bitstream_t *bitstream) +{ + int ret = 0; + + /* Align to the next byte boundary while considering the effects of + bit stuffing. */ + if (jpc_bitstream_align(bitstream)) { + ret = -1; + } + + /* If necessary, close the underlying (character) stream. */ + if (!(bitstream->flags_ & JPC_BITSTREAM_NOCLOSE) && bitstream->stream_) { + if (jas_stream_close(bitstream->stream_)) { + ret = -1; + } + bitstream->stream_ = 0; + } + + jas_free(bitstream); + return ret; +} + +/* Allocate a new bit stream. */ +static jpc_bitstream_t *jpc_bitstream_alloc() +{ + jpc_bitstream_t *bitstream; + + /* Allocate memory for the new bit stream object. */ + if (!(bitstream = jas_malloc(sizeof(jpc_bitstream_t)))) { + return 0; + } + /* Initialize all of the data members. */ + bitstream->stream_ = 0; + bitstream->cnt_ = 0; + bitstream->flags_ = 0; + bitstream->openmode_ = 0; + + return bitstream; +} + +/******************************************************************************\ +* Code for reading/writing from/to bit streams. +\******************************************************************************/ + +/* Get a bit from a bit stream. */ +int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream) +{ + int ret; + JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func(%p)\n", bitstream)); + ret = jpc_bitstream_getbit_macro(bitstream); + JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func -> %d\n", ret)); + return ret; +} + +/* Put a bit to a bit stream. */ +int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int b) +{ + int ret; + JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func(%p, %d)\n", bitstream, b)); + ret = jpc_bitstream_putbit_macro(bitstream, b); + JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func() -> %d\n", ret)); + return ret; +} + +/* Get one or more bits from a bit stream. */ +long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n) +{ + long v; + int u; + + /* We can reliably get at most 31 bits since ISO/IEC 9899 only + guarantees that a long can represent values up to 2^31-1. */ + assert(n >= 0 && n < 32); + + /* Get the number of bits requested from the specified bit stream. */ + v = 0; + while (--n >= 0) { + if ((u = jpc_bitstream_getbit(bitstream)) < 0) { + return -1; + } + v = (v << 1) | u; + } + return v; +} + +/* Put one or more bits to a bit stream. */ +int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v) +{ + int m; + + /* We can reliably put at most 31 bits since ISO/IEC 9899 only + guarantees that a long can represent values up to 2^31-1. */ + assert(n >= 0 && n < 32); + /* Ensure that only the bits to be output are nonzero. */ + assert(!(v & (~JAS_ONES(n)))); + + /* Put the desired number of bits to the specified bit stream. */ + m = n - 1; + while (--n >= 0) { + if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) { + return EOF; + } + v <<= 1; + } + return 0; +} + +/******************************************************************************\ +* Code for buffer filling and flushing. +\******************************************************************************/ + +/* Fill the buffer for a bit stream. */ +int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream) +{ + int c; + /* Note: The count has already been decremented by the caller. */ + assert(bitstream->openmode_ & JPC_BITSTREAM_READ); + assert(bitstream->cnt_ <= 0); + + if (bitstream->flags_ & JPC_BITSTREAM_ERR) { + bitstream->cnt_ = 0; + return -1; + } + + if (bitstream->flags_ & JPC_BITSTREAM_EOF) { + bitstream->buf_ = 0x7f; + bitstream->cnt_ = 7; + return 1; + } + + bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff; + if ((c = jas_stream_getc((bitstream)->stream_)) == EOF) { + bitstream->flags_ |= JPC_BITSTREAM_EOF; + return 1; + } + bitstream->cnt_ = (bitstream->buf_ == 0xff00) ? 6 : 7; + bitstream->buf_ |= c & ((1 << (bitstream->cnt_ + 1)) - 1); + return (bitstream->buf_ >> bitstream->cnt_) & 1; +} + + +/******************************************************************************\ +* Code related to flushing. +\******************************************************************************/ + +/* Does the bit stream need to be aligned to a byte boundary (considering + the effects of bit stuffing)? */ +int jpc_bitstream_needalign(jpc_bitstream_t *bitstream) +{ + if (bitstream->openmode_ & JPC_BITSTREAM_READ) { + /* The bit stream is open for reading. */ + /* If there are any bits buffered for reading, or the + previous byte forced a stuffed bit, alignment is + required. */ + if ((bitstream->cnt_ < 8 && bitstream->cnt_ > 0) || + ((bitstream->buf_ >> 8) & 0xff) == 0xff) { + return 1; + } + } else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) { + /* The bit stream is open for writing. */ + /* If there are any bits buffered for writing, or the + previous byte forced a stuffed bit, alignment is + required. */ + if ((bitstream->cnt_ < 8 && bitstream->cnt_ >= 0) || + ((bitstream->buf_ >> 8) & 0xff) == 0xff) { + return 1; + } + } else { + /* This should not happen. Famous last words, eh? :-) */ + assert(0); + return -1; + } + return 0; +} + +/* How many additional bytes would be output if we align the bit stream? */ +int jpc_bitstream_pending(jpc_bitstream_t *bitstream) +{ + if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) { + /* The bit stream is being used for writing. */ +#if 1 + /* XXX - Is this really correct? Check someday... */ + if (bitstream->cnt_ < 8) { + return 1; + } +#else + if (bitstream->cnt_ < 8) { + if (((bitstream->buf_ >> 8) & 0xff) == 0xff) { + return 2; + } + return 1; + } +#endif + return 0; + } else { + /* This operation should not be invoked on a bit stream that + is being used for reading. */ + return -1; + } +} + +/* Align the bit stream to a byte boundary. */ +int jpc_bitstream_align(jpc_bitstream_t *bitstream) +{ + int ret; + if (bitstream->openmode_ & JPC_BITSTREAM_READ) { + ret = jpc_bitstream_inalign(bitstream, 0, 0); + } else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) { + ret = jpc_bitstream_outalign(bitstream, 0); + } else { + abort(); + } + return ret; +} + +/* Align a bit stream in the input case. */ +int jpc_bitstream_inalign(jpc_bitstream_t *bitstream, int fillmask, + int filldata) +{ + int n; + int v; + int u; + int numfill; + int m; + + numfill = 7; + m = 0; + v = 0; + if (bitstream->cnt_ > 0) { + n = bitstream->cnt_; + } else if (!bitstream->cnt_) { + n = ((bitstream->buf_ & 0xff) == 0xff) ? 7 : 0; + } else { + n = 0; + } + if (n > 0) { + if ((u = jpc_bitstream_getbits(bitstream, n)) < 0) { + return -1; + } + m += n; + v = (v << n) | u; + } + if ((bitstream->buf_ & 0xff) == 0xff) { + if ((u = jpc_bitstream_getbits(bitstream, 7)) < 0) { + return -1; + } + v = (v << 7) | u; + m += 7; + } + if (m > numfill) { + v >>= m - numfill; + } else { + filldata >>= numfill - m; + fillmask >>= numfill - m; + } + if (((~(v ^ filldata)) & fillmask) != fillmask) { + /* The actual fill pattern does not match the expected one. */ + return 1; + } + + return 0; +} + +/* Align a bit stream in the output case. */ +int jpc_bitstream_outalign(jpc_bitstream_t *bitstream, int filldata) +{ + int n; + int v; + + /* Ensure that this bit stream is open for writing. */ + assert(bitstream->openmode_ & JPC_BITSTREAM_WRITE); + + /* Ensure that the first bit of fill data is zero. */ + /* Note: The first bit of fill data must be zero. If this were not + the case, the fill data itself could cause further bit stuffing to + be required (which would cause numerous complications). */ + assert(!(filldata & (~0x3f))); + + if (!bitstream->cnt_) { + if ((bitstream->buf_ & 0xff) == 0xff) { + n = 7; + v = filldata; + } else { + n = 0; + v = 0; + } + } else if (bitstream->cnt_ > 0 && bitstream->cnt_ < 8) { + n = bitstream->cnt_; + v = filldata >> (7 - n); + } else { + n = 0; + v = 0; + return 0; + } + + /* Write the appropriate fill data to the bit stream. */ + if (n > 0) { + if (jpc_bitstream_putbits(bitstream, n, v)) { + return -1; + } + } + if (bitstream->cnt_ < 8) { + assert(bitstream->cnt_ >= 0 && bitstream->cnt_ < 8); + assert((bitstream->buf_ & 0xff) != 0xff); + /* Force the pending byte of output to be written to the + underlying (character) stream. */ + if (jas_stream_putc(bitstream->stream_, bitstream->buf_ & 0xff) == EOF) { + return -1; + } + bitstream->cnt_ = 8; + bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff; + } + + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_bs.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_bs.h new file mode 100644 index 0000000..8d44fa4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_bs.h @@ -0,0 +1,280 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Bit Stream Class + * + * $Id$ + */ + +#ifndef JPC_BS_H +#define JPC_BS_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_stream.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* + * Bit stream open mode flags. + */ + +/* Bit stream open for reading. */ +#define JPC_BITSTREAM_READ 0x01 +/* Bit stream open for writing. */ +#define JPC_BITSTREAM_WRITE 0x02 + +/* + * Bit stream flags. + */ + +/* Do not close underlying character stream. */ +#define JPC_BITSTREAM_NOCLOSE 0x01 +/* End of file has been reached while reading. */ +#define JPC_BITSTREAM_EOF 0x02 +/* An I/O error has occured. */ +#define JPC_BITSTREAM_ERR 0x04 + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* Bit stream class. */ + +typedef struct { + + /* Some miscellaneous flags. */ + int flags_; + + /* The input/output buffer. */ + uint_fast16_t buf_; + + /* The number of bits remaining in the byte being read/written. */ + int cnt_; + + /* The underlying stream associated with this bit stream. */ + jas_stream_t *stream_; + + /* The mode in which this bit stream was opened. */ + int openmode_; + +} jpc_bitstream_t; + +/******************************************************************************\ +* Functions/macros for opening and closing bit streams.. +\******************************************************************************/ + +/* Open a stream as a bit stream. */ +jpc_bitstream_t *jpc_bitstream_sopen(jas_stream_t *stream, char *mode); + +/* Close a bit stream. */ +int jpc_bitstream_close(jpc_bitstream_t *bitstream); + +/******************************************************************************\ +* Functions/macros for reading from and writing to bit streams.. +\******************************************************************************/ + +/* Read a bit from a bit stream. */ +#if defined(DEBUG) +#define jpc_bitstream_getbit(bitstream) \ + jpc_bitstream_getbit_func(bitstream) +#else +#define jpc_bitstream_getbit(bitstream) \ + jpc_bitstream_getbit_macro(bitstream) +#endif + +/* Write a bit to a bit stream. */ +#if defined(DEBUG) +#define jpc_bitstream_putbit(bitstream, v) \ + jpc_bitstream_putbit_func(bitstream, v) +#else +#define jpc_bitstream_putbit(bitstream, v) \ + jpc_bitstream_putbit_macro(bitstream, v) +#endif + +/* Read one or more bits from a bit stream. */ +long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n); + +/* Write one or more bits to a bit stream. */ +int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v); + +/******************************************************************************\ +* Functions/macros for flushing and aligning bit streams. +\******************************************************************************/ + +/* Align the current position within the bit stream to the next byte + boundary. */ +int jpc_bitstream_align(jpc_bitstream_t *bitstream); + +/* Align the current position in the bit stream with the next byte boundary, + ensuring that certain bits consumed in the process match a particular + pattern. */ +int jpc_bitstream_inalign(jpc_bitstream_t *bitstream, int fillmask, + int filldata); + +/* Align the current position in the bit stream with the next byte boundary, + writing bits from the specified pattern (if necessary) in the process. */ +int jpc_bitstream_outalign(jpc_bitstream_t *bitstream, int filldata); + +/* Check if a bit stream needs alignment. */ +int jpc_bitstream_needalign(jpc_bitstream_t *bitstream); + +/* How many additional bytes would be output if the bit stream was aligned? */ +int jpc_bitstream_pending(jpc_bitstream_t *bitstream); + +/******************************************************************************\ +* Functions/macros for querying state information for bit streams. +\******************************************************************************/ + +/* Has EOF been encountered on a bit stream? */ +#define jpc_bitstream_eof(bitstream) \ + ((bitstream)->flags_ & JPC_BITSTREAM_EOF) + +/******************************************************************************\ +* Internals. +\******************************************************************************/ + +/* DO NOT DIRECTLY INVOKE ANY OF THE MACROS OR FUNCTIONS BELOW. THEY ARE + FOR INTERNAL USE ONLY. */ + +int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream); + +int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int v); + +int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream); + +#define jpc_bitstream_getbit_macro(bitstream) \ + (assert((bitstream)->openmode_ & JPC_BITSTREAM_READ), \ + (--(bitstream)->cnt_ >= 0) ? \ + ((int)(((bitstream)->buf_ >> (bitstream)->cnt_) & 1)) : \ + jpc_bitstream_fillbuf(bitstream)) + +#define jpc_bitstream_putbit_macro(bitstream, bit) \ + (assert((bitstream)->openmode_ & JPC_BITSTREAM_WRITE), \ + (--(bitstream)->cnt_ < 0) ? \ + ((bitstream)->buf_ = ((bitstream)->buf_ << 8) & 0xffff, \ + (bitstream)->cnt_ = ((bitstream)->buf_ == 0xff00) ? 6 : 7, \ + (bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \ + (jas_stream_putc((bitstream)->stream_, (bitstream)->buf_ >> 8) == EOF) \ + ? (EOF) : ((bit) & 1)) : \ + ((bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \ + (bit) & 1)) + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cod.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cod.h new file mode 100644 index 0000000..6091283 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cod.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * $Id$ + */ + +#ifndef JPC_COD_H +#define JPC_COD_H + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* The nominal word size used by this implementation. */ +#define JPC_PREC 32 + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cs.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cs.c new file mode 100644 index 0000000..b0be7fb --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cs.c @@ -0,0 +1,1694 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * JPEG-2000 Code Stream Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_malloc.h" +#include "jasper/jas_debug.h" + +#include "jpc_cs.h" + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* Marker segment table entry. */ +typedef struct { + int id; + char *name; + jpc_msops_t ops; +} jpc_mstabent_t; + +/******************************************************************************\ +* Local prototypes. +\******************************************************************************/ + +static jpc_mstabent_t *jpc_mstab_lookup(int id); + +static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static void jpc_poc_destroyparms(jpc_ms_t *ms); + +static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); +static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); + +static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); +static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); + +static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out); +static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out); + +static void jpc_siz_destroyparms(jpc_ms_t *ms); +static void jpc_qcd_destroyparms(jpc_ms_t *ms); +static void jpc_qcc_destroyparms(jpc_ms_t *ms); +static void jpc_cod_destroyparms(jpc_ms_t *ms); +static void jpc_coc_destroyparms(jpc_ms_t *ms); +static void jpc_unk_destroyparms(jpc_ms_t *ms); +static void jpc_ppm_destroyparms(jpc_ms_t *ms); +static void jpc_ppt_destroyparms(jpc_ms_t *ms); +static void jpc_crg_destroyparms(jpc_ms_t *ms); +static void jpc_com_destroyparms(jpc_ms_t *ms); + +static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms); +static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, + jas_stream_t *in, uint_fast16_t len); +static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, + jas_stream_t *out); +static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms); +static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms); +static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms); + +/******************************************************************************\ +* Global data. +\******************************************************************************/ + +static jpc_mstabent_t jpc_mstab[] = { + {JPC_MS_SOC, "SOC", {0, 0, 0, 0}}, + {JPC_MS_SOT, "SOT", {0, jpc_sot_getparms, jpc_sot_putparms, + jpc_sot_dumpparms}}, + {JPC_MS_SOD, "SOD", {0, 0, 0, 0}}, + {JPC_MS_EOC, "EOC", {0, 0, 0, 0}}, + {JPC_MS_SIZ, "SIZ", {jpc_siz_destroyparms, jpc_siz_getparms, + jpc_siz_putparms, jpc_siz_dumpparms}}, + {JPC_MS_COD, "COD", {jpc_cod_destroyparms, jpc_cod_getparms, + jpc_cod_putparms, jpc_cod_dumpparms}}, + {JPC_MS_COC, "COC", {jpc_coc_destroyparms, jpc_coc_getparms, + jpc_coc_putparms, jpc_coc_dumpparms}}, + {JPC_MS_RGN, "RGN", {0, jpc_rgn_getparms, jpc_rgn_putparms, + jpc_rgn_dumpparms}}, + {JPC_MS_QCD, "QCD", {jpc_qcd_destroyparms, jpc_qcd_getparms, + jpc_qcd_putparms, jpc_qcd_dumpparms}}, + {JPC_MS_QCC, "QCC", {jpc_qcc_destroyparms, jpc_qcc_getparms, + jpc_qcc_putparms, jpc_qcc_dumpparms}}, + {JPC_MS_POC, "POC", {jpc_poc_destroyparms, jpc_poc_getparms, + jpc_poc_putparms, jpc_poc_dumpparms}}, + {JPC_MS_TLM, "TLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}}, + {JPC_MS_PLM, "PLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}}, + {JPC_MS_PPM, "PPM", {jpc_ppm_destroyparms, jpc_ppm_getparms, + jpc_ppm_putparms, jpc_ppm_dumpparms}}, + {JPC_MS_PPT, "PPT", {jpc_ppt_destroyparms, jpc_ppt_getparms, + jpc_ppt_putparms, jpc_ppt_dumpparms}}, + {JPC_MS_SOP, "SOP", {0, jpc_sop_getparms, jpc_sop_putparms, + jpc_sop_dumpparms}}, + {JPC_MS_EPH, "EPH", {0, 0, 0, 0}}, + {JPC_MS_CRG, "CRG", {0, jpc_crg_getparms, jpc_crg_putparms, + jpc_crg_dumpparms}}, + {JPC_MS_COM, "COM", {jpc_com_destroyparms, jpc_com_getparms, + jpc_com_putparms, jpc_com_dumpparms}}, + {-1, "UNKNOWN", {jpc_unk_destroyparms, jpc_unk_getparms, + jpc_unk_putparms, jpc_unk_dumpparms}} +}; + +/******************************************************************************\ +* Code stream manipulation functions. +\******************************************************************************/ + +/* Create a code stream state object. */ +jpc_cstate_t *jpc_cstate_create() +{ + jpc_cstate_t *cstate; + if (!(cstate = jas_malloc(sizeof(jpc_cstate_t)))) { + return 0; + } + cstate->numcomps = 0; + return cstate; +} + +/* Destroy a code stream state object. */ +void jpc_cstate_destroy(jpc_cstate_t *cstate) +{ + jas_free(cstate); +} + +/* Read a marker segment from a stream. */ +jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate) +{ + jpc_ms_t *ms; + jpc_mstabent_t *mstabent; + jas_stream_t *tmpstream; + + if (!(ms = jpc_ms_create(0))) { + return 0; + } + + /* Get the marker type. */ + if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN || + ms->id > JPC_MS_MAX) { + jpc_ms_destroy(ms); + return 0; + } + + mstabent = jpc_mstab_lookup(ms->id); + ms->ops = &mstabent->ops; + + /* Get the marker segment length and parameters if present. */ + /* Note: It is tacitly assumed that a marker segment cannot have + parameters unless it has a length field. That is, there cannot + be a parameters field without a length field and vice versa. */ + if (JPC_MS_HASPARMS(ms->id)) { + /* Get the length of the marker segment. */ + if (jpc_getuint16(in, &ms->len) || ms->len < 3) { + jpc_ms_destroy(ms); + return 0; + } + /* Calculate the length of the marker segment parameters. */ + ms->len -= 2; + /* Create and prepare a temporary memory stream from which to + read the marker segment parameters. */ + /* Note: This approach provides a simple way of ensuring that + we never read beyond the end of the marker segment (even if + the marker segment length is errantly set too small). */ + if (!(tmpstream = jas_stream_memopen(0, 0))) { + jpc_ms_destroy(ms); + return 0; + } + if (jas_stream_copy(tmpstream, in, ms->len) || + jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) { + jas_stream_close(tmpstream); + jpc_ms_destroy(ms); + return 0; + } + /* Get the marker segment parameters. */ + if ((*ms->ops->getparms)(ms, cstate, tmpstream)) { + ms->ops = 0; + jpc_ms_destroy(ms); + jas_stream_close(tmpstream); + return 0; + } + + if (jas_getdbglevel() > 0) { + jpc_ms_dump(ms, stderr); + } + + if (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) { + fprintf(stderr, + "warning: trailing garbage in marker segment (%ld bytes)\n", + ms->len - jas_stream_tell(tmpstream)); + } + + /* Close the temporary stream. */ + jas_stream_close(tmpstream); + + } else { + /* There are no marker segment parameters. */ + ms->len = 0; + + if (jas_getdbglevel() > 0) { + jpc_ms_dump(ms, stderr); + } + } + + /* Update the code stream state information based on the type of + marker segment read. */ + /* Note: This is a bit of a hack, but I'm not going to define another + type of virtual function for this one special case. */ + if (ms->id == JPC_MS_SIZ) { + cstate->numcomps = ms->parms.siz.numcomps; + } + + return ms; +} + +/* Write a marker segment to a stream. */ +int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms) +{ + jas_stream_t *tmpstream; + int len; + + /* Output the marker segment type. */ + if (jpc_putuint16(out, ms->id)) { + return -1; + } + + /* Output the marker segment length and parameters if necessary. */ + if (ms->ops->putparms) { + /* Create a temporary stream in which to buffer the + parameter data. */ + if (!(tmpstream = jas_stream_memopen(0, 0))) { + return -1; + } + if ((*ms->ops->putparms)(ms, cstate, tmpstream)) { + jas_stream_close(tmpstream); + return -1; + } + /* Get the number of bytes of parameter data written. */ + if ((len = jas_stream_tell(tmpstream)) < 0) { + jas_stream_close(tmpstream); + return -1; + } + ms->len = len; + /* Write the marker segment length and parameter data to + the output stream. */ + if (jas_stream_seek(tmpstream, 0, SEEK_SET) < 0 || + jpc_putuint16(out, ms->len + 2) || + jas_stream_copy(out, tmpstream, ms->len) < 0) { + jas_stream_close(tmpstream); + return -1; + } + /* Close the temporary stream. */ + jas_stream_close(tmpstream); + } + + /* This is a bit of a hack, but I'm not going to define another + type of virtual function for this one special case. */ + if (ms->id == JPC_MS_SIZ) { + cstate->numcomps = ms->parms.siz.numcomps; + } + + if (jas_getdbglevel() > 0) { + jpc_ms_dump(ms, stderr); + } + + return 0; +} + +/******************************************************************************\ +* Marker segment operations. +\******************************************************************************/ + +/* Create a marker segment of the specified type. */ +jpc_ms_t *jpc_ms_create(int type) +{ + jpc_ms_t *ms; + jpc_mstabent_t *mstabent; + + if (!(ms = jas_malloc(sizeof(jpc_ms_t)))) { + return 0; + } + ms->id = type; + ms->len = 0; + mstabent = jpc_mstab_lookup(ms->id); + ms->ops = &mstabent->ops; + memset(&ms->parms, 0, sizeof(jpc_msparms_t)); + return ms; +} + +/* Destroy a marker segment. */ +void jpc_ms_destroy(jpc_ms_t *ms) +{ + if (ms->ops && ms->ops->destroyparms) { + (*ms->ops->destroyparms)(ms); + } + jas_free(ms); +} + +/* Dump a marker segment to a stream for debugging. */ +void jpc_ms_dump(jpc_ms_t *ms, FILE *out) +{ + jpc_mstabent_t *mstabent; + mstabent = jpc_mstab_lookup(ms->id); + fprintf(out, "type = 0x%04x (%s);", ms->id, mstabent->name); + if (JPC_MS_HASPARMS(ms->id)) { + fprintf(out, " len = %d;", ms->len + 2); + if (ms->ops->dumpparms) { + (*ms->ops->dumpparms)(ms, out); + } else { + fprintf(out, "\n"); + } + } else { + fprintf(out, "\n"); + } +} + +/******************************************************************************\ +* SOT marker segment operations. +\******************************************************************************/ + +static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_sot_t *sot = &ms->parms.sot; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (jpc_getuint16(in, &sot->tileno) || + jpc_getuint32(in, &sot->len) || + jpc_getuint8(in, &sot->partno) || + jpc_getuint8(in, &sot->numparts)) { + return -1; + } + if (jas_stream_eof(in)) { + return -1; + } + return 0; +} + +static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_sot_t *sot = &ms->parms.sot; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (jpc_putuint16(out, sot->tileno) || + jpc_putuint32(out, sot->len) || + jpc_putuint8(out, sot->partno) || + jpc_putuint8(out, sot->numparts)) { + return -1; + } + return 0; +} + +static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_sot_t *sot = &ms->parms.sot; + fprintf(out, "tileno = %d; len = %d; partno = %d; numparts = %d\n", + sot->tileno, sot->len, sot->partno, sot->numparts); + return 0; +} + +/******************************************************************************\ +* SIZ marker segment operations. +\******************************************************************************/ + +static void jpc_siz_destroyparms(jpc_ms_t *ms) +{ + jpc_siz_t *siz = &ms->parms.siz; + if (siz->comps) { + jas_free(siz->comps); + } +} + +static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + jas_stream_t *in) +{ + jpc_siz_t *siz = &ms->parms.siz; + unsigned int i; + uint_fast8_t tmp; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (jpc_getuint16(in, &siz->caps) || + jpc_getuint32(in, &siz->width) || + jpc_getuint32(in, &siz->height) || + jpc_getuint32(in, &siz->xoff) || + jpc_getuint32(in, &siz->yoff) || + jpc_getuint32(in, &siz->tilewidth) || + jpc_getuint32(in, &siz->tileheight) || + jpc_getuint32(in, &siz->tilexoff) || + jpc_getuint32(in, &siz->tileyoff) || + jpc_getuint16(in, &siz->numcomps)) { + return -1; + } + if (!siz->width || !siz->height || !siz->tilewidth || + !siz->tileheight || !siz->numcomps) { + return -1; + } + if (!(siz->comps = jas_malloc(siz->numcomps * sizeof(jpc_sizcomp_t)))) { + return -1; + } + for (i = 0; i < siz->numcomps; ++i) { + if (jpc_getuint8(in, &tmp) || + jpc_getuint8(in, &siz->comps[i].hsamp) || + jpc_getuint8(in, &siz->comps[i].vsamp)) { + jas_free(siz->comps); + return -1; + } + siz->comps[i].sgnd = (tmp >> 7) & 1; + siz->comps[i].prec = (tmp & 0x7f) + 1; + } + if (jas_stream_eof(in)) { + jas_free(siz->comps); + return -1; + } + return 0; +} + +static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_siz_t *siz = &ms->parms.siz; + unsigned int i; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + assert(siz->width && siz->height && siz->tilewidth && + siz->tileheight && siz->numcomps); + if (jpc_putuint16(out, siz->caps) || + jpc_putuint32(out, siz->width) || + jpc_putuint32(out, siz->height) || + jpc_putuint32(out, siz->xoff) || + jpc_putuint32(out, siz->yoff) || + jpc_putuint32(out, siz->tilewidth) || + jpc_putuint32(out, siz->tileheight) || + jpc_putuint32(out, siz->tilexoff) || + jpc_putuint32(out, siz->tileyoff) || + jpc_putuint16(out, siz->numcomps)) { + return -1; + } + for (i = 0; i < siz->numcomps; ++i) { + if (jpc_putuint8(out, ((siz->comps[i].sgnd & 1) << 7) | + ((siz->comps[i].prec - 1) & 0x7f)) || + jpc_putuint8(out, siz->comps[i].hsamp) || + jpc_putuint8(out, siz->comps[i].vsamp)) { + return -1; + } + } + return 0; +} + +static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_siz_t *siz = &ms->parms.siz; + unsigned int i; + fprintf(out, "caps = 0x%02x;\n", siz->caps); + fprintf(out, "width = %d; height = %d; xoff = %d; yoff = %d;\n", + siz->width, siz->height, siz->xoff, siz->yoff); + fprintf(out, "tilewidth = %d; tileheight = %d; tilexoff = %d; " + "tileyoff = %d;\n", siz->tilewidth, siz->tileheight, siz->tilexoff, + siz->tileyoff); + for (i = 0; i < siz->numcomps; ++i) { + fprintf(out, "prec[%d] = %d; sgnd[%d] = %d; hsamp[%d] = %d; " + "vsamp[%d] = %d\n", i, siz->comps[i].prec, i, + siz->comps[i].sgnd, i, siz->comps[i].hsamp, i, + siz->comps[i].vsamp); + } + return 0; +} + +/******************************************************************************\ +* COD marker segment operations. +\******************************************************************************/ + +static void jpc_cod_destroyparms(jpc_ms_t *ms) +{ + jpc_cod_t *cod = &ms->parms.cod; + jpc_cox_destroycompparms(&cod->compparms); +} + +static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_cod_t *cod = &ms->parms.cod; + if (jpc_getuint8(in, &cod->csty)) { + return -1; + } + if (jpc_getuint8(in, &cod->prg) || + jpc_getuint16(in, &cod->numlyrs) || + jpc_getuint8(in, &cod->mctrans)) { + return -1; + } + if (jpc_cox_getcompparms(ms, cstate, in, + (cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) { + return -1; + } + if (jas_stream_eof(in)) { + jpc_cod_destroyparms(ms); + return -1; + } + return 0; +} + +static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_cod_t *cod = &ms->parms.cod; + assert(cod->numlyrs > 0 && cod->compparms.numdlvls <= 32); + assert(cod->compparms.numdlvls == cod->compparms.numrlvls - 1); + if (jpc_putuint8(out, cod->compparms.csty) || + jpc_putuint8(out, cod->prg) || + jpc_putuint16(out, cod->numlyrs) || + jpc_putuint8(out, cod->mctrans)) { + return -1; + } + if (jpc_cox_putcompparms(ms, cstate, out, + (cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) { + return -1; + } + return 0; +} + +static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_cod_t *cod = &ms->parms.cod; + int i; + fprintf(out, "csty = 0x%02x;\n", cod->compparms.csty); + fprintf(out, "numdlvls = %d; qmfbid = %d; mctrans = %d\n", + cod->compparms.numdlvls, cod->compparms.qmfbid, cod->mctrans); + fprintf(out, "prg = %d; numlyrs = %d;\n", + cod->prg, cod->numlyrs); + fprintf(out, "cblkwidthval = %d; cblkheightval = %d; " + "cblksty = 0x%02x;\n", cod->compparms.cblkwidthval, cod->compparms.cblkheightval, + cod->compparms.cblksty); + if (cod->csty & JPC_COX_PRT) { + for (i = 0; i < cod->compparms.numrlvls; ++i) { + fprintf(stderr, "prcwidth[%d] = %d, prcheight[%d] = %d\n", + i, cod->compparms.rlvls[i].parwidthval, + i, cod->compparms.rlvls[i].parheightval); + } + } + return 0; +} + +/******************************************************************************\ +* COC marker segment operations. +\******************************************************************************/ + +static void jpc_coc_destroyparms(jpc_ms_t *ms) +{ + jpc_coc_t *coc = &ms->parms.coc; + jpc_cox_destroycompparms(&coc->compparms); +} + +static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_coc_t *coc = &ms->parms.coc; + uint_fast8_t tmp; + if (cstate->numcomps <= 256) { + if (jpc_getuint8(in, &tmp)) { + return -1; + } + coc->compno = tmp; + } else { + if (jpc_getuint16(in, &coc->compno)) { + return -1; + } + } + if (jpc_getuint8(in, &coc->compparms.csty)) { + return -1; + } + if (jpc_cox_getcompparms(ms, cstate, in, + (coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) { + return -1; + } + if (jas_stream_eof(in)) { + return -1; + } + return 0; +} + +static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_coc_t *coc = &ms->parms.coc; + assert(coc->compparms.numdlvls <= 32); + if (cstate->numcomps <= 256) { + if (jpc_putuint8(out, coc->compno)) { + return -1; + } + } else { + if (jpc_putuint16(out, coc->compno)) { + return -1; + } + } + if (jpc_putuint8(out, coc->compparms.csty)) { + return -1; + } + if (jpc_cox_putcompparms(ms, cstate, out, + (coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) { + return -1; + } + return 0; +} + +static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_coc_t *coc = &ms->parms.coc; + fprintf(out, "compno = %d; csty = 0x%02x; numdlvls = %d;\n", + coc->compno, coc->compparms.csty, coc->compparms.numdlvls); + fprintf(out, "cblkwidthval = %d; cblkheightval = %d; " + "cblksty = 0x%02x; qmfbid = %d;\n", coc->compparms.cblkwidthval, + coc->compparms.cblkheightval, coc->compparms.cblksty, coc->compparms.qmfbid); + return 0; +} +/******************************************************************************\ +* COD/COC marker segment operation helper functions. +\******************************************************************************/ + +static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms) +{ + /* Eliminate compiler warning about unused variables. */ + compparms = 0; +} + +static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms) +{ + uint_fast8_t tmp; + int i; + + /* Eliminate compiler warning about unused variables. */ + ms = 0; + cstate = 0; + + if (jpc_getuint8(in, &compparms->numdlvls) || + jpc_getuint8(in, &compparms->cblkwidthval) || + jpc_getuint8(in, &compparms->cblkheightval) || + jpc_getuint8(in, &compparms->cblksty) || + jpc_getuint8(in, &compparms->qmfbid)) { + return -1; + } + compparms->numrlvls = compparms->numdlvls + 1; + if (prtflag) { + for (i = 0; i < compparms->numrlvls; ++i) { + if (jpc_getuint8(in, &tmp)) { + jpc_cox_destroycompparms(compparms); + return -1; + } + compparms->rlvls[i].parwidthval = tmp & 0xf; + compparms->rlvls[i].parheightval = (tmp >> 4) & 0xf; + } +/* Sigh. This bit should be in the same field in both COC and COD mrk segs. */ +compparms->csty |= JPC_COX_PRT; + } else { + } + if (jas_stream_eof(in)) { + jpc_cox_destroycompparms(compparms); + return -1; + } + return 0; +} + +static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms) +{ + int i; + assert(compparms->numdlvls <= 32); + + /* Eliminate compiler warning about unused variables. */ + ms = 0; + cstate = 0; + + if (jpc_putuint8(out, compparms->numdlvls) || + jpc_putuint8(out, compparms->cblkwidthval) || + jpc_putuint8(out, compparms->cblkheightval) || + jpc_putuint8(out, compparms->cblksty) || + jpc_putuint8(out, compparms->qmfbid)) { + return -1; + } + if (prtflag) { + for (i = 0; i < compparms->numrlvls; ++i) { + if (jpc_putuint8(out, + ((compparms->rlvls[i].parheightval & 0xf) << 4) | + (compparms->rlvls[i].parwidthval & 0xf))) { + return -1; + } + } + } + return 0; +} + +/******************************************************************************\ +* RGN marker segment operations. +\******************************************************************************/ + +static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_rgn_t *rgn = &ms->parms.rgn; + uint_fast8_t tmp; + if (cstate->numcomps <= 256) { + if (jpc_getuint8(in, &tmp)) { + return -1; + } + rgn->compno = tmp; + } else { + if (jpc_getuint16(in, &rgn->compno)) { + return -1; + } + } + if (jpc_getuint8(in, &rgn->roisty) || + jpc_getuint8(in, &rgn->roishift)) { + return -1; + } + return 0; +} + +static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_rgn_t *rgn = &ms->parms.rgn; + if (cstate->numcomps <= 256) { + if (jpc_putuint8(out, rgn->compno)) { + return -1; + } + } else { + if (jpc_putuint16(out, rgn->compno)) { + return -1; + } + } + if (jpc_putuint8(out, rgn->roisty) || + jpc_putuint8(out, rgn->roishift)) { + return -1; + } + return 0; +} + +static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_rgn_t *rgn = &ms->parms.rgn; + fprintf(out, "compno = %d; roisty = %d; roishift = %d\n", + rgn->compno, rgn->roisty, rgn->roishift); + return 0; +} + +/******************************************************************************\ +* QCD marker segment operations. +\******************************************************************************/ + +static void jpc_qcd_destroyparms(jpc_ms_t *ms) +{ + jpc_qcd_t *qcd = &ms->parms.qcd; + jpc_qcx_destroycompparms(&qcd->compparms); +} + +static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms; + return jpc_qcx_getcompparms(compparms, cstate, in, ms->len); +} + +static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms; + return jpc_qcx_putcompparms(compparms, cstate, out); +} + +static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_qcd_t *qcd = &ms->parms.qcd; + int i; + fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n", + (int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes); + for (i = 0; i < qcd->compparms.numstepsizes; ++i) { + fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n", + i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]), + i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])); + } + return 0; +} + +/******************************************************************************\ +* QCC marker segment operations. +\******************************************************************************/ + +static void jpc_qcc_destroyparms(jpc_ms_t *ms) +{ + jpc_qcc_t *qcc = &ms->parms.qcc; + jpc_qcx_destroycompparms(&qcc->compparms); +} + +static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_qcc_t *qcc = &ms->parms.qcc; + uint_fast8_t tmp; + int len; + len = ms->len; + if (cstate->numcomps <= 256) { + jpc_getuint8(in, &tmp); + qcc->compno = tmp; + --len; + } else { + jpc_getuint16(in, &qcc->compno); + len -= 2; + } + if (jpc_qcx_getcompparms(&qcc->compparms, cstate, in, len)) { + return -1; + } + if (jas_stream_eof(in)) { + jpc_qcc_destroyparms(ms); + return -1; + } + return 0; +} + +static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_qcc_t *qcc = &ms->parms.qcc; + if (cstate->numcomps <= 256) { + jpc_putuint8(out, qcc->compno); + } else { + jpc_putuint16(out, qcc->compno); + } + if (jpc_qcx_putcompparms(&qcc->compparms, cstate, out)) { + return -1; + } + return 0; +} + +static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_qcc_t *qcc = &ms->parms.qcc; + int i; + fprintf(out, "compno = %d; qntsty = %d; numguard = %d; " + "numstepsizes = %d\n", qcc->compno, qcc->compparms.qntsty, qcc->compparms.numguard, + qcc->compparms.numstepsizes); + for (i = 0; i < qcc->compparms.numstepsizes; ++i) { + fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n", + i, (unsigned) JPC_QCX_GETEXPN(qcc->compparms.stepsizes[i]), + i, (unsigned) JPC_QCX_GETMANT(qcc->compparms.stepsizes[i])); + } + return 0; +} + +/******************************************************************************\ +* QCD/QCC marker segment helper functions. +\******************************************************************************/ + +static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms) +{ + if (compparms->stepsizes) { + jas_free(compparms->stepsizes); + } +} + +static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, + jas_stream_t *in, uint_fast16_t len) +{ + uint_fast8_t tmp; + int n; + int i; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + n = 0; + jpc_getuint8(in, &tmp); + ++n; + compparms->qntsty = tmp & 0x1f; + compparms->numguard = (tmp >> 5) & 7; + switch (compparms->qntsty) { + case JPC_QCX_SIQNT: + compparms->numstepsizes = 1; + break; + case JPC_QCX_NOQNT: + compparms->numstepsizes = (len - n); + break; + case JPC_QCX_SEQNT: + /* XXX - this is a hack */ + compparms->numstepsizes = (len - n) / 2; + break; + } +if (compparms->numstepsizes > 0) { + compparms->stepsizes = jas_malloc(compparms->numstepsizes * + sizeof(uint_fast32_t)); + assert(compparms->stepsizes); + for (i = 0; i < compparms->numstepsizes; ++i) { + if (compparms->qntsty == JPC_QCX_NOQNT) { + jpc_getuint8(in, &tmp); + compparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3); + } else { + jpc_getuint16(in, &compparms->stepsizes[i]); + } + } +} else { + compparms->stepsizes = 0; +} + if (jas_stream_error(in) || jas_stream_eof(in)) { + jpc_qcx_destroycompparms(compparms); + return -1; + } + return 0; +} + +static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, + jas_stream_t *out) +{ + int i; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + jpc_putuint8(out, ((compparms->numguard & 7) << 5) | compparms->qntsty); + for (i = 0; i < compparms->numstepsizes; ++i) { + if (compparms->qntsty == JPC_QCX_NOQNT) { + jpc_putuint8(out, JPC_QCX_GETEXPN( + compparms->stepsizes[i]) << 3); + } else { + jpc_putuint16(out, compparms->stepsizes[i]); + } + } + return 0; +} + +/******************************************************************************\ +* SOP marker segment operations. +\******************************************************************************/ + +static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_sop_t *sop = &ms->parms.sop; + + /* Eliminate compiler warning about unused variable. */ + cstate = 0; + + if (jpc_getuint16(in, &sop->seqno)) { + return -1; + } + return 0; +} + +static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_sop_t *sop = &ms->parms.sop; + + /* Eliminate compiler warning about unused variable. */ + cstate = 0; + + if (jpc_putuint16(out, sop->seqno)) { + return -1; + } + return 0; +} + +static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_sop_t *sop = &ms->parms.sop; + fprintf(out, "seqno = %d;\n", sop->seqno); + return 0; +} + +/******************************************************************************\ +* PPM marker segment operations. +\******************************************************************************/ + +static void jpc_ppm_destroyparms(jpc_ms_t *ms) +{ + jpc_ppm_t *ppm = &ms->parms.ppm; + if (ppm->data) { + jas_free(ppm->data); + } +} + +static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_ppm_t *ppm = &ms->parms.ppm; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + ppm->data = 0; + + if (ms->len < 1) { + goto error; + } + if (jpc_getuint8(in, &ppm->ind)) { + goto error; + } + + ppm->len = ms->len - 1; + if (ppm->len > 0) { + if (!(ppm->data = jas_malloc(ppm->len * sizeof(unsigned char)))) { + goto error; + } + if (JAS_CAST(uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) { + goto error; + } + } else { + ppm->data = 0; + } + return 0; + +error: + jpc_ppm_destroyparms(ms); + return -1; +} + +static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_ppm_t *ppm = &ms->parms.ppm; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) { + return -1; + } + return 0; +} + +static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_ppm_t *ppm = &ms->parms.ppm; + fprintf(out, "ind=%d; len = %d;\n", ppm->ind, ppm->len); + if (ppm->len > 0) { + fprintf(out, "data =\n"); + jas_memdump(out, ppm->data, ppm->len); + } + return 0; +} + +/******************************************************************************\ +* PPT marker segment operations. +\******************************************************************************/ + +static void jpc_ppt_destroyparms(jpc_ms_t *ms) +{ + jpc_ppt_t *ppt = &ms->parms.ppt; + if (ppt->data) { + jas_free(ppt->data); + } +} + +static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_ppt_t *ppt = &ms->parms.ppt; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + ppt->data = 0; + + if (ms->len < 1) { + goto error; + } + if (jpc_getuint8(in, &ppt->ind)) { + goto error; + } + ppt->len = ms->len - 1; + if (ppt->len > 0) { + if (!(ppt->data = jas_malloc(ppt->len * sizeof(unsigned char)))) { + goto error; + } + if (jas_stream_read(in, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) { + goto error; + } + } else { + ppt->data = 0; + } + return 0; + +error: + jpc_ppt_destroyparms(ms); + return -1; +} + +static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_ppt_t *ppt = &ms->parms.ppt; + + /* Eliminate compiler warning about unused variable. */ + cstate = 0; + + if (jpc_putuint8(out, ppt->ind)) { + return -1; + } + if (jas_stream_write(out, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) { + return -1; + } + return 0; +} + +static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_ppt_t *ppt = &ms->parms.ppt; + fprintf(out, "ind=%d; len = %d;\n", ppt->ind, ppt->len); + if (ppt->len > 0) { + fprintf(out, "data =\n"); + jas_memdump(out, ppt->data, ppt->len); + } + return 0; +} + +/******************************************************************************\ +* POC marker segment operations. +\******************************************************************************/ + +static void jpc_poc_destroyparms(jpc_ms_t *ms) +{ + jpc_poc_t *poc = &ms->parms.poc; + if (poc->pchgs) { + jas_free(poc->pchgs); + } +} + +static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_poc_t *poc = &ms->parms.poc; + jpc_pocpchg_t *pchg; + int pchgno; + uint_fast8_t tmp; + poc->numpchgs = (cstate->numcomps > 256) ? (ms->len / 9) : + (ms->len / 7); + if (!(poc->pchgs = jas_malloc(poc->numpchgs * sizeof(jpc_pocpchg_t)))) { + goto error; + } + for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno, + ++pchg) { + if (jpc_getuint8(in, &pchg->rlvlnostart)) { + goto error; + } + if (cstate->numcomps > 256) { + if (jpc_getuint16(in, &pchg->compnostart)) { + goto error; + } + } else { + if (jpc_getuint8(in, &tmp)) { + goto error; + }; + pchg->compnostart = tmp; + } + if (jpc_getuint16(in, &pchg->lyrnoend) || + jpc_getuint8(in, &pchg->rlvlnoend)) { + goto error; + } + if (cstate->numcomps > 256) { + if (jpc_getuint16(in, &pchg->compnoend)) { + goto error; + } + } else { + if (jpc_getuint8(in, &tmp)) { + goto error; + } + pchg->compnoend = tmp; + } + if (jpc_getuint8(in, &pchg->prgord)) { + goto error; + } + if (pchg->rlvlnostart > pchg->rlvlnoend || + pchg->compnostart > pchg->compnoend) { + goto error; + } + } + return 0; + +error: + jpc_poc_destroyparms(ms); + return -1; +} + +static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_poc_t *poc = &ms->parms.poc; + jpc_pocpchg_t *pchg; + int pchgno; + for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno, + ++pchg) { + if (jpc_putuint8(out, pchg->rlvlnostart) || + ((cstate->numcomps > 256) ? + jpc_putuint16(out, pchg->compnostart) : + jpc_putuint8(out, pchg->compnostart)) || + jpc_putuint16(out, pchg->lyrnoend) || + jpc_putuint8(out, pchg->rlvlnoend) || + ((cstate->numcomps > 256) ? + jpc_putuint16(out, pchg->compnoend) : + jpc_putuint8(out, pchg->compnoend)) || + jpc_putuint8(out, pchg->prgord)) { + return -1; + } + } + return 0; +} + +static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_poc_t *poc = &ms->parms.poc; + jpc_pocpchg_t *pchg; + int pchgno; + for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; + ++pchgno, ++pchg) { + fprintf(out, "po[%d] = %d; ", pchgno, pchg->prgord); + fprintf(out, "cs[%d] = %d; ce[%d] = %d; ", + pchgno, pchg->compnostart, pchgno, pchg->compnoend); + fprintf(out, "rs[%d] = %d; re[%d] = %d; ", + pchgno, pchg->rlvlnostart, pchgno, pchg->rlvlnoend); + fprintf(out, "le[%d] = %d\n", pchgno, pchg->lyrnoend); + } + return 0; +} + +/******************************************************************************\ +* CRG marker segment operations. +\******************************************************************************/ + +static void jpc_crg_destroyparms(jpc_ms_t *ms) +{ + jpc_crg_t *crg = &ms->parms.crg; + if (crg->comps) { + jas_free(crg->comps); + } +} + +static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_crg_t *crg = &ms->parms.crg; + jpc_crgcomp_t *comp; + uint_fast16_t compno; + crg->numcomps = cstate->numcomps; + if (!(crg->comps = jas_malloc(cstate->numcomps * sizeof(uint_fast16_t)))) { + return -1; + } + for (compno = 0, comp = crg->comps; compno < cstate->numcomps; + ++compno, ++comp) { + if (jpc_getuint16(in, &comp->hoff) || + jpc_getuint16(in, &comp->voff)) { + jpc_crg_destroyparms(ms); + return -1; + } + } + return 0; +} + +static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_crg_t *crg = &ms->parms.crg; + int compno; + jpc_crgcomp_t *comp; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno, + ++comp) { + if (jpc_putuint16(out, comp->hoff) || + jpc_putuint16(out, comp->voff)) { + return -1; + } + } + return 0; +} + +static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_crg_t *crg = &ms->parms.crg; + int compno; + jpc_crgcomp_t *comp; + for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno, + ++comp) { + fprintf(out, "hoff[%d] = %d; voff[%d] = %d\n", compno, + comp->hoff, compno, comp->voff); + } + return 0; +} + +/******************************************************************************\ +* Operations for COM marker segment. +\******************************************************************************/ + +static void jpc_com_destroyparms(jpc_ms_t *ms) +{ + jpc_com_t *com = &ms->parms.com; + if (com->data) { + jas_free(com->data); + } +} + +static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_com_t *com = &ms->parms.com; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (jpc_getuint16(in, &com->regid)) { + return -1; + } + com->len = ms->len - 2; + if (com->len > 0) { + if (!(com->data = jas_malloc(com->len))) { + return -1; + } + if (jas_stream_read(in, com->data, com->len) != JAS_CAST(int, com->len)) { + return -1; + } + } else { + com->data = 0; + } + return 0; +} + +static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + jpc_com_t *com = &ms->parms.com; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (jpc_putuint16(out, com->regid)) { + return -1; + } + if (jas_stream_write(out, com->data, com->len) != JAS_CAST(int, com->len)) { + return -1; + } + return 0; +} + +static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out) +{ + jpc_com_t *com = &ms->parms.com; + unsigned int i; + int printable; + fprintf(out, "regid = %d;\n", com->regid); + printable = 1; + for (i = 0; i < com->len; ++i) { + if (!isprint(com->data[i])) { + printable = 0; + break; + } + } + if (printable) { + fprintf(out, "data = "); + fwrite(com->data, sizeof(char), com->len, out); + fprintf(out, "\n"); + } + return 0; +} + +/******************************************************************************\ +* Operations for unknown types of marker segments. +\******************************************************************************/ + +static void jpc_unk_destroyparms(jpc_ms_t *ms) +{ + jpc_unk_t *unk = &ms->parms.unk; + if (unk->data) { + jas_free(unk->data); + } +} + +static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) +{ + jpc_unk_t *unk = &ms->parms.unk; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (ms->len > 0) { + if (!(unk->data = jas_malloc(ms->len * sizeof(unsigned char)))) { + return -1; + } + if (jas_stream_read(in, (char *) unk->data, ms->len) != JAS_CAST(int, ms->len)) { + jas_free(unk->data); + return -1; + } + unk->len = ms->len; + } else { + unk->data = 0; + unk->len = 0; + } + return 0; +} + +static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) +{ + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + ms = 0; + out = 0; + + /* If this function is called, we are trying to write an unsupported + type of marker segment. Return with an error indication. */ + return -1; +} + +static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out) +{ + unsigned int i; + jpc_unk_t *unk = &ms->parms.unk; + for (i = 0; i < unk->len; ++i) { + fprintf(out, "%02x ", unk->data[i]); + } + return 0; +} + +/******************************************************************************\ +* Primitive I/O operations. +\******************************************************************************/ + +int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val) +{ + int c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + if (val) { + *val = c; + } + return 0; +} + +int jpc_putuint8(jas_stream_t *out, uint_fast8_t val) +{ + if (jas_stream_putc(out, val & 0xff) == EOF) { + return -1; + } + return 0; +} + +int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val) +{ + uint_fast16_t v; + int c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + if (val) { + *val = v; + } + return 0; +} + +int jpc_putuint16(jas_stream_t *out, uint_fast16_t val) +{ + if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF || + jas_stream_putc(out, val & 0xff) == EOF) { + return -1; + } + return 0; +} + +int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val) +{ + uint_fast32_t v; + int c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | c; + if (val) { + *val = v; + } + return 0; +} + +int jpc_putuint32(jas_stream_t *out, uint_fast32_t val) +{ + if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF || + jas_stream_putc(out, (val >> 16) & 0xff) == EOF || + jas_stream_putc(out, (val >> 8) & 0xff) == EOF || + jas_stream_putc(out, val & 0xff) == EOF) { + return -1; + } + return 0; +} + +/******************************************************************************\ +* Miscellany +\******************************************************************************/ + +static jpc_mstabent_t *jpc_mstab_lookup(int id) +{ + jpc_mstabent_t *mstabent; + for (mstabent = jpc_mstab;; ++mstabent) { + if (mstabent->id == id || mstabent->id < 0) { + return mstabent; + } + } + assert(0); + return 0; +} + +int jpc_validate(jas_stream_t *in) +{ + int n; + int i; + unsigned char buf[2]; + + assert(JAS_STREAM_MAXPUTBACK >= 2); + + if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) { + return -1; + } + for (i = n - 1; i >= 0; --i) { + if (jas_stream_ungetc(in, buf[i]) == EOF) { + return -1; + } + } + if (n < 2) { + return -1; + } + if (buf[0] == (JPC_MS_SOC >> 8) && buf[1] == (JPC_MS_SOC & 0xff)) { + return 0; + } + return -1; +} + +int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long len) +{ + return jas_stream_copy(out, in, len); +} + +int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long len) +{ + return jas_stream_copy(out, in, len); +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cs.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cs.h new file mode 100644 index 0000000..b81ba0e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_cs.h @@ -0,0 +1,812 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * JPEG-2000 Code Stream Library + * + * $Id$ + */ + +#ifndef JPC_CS_H +#define JPC_CS_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_image.h" +#include "jasper/jas_stream.h" + +#include "jpc_cod.h" + +/******************************************************************************\ +* Constants and Types. +\******************************************************************************/ + +/* The maximum number of resolution levels. */ +#define JPC_MAXRLVLS 33 + +/* The maximum number of bands. */ +#define JPC_MAXBANDS (3 * JPC_MAXRLVLS + 1) + +/* The maximum number of layers. */ +#define JPC_MAXLYRS 16384 + +/**************************************\ +* Code stream. +\**************************************/ + +/* + * Code stream states. + */ + +/* Initial. */ +#define JPC_CS_INIT 0 +/* Main header. */ +#define JPC_CS_MHDR 1 +/* Tile-part header. */ +#define JPC_CS_THDR 2 +/* Main trailer. */ +#define JPC_CS_MTLR 3 +/* Tile-part data. */ +#define JPC_CS_TDATA 4 + +/* + * Unfortunately, the code stream syntax was not designed in such a way that + * any given marker segment can be correctly decoded without additional state + * derived from previously decoded marker segments. + * For example, a RGN/COC/QCC marker segment cannot be decoded unless the + * number of components is known. + */ + +/* + * Code stream state information. + */ + +typedef struct { + + /* The number of components. */ + uint_fast16_t numcomps; + +} jpc_cstate_t; + +/**************************************\ +* SOT marker segment parameters. +\**************************************/ + +typedef struct { + + /* The tile number. */ + uint_fast16_t tileno; + + /* The combined length of the marker segment and its auxilary data + (i.e., packet data). */ + uint_fast32_t len; + + /* The tile-part instance. */ + uint_fast8_t partno; + + /* The number of tile-parts. */ + uint_fast8_t numparts; + +} jpc_sot_t; + +/**************************************\ +* SIZ marker segment parameters. +\**************************************/ + +/* Per component information. */ + +typedef struct { + + /* The precision of the samples. */ + uint_fast8_t prec; + + /* The signedness of the samples. */ + uint_fast8_t sgnd; + + /* The horizontal separation of samples with respect to the reference + grid. */ + uint_fast8_t hsamp; + + /* The vertical separation of samples with respect to the reference + grid. */ + uint_fast8_t vsamp; + +} jpc_sizcomp_t; + +/* SIZ marker segment parameters. */ + +typedef struct { + + /* The code stream capabilities. */ + uint_fast16_t caps; + + /* The width of the image in units of the reference grid. */ + uint_fast32_t width; + + /* The height of the image in units of the reference grid. */ + uint_fast32_t height; + + /* The horizontal offset from the origin of the reference grid to the + left side of the image area. */ + uint_fast32_t xoff; + + /* The vertical offset from the origin of the reference grid to the + top side of the image area. */ + uint_fast32_t yoff; + + /* The nominal width of a tile in units of the reference grid. */ + uint_fast32_t tilewidth; + + /* The nominal height of a tile in units of the reference grid. */ + uint_fast32_t tileheight; + + /* The horizontal offset from the origin of the reference grid to the + left side of the first tile. */ + uint_fast32_t tilexoff; + + /* The vertical offset from the origin of the reference grid to the + top side of the first tile. */ + uint_fast32_t tileyoff; + + /* The number of components. */ + uint_fast16_t numcomps; + + /* The per-component information. */ + jpc_sizcomp_t *comps; + +} jpc_siz_t; + +/**************************************\ +* COD marker segment parameters. +\**************************************/ + +/* + * Coding style constants. + */ + +/* Precincts may be used. */ +#define JPC_COX_PRT 0x01 +/* SOP marker segments may be used. */ +#define JPC_COD_SOP 0x02 +/* EPH marker segments may be used. */ +#define JPC_COD_EPH 0x04 + +/* + * Progression order constants. + */ + +/* Layer-resolution-component-precinct progressive + (i.e., progressive by fidelity). */ +#define JPC_COD_LRCPPRG 0 +/* Resolution-layer-component-precinct progressive + (i.e., progressive by resolution). */ +#define JPC_COD_RLCPPRG 1 +/* Resolution-precinct-component-layer progressive. */ +#define JPC_COD_RPCLPRG 2 +/* Precinct-component-resolution-layer progressive. */ +#define JPC_COD_PCRLPRG 3 +/* Component-position-resolution-layer progressive. */ +#define JPC_COD_CPRLPRG 4 + +/* + * Code block style constants. + */ + +#define JPC_COX_LAZY 0x01 /* Selective arithmetic coding bypass. */ +#define JPC_COX_RESET 0x02 /* Reset context probabilities. */ +#define JPC_COX_TERMALL 0x04 /* Terminate all coding passes. */ +#define JPC_COX_VSC 0x08 /* Vertical stripe causal context formation. */ +#define JPC_COX_PTERM 0x10 /* Predictable termination. */ +#define JPC_COX_SEGSYM 0x20 /* Use segmentation symbols. */ + +/* Transform constants. */ +#define JPC_COX_INS 0x00 /* Irreversible 9/7. */ +#define JPC_COX_RFT 0x01 /* Reversible 5/3. */ + +/* Multicomponent transform constants. */ +#define JPC_COD_NOMCT 0x00 /* No multicomponent transform. */ +#define JPC_COD_MCT 0x01 /* Multicomponent transform. */ + +/* Get the code block size value from the code block size exponent. */ +#define JPC_COX_CBLKSIZEEXPN(x) ((x) - 2) +/* Get the code block size exponent from the code block size value. */ +#define JPC_COX_GETCBLKSIZEEXPN(x) ((x) + 2) + +/* Per resolution-level information. */ + +typedef struct { + + /* The packet partition width. */ + uint_fast8_t parwidthval; + + /* The packet partition height. */ + uint_fast8_t parheightval; + +} jpc_coxrlvl_t; + +/* Per component information. */ + +typedef struct { + + /* The coding style. */ + uint_fast8_t csty; + + /* The number of decomposition levels. */ + uint_fast8_t numdlvls; + + /* The nominal code block width specifier. */ + uint_fast8_t cblkwidthval; + + /* The nominal code block height specifier. */ + uint_fast8_t cblkheightval; + + /* The style of coding passes. */ + uint_fast8_t cblksty; + + /* The QMFB employed. */ + uint_fast8_t qmfbid; + + /* The number of resolution levels. */ + int numrlvls; + + /* The per-resolution-level information. */ + jpc_coxrlvl_t rlvls[JPC_MAXRLVLS]; + +} jpc_coxcp_t; + +/* COD marker segment parameters. */ + +typedef struct { + + /* The general coding style. */ + uint_fast8_t csty; + + /* The progression order. */ + uint_fast8_t prg; + + /* The number of layers. */ + uint_fast16_t numlyrs; + + /* The multicomponent transform. */ + uint_fast8_t mctrans; + + /* Component-related parameters. */ + jpc_coxcp_t compparms; + +} jpc_cod_t; + +/* COC marker segment parameters. */ + +typedef struct { + + /* The component number. */ + uint_fast16_t compno; + + /* Component-related parameters. */ + jpc_coxcp_t compparms; + +} jpc_coc_t; + +/**************************************\ +* RGN marker segment parameters. +\**************************************/ + +/* The maxshift ROI style. */ +#define JPC_RGN_MAXSHIFT 0x00 + +typedef struct { + + /* The component to which the marker applies. */ + uint_fast16_t compno; + + /* The ROI style. */ + uint_fast8_t roisty; + + /* The ROI shift value. */ + uint_fast8_t roishift; + +} jpc_rgn_t; + +/**************************************\ +* QCD/QCC marker segment parameters. +\**************************************/ + +/* + * Quantization style constants. + */ + +#define JPC_QCX_NOQNT 0 /* No quantization. */ +#define JPC_QCX_SIQNT 1 /* Scalar quantization, implicit. */ +#define JPC_QCX_SEQNT 2 /* Scalar quantization, explicit. */ + +/* + * Stepsize manipulation macros. + */ + +#define JPC_QCX_GETEXPN(x) ((x) >> 11) +#define JPC_QCX_GETMANT(x) ((x) & 0x07ff) +#define JPC_QCX_EXPN(x) (assert(!((x) & (~0x1f))), (((x) & 0x1f) << 11)) +#define JPC_QCX_MANT(x) (assert(!((x) & (~0x7ff))), ((x) & 0x7ff)) + +/* Per component information. */ + +typedef struct { + + /* The quantization style. */ + uint_fast8_t qntsty; + + /* The number of step sizes. */ + int numstepsizes; + + /* The step sizes. */ + uint_fast16_t *stepsizes; + + /* The number of guard bits. */ + uint_fast8_t numguard; + +} jpc_qcxcp_t; + +/* QCC marker segment parameters. */ + +typedef struct { + + /* The component associated with this marker segment. */ + uint_fast16_t compno; + + /* The parameters. */ + jpc_qcxcp_t compparms; + +} jpc_qcc_t; + +/* QCD marker segment parameters. */ + +typedef struct { + + /* The parameters. */ + jpc_qcxcp_t compparms; + +} jpc_qcd_t; + +/**************************************\ +* POD marker segment parameters. +\**************************************/ + +typedef struct { + + /* The progression order. */ + uint_fast8_t prgord; + + /* The lower bound (inclusive) on the resolution level for the + progression order volume. */ + uint_fast8_t rlvlnostart; + + /* The upper bound (exclusive) on the resolution level for the + progression order volume. */ + uint_fast8_t rlvlnoend; + + /* The lower bound (inclusive) on the component for the progression + order volume. */ + uint_fast16_t compnostart; + + /* The upper bound (exclusive) on the component for the progression + order volume. */ + uint_fast16_t compnoend; + + /* The upper bound (exclusive) on the layer for the progression + order volume. */ + uint_fast16_t lyrnoend; + +} jpc_pocpchg_t; + +/* An alias for the above type. */ +typedef jpc_pocpchg_t jpc_pchg_t; + +/* POC marker segment parameters. */ + +typedef struct { + + /* The number of progression order changes. */ + int numpchgs; + + /* The per-progression-order-change information. */ + jpc_pocpchg_t *pchgs; + +} jpc_poc_t; + +/**************************************\ +* PPM/PPT marker segment parameters. +\**************************************/ + +/* PPM marker segment parameters. */ + +typedef struct { + + /* The index. */ + uint_fast8_t ind; + + /* The length. */ + uint_fast16_t len; + + /* The data. */ + uchar *data; + +} jpc_ppm_t; + +/* PPT marker segment parameters. */ + +typedef struct { + + /* The index. */ + uint_fast8_t ind; + + /* The length. */ + uint_fast32_t len; + + /* The data. */ + unsigned char *data; + +} jpc_ppt_t; + +/**************************************\ +* COM marker segment parameters. +\**************************************/ + +/* + * Registration IDs. + */ + +#define JPC_COM_BIN 0x00 +#define JPC_COM_LATIN 0x01 + +typedef struct { + + /* The registration ID. */ + uint_fast16_t regid; + + /* The length of the data in bytes. */ + uint_fast16_t len; + + /* The data. */ + uchar *data; + +} jpc_com_t; + +/**************************************\ +* SOP marker segment parameters. +\**************************************/ + +typedef struct { + + /* The sequence number. */ + uint_fast16_t seqno; + +} jpc_sop_t; + +/**************************************\ +* CRG marker segment parameters. +\**************************************/ + +/* Per component information. */ + +typedef struct { + + /* The horizontal offset. */ + uint_fast16_t hoff; + + /* The vertical offset. */ + uint_fast16_t voff; + +} jpc_crgcomp_t; + +typedef struct { + + /* The number of components. */ + int numcomps; + + /* Per component information. */ + jpc_crgcomp_t *comps; + +} jpc_crg_t; + +/**************************************\ +* Marker segment parameters for unknown marker type. +\**************************************/ + +typedef struct { + + /* The data. */ + uchar *data; + + /* The length. */ + uint_fast16_t len; + +} jpc_unk_t; + +/**************************************\ +* Generic marker segment parameters. +\**************************************/ + +typedef union { + int soc; /* unused */ + jpc_sot_t sot; + int sod; /* unused */ + int eoc; /* unused */ + jpc_siz_t siz; + jpc_cod_t cod; + jpc_coc_t coc; + jpc_rgn_t rgn; + jpc_qcd_t qcd; + jpc_qcc_t qcc; + jpc_poc_t poc; + /* jpc_plm_t plm; */ + /* jpc_plt_t plt; */ + jpc_ppm_t ppm; + jpc_ppt_t ppt; + jpc_sop_t sop; + int eph; /* unused */ + jpc_com_t com; + jpc_crg_t crg; + jpc_unk_t unk; +} jpc_msparms_t; + +/**************************************\ +* Marker segment. +\**************************************/ + +/* Marker segment IDs. */ + +/* The smallest valid marker value. */ +#define JPC_MS_MIN 0xff00 + +/* The largest valid marker value. */ +#define JPC_MS_MAX 0xffff + +/* The minimum marker value that cannot occur within packet data. */ +#define JPC_MS_INMIN 0xff80 +/* The maximum marker value that cannot occur within packet data. */ +#define JPC_MS_INMAX 0xffff + +/* Delimiting marker segments. */ +#define JPC_MS_SOC 0xff4f /* Start of code stream (SOC). */ +#define JPC_MS_SOT 0xff90 /* Start of tile-part (SOT). */ +#define JPC_MS_SOD 0xff93 /* Start of data (SOD). */ +#define JPC_MS_EOC 0xffd9 /* End of code stream (EOC). */ + +/* Fixed information marker segments. */ +#define JPC_MS_SIZ 0xff51 /* Image and tile size (SIZ). */ + +/* Functional marker segments. */ +#define JPC_MS_COD 0xff52 /* Coding style default (COD). */ +#define JPC_MS_COC 0xff53 /* Coding style component (COC). */ +#define JPC_MS_RGN 0xff5e /* Region of interest (RGN). */ +#define JPC_MS_QCD 0xff5c /* Quantization default (QCD). */ +#define JPC_MS_QCC 0xff5d /* Quantization component (QCC). */ +#define JPC_MS_POC 0xff5f /* Progression order default (POC). */ + +/* Pointer marker segments. */ +#define JPC_MS_TLM 0xff55 /* Tile-part lengths, main header (TLM). */ +#define JPC_MS_PLM 0xff57 /* Packet length, main header (PLM). */ +#define JPC_MS_PLT 0xff58 /* Packet length, tile-part header (PLT). */ +#define JPC_MS_PPM 0xff60 /* Packed packet headers, main header (PPM). */ +#define JPC_MS_PPT 0xff61 /* Packet packet headers, tile-part header (PPT). */ + +/* In bit stream marker segments. */ +#define JPC_MS_SOP 0xff91 /* Start of packet (SOP). */ +#define JPC_MS_EPH 0xff92 /* End of packet header (EPH). */ + +/* Informational marker segments. */ +#define JPC_MS_CRG 0xff63 /* Component registration (CRG). */ +#define JPC_MS_COM 0xff64 /* Comment (COM). */ + +/* Forward declaration. */ +struct jpc_msops_s; + +/* Generic marker segment class. */ + +typedef struct { + + /* The type of marker segment. */ + uint_fast16_t id; + + /* The length of the marker segment. */ + uint_fast16_t len; + + /* The starting offset within the stream. */ + uint_fast32_t off; + + /* The parameters of the marker segment. */ + jpc_msparms_t parms; + + /* The marker segment operations. */ + struct jpc_msops_s *ops; + +} jpc_ms_t; + +/* Marker segment operations (which depend on the marker segment type). */ + +typedef struct jpc_msops_s { + + /* Destroy the marker segment parameters. */ + void (*destroyparms)(jpc_ms_t *ms); + + /* Get the marker segment parameters from a stream. */ + int (*getparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); + + /* Put the marker segment parameters to a stream. */ + int (*putparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); + + /* Dump the marker segment parameters (for debugging). */ + int (*dumpparms)(jpc_ms_t *ms, FILE *out); + +} jpc_msops_t; + +/******************************************************************************\ +* Macros/Functions. +\******************************************************************************/ + +/* Create a code-stream state object. */ +jpc_cstate_t *jpc_cstate_create(void); + +/* Destroy a code-stream state object. */ +void jpc_cstate_destroy(jpc_cstate_t *cstate); + +/* Create a marker segment. */ +jpc_ms_t *jpc_ms_create(int type); + +/* Destroy a marker segment. */ +void jpc_ms_destroy(jpc_ms_t *ms); + +/* Does a marker segment have parameters? */ +#define JPC_MS_HASPARMS(x) \ + (!((x) == JPC_MS_SOC || (x) == JPC_MS_SOD || (x) == JPC_MS_EOC || \ + (x) == JPC_MS_EPH || ((x) >= 0xff30 && (x) <= 0xff3f))) + +/* Get the marker segment type. */ +#define jpc_ms_gettype(ms) \ + ((ms)->id) + +/* Read a marker segment from a stream. */ +jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate); + +/* Write a marker segment to a stream. */ +int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms); + +/* Copy code stream data from one stream to another. */ +int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long n); + +/* Copy code stream data from one stream to another. */ +int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long n); + +/* Dump a marker segment (for debugging). */ +void jpc_ms_dump(jpc_ms_t *ms, FILE *out); + +/* Read a 8-bit unsigned integer from a stream. */ +int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val); + +/* Read a 16-bit unsigned integer from a stream. */ +int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val); + +/* Read a 32-bit unsigned integer from a stream. */ +int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val); + +/* Write a 8-bit unsigned integer to a stream. */ +int jpc_putuint8(jas_stream_t *out, uint_fast8_t val); + +/* Write a 16-bit unsigned integer to a stream. */ +int jpc_putuint16(jas_stream_t *out, uint_fast16_t val); + +/* Write a 32-bit unsigned integer to a stream. */ +int jpc_putuint32(jas_stream_t *out, uint_fast32_t val); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_dec.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_dec.c new file mode 100644 index 0000000..b096688 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_dec.c @@ -0,0 +1,2361 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_math.h" +#include "jasper/jas_tvp.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_debug.h" + +#include "jpc_fix.h" +#include "jpc_dec.h" +#include "jpc_cs.h" +#include "jpc_mct.h" +#include "jpc_t2dec.h" +#include "jpc_t1dec.h" +#include "jpc_math.h" + +/******************************************************************************\ +* +\******************************************************************************/ + +#define JPC_MHSOC 0x0001 + /* In the main header, expecting a SOC marker segment. */ +#define JPC_MHSIZ 0x0002 + /* In the main header, expecting a SIZ marker segment. */ +#define JPC_MH 0x0004 + /* In the main header, expecting "other" marker segments. */ +#define JPC_TPHSOT 0x0008 + /* In a tile-part header, expecting a SOT marker segment. */ +#define JPC_TPH 0x0010 + /* In a tile-part header, expecting "other" marker segments. */ +#define JPC_MT 0x0020 + /* In the main trailer. */ + +typedef struct { + + uint_fast16_t id; + /* The marker segment type. */ + + int validstates; + /* The states in which this type of marker segment can be + validly encountered. */ + + int (*action)(jpc_dec_t *dec, jpc_ms_t *ms); + /* The action to take upon encountering this type of marker segment. */ + +} jpc_dec_mstabent_t; + +/******************************************************************************\ +* +\******************************************************************************/ + +/* COD/COC parameters have been specified. */ +#define JPC_CSET 0x0001 +/* QCD/QCC parameters have been specified. */ +#define JPC_QSET 0x0002 +/* COD/COC parameters set from a COC marker segment. */ +#define JPC_COC 0x0004 +/* QCD/QCC parameters set from a QCC marker segment. */ +#define JPC_QCC 0x0008 + +/******************************************************************************\ +* Local function prototypes. +\******************************************************************************/ + +static int jpc_dec_dump(jpc_dec_t *dec, FILE *out); + +jpc_ppxstab_t *jpc_ppxstab_create(void); +void jpc_ppxstab_destroy(jpc_ppxstab_t *tab); +int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents); +int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent); +jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab); +int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab); +jpc_ppxstabent_t *jpc_ppxstabent_create(void); +void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent); + +int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist); +jpc_streamlist_t *jpc_streamlist_create(void); +int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno, + jas_stream_t *stream); +jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno); +void jpc_streamlist_destroy(jpc_streamlist_t *streamlist); +jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno); + +static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp); +static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps); +static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp); +static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp); +static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod); +static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc); +static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, + jpc_coxcp_t *compparms, int flags); +static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd); +static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc); +static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, + jpc_qcxcp_t *compparms, int flags); +static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn); +static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp); +static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp); +static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset); +static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc); + +static int jpc_dec_decode(jpc_dec_t *dec); +static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in); +static void jpc_dec_destroy(jpc_dec_t *dec); +static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize); +static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps); +static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits); +static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile); +static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile); +static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile); +static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms); +static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts); + +static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id); + +/******************************************************************************\ +* Global data. +\******************************************************************************/ + +jpc_dec_mstabent_t jpc_dec_mstab[] = { + {JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc}, + {JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot}, + {JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod}, + {JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc}, + {JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz}, + {JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod}, + {JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc}, + {JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn}, + {JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd}, + {JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc}, + {JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc}, + {JPC_MS_TLM, JPC_MH, 0}, + {JPC_MS_PLM, JPC_MH, 0}, + {JPC_MS_PLT, JPC_TPH, 0}, + {JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm}, + {JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt}, + {JPC_MS_SOP, 0, 0}, + {JPC_MS_CRG, JPC_MH, jpc_dec_process_crg}, + {JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com}, + {0, JPC_MH | JPC_TPH, jpc_dec_process_unk} +}; + +/******************************************************************************\ +* The main entry point for the JPEG-2000 decoder. +\******************************************************************************/ + +jas_image_t *jpc_decode(jas_stream_t *in, char *optstr) +{ + jpc_dec_importopts_t opts; + jpc_dec_t *dec; + jas_image_t *image; + + dec = 0; + + if (jpc_dec_parseopts(optstr, &opts)) { + goto error; + } + + jpc_initluts(); + + if (!(dec = jpc_dec_create(&opts, in))) { + goto error; + } + + /* Do most of the work. */ + if (jpc_dec_decode(dec)) { + goto error; + } + + if (jas_image_numcmpts(dec->image) >= 3) { + jas_image_setclrspc(dec->image, JAS_CLRSPC_SRGB); + jas_image_setcmpttype(dec->image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); + jas_image_setcmpttype(dec->image, 1, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); + jas_image_setcmpttype(dec->image, 2, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); + } else { + jas_image_setclrspc(dec->image, JAS_CLRSPC_SGRAY); + jas_image_setcmpttype(dec->image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); + } + + /* Save the return value. */ + image = dec->image; + + /* Stop the image from being discarded. */ + dec->image = 0; + + /* Destroy decoder. */ + jpc_dec_destroy(dec); + + return image; + +error: + if (dec) { + jpc_dec_destroy(dec); + } + return 0; +} + +typedef enum { + OPT_MAXLYRS, + OPT_MAXPKTS, + OPT_DEBUG +} optid_t; + +jas_taginfo_t decopts[] = { + {OPT_MAXLYRS, "maxlyrs"}, + {OPT_MAXPKTS, "maxpkts"}, + {OPT_DEBUG, "debug"}, + {-1, 0} +}; + +static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts) +{ + jas_tvparser_t *tvp; + + opts->debug = 0; + opts->maxlyrs = JPC_MAXLYRS; + opts->maxpkts = -1; + + if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { + return -1; + } + + while (!jas_tvparser_next(tvp)) { + switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts, + jas_tvparser_gettag(tvp)))->id) { + case OPT_MAXLYRS: + opts->maxlyrs = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_DEBUG: + opts->debug = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_MAXPKTS: + opts->maxpkts = atoi(jas_tvparser_getval(tvp)); + break; + default: + fprintf(stderr, "warning: ignoring invalid option %s\n", + jas_tvparser_gettag(tvp)); + break; + } + } + + jas_tvparser_destroy(tvp); + + return 0; +} + +/******************************************************************************\ +* Code for table-driven code stream decoder. +\******************************************************************************/ + +static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id) +{ + jpc_dec_mstabent_t *mstabent; + for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) { + if (mstabent->id == id) { + break; + } + } + return mstabent; +} + +static int jpc_dec_decode(jpc_dec_t *dec) +{ + jpc_ms_t *ms; + jpc_dec_mstabent_t *mstabent; + int ret; + jpc_cstate_t *cstate; + + if (!(cstate = jpc_cstate_create())) { + return -1; + } + dec->cstate = cstate; + + /* Initially, we should expect to encounter a SOC marker segment. */ + dec->state = JPC_MHSOC; + + for (;;) { + + /* Get the next marker segment in the code stream. */ + if (!(ms = jpc_getms(dec->in, cstate))) { + fprintf(stderr, "cannot get marker segment\n"); + return -1; + } + + mstabent = jpc_dec_mstab_lookup(ms->id); + assert(mstabent); + + /* Ensure that this type of marker segment is permitted + at this point in the code stream. */ + if (!(dec->state & mstabent->validstates)) { + fprintf(stderr, "unexpected marker segment type\n"); + jpc_ms_destroy(ms); + return -1; + } + + /* Process the marker segment. */ + if (mstabent->action) { + ret = (*mstabent->action)(dec, ms); + } else { + /* No explicit action is required. */ + ret = 0; + } + + /* Destroy the marker segment. */ + jpc_ms_destroy(ms); + + if (ret < 0) { + return -1; + } else if (ret > 0) { + break; + } + + } + + return 0; +} + +static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms) +{ + int cmptno; + jpc_dec_cmpt_t *cmpt; + jpc_crg_t *crg; + + crg = &ms->parms.crg; + for (cmptno = 0, cmpt = dec->cmpts; cmptno < dec->numcomps; ++cmptno, + ++cmpt) { + /* Ignore the information in the CRG marker segment for now. + This information serves no useful purpose for decoding anyhow. + Some other parts of the code need to be changed if these lines + are uncommented. + cmpt->hsubstep = crg->comps[cmptno].hoff; + cmpt->vsubstep = crg->comps[cmptno].voff; + */ + } + return 0; +} + +static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms) +{ + /* Eliminate warnings about unused variables. */ + ms = 0; + + /* We should expect to encounter a SIZ marker segment next. */ + dec->state = JPC_MHSIZ; + + return 0; +} + +static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_dec_tile_t *tile; + jpc_sot_t *sot = &ms->parms.sot; + jas_image_cmptparm_t *compinfos; + jas_image_cmptparm_t *compinfo; + jpc_dec_cmpt_t *cmpt; + int cmptno; + + if (dec->state == JPC_MH) { + + compinfos = jas_malloc(dec->numcomps * sizeof(jas_image_cmptparm_t)); + assert(compinfos); + for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos; + cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) { + compinfo->tlx = 0; + compinfo->tly = 0; + compinfo->prec = cmpt->prec; + compinfo->sgnd = cmpt->sgnd; + compinfo->width = cmpt->width; + compinfo->height = cmpt->height; + compinfo->hstep = cmpt->hstep; + compinfo->vstep = cmpt->vstep; + } + + if (!(dec->image = jas_image_create(dec->numcomps, compinfos, + JAS_CLRSPC_UNKNOWN))) { + return -1; + } + jas_free(compinfos); + + /* Is the packet header information stored in PPM marker segments in + the main header? */ + if (dec->ppmstab) { + /* Convert the PPM marker segment data into a collection of streams + (one stream per tile-part). */ + if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) { + abort(); + } + jpc_ppxstab_destroy(dec->ppmstab); + dec->ppmstab = 0; + } + } + + if (sot->len > 0) { + dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len - + 4 + sot->len; + } else { + dec->curtileendoff = 0; + } + + if (JAS_CAST(int, sot->tileno) > dec->numtiles) { + fprintf(stderr, "invalid tile number in SOT marker segment\n"); + return -1; + } + /* Set the current tile. */ + dec->curtile = &dec->tiles[sot->tileno]; + tile = dec->curtile; + /* Ensure that this is the expected part number. */ + if (sot->partno != tile->partno) { + return -1; + } + if (tile->numparts > 0 && sot->partno >= tile->numparts) { + return -1; + } + if (!tile->numparts && sot->numparts > 0) { + tile->numparts = sot->numparts; + } + + tile->pptstab = 0; + + switch (tile->state) { + case JPC_TILE_INIT: + /* This is the first tile-part for this tile. */ + tile->state = JPC_TILE_ACTIVE; + assert(!tile->cp); + if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) { + return -1; + } + jpc_dec_cp_resetflags(dec->cp); + break; + default: + if (sot->numparts == sot->partno - 1) { + tile->state = JPC_TILE_ACTIVELAST; + } + break; + } + + /* Note: We do not increment the expected tile-part number until + all processing for this tile-part is complete. */ + + /* We should expect to encounter other tile-part header marker + segments next. */ + dec->state = JPC_TPH; + + return 0; +} + +static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_dec_tile_t *tile; + int pos; + + /* Eliminate compiler warnings about unused variables. */ + ms = 0; + + if (!(tile = dec->curtile)) { + return -1; + } + + if (!tile->partno) { + if (!jpc_dec_cp_isvalid(tile->cp)) { + return -1; + } + jpc_dec_cp_prepare(tile->cp); + if (jpc_dec_tileinit(dec, tile)) { + return -1; + } + } + + /* Are packet headers stored in the main header or tile-part header? */ + if (dec->pkthdrstreams) { + /* Get the stream containing the packet header data for this + tile-part. */ + if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) { + return -1; + } + } + + if (tile->pptstab) { + if (!tile->pkthdrstream) { + if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) { + return -1; + } + } + pos = jas_stream_tell(tile->pkthdrstream); + jas_stream_seek(tile->pkthdrstream, 0, SEEK_END); + if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) { + return -1; + } + jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET); + jpc_ppxstab_destroy(tile->pptstab); + tile->pptstab = 0; + } + + if (jas_getdbglevel() >= 10) { + jpc_dec_dump(dec, stderr); + } + + if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream : + dec->in, dec->in)) { + fprintf(stderr, "jpc_dec_decodepkts failed\n"); + return -1; + } + + /* Gobble any unconsumed tile data. */ + if (dec->curtileendoff > 0) { + long curoff; + uint_fast32_t n; + curoff = jas_stream_getrwcount(dec->in); + if (curoff < dec->curtileendoff) { + n = dec->curtileendoff - curoff; + fprintf(stderr, + "warning: ignoring trailing garbage (%lu bytes)\n", + (unsigned long) n); + + while (n-- > 0) { + if (jas_stream_getc(dec->in) == EOF) { + fprintf(stderr, "read error\n"); + return -1; + } + } + } else if (curoff > dec->curtileendoff) { + fprintf(stderr, + "warning: not enough tile data (%lu bytes)\n", + (unsigned long) curoff - dec->curtileendoff); + } + + } + + if (tile->numparts > 0 && tile->partno == tile->numparts - 1) { + if (jpc_dec_tiledecode(dec, tile)) { + return -1; + } + jpc_dec_tilefini(dec, tile); + } + + dec->curtile = 0; + + /* Increment the expected tile-part number. */ + ++tile->partno; + + /* We should expect to encounter a SOT marker segment next. */ + dec->state = JPC_TPHSOT; + + return 0; +} + +static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + jpc_dec_tcomp_t *tcomp; + int compno; + int rlvlno; + jpc_dec_rlvl_t *rlvl; + jpc_dec_band_t *band; + jpc_dec_prc_t *prc; + int bndno; + jpc_tsfb_band_t *bnd; + int bandno; + jpc_dec_ccp_t *ccp; + int prccnt; + jpc_dec_cblk_t *cblk; + int cblkcnt; + uint_fast32_t tlprcxstart; + uint_fast32_t tlprcystart; + uint_fast32_t brprcxend; + uint_fast32_t brprcyend; + uint_fast32_t tlcbgxstart; + uint_fast32_t tlcbgystart; + uint_fast32_t brcbgxend; + uint_fast32_t brcbgyend; + uint_fast32_t cbgxstart; + uint_fast32_t cbgystart; + uint_fast32_t cbgxend; + uint_fast32_t cbgyend; + uint_fast32_t tlcblkxstart; + uint_fast32_t tlcblkystart; + uint_fast32_t brcblkxend; + uint_fast32_t brcblkyend; + uint_fast32_t cblkxstart; + uint_fast32_t cblkystart; + uint_fast32_t cblkxend; + uint_fast32_t cblkyend; + uint_fast32_t tmpxstart; + uint_fast32_t tmpystart; + uint_fast32_t tmpxend; + uint_fast32_t tmpyend; + jpc_dec_cp_t *cp; + jpc_tsfb_band_t bnds[64]; + jpc_pchg_t *pchg; + int pchgno; + jpc_dec_cmpt_t *cmpt; + + cp = tile->cp; + tile->realmode = 0; + if (cp->mctid == JPC_MCT_ICT) { + tile->realmode = 1; + } + + for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < + dec->numcomps; ++compno, ++tcomp, ++cmpt) { + ccp = &tile->cp->ccps[compno]; + if (ccp->qmfbid == JPC_COX_INS) { + tile->realmode = 1; + } + tcomp->numrlvls = ccp->numrlvls; + if (!(tcomp->rlvls = jas_malloc(tcomp->numrlvls * + sizeof(jpc_dec_rlvl_t)))) { + return -1; + } + if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart, + cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep), + JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend, + cmpt->vstep)))) { + return -1; + } + if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid, + tcomp->numrlvls - 1))) { + return -1; + } +{ + jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), jas_seq2d_yend(tcomp->data), bnds); +} + for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; + ++rlvlno, ++rlvl) { +rlvl->bands = 0; + rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart, + tcomp->numrlvls - 1 - rlvlno); + rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart, + tcomp->numrlvls - 1 - rlvlno); + rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend, + tcomp->numrlvls - 1 - rlvlno); + rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend, + tcomp->numrlvls - 1 - rlvlno); + rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno]; + rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno]; + tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart, + rlvl->prcwidthexpn) << rlvl->prcwidthexpn; + tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart, + rlvl->prcheightexpn) << rlvl->prcheightexpn; + brprcxend = JPC_CEILDIVPOW2(rlvl->xend, + rlvl->prcwidthexpn) << rlvl->prcwidthexpn; + brprcyend = JPC_CEILDIVPOW2(rlvl->yend, + rlvl->prcheightexpn) << rlvl->prcheightexpn; + rlvl->numhprcs = (brprcxend - tlprcxstart) >> + rlvl->prcwidthexpn; + rlvl->numvprcs = (brprcyend - tlprcystart) >> + rlvl->prcheightexpn; + rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; + + if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) { + rlvl->bands = 0; + rlvl->numprcs = 0; + rlvl->numhprcs = 0; + rlvl->numvprcs = 0; + continue; + } + if (!rlvlno) { + tlcbgxstart = tlprcxstart; + tlcbgystart = tlprcystart; + brcbgxend = brprcxend; + brcbgyend = brprcyend; + rlvl->cbgwidthexpn = rlvl->prcwidthexpn; + rlvl->cbgheightexpn = rlvl->prcheightexpn; + } else { + tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1); + tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1); + brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1); + brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1); + rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; + rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; + } + rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn, + rlvl->cbgwidthexpn); + rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn, + rlvl->cbgheightexpn); + + rlvl->numbands = (!rlvlno) ? 1 : 3; + if (!(rlvl->bands = jas_malloc(rlvl->numbands * + sizeof(jpc_dec_band_t)))) { + return -1; + } + for (bandno = 0, band = rlvl->bands; + bandno < rlvl->numbands; ++bandno, ++band) { + bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + + bandno + 1); + bnd = &bnds[bndno]; + + band->orient = bnd->orient; + band->stepsize = ccp->stepsizes[bndno]; + band->analgain = JPC_NOMINALGAIN(ccp->qmfbid, + tcomp->numrlvls - 1, rlvlno, band->orient); + band->absstepsize = jpc_calcabsstepsize(band->stepsize, + cmpt->prec + band->analgain); + band->numbps = ccp->numguardbits + + JPC_QCX_GETEXPN(band->stepsize) - 1; + band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ? + (JPC_PREC - 1 - band->numbps) : ccp->roishift; + band->data = 0; + band->prcs = 0; + if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) { + continue; + } + if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { + return -1; + } + jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, bnd->locystart, bnd->locxend, bnd->locyend); + jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart); + + assert(rlvl->numprcs); + + if (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_dec_prc_t)))) { + return -1; + } + +/************************************************/ + cbgxstart = tlcbgxstart; + cbgystart = tlcbgystart; + for (prccnt = rlvl->numprcs, prc = band->prcs; + prccnt > 0; --prccnt, ++prc) { + cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn); + cbgyend = cbgystart + (1 << rlvl->cbgheightexpn); + prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, jas_seq2d_xstart(band->data))); + prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, jas_seq2d_ystart(band->data))); + prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, jas_seq2d_xend(band->data))); + prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, jas_seq2d_yend(band->data))); + if (prc->xend > prc->xstart && prc->yend > prc->ystart) { + tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart, + rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; + tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart, + rlvl->cblkheightexpn) << rlvl->cblkheightexpn; + brcblkxend = JPC_CEILDIVPOW2(prc->xend, + rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; + brcblkyend = JPC_CEILDIVPOW2(prc->yend, + rlvl->cblkheightexpn) << rlvl->cblkheightexpn; + prc->numhcblks = (brcblkxend - tlcblkxstart) >> + rlvl->cblkwidthexpn; + prc->numvcblks = (brcblkyend - tlcblkystart) >> + rlvl->cblkheightexpn; + prc->numcblks = prc->numhcblks * prc->numvcblks; + assert(prc->numcblks > 0); + + if (!(prc->incltagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { + return -1; + } + if (!(prc->numimsbstagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { + return -1; + } + if (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_dec_cblk_t)))) { + return -1; + } + + cblkxstart = cbgxstart; + cblkystart = cbgystart; + for (cblkcnt = prc->numcblks, cblk = prc->cblks; cblkcnt > 0;) { + cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn); + cblkyend = cblkystart + (1 << rlvl->cblkheightexpn); + tmpxstart = JAS_MAX(cblkxstart, prc->xstart); + tmpystart = JAS_MAX(cblkystart, prc->ystart); + tmpxend = JAS_MIN(cblkxend, prc->xend); + tmpyend = JAS_MIN(cblkyend, prc->yend); + if (tmpxend > tmpxstart && tmpyend > tmpystart) { + cblk->firstpassno = -1; + cblk->mqdec = 0; + cblk->nulldec = 0; + cblk->flags = 0; + cblk->numpasses = 0; + cblk->segs.head = 0; + cblk->segs.tail = 0; + cblk->curseg = 0; + cblk->numimsbs = 0; + cblk->numlenbits = 3; + cblk->flags = 0; + if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) { + return -1; + } + jas_seq2d_bindsub(cblk->data, band->data, tmpxstart, tmpystart, tmpxend, tmpyend); + ++cblk; + --cblkcnt; + } + cblkxstart += 1 << rlvl->cblkwidthexpn; + if (cblkxstart >= cbgxend) { + cblkxstart = cbgxstart; + cblkystart += 1 << rlvl->cblkheightexpn; + } + } + + } else { + prc->cblks = 0; + prc->incltagtree = 0; + prc->numimsbstagtree = 0; + } + cbgxstart += 1 << rlvl->cbgwidthexpn; + if (cbgxstart >= brcbgxend) { + cbgxstart = tlcbgxstart; + cbgystart += 1 << rlvl->cbgheightexpn; + } + + } +/********************************************/ + } + } + } + +if (!(tile->pi = jpc_dec_pi_create(dec, tile))) +{ + return -1; +} + + for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist); + ++pchgno) { + pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno)); + assert(pchg); + jpc_pi_addpchg(tile->pi, pchg); + } + jpc_pi_init(tile->pi); + + return 0; +} + +static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + jpc_dec_tcomp_t *tcomp; + int compno; + int bandno; + int rlvlno; + jpc_dec_band_t *band; + jpc_dec_rlvl_t *rlvl; + int prcno; + jpc_dec_prc_t *prc; + jpc_dec_seg_t *seg; + jpc_dec_cblk_t *cblk; + int cblkno; + +if (tile->tcomps) { + + for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; + ++compno, ++tcomp) { + for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; + ++rlvlno, ++rlvl) { +if (!rlvl->bands) { + continue; +} + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { +if (band->prcs) { + for (prcno = 0, prc = band->prcs; prcno < + rlvl->numprcs; ++prcno, ++prc) { +if (!prc->cblks) { + continue; +} + for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { + + while (cblk->segs.head) { + seg = cblk->segs.head; + jpc_seglist_remove(&cblk->segs, seg); + jpc_seg_destroy(seg); + } + jas_matrix_destroy(cblk->data); + if (cblk->mqdec) { + jpc_mqdec_destroy(cblk->mqdec); + } + if (cblk->nulldec) { + jpc_bitstream_close(cblk->nulldec); + } + if (cblk->flags) { + jas_matrix_destroy(cblk->flags); + } + } + if (prc->incltagtree) { + jpc_tagtree_destroy(prc->incltagtree); + } + if (prc->numimsbstagtree) { + jpc_tagtree_destroy(prc->numimsbstagtree); + } + if (prc->cblks) { + jas_free(prc->cblks); + } + } +} + if (band->data) { + jas_matrix_destroy(band->data); + } + if (band->prcs) { + jas_free(band->prcs); + } + } + if (rlvl->bands) { + jas_free(rlvl->bands); + } + } + if (tcomp->rlvls) { + jas_free(tcomp->rlvls); + } + if (tcomp->data) { + jas_matrix_destroy(tcomp->data); + } + if (tcomp->tsfb) { + jpc_tsfb_destroy(tcomp->tsfb); + } + } +} + if (tile->cp) { + jpc_dec_cp_destroy(tile->cp); + tile->cp = 0; + } + if (tile->tcomps) { + jas_free(tile->tcomps); + tile->tcomps = 0; + } + if (tile->pi) { + jpc_pi_destroy(tile->pi); + tile->pi = 0; + } + if (tile->pkthdrstream) { + jas_stream_close(tile->pkthdrstream); + tile->pkthdrstream = 0; + } + if (tile->pptstab) { + jpc_ppxstab_destroy(tile->pptstab); + tile->pptstab = 0; + } + + tile->state = JPC_TILE_DONE; + + return 0; +} + +static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + int i; + int j; + jpc_dec_tcomp_t *tcomp; + jpc_dec_rlvl_t *rlvl; + jpc_dec_band_t *band; + int compno; + int rlvlno; + int bandno; + int adjust; + int v; + jpc_dec_ccp_t *ccp; + jpc_dec_cmpt_t *cmpt; + + if (jpc_dec_decodecblks(dec, tile)) { + fprintf(stderr, "jpc_dec_decodecblks failed\n"); + return -1; + } + + /* Perform dequantization. */ + for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; + ++compno, ++tcomp) { + ccp = &tile->cp->ccps[compno]; + for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; + ++rlvlno, ++rlvl) { + if (!rlvl->bands) { + continue; + } + for (bandno = 0, band = rlvl->bands; + bandno < rlvl->numbands; ++bandno, ++band) { + if (!band->data) { + continue; + } + jpc_undo_roi(band->data, band->roishift, ccp->roishift - + band->roishift, band->numbps); + if (tile->realmode) { + jas_matrix_asl(band->data, JPC_FIX_FRACBITS); + jpc_dequantize(band->data, band->absstepsize); + } + + } + } + } + + /* Apply an inverse wavelet transform if necessary. */ + for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; + ++compno, ++tcomp) { + ccp = &tile->cp->ccps[compno]; + jpc_tsfb_synthesize(tcomp->tsfb, ((ccp->qmfbid == + JPC_COX_RFT) ? JPC_TSFB_RITIMODE : 0), tcomp->data); + } + + + /* Apply an inverse intercomponent transform if necessary. */ + switch (tile->cp->mctid) { + case JPC_MCT_RCT: + assert(dec->numcomps == 3); + jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data, + tile->tcomps[2].data); + break; + case JPC_MCT_ICT: + assert(dec->numcomps == 3); + jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data, + tile->tcomps[2].data); + break; + } + + /* Perform rounding and convert to integer values. */ + if (tile->realmode) { + for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; + ++compno, ++tcomp) { + for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { + for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { + v = jas_matrix_get(tcomp->data, i, j); + v = jpc_fix_round(v); + jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v)); + } + } + } + } + + /* Perform level shift. */ + for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < + dec->numcomps; ++compno, ++tcomp, ++cmpt) { + adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1)); + for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { + for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { + *jas_matrix_getref(tcomp->data, i, j) += adjust; + } + } + } + + /* Perform clipping. */ + for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < + dec->numcomps; ++compno, ++tcomp, ++cmpt) { + jpc_fix_t mn; + jpc_fix_t mx; + mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0); + mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 << + cmpt->prec) - 1); + jas_matrix_clip(tcomp->data, mn, mx); + } + + /* XXX need to free tsfb struct */ + + /* Write the data for each component of the image. */ + for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < + dec->numcomps; ++compno, ++tcomp, ++cmpt) { + if (jas_image_writecmpt(dec->image, compno, tcomp->xstart - + JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart - + JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols( + tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) { + fprintf(stderr, "write component failed\n"); + return -4; + } + } + + return 0; +} + +static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms) +{ + int tileno; + jpc_dec_tile_t *tile; + + /* Eliminate compiler warnings about unused variables. */ + ms = 0; + + for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, + ++tile) { + if (tile->state == JPC_TILE_ACTIVE) { + if (jpc_dec_tiledecode(dec, tile)) { + return -1; + } + } + jpc_dec_tilefini(dec, tile); + } + + /* We are done processing the code stream. */ + dec->state = JPC_MT; + + return 1; +} + +static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_siz_t *siz = &ms->parms.siz; + int compno; + int tileno; + jpc_dec_tile_t *tile; + jpc_dec_tcomp_t *tcomp; + int htileno; + int vtileno; + jpc_dec_cmpt_t *cmpt; + + dec->xstart = siz->xoff; + dec->ystart = siz->yoff; + dec->xend = siz->width; + dec->yend = siz->height; + dec->tilewidth = siz->tilewidth; + dec->tileheight = siz->tileheight; + dec->tilexoff = siz->tilexoff; + dec->tileyoff = siz->tileyoff; + dec->numcomps = siz->numcomps; + if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { + return -1; + } + + if (!(dec->cmpts = jas_malloc(dec->numcomps * sizeof(jpc_dec_cmpt_t)))) { + return -1; + } + + for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, + ++cmpt) { + cmpt->prec = siz->comps[compno].prec; + cmpt->sgnd = siz->comps[compno].sgnd; + cmpt->hstep = siz->comps[compno].hsamp; + cmpt->vstep = siz->comps[compno].vsamp; + cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - + JPC_CEILDIV(dec->xstart, cmpt->hstep); + cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - + JPC_CEILDIV(dec->ystart, cmpt->vstep); + cmpt->hsubstep = 0; + cmpt->vsubstep = 0; + } + + dec->image = 0; + + dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); + dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); + dec->numtiles = dec->numhtiles * dec->numvtiles; + if (!(dec->tiles = jas_malloc(dec->numtiles * sizeof(jpc_dec_tile_t)))) { + return -1; + } + + for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, + ++tile) { + htileno = tileno % dec->numhtiles; + vtileno = tileno / dec->numhtiles; + tile->realmode = 0; + tile->state = JPC_TILE_INIT; + tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, + dec->xstart); + tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, + dec->ystart); + tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * + dec->tilewidth, dec->xend); + tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * + dec->tileheight, dec->yend); + tile->numparts = 0; + tile->partno = 0; + tile->pkthdrstream = 0; + tile->pkthdrstreampos = 0; + tile->pptstab = 0; + tile->cp = 0; + if (!(tile->tcomps = jas_malloc(dec->numcomps * + sizeof(jpc_dec_tcomp_t)))) { + return -1; + } + for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; + compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { + tcomp->rlvls = 0; + tcomp->data = 0; + tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); + tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); + tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); + tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); + tcomp->tsfb = 0; + } + } + + dec->pkthdrstreams = 0; + + /* We should expect to encounter other main header marker segments + or an SOT marker segment next. */ + dec->state = JPC_MH; + + return 0; +} + +static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_cod_t *cod = &ms->parms.cod; + jpc_dec_tile_t *tile; + + switch (dec->state) { + case JPC_MH: + jpc_dec_cp_setfromcod(dec->cp, cod); + break; + case JPC_TPH: + if (!(tile = dec->curtile)) { + return -1; + } + if (tile->partno != 0) { + return -1; + } + jpc_dec_cp_setfromcod(tile->cp, cod); + break; + } + return 0; +} + +static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_coc_t *coc = &ms->parms.coc; + jpc_dec_tile_t *tile; + + if (JAS_CAST(int, coc->compno) > dec->numcomps) { + fprintf(stderr, + "invalid component number in COC marker segment\n"); + return -1; + } + switch (dec->state) { + case JPC_MH: + jpc_dec_cp_setfromcoc(dec->cp, coc); + break; + case JPC_TPH: + if (!(tile = dec->curtile)) { + return -1; + } + if (tile->partno > 0) { + return -1; + } + jpc_dec_cp_setfromcoc(tile->cp, coc); + break; + } + return 0; +} + +static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_rgn_t *rgn = &ms->parms.rgn; + jpc_dec_tile_t *tile; + + if (JAS_CAST(int, rgn->compno) > dec->numcomps) { + fprintf(stderr, + "invalid component number in RGN marker segment\n"); + return -1; + } + switch (dec->state) { + case JPC_MH: + jpc_dec_cp_setfromrgn(dec->cp, rgn); + break; + case JPC_TPH: + if (!(tile = dec->curtile)) { + return -1; + } + if (tile->partno > 0) { + return -1; + } + jpc_dec_cp_setfromrgn(tile->cp, rgn); + break; + } + + return 0; +} + +static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_qcd_t *qcd = &ms->parms.qcd; + jpc_dec_tile_t *tile; + + switch (dec->state) { + case JPC_MH: + jpc_dec_cp_setfromqcd(dec->cp, qcd); + break; + case JPC_TPH: + if (!(tile = dec->curtile)) { + return -1; + } + if (tile->partno > 0) { + return -1; + } + jpc_dec_cp_setfromqcd(tile->cp, qcd); + break; + } + return 0; +} + +static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_qcc_t *qcc = &ms->parms.qcc; + jpc_dec_tile_t *tile; + + if (JAS_CAST(int, qcc->compno) > dec->numcomps) { + fprintf(stderr, + "invalid component number in QCC marker segment\n"); + return -1; + } + switch (dec->state) { + case JPC_MH: + jpc_dec_cp_setfromqcc(dec->cp, qcc); + break; + case JPC_TPH: + if (!(tile = dec->curtile)) { + return -1; + } + if (tile->partno > 0) { + return -1; + } + jpc_dec_cp_setfromqcc(tile->cp, qcc); + break; + } + return 0; +} + +static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_poc_t *poc = &ms->parms.poc; + jpc_dec_tile_t *tile; + switch (dec->state) { + case JPC_MH: + if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) { + return -1; + } + break; + case JPC_TPH: + if (!(tile = dec->curtile)) { + return -1; + } + if (!tile->partno) { + if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) { + return -1; + } + } else { + jpc_pi_addpchgfrompoc(tile->pi, poc); + } + break; + } + return 0; +} + +static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_ppm_t *ppm = &ms->parms.ppm; + jpc_ppxstabent_t *ppmstabent; + + if (!dec->ppmstab) { + if (!(dec->ppmstab = jpc_ppxstab_create())) { + return -1; + } + } + + if (!(ppmstabent = jpc_ppxstabent_create())) { + return -1; + } + ppmstabent->ind = ppm->ind; + ppmstabent->data = ppm->data; + ppm->data = 0; + ppmstabent->len = ppm->len; + if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) { + return -1; + } + return 0; +} + +static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms) +{ + jpc_ppt_t *ppt = &ms->parms.ppt; + jpc_dec_tile_t *tile; + jpc_ppxstabent_t *pptstabent; + + tile = dec->curtile; + if (!tile->pptstab) { + if (!(tile->pptstab = jpc_ppxstab_create())) { + return -1; + } + } + if (!(pptstabent = jpc_ppxstabent_create())) { + return -1; + } + pptstabent->ind = ppt->ind; + pptstabent->data = ppt->data; + ppt->data = 0; + pptstabent->len = ppt->len; + if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) { + return -1; + } + return 0; +} + +static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms) +{ + /* Eliminate compiler warnings about unused variables. */ + dec = 0; + ms = 0; + + return 0; +} + +static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms) +{ + /* Eliminate compiler warnings about unused variables. */ + dec = 0; + + fprintf(stderr, "warning: ignoring unknown marker segment\n"); + jpc_ms_dump(ms, stderr); + return 0; +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps) +{ + jpc_dec_cp_t *cp; + jpc_dec_ccp_t *ccp; + int compno; + + if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) { + return 0; + } + cp->flags = 0; + cp->numcomps = numcomps; + cp->prgord = 0; + cp->numlyrs = 0; + cp->mctid = 0; + cp->csty = 0; + if (!(cp->ccps = jas_malloc(cp->numcomps * sizeof(jpc_dec_ccp_t)))) { + return 0; + } + if (!(cp->pchglist = jpc_pchglist_create())) { + jas_free(cp->ccps); + return 0; + } + for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; + ++compno, ++ccp) { + ccp->flags = 0; + ccp->numrlvls = 0; + ccp->cblkwidthexpn = 0; + ccp->cblkheightexpn = 0; + ccp->qmfbid = 0; + ccp->numstepsizes = 0; + ccp->numguardbits = 0; + ccp->roishift = 0; + ccp->cblkctx = 0; + } + return cp; +} + +static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp) +{ + jpc_dec_cp_t *newcp; + jpc_dec_ccp_t *newccp; + jpc_dec_ccp_t *ccp; + int compno; + + if (!(newcp = jpc_dec_cp_create(cp->numcomps))) { + return 0; + } + newcp->flags = cp->flags; + newcp->prgord = cp->prgord; + newcp->numlyrs = cp->numlyrs; + newcp->mctid = cp->mctid; + newcp->csty = cp->csty; + jpc_pchglist_destroy(newcp->pchglist); + newcp->pchglist = 0; + if (!(newcp->pchglist = jpc_pchglist_copy(cp->pchglist))) { + jas_free(newcp); + return 0; + } + for (compno = 0, newccp = newcp->ccps, ccp = cp->ccps; + compno < cp->numcomps; + ++compno, ++newccp, ++ccp) { + *newccp = *ccp; + } + return newcp; +} + +static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp) +{ + int compno; + jpc_dec_ccp_t *ccp; + cp->flags &= (JPC_CSET | JPC_QSET); + for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; + ++compno, ++ccp) { + ccp->flags = 0; + } +} + +static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp) +{ + if (cp->ccps) { + jas_free(cp->ccps); + } + if (cp->pchglist) { + jpc_pchglist_destroy(cp->pchglist); + } + jas_free(cp); +} + +static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp) +{ + uint_fast16_t compcnt; + jpc_dec_ccp_t *ccp; + + if (!(cp->flags & JPC_CSET) || !(cp->flags & JPC_QSET)) { + return 0; + } + for (compcnt = cp->numcomps, ccp = cp->ccps; compcnt > 0; --compcnt, + ++ccp) { + /* Is there enough step sizes for the number of bands? */ + if ((ccp->qsty != JPC_QCX_SIQNT && JAS_CAST(int, ccp->numstepsizes) < 3 * + ccp->numrlvls - 2) || (ccp->qsty == JPC_QCX_SIQNT && + ccp->numstepsizes != 1)) { + return 0; + } + } + return 1; +} + +static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, + uint_fast16_t *stepsizes) +{ + int bandno; + int numbands; + uint_fast16_t expn; + uint_fast16_t mant; + expn = JPC_QCX_GETEXPN(refstepsize); + mant = JPC_QCX_GETMANT(refstepsize); + numbands = 3 * numrlvls - 2; + for (bandno = 0; bandno < numbands; ++bandno) { + stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); + } +} + +static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp) +{ + jpc_dec_ccp_t *ccp; + int compno; + int i; + for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; + ++compno, ++ccp) { + if (!(ccp->csty & JPC_COX_PRT)) { + for (i = 0; i < JPC_MAXRLVLS; ++i) { + ccp->prcwidthexpns[i] = 15; + ccp->prcheightexpns[i] = 15; + } + } + if (ccp->qsty == JPC_QCX_SIQNT) { + calcstepsizes(ccp->stepsizes[0], ccp->numrlvls, ccp->stepsizes); + } + } + return 0; +} + +static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod) +{ + jpc_dec_ccp_t *ccp; + int compno; + cp->flags |= JPC_CSET; + cp->prgord = cod->prg; + if (cod->mctrans) { + cp->mctid = (cod->compparms.qmfbid == JPC_COX_INS) ? (JPC_MCT_ICT) : (JPC_MCT_RCT); + } else { + cp->mctid = JPC_MCT_NONE; + } + cp->numlyrs = cod->numlyrs; + cp->csty = cod->csty & (JPC_COD_SOP | JPC_COD_EPH); + for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; + ++compno, ++ccp) { + jpc_dec_cp_setfromcox(cp, ccp, &cod->compparms, 0); + } + cp->flags |= JPC_CSET; + return 0; +} + +static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc) +{ + jpc_dec_cp_setfromcox(cp, &cp->ccps[coc->compno], &coc->compparms, JPC_COC); + return 0; +} + +static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, + jpc_coxcp_t *compparms, int flags) +{ + int rlvlno; + + /* Eliminate compiler warnings about unused variables. */ + cp = 0; + + if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) { + ccp->numrlvls = compparms->numdlvls + 1; + ccp->cblkwidthexpn = JPC_COX_GETCBLKSIZEEXPN( + compparms->cblkwidthval); + ccp->cblkheightexpn = JPC_COX_GETCBLKSIZEEXPN( + compparms->cblkheightval); + ccp->qmfbid = compparms->qmfbid; + ccp->cblkctx = compparms->cblksty; + ccp->csty = compparms->csty & JPC_COX_PRT; + for (rlvlno = 0; rlvlno < compparms->numrlvls; ++rlvlno) { + ccp->prcwidthexpns[rlvlno] = + compparms->rlvls[rlvlno].parwidthval; + ccp->prcheightexpns[rlvlno] = + compparms->rlvls[rlvlno].parheightval; + } + ccp->flags |= flags | JPC_CSET; + } + return 0; +} + +static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd) +{ + int compno; + jpc_dec_ccp_t *ccp; + for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; + ++compno, ++ccp) { + jpc_dec_cp_setfromqcx(cp, ccp, &qcd->compparms, 0); + } + cp->flags |= JPC_QSET; + return 0; +} + +static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc) +{ + return jpc_dec_cp_setfromqcx(cp, &cp->ccps[qcc->compno], &qcc->compparms, JPC_QCC); +} + +static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, + jpc_qcxcp_t *compparms, int flags) +{ + int bandno; + + /* Eliminate compiler warnings about unused variables. */ + cp = 0; + + if ((flags & JPC_QCC) || !(ccp->flags & JPC_QCC)) { + ccp->flags |= flags | JPC_QSET; + for (bandno = 0; bandno < compparms->numstepsizes; ++bandno) { + ccp->stepsizes[bandno] = compparms->stepsizes[bandno]; + } + ccp->numstepsizes = compparms->numstepsizes; + ccp->numguardbits = compparms->numguard; + ccp->qsty = compparms->qntsty; + } + return 0; +} + +static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn) +{ + jpc_dec_ccp_t *ccp; + ccp = &cp->ccps[rgn->compno]; + ccp->roishift = rgn->roishift; + return 0; +} + +static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc) +{ + int pchgno; + jpc_pchg_t *pchg; + for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) { + if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) { + return -1; + } + if (jpc_pchglist_insert(pi->pchglist, -1, pchg)) { + return -1; + } + } + return 0; +} + +static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset) +{ + int pchgno; + jpc_pchg_t *pchg; + if (reset) { + while (jpc_pchglist_numpchgs(cp->pchglist) > 0) { + pchg = jpc_pchglist_remove(cp->pchglist, 0); + jpc_pchg_destroy(pchg); + } + } + for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) { + if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) { + return -1; + } + if (jpc_pchglist_insert(cp->pchglist, -1, pchg)) { + return -1; + } + } + return 0; +} + +static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits) +{ + jpc_fix_t absstepsize; + int n; + + absstepsize = jpc_inttofix(1); + n = JPC_FIX_FRACBITS - 11; + absstepsize |= (n >= 0) ? (JPC_QCX_GETMANT(stepsize) << n) : + (JPC_QCX_GETMANT(stepsize) >> (-n)); + n = numbits - JPC_QCX_GETEXPN(stepsize); + absstepsize = (n >= 0) ? (absstepsize << n) : (absstepsize >> (-n)); + return absstepsize; +} + +static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize) +{ + int i; + int j; + int t; + + assert(absstepsize >= 0); + if (absstepsize == jpc_inttofix(1)) { + return; + } + + for (i = 0; i < jas_matrix_numrows(x); ++i) { + for (j = 0; j < jas_matrix_numcols(x); ++j) { + t = jas_matrix_get(x, i, j); + if (t) { + t = jpc_fix_mul(t, absstepsize); + } else { + t = 0; + } + jas_matrix_set(x, i, j, t); + } + } + +} + +static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps) +{ + int i; + int j; + int thresh; + jpc_fix_t val; + jpc_fix_t mag; + bool warn; + uint_fast32_t mask; + + if (roishift == 0 && bgshift == 0) { + return; + } + thresh = 1 << roishift; + + warn = false; + for (i = 0; i < jas_matrix_numrows(x); ++i) { + for (j = 0; j < jas_matrix_numcols(x); ++j) { + val = jas_matrix_get(x, i, j); + mag = JAS_ABS(val); + if (mag >= thresh) { + /* We are dealing with ROI data. */ + mag >>= roishift; + val = (val < 0) ? (-mag) : mag; + jas_matrix_set(x, i, j, val); + } else { + /* We are dealing with non-ROI (i.e., background) data. */ + mag <<= bgshift; + mask = (1 << numbps) - 1; + /* Perform a basic sanity check on the sample value. */ + /* Some implementations write garbage in the unused + most-significant bit planes introduced by ROI shifting. + Here we ensure that any such bits are masked off. */ + if (mag & (~mask)) { + if (!warn) { + fprintf(stderr, + "warning: possibly corrupt code stream\n"); + warn = true; + } + mag &= mask; + } + val = (val < 0) ? (-mag) : mag; + jas_matrix_set(x, i, j, val); + } + } + } +} + +static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in) +{ + jpc_dec_t *dec; + + if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) { + return 0; + } + + dec->image = 0; + dec->xstart = 0; + dec->ystart = 0; + dec->xend = 0; + dec->yend = 0; + dec->tilewidth = 0; + dec->tileheight = 0; + dec->tilexoff = 0; + dec->tileyoff = 0; + dec->numhtiles = 0; + dec->numvtiles = 0; + dec->numtiles = 0; + dec->tiles = 0; + dec->curtile = 0; + dec->numcomps = 0; + dec->in = in; + dec->cp = 0; + dec->maxlyrs = impopts->maxlyrs; + dec->maxpkts = impopts->maxpkts; +dec->numpkts = 0; + dec->ppmseqno = 0; + dec->state = 0; + dec->cmpts = 0; + dec->pkthdrstreams = 0; + dec->ppmstab = 0; + dec->curtileendoff = 0; + + return dec; +} + +static void jpc_dec_destroy(jpc_dec_t *dec) +{ + if (dec->cstate) { + jpc_cstate_destroy(dec->cstate); + } + if (dec->pkthdrstreams) { + jpc_streamlist_destroy(dec->pkthdrstreams); + } + if (dec->image) { + jas_image_destroy(dec->image); + } + + if (dec->cp) { + jpc_dec_cp_destroy(dec->cp); + } + + if (dec->cmpts) { + jas_free(dec->cmpts); + } + + if (dec->tiles) { + jas_free(dec->tiles); + } + + jas_free(dec); +} + +/******************************************************************************\ +* +\******************************************************************************/ + +void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, jpc_dec_seg_t *node) +{ + jpc_dec_seg_t *prev; + jpc_dec_seg_t *next; + + prev = ins; + node->prev = prev; + next = prev ? (prev->next) : 0; + node->prev = prev; + node->next = next; + if (prev) { + prev->next = node; + } else { + list->head = node; + } + if (next) { + next->prev = node; + } else { + list->tail = node; + } +} + +void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *seg) +{ + jpc_dec_seg_t *prev; + jpc_dec_seg_t *next; + + prev = seg->prev; + next = seg->next; + if (prev) { + prev->next = next; + } else { + list->head = next; + } + if (next) { + next->prev = prev; + } else { + list->tail = prev; + } + seg->prev = 0; + seg->next = 0; +} + +jpc_dec_seg_t *jpc_seg_alloc() +{ + jpc_dec_seg_t *seg; + + if (!(seg = jas_malloc(sizeof(jpc_dec_seg_t)))) { + return 0; + } + seg->prev = 0; + seg->next = 0; + seg->passno = -1; + seg->numpasses = 0; + seg->maxpasses = 0; + seg->type = JPC_SEG_INVALID; + seg->stream = 0; + seg->cnt = 0; + seg->complete = 0; + seg->lyrno = -1; + return seg; +} + +void jpc_seg_destroy(jpc_dec_seg_t *seg) +{ + if (seg->stream) { + jas_stream_close(seg->stream); + } + jas_free(seg); +} + +static int jpc_dec_dump(jpc_dec_t *dec, FILE *out) +{ + jpc_dec_tile_t *tile; + int tileno; + jpc_dec_tcomp_t *tcomp; + int compno; + jpc_dec_rlvl_t *rlvl; + int rlvlno; + jpc_dec_band_t *band; + int bandno; + jpc_dec_prc_t *prc; + int prcno; + jpc_dec_cblk_t *cblk; + int cblkno; + + for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; + ++tileno, ++tile) { + for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; + ++compno, ++tcomp) { + for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < + tcomp->numrlvls; ++rlvlno, ++rlvl) { +fprintf(out, "RESOLUTION LEVEL %d\n", rlvlno); +fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", + rlvl->xstart, rlvl->ystart, rlvl->xend, rlvl->yend, rlvl->xend - + rlvl->xstart, rlvl->yend - rlvl->ystart); + for (bandno = 0, band = rlvl->bands; + bandno < rlvl->numbands; ++bandno, ++band) { +fprintf(out, "BAND %d\n", bandno); +fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", + jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data), + jas_seq2d_yend(band->data), jas_seq2d_xend(band->data) - jas_seq2d_xstart(band->data), + jas_seq2d_yend(band->data) - jas_seq2d_ystart(band->data)); + for (prcno = 0, prc = band->prcs; + prcno < rlvl->numprcs; ++prcno, + ++prc) { +fprintf(out, "CODE BLOCK GROUP %d\n", prcno); +fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", + prc->xstart, prc->ystart, prc->xend, prc->yend, prc->xend - + prc->xstart, prc->yend - prc->ystart); + for (cblkno = 0, cblk = + prc->cblks; cblkno < + prc->numcblks; ++cblkno, + ++cblk) { +fprintf(out, "CODE BLOCK %d\n", cblkno); +fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", + jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data), + jas_seq2d_yend(cblk->data), jas_seq2d_xend(cblk->data) - jas_seq2d_xstart(cblk->data), + jas_seq2d_yend(cblk->data) - jas_seq2d_ystart(cblk->data)); + } + } + } + } + } + } + + return 0; +} + +jpc_streamlist_t *jpc_streamlist_create() +{ + jpc_streamlist_t *streamlist; + int i; + + if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) { + return 0; + } + streamlist->numstreams = 0; + streamlist->maxstreams = 100; + if (!(streamlist->streams = jas_malloc(streamlist->maxstreams * + sizeof(jas_stream_t *)))) { + jas_free(streamlist); + return 0; + } + for (i = 0; i < streamlist->maxstreams; ++i) { + streamlist->streams[i] = 0; + } + return streamlist; +} + +int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno, + jas_stream_t *stream) +{ + jas_stream_t **newstreams; + int newmaxstreams; + int i; + /* Grow the array of streams if necessary. */ + if (streamlist->numstreams >= streamlist->maxstreams) { + newmaxstreams = streamlist->maxstreams + 1024; + if (!(newstreams = jas_realloc(streamlist->streams, + (newmaxstreams + 1024) * sizeof(jas_stream_t *)))) { + return -1; + } + for (i = streamlist->numstreams; i < streamlist->maxstreams; ++i) { + streamlist->streams[i] = 0; + } + streamlist->maxstreams = newmaxstreams; + streamlist->streams = newstreams; + } + if (streamno != streamlist->numstreams) { + /* Can only handle insertion at start of list. */ + return -1; + } + streamlist->streams[streamno] = stream; + ++streamlist->numstreams; + return 0; +} + +jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno) +{ + jas_stream_t *stream; + int i; + if (streamno >= streamlist->numstreams) { + abort(); + } + stream = streamlist->streams[streamno]; + for (i = streamno + 1; i < streamlist->numstreams; ++i) { + streamlist->streams[i - 1] = streamlist->streams[i]; + } + --streamlist->numstreams; + return stream; +} + +void jpc_streamlist_destroy(jpc_streamlist_t *streamlist) +{ + int streamno; + if (streamlist->streams) { + for (streamno = 0; streamno < streamlist->numstreams; + ++streamno) { + jas_stream_close(streamlist->streams[streamno]); + } + jas_free(streamlist->streams); + } + jas_free(streamlist); +} + +jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno) +{ + assert(streamno < streamlist->numstreams); + return streamlist->streams[streamno]; +} + +int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist) +{ + return streamlist->numstreams; +} + +jpc_ppxstab_t *jpc_ppxstab_create() +{ + jpc_ppxstab_t *tab; + + if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) { + return 0; + } + tab->numents = 0; + tab->maxents = 0; + tab->ents = 0; + return tab; +} + +void jpc_ppxstab_destroy(jpc_ppxstab_t *tab) +{ + int i; + for (i = 0; i < tab->numents; ++i) { + jpc_ppxstabent_destroy(tab->ents[i]); + } + if (tab->ents) { + jas_free(tab->ents); + } + jas_free(tab); +} + +int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents) +{ + jpc_ppxstabent_t **newents; + if (tab->maxents < maxents) { + newents = (tab->ents) ? jas_realloc(tab->ents, maxents * + sizeof(jpc_ppxstabent_t *)) : jas_malloc(maxents * sizeof(jpc_ppxstabent_t *)); + if (!newents) { + return -1; + } + tab->ents = newents; + tab->maxents = maxents; + } + return 0; +} + +int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent) +{ + int inspt; + int i; + + for (i = 0; i < tab->numents; ++i) { + if (tab->ents[i]->ind > ent->ind) { + break; + } + } + inspt = i; + + if (tab->numents >= tab->maxents) { + if (jpc_ppxstab_grow(tab, tab->maxents + 128)) { + return -1; + } + } + + for (i = tab->numents; i > inspt; --i) { + tab->ents[i] = tab->ents[i - 1]; + } + tab->ents[i] = ent; + ++tab->numents; + + return 0; +} + +jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab) +{ + jpc_streamlist_t *streams; + uchar *dataptr; + uint_fast32_t datacnt; + uint_fast32_t tpcnt; + jpc_ppxstabent_t *ent; + int entno; + jas_stream_t *stream; + int n; + + if (!(streams = jpc_streamlist_create())) { + goto error; + } + + if (!tab->numents) { + return streams; + } + + entno = 0; + ent = tab->ents[entno]; + dataptr = ent->data; + datacnt = ent->len; + for (;;) { + + /* Get the length of the packet header data for the current + tile-part. */ + if (datacnt < 4) { + goto error; + } + if (!(stream = jas_stream_memopen(0, 0))) { + goto error; + } + if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams), + stream)) { + goto error; + } + tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8) + | dataptr[3]; + datacnt -= 4; + dataptr += 4; + + /* Get the packet header data for the current tile-part. */ + while (tpcnt) { + if (!datacnt) { + if (++entno >= tab->numents) { + goto error; + } + ent = tab->ents[entno]; + dataptr = ent->data; + datacnt = ent->len; + } + n = JAS_MIN(tpcnt, datacnt); + if (jas_stream_write(stream, dataptr, n) != n) { + goto error; + } + tpcnt -= n; + dataptr += n; + datacnt -= n; + } + jas_stream_rewind(stream); + if (!datacnt) { + if (++entno >= tab->numents) { + break; + } + ent = tab->ents[entno]; + dataptr = ent->data; + datacnt = ent->len; + } + } + + return streams; + +error: + jpc_streamlist_destroy(streams); + return 0; +} + +int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab) +{ + int i; + jpc_ppxstabent_t *ent; + for (i = 0; i < tab->numents; ++i) { + ent = tab->ents[i]; + if (jas_stream_write(out, ent->data, ent->len) != JAS_CAST(int, ent->len)) { + return -1; + } + } + return 0; +} + +jpc_ppxstabent_t *jpc_ppxstabent_create() +{ + jpc_ppxstabent_t *ent; + if (!(ent = jas_malloc(sizeof(jpc_ppxstabent_t)))) { + return 0; + } + ent->data = 0; + ent->len = 0; + ent->ind = 0; + return ent; +} + +void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent) +{ + if (ent->data) { + jas_free(ent->data); + } + jas_free(ent); +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_dec.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_dec.h new file mode 100644 index 0000000..29d5937 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_dec.h @@ -0,0 +1,745 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * JPEG-2000 Decoder + * + * $Id$ + */ + +#ifndef JPC_DEC_H +#define JPC_DEC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_stream.h" + +#include "jpc_tsfb.h" +#include "jpc_bs.h" +#include "jpc_tagtree.h" +#include "jpc_cs.h" +#include "jpc_cod.h" +#include "jpc_mqdec.h" +#include "jpc_t2cod.h" + +/******************************************************************************\ +* Below are some ugly warts necessary to support packed packet headers. +\******************************************************************************/ + +/* PPM/PPT marker segment table entry. */ + +typedef struct { + + /* The index for this entry. */ + uint_fast16_t ind; + + /* The data length. */ + uint_fast32_t len; + + /* The data. */ + uchar *data; + +} jpc_ppxstabent_t; + +/* PPM/PPT marker segment table. */ + +typedef struct { + + /* The number of entries. */ + int numents; + + /* The maximum number of entries (i.e., the allocated size of the array + below). */ + int maxents; + + /* The table entries. */ + jpc_ppxstabent_t **ents; + +} jpc_ppxstab_t; + +/* Stream list class. */ + +typedef struct { + + /* The number of streams in this list. */ + int numstreams; + + /* The maximum number of streams that can be accomodated without + growing the streams array. */ + int maxstreams; + + /* The streams. */ + jas_stream_t **streams; + +} jpc_streamlist_t; + +/******************************************************************************\ +* Coding parameters class. +\******************************************************************************/ + +/* Per-component coding parameters. */ + +typedef struct { + + /* How were various coding parameters set? */ + int flags; + + /* Per-component coding style parameters (e.g., explicit precinct sizes) */ + uint_fast8_t csty; + + /* The number of resolution levels. */ + uint_fast8_t numrlvls; + + /* The code block width exponent. */ + uint_fast8_t cblkwidthexpn; + + /* The code block height exponent. */ + uint_fast8_t cblkheightexpn; + + /* The QMFB ID. */ + uint_fast8_t qmfbid; + + /* The quantization style. */ + uint_fast8_t qsty; + + /* The number of quantizer step sizes. */ + uint_fast16_t numstepsizes; + + /* The step sizes. */ + uint_fast16_t stepsizes[3 * JPC_MAXRLVLS + 1]; + + /* The number of guard bits. */ + uint_fast8_t numguardbits; + + /* The ROI shift value. */ + uint_fast8_t roishift; + + /* The code block parameters. */ + uint_fast8_t cblkctx; + + /* The precinct width exponents. */ + uint_fast8_t prcwidthexpns[JPC_MAXRLVLS]; + + /* The precinct height exponents. */ + uint_fast8_t prcheightexpns[JPC_MAXRLVLS]; + +} jpc_dec_ccp_t; + +/* Coding paramters. */ + +typedef struct { + + /* How were these coding parameters set? */ + int flags; + + /* Progression change list. */ + jpc_pchglist_t *pchglist; + + /* Progression order. */ + uint_fast8_t prgord; + + /* The number of layers. */ + uint_fast16_t numlyrs; + + /* The MCT ID. */ + uint_fast8_t mctid; + + /* The coding style parameters (e.g., SOP, EPH). */ + uint_fast8_t csty; + + /* The number of components. */ + int numcomps; + + /* The per-component coding parameters. */ + jpc_dec_ccp_t *ccps; + +} jpc_dec_cp_t; + +/******************************************************************************\ +* Decoder class. +\******************************************************************************/ + +/* Decoder per-segment state information. */ + +typedef struct jpc_dec_seg_s { + + /* The next segment in the list. */ + struct jpc_dec_seg_s *next; + + /* The previous segment in the list. */ + struct jpc_dec_seg_s *prev; + + /* The starting pass number for this segment. */ + int passno; + + /* The number of passes in this segment. */ + int numpasses; + + /* The maximum number of passes in this segment. */ + int maxpasses; + + /* The type of data in this segment (i.e., MQ or raw). */ + int type; + + /* A stream containing the data for this segment. */ + jas_stream_t *stream; + + /* The number of bytes destined for this segment from the packet + currently being decoded. */ + int cnt; + + /* A flag indicating if this segment has been terminated. */ + int complete; + + /* The layer number to which this segment belongs. */ + /* If the segment spans multiple layers, then the largest layer number + spanned by the segment is used. */ + int lyrno; + +} jpc_dec_seg_t; + +/* Decoder segment list. */ + +typedef struct { + + /* The first entry in the list. */ + jpc_dec_seg_t *head; + + /* The last entry in the list. */ + jpc_dec_seg_t *tail; + +} jpc_dec_seglist_t; + +/* Decoder per-code-block state information. */ + +typedef struct { + + /* The number of passes. */ + int numpasses; + + /* A list of segments that still need to be decoded. */ + jpc_dec_seglist_t segs; + + /* The first incomplete/partial segment. */ + jpc_dec_seg_t *curseg; + + /* The number of leading insignificant bit planes for this code block. */ + int numimsbs; + + /* The number of bits used to encode pass data lengths. */ + int numlenbits; + + /* The first pass number containing data for this code block. */ + int firstpassno; + + /* The MQ decoder. */ + jpc_mqdec_t *mqdec; + + /* The raw bit stream decoder. */ + jpc_bitstream_t *nulldec; + + /* The per-sample state information for this code block. */ + jas_matrix_t *flags; + + /* The sample data associated with this code block. */ + jas_matrix_t *data; + +} jpc_dec_cblk_t; + +/* Decoder per-code-block-group state information. */ + +typedef struct { + + /* The x-coordinate of the top-left corner of the precinct. */ + uint_fast32_t xstart; + + /* The y-coordinate of the top-left corner of the precinct. */ + uint_fast32_t ystart; + + /* The x-coordinate of the bottom-right corner of the precinct + (plus one). */ + uint_fast32_t xend; + + /* The y-coordinate of the bottom-right corner of the precinct + (plus one). */ + uint_fast32_t yend; + + /* The number of code blocks spanning this precinct in the horizontal + direction. */ + int numhcblks; + + /* The number of code blocks spanning this precinct in the vertical + direction. */ + int numvcblks; + + /* The total number of code blocks in this precinct. */ + int numcblks; + + /* The per code block information. */ + jpc_dec_cblk_t *cblks; + + /* The inclusion tag tree. */ + jpc_tagtree_t *incltagtree; + + /* The insignificant MSBs tag tree. */ + jpc_tagtree_t *numimsbstagtree; + +} jpc_dec_prc_t; + +/* Decoder per-band state information. */ + +typedef struct { + + /* The per-code-block-group state information. */ + jpc_dec_prc_t *prcs; + + /* The sample data associated with this band. */ + jas_matrix_t *data; + + /* The orientation of this band (i.e., LL, LH, HL, or HH). */ + int orient; + + /* The encoded quantizer step size. */ + int stepsize; + + /* The absolute quantizer step size. */ + jpc_fix_t absstepsize; + + /* The number of bit planes for this band. */ + int numbps; + + /* The analysis gain associated with this band. */ + int analgain; + + /* The ROI shift value for this band. */ + int roishift; + +} jpc_dec_band_t; + +/* Decoder per-resolution-level state information. */ + +typedef struct { + + /* The number of bands associated with this resolution level. */ + int numbands; + + /* The per-band information. */ + jpc_dec_band_t *bands; + + /* The x-coordinate of the top-left corner of the tile-component + at this resolution. */ + uint_fast32_t xstart; + + /* The y-coordinate of the top-left corner of the tile-component + at this resolution. */ + uint_fast32_t ystart; + + /* The x-coordinate of the bottom-right corner of the tile-component + at this resolution (plus one). */ + uint_fast32_t xend; + + /* The y-coordinate of the bottom-right corner of the tile-component + at this resolution (plus one). */ + uint_fast32_t yend; + + /* The exponent value for the nominal precinct width measured + relative to the associated LL band. */ + int prcwidthexpn; + + /* The exponent value for the nominal precinct height measured + relative to the associated LL band. */ + int prcheightexpn; + + /* The number of precincts in the horizontal direction. */ + int numhprcs; + + /* The number of precincts in the vertical direction. */ + int numvprcs; + + /* The total number of precincts. */ + int numprcs; + + /* The exponent value for the nominal code block group width. + This quantity is associated with the next lower resolution level + (assuming that there is one). */ + int cbgwidthexpn; + + /* The exponent value for the nominal code block group height + This quantity is associated with the next lower resolution level + (assuming that there is one). */ + int cbgheightexpn; + + /* The exponent value for the code block width. */ + uint_fast16_t cblkwidthexpn; + + /* The exponent value for the code block height. */ + uint_fast16_t cblkheightexpn; + +} jpc_dec_rlvl_t; + +/* Decoder per-tile-component state information. */ + +typedef struct { + + /* The x-coordinate of the top-left corner of the tile-component + in the coordinate system of the tile-component. */ + uint_fast32_t xstart; + + /* The y-coordinate of the top-left corner of the tile-component + in the coordinate system of the tile-component. */ + uint_fast32_t ystart; + + /* The x-coordinate of the bottom-right corner of the tile-component + in the coordinate system of the tile-component (plus one). */ + uint_fast32_t xend; + + /* The y-coordinate of the bottom-right corner of the tile-component + in the coordinate system of the tile-component (plus one). */ + uint_fast32_t yend; + + /* The component data for the current tile. */ + jas_matrix_t *data; + + /* The number of resolution levels. */ + int numrlvls; + + /* The per resolution level information. */ + jpc_dec_rlvl_t *rlvls; + + /* The TSFB. */ + jpc_tsfb_t *tsfb; + +} jpc_dec_tcomp_t; + +/* + * Tile states. + */ + +#define JPC_TILE_INIT 0 +#define JPC_TILE_ACTIVE 1 +#define JPC_TILE_ACTIVELAST 2 +#define JPC_TILE_DONE 3 + +/* Decoder per-tile state information. */ + +typedef struct { + + /* The processing state for this tile. */ + int state; + + /* The x-coordinate of the top-left corner of the tile on the reference + grid. */ + uint_fast32_t xstart; + + /* The y-coordinate of the top-left corner of the tile on the reference + grid. */ + uint_fast32_t ystart; + + /* The x-coordinate of the bottom-right corner of the tile on the + reference grid (plus one). */ + uint_fast32_t xend; + + /* The y-coordinate of the bottom-right corner of the tile on the + reference grid (plus one). */ + uint_fast32_t yend; + + /* The packed packet header data for this tile. */ + jpc_ppxstab_t *pptstab; + + /* A stream containing the packed packet header data for this tile. */ + jas_stream_t *pkthdrstream; + + /* The current position within the packed packet header stream. */ + long pkthdrstreampos; + + /* The coding parameters for this tile. */ + jpc_dec_cp_t *cp; + + /* The per tile-component information. */ + jpc_dec_tcomp_t *tcomps; + + /* The next expected tile-part number. */ + int partno; + + /* The number of tile-parts. */ + int numparts; + + /* The coding mode. */ + int realmode; + + /* The packet iterator for this tile. */ + jpc_pi_t *pi; + +} jpc_dec_tile_t; + +/* Decoder per-component state information. */ + +typedef struct { + + /* The horizontal sampling period. */ + uint_fast32_t hstep; + + /* The vertical sampling period. */ + uint_fast32_t vstep; + + /* The number of samples in the horizontal direction. */ + uint_fast32_t width; + + /* The number of samples in the vertical direction. */ + uint_fast32_t height; + + /* The precision of the sample data. */ + uint_fast16_t prec; + + /* The signedness of the sample data. */ + bool sgnd; + + /* The sample alignment horizontal offset. */ + uint_fast32_t hsubstep; + + /* The sample alignment vertical offset. */ + uint_fast32_t vsubstep; + +} jpc_dec_cmpt_t; + +/* Decoder state information. */ + +typedef struct { + + /* The decoded image. */ + jas_image_t *image; + + /* The x-coordinate of the top-left corner of the image area on + the reference grid. */ + uint_fast32_t xstart; + + /* The y-coordinate of the top-left corner of the image area on + the reference grid. */ + uint_fast32_t ystart; + + /* The x-coordinate of the bottom-right corner of the image area on + the reference grid (plus one). */ + uint_fast32_t xend; + + /* The y-coordinate of the bottom-right corner of the image area on + the reference grid (plus one). */ + uint_fast32_t yend; + + /* The nominal tile width in units of the image reference grid. */ + uint_fast32_t tilewidth; + + /* The nominal tile height in units of the image reference grid. */ + uint_fast32_t tileheight; + + /* The horizontal offset from the origin of the reference grid to the + left side of the first tile. */ + uint_fast32_t tilexoff; + + /* The vertical offset from the origin of the reference grid to the + top side of the first tile. */ + uint_fast32_t tileyoff; + + /* The number of tiles spanning the image area in the vertical + direction. */ + int numhtiles; + + /* The number of tiles spanning the image area in the horizontal + direction. */ + int numvtiles; + + /* The total number of tiles. */ + int numtiles; + + /* The per-tile information. */ + jpc_dec_tile_t *tiles; + + /* The tile currently being processed. */ + jpc_dec_tile_t *curtile; + + /* The number of components. */ + int numcomps; + + /* The stream containing the input JPEG-2000 code stream data. */ + jas_stream_t *in; + + /* The default coding parameters for all tiles. */ + jpc_dec_cp_t *cp; + + /* The maximum number of layers that may be decoded. */ + int maxlyrs; + + /* The maximum number of packets that may be decoded. */ + int maxpkts; + + /* The number of packets decoded so far in the processing of the entire + code stream. */ + int numpkts; + + /* The next expected PPM marker segment sequence number. */ + int ppmseqno; + + /* The current state for code stream processing. */ + int state; + + /* The per-component information. */ + jpc_dec_cmpt_t *cmpts; + + /* The information from PPM marker segments. */ + jpc_ppxstab_t *ppmstab; + + /* A list of streams containing packet header data from PPM marker + segments. */ + jpc_streamlist_t *pkthdrstreams; + + /* The expected ending offset for a tile-part. */ + long curtileendoff; + + /* This is required by the tier-2 decoder. */ + jpc_cstate_t *cstate; + +} jpc_dec_t; + +/* Decoder options. */ + +typedef struct { + + /* The debug level for the decoder. */ + int debug; + + /* The maximum number of layers to decode. */ + int maxlyrs; + + /* The maximum number of packets to decode. */ + int maxpkts; + +} jpc_dec_importopts_t; + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Create a decoder segment object. */ +jpc_dec_seg_t *jpc_seg_alloc(void); + +/* Destroy a decoder segment object. */ +void jpc_seg_destroy(jpc_dec_seg_t *seg); + +/* Remove a segment from a segment list. */ +void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *node); + +/* Insert a segment into a segment list. */ +void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, + jpc_dec_seg_t *node); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_enc.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_enc.c new file mode 100644 index 0000000..99962c4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_enc.c @@ -0,0 +1,2672 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include +#include + +#include "jasper/jas_string.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_image.h" +#include "jasper/jas_fix.h" +#include "jasper/jas_tvp.h" +#include "jasper/jas_version.h" +#include "jasper/jas_math.h" +#include "jasper/jas_debug.h" + +#include "jpc_flt.h" +#include "jpc_fix.h" +#include "jpc_tagtree.h" +#include "jpc_enc.h" +#include "jpc_cs.h" +#include "jpc_mct.h" +#include "jpc_tsfb.h" +#include "jpc_qmfb.h" +#include "jpc_t1enc.h" +#include "jpc_t2enc.h" +#include "jpc_cod.h" +#include "jpc_math.h" +#include "jpc_util.h" + +/******************************************************************************\ +* +\******************************************************************************/ + +#define JPC_POW2(n) \ + (1 << (n)) + +#define JPC_FLOORTOMULTPOW2(x, n) \ + (((n) > 0) ? ((x) & (~((1 << n) - 1))) : (x)) +/* Round to the nearest multiple of the specified power of two in the + direction of negative infinity. */ + +#define JPC_CEILTOMULTPOW2(x, n) \ + (((n) > 0) ? JPC_FLOORTOMULTPOW2(((x) + (1 << (n)) - 1), n) : (x)) +/* Round to the nearest multiple of the specified power of two in the + direction of positive infinity. */ + +#define JPC_POW2(n) \ + (1 << (n)) + +jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno); +void jpc_enc_tile_destroy(jpc_enc_tile_t *tile); + +static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp, + jas_image_t *image, jpc_enc_tile_t *tile); +static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt); +static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp, + jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos); +static void rlvl_destroy(jpc_enc_rlvl_t *rlvl); +static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp, + jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos); +static void band_destroy(jpc_enc_band_t *bands); +static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, + jpc_enc_band_t *band); +static void prc_destroy(jpc_enc_prc_t *prcs); +static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp, + jpc_enc_prc_t *prc); +static void cblk_destroy(jpc_enc_cblk_t *cblks); +int ratestrtosize(char *s, uint_fast32_t rawsize, uint_fast32_t *size); +static void pass_destroy(jpc_enc_pass_t *pass); +void jpc_enc_dump(jpc_enc_t *enc); + +/******************************************************************************\ +* Local prototypes. +\******************************************************************************/ + +int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk); +void calcrdslopes(jpc_enc_cblk_t *cblk); +void dump_layeringinfo(jpc_enc_t *enc); +static int jpc_calcssexp(jpc_fix_t stepsize); +static int jpc_calcssmant(jpc_fix_t stepsize); +void quantize(jas_matrix_t *data, jpc_fix_t stepsize); +static int jpc_enc_encodemainhdr(jpc_enc_t *enc); +static int jpc_enc_encodemainbody(jpc_enc_t *enc); +int jpc_enc_encodetiledata(jpc_enc_t *enc); +jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image); +void jpc_enc_destroy(jpc_enc_t *enc); +static int jpc_enc_encodemainhdr(jpc_enc_t *enc); +static int jpc_enc_encodemainbody(jpc_enc_t *enc); +int jpc_enc_encodetiledata(jpc_enc_t *enc); +int rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens); +int setins(int numvalues, jpc_flt_t *values, jpc_flt_t value); +static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image); +void jpc_enc_cp_destroy(jpc_enc_cp_t *cp); +static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn); + +static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn) +{ + int p; + uint_fast32_t mant; + uint_fast32_t expn; + int n; + + if (absdelta < 0) { + abort(); + } + + p = jpc_firstone(absdelta) - JPC_FIX_FRACBITS; + n = 11 - jpc_firstone(absdelta); + mant = ((n < 0) ? (absdelta >> (-n)) : (absdelta << n)) & 0x7ff; + expn = scaleexpn - p; + if (scaleexpn < p) { + abort(); + } + return JPC_QCX_EXPN(expn) | JPC_QCX_MANT(mant); +} + +typedef enum { + OPT_DEBUG, + OPT_IMGAREAOFFX, + OPT_IMGAREAOFFY, + OPT_TILEGRDOFFX, + OPT_TILEGRDOFFY, + OPT_TILEWIDTH, + OPT_TILEHEIGHT, + OPT_PRCWIDTH, + OPT_PRCHEIGHT, + OPT_CBLKWIDTH, + OPT_CBLKHEIGHT, + OPT_MODE, + OPT_PRG, + OPT_NOMCT, + OPT_MAXRLVLS, + OPT_SOP, + OPT_EPH, + OPT_LAZY, + OPT_TERMALL, + OPT_SEGSYM, + OPT_VCAUSAL, + OPT_RESET, + OPT_PTERM, + OPT_NUMGBITS, + OPT_RATE, + OPT_ILYRRATES, + OPT_JP2OVERHEAD +} optid_t; + +jas_taginfo_t encopts[] = { + {OPT_DEBUG, "debug"}, + {OPT_IMGAREAOFFX, "imgareatlx"}, + {OPT_IMGAREAOFFY, "imgareatly"}, + {OPT_TILEGRDOFFX, "tilegrdtlx"}, + {OPT_TILEGRDOFFY, "tilegrdtly"}, + {OPT_TILEWIDTH, "tilewidth"}, + {OPT_TILEHEIGHT, "tileheight"}, + {OPT_PRCWIDTH, "prcwidth"}, + {OPT_PRCHEIGHT, "prcheight"}, + {OPT_CBLKWIDTH, "cblkwidth"}, + {OPT_CBLKHEIGHT, "cblkheight"}, + {OPT_MODE, "mode"}, + {OPT_PRG, "prg"}, + {OPT_NOMCT, "nomct"}, + {OPT_MAXRLVLS, "numrlvls"}, + {OPT_SOP, "sop"}, + {OPT_EPH, "eph"}, + {OPT_LAZY, "lazy"}, + {OPT_TERMALL, "termall"}, + {OPT_SEGSYM, "segsym"}, + {OPT_VCAUSAL, "vcausal"}, + {OPT_PTERM, "pterm"}, + {OPT_RESET, "resetprob"}, + {OPT_NUMGBITS, "numgbits"}, + {OPT_RATE, "rate"}, + {OPT_ILYRRATES, "ilyrrates"}, + {OPT_JP2OVERHEAD, "_jp2overhead"}, + {-1, 0} +}; + +typedef enum { + PO_L = 0, + PO_R +} poid_t; + + +jas_taginfo_t prgordtab[] = { + {JPC_COD_LRCPPRG, "lrcp"}, + {JPC_COD_RLCPPRG, "rlcp"}, + {JPC_COD_RPCLPRG, "rpcl"}, + {JPC_COD_PCRLPRG, "pcrl"}, + {JPC_COD_CPRLPRG, "cprl"}, + {-1, 0} +}; + +typedef enum { + MODE_INT, + MODE_REAL +} modeid_t; + +jas_taginfo_t modetab[] = { + {MODE_INT, "int"}, + {MODE_REAL, "real"}, + {-1, 0} +}; + +/******************************************************************************\ +* The main encoder entry point. +\******************************************************************************/ + +int jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + jpc_enc_t *enc; + jpc_enc_cp_t *cp; + + enc = 0; + cp = 0; + + jpc_initluts(); + + if (!(cp = cp_create(optstr, image))) { + fprintf(stderr, "invalid JP encoder options\n"); + goto error; + } + + if (!(enc = jpc_enc_create(cp, out, image))) { + goto error; + } + cp = 0; + + /* Encode the main header. */ + if (jpc_enc_encodemainhdr(enc)) { + goto error; + } + + /* Encode the main body. This constitutes most of the encoding work. */ + if (jpc_enc_encodemainbody(enc)) { + goto error; + } + + /* Write EOC marker segment. */ + if (!(enc->mrk = jpc_ms_create(JPC_MS_EOC))) { + goto error; + } + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { + fprintf(stderr, "cannot write EOI marker\n"); + goto error; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + + if (jas_stream_flush(enc->out)) { + goto error; + } + + jpc_enc_destroy(enc); + + return 0; + +error: + if (cp) { + jpc_enc_cp_destroy(cp); + } + if (enc) { + jpc_enc_destroy(enc); + } + return -1; +} + +/******************************************************************************\ +* Option parsing code. +\******************************************************************************/ + +static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image) +{ + jpc_enc_cp_t *cp; + jas_tvparser_t *tvp; + int ret; + int numilyrrates; + double *ilyrrates; + int i; + int tagid; + jpc_enc_tcp_t *tcp; + jpc_enc_tccp_t *tccp; + jpc_enc_ccp_t *ccp; + int cmptno; + uint_fast16_t rlvlno; + uint_fast16_t prcwidthexpn; + uint_fast16_t prcheightexpn; + bool enablemct; + uint_fast32_t jp2overhead; + uint_fast16_t lyrno; + uint_fast32_t hsteplcm; + uint_fast32_t vsteplcm; + bool mctvalid; + + tvp = 0; + cp = 0; + ilyrrates = 0; + numilyrrates = 0; + + if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) { + goto error; + } + + prcwidthexpn = 15; + prcheightexpn = 15; + enablemct = true; + jp2overhead = 0; + + cp->ccps = 0; + cp->debug = 0; + cp->imgareatlx = UINT_FAST32_MAX; + cp->imgareatly = UINT_FAST32_MAX; + cp->refgrdwidth = 0; + cp->refgrdheight = 0; + cp->tilegrdoffx = UINT_FAST32_MAX; + cp->tilegrdoffy = UINT_FAST32_MAX; + cp->tilewidth = 0; + cp->tileheight = 0; + cp->numcmpts = jas_image_numcmpts(image); + + hsteplcm = 1; + vsteplcm = 1; + for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { + if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <= + jas_image_brx(image) || jas_image_cmptbry(image, cmptno) + + jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) { + fprintf(stderr, "unsupported image type\n"); + goto error; + } + /* Note: We ought to be calculating the LCMs here. Fix some day. */ + hsteplcm *= jas_image_cmpthstep(image, cmptno); + vsteplcm *= jas_image_cmptvstep(image, cmptno); + } + + if (!(cp->ccps = jas_malloc(cp->numcmpts * sizeof(jpc_enc_ccp_t)))) { + goto error; + } + for (cmptno = 0, ccp = cp->ccps; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, + ++ccp) { + ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno); + ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno); + /* XXX - this isn't quite correct for more general image */ + ccp->sampgrdsubstepx = 0; + ccp->sampgrdsubstepx = 0; + ccp->prec = jas_image_cmptprec(image, cmptno); + ccp->sgnd = jas_image_cmptsgnd(image, cmptno); + ccp->numstepsizes = 0; + memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes)); + } + + cp->rawsize = jas_image_rawsize(image); + cp->totalsize = UINT_FAST32_MAX; + + tcp = &cp->tcp; + tcp->csty = 0; + tcp->intmode = true; + tcp->prg = JPC_COD_LRCPPRG; + tcp->numlyrs = 1; + tcp->ilyrrates = 0; + + tccp = &cp->tccp; + tccp->csty = 0; + tccp->maxrlvls = 6; + tccp->cblkwidthexpn = 6; + tccp->cblkheightexpn = 6; + tccp->cblksty = 0; + tccp->numgbits = 2; + + if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { + goto error; + } + + while (!(ret = jas_tvparser_next(tvp))) { + switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts, + jas_tvparser_gettag(tvp)))->id) { + case OPT_DEBUG: + cp->debug = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_IMGAREAOFFX: + cp->imgareatlx = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_IMGAREAOFFY: + cp->imgareatly = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_TILEGRDOFFX: + cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_TILEGRDOFFY: + cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_TILEWIDTH: + cp->tilewidth = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_TILEHEIGHT: + cp->tileheight = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_PRCWIDTH: + prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); + break; + case OPT_PRCHEIGHT: + prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); + break; + case OPT_CBLKWIDTH: + tccp->cblkwidthexpn = + jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); + break; + case OPT_CBLKHEIGHT: + tccp->cblkheightexpn = + jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); + break; + case OPT_MODE: + if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab, + jas_tvparser_getval(tvp)))->id) < 0) { + fprintf(stderr, + "ignoring invalid mode %s\n", + jas_tvparser_getval(tvp)); + } else { + tcp->intmode = (tagid == MODE_INT); + } + break; + case OPT_PRG: + if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab, + jas_tvparser_getval(tvp)))->id) < 0) { + fprintf(stderr, + "ignoring invalid progression order %s\n", + jas_tvparser_getval(tvp)); + } else { + tcp->prg = tagid; + } + break; + case OPT_NOMCT: + enablemct = false; + break; + case OPT_MAXRLVLS: + tccp->maxrlvls = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_SOP: + cp->tcp.csty |= JPC_COD_SOP; + break; + case OPT_EPH: + cp->tcp.csty |= JPC_COD_EPH; + break; + case OPT_LAZY: + tccp->cblksty |= JPC_COX_LAZY; + break; + case OPT_TERMALL: + tccp->cblksty |= JPC_COX_TERMALL; + break; + case OPT_SEGSYM: + tccp->cblksty |= JPC_COX_SEGSYM; + break; + case OPT_VCAUSAL: + tccp->cblksty |= JPC_COX_VSC; + break; + case OPT_RESET: + tccp->cblksty |= JPC_COX_RESET; + break; + case OPT_PTERM: + tccp->cblksty |= JPC_COX_PTERM; + break; + case OPT_NUMGBITS: + cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp)); + break; + case OPT_RATE: + if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize, + &cp->totalsize)) { + fprintf(stderr, + "ignoring bad rate specifier %s\n", + jas_tvparser_getval(tvp)); + } + break; + case OPT_ILYRRATES: + if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates, + &ilyrrates)) { + fprintf(stderr, + "warning: invalid intermediate layer rates specifier ignored (%s)\n", + jas_tvparser_getval(tvp)); + } + break; + + case OPT_JP2OVERHEAD: + jp2overhead = atoi(jas_tvparser_getval(tvp)); + break; + default: + fprintf(stderr, "warning: ignoring invalid option %s\n", + jas_tvparser_gettag(tvp)); + break; + } + } + + jas_tvparser_destroy(tvp); + tvp = 0; + + if (cp->totalsize != UINT_FAST32_MAX) { + cp->totalsize = (cp->totalsize > jp2overhead) ? + (cp->totalsize - jp2overhead) : 0; + } + + if (cp->imgareatlx == UINT_FAST32_MAX) { + cp->imgareatlx = 0; + } else { + if (hsteplcm != 1) { + fprintf(stderr, "warning: overriding imgareatlx value\n"); + } + cp->imgareatlx *= hsteplcm; + } + if (cp->imgareatly == UINT_FAST32_MAX) { + cp->imgareatly = 0; + } else { + if (vsteplcm != 1) { + fprintf(stderr, "warning: overriding imgareatly value\n"); + } + cp->imgareatly *= vsteplcm; + } + cp->refgrdwidth = cp->imgareatlx + jas_image_width(image); + cp->refgrdheight = cp->imgareatly + jas_image_height(image); + if (cp->tilegrdoffx == UINT_FAST32_MAX) { + cp->tilegrdoffx = cp->imgareatlx; + } + if (cp->tilegrdoffy == UINT_FAST32_MAX) { + cp->tilegrdoffy = cp->imgareatly; + } + if (!cp->tilewidth) { + cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx; + } + if (!cp->tileheight) { + cp->tileheight = cp->refgrdheight - cp->tilegrdoffy; + } + + if (cp->numcmpts == 3) { + mctvalid = true; + for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { + if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) || + jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) || + jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) || + jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) { + mctvalid = false; + } + } + } else { + mctvalid = false; + } + if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) { + fprintf(stderr, "warning: color space apparently not RGB\n"); + } + if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) { + tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT); + } else { + tcp->mctid = JPC_MCT_NONE; + } + tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS); + + for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { + tccp->prcwidthexpns[rlvlno] = prcwidthexpn; + tccp->prcheightexpns[rlvlno] = prcheightexpn; + } + if (prcwidthexpn != 15 || prcheightexpn != 15) { + tccp->csty |= JPC_COX_PRT; + } + + /* Ensure that the tile width and height is valid. */ + if (!cp->tilewidth) { + fprintf(stderr, "invalid tile width %lu\n", (unsigned long) + cp->tilewidth); + goto error; + } + if (!cp->tileheight) { + fprintf(stderr, "invalid tile height %lu\n", (unsigned long) + cp->tileheight); + goto error; + } + + /* Ensure that the tile grid offset is valid. */ + if (cp->tilegrdoffx > cp->imgareatlx || + cp->tilegrdoffy > cp->imgareatly || + cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx || + cp->tilegrdoffy + cp->tileheight < cp->imgareatly) { + fprintf(stderr, "invalid tile grid offset (%lu, %lu)\n", + (unsigned long) cp->tilegrdoffx, (unsigned long) + cp->tilegrdoffy); + goto error; + } + + cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx, + cp->tilewidth); + cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy, + cp->tileheight); + cp->numtiles = cp->numhtiles * cp->numvtiles; + + if (ilyrrates && numilyrrates > 0) { + tcp->numlyrs = numilyrrates + 1; + if (!(tcp->ilyrrates = jas_malloc((tcp->numlyrs - 1) * + sizeof(jpc_fix_t)))) { + goto error; + } + for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) { + tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]); + } + } + + /* Ensure that the integer mode is used in the case of lossless + coding. */ + if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) { + fprintf(stderr, "cannot use real mode for lossless coding\n"); + goto error; + } + + /* Ensure that the precinct width is valid. */ + if (prcwidthexpn > 15) { + fprintf(stderr, "invalid precinct width\n"); + goto error; + } + + /* Ensure that the precinct height is valid. */ + if (prcheightexpn > 15) { + fprintf(stderr, "invalid precinct height\n"); + goto error; + } + + /* Ensure that the code block width is valid. */ + if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) { + fprintf(stderr, "invalid code block width %d\n", + JPC_POW2(cp->tccp.cblkwidthexpn)); + goto error; + } + + /* Ensure that the code block height is valid. */ + if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) { + fprintf(stderr, "invalid code block height %d\n", + JPC_POW2(cp->tccp.cblkheightexpn)); + goto error; + } + + /* Ensure that the code block size is not too large. */ + if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) { + fprintf(stderr, "code block size too large\n"); + goto error; + } + + /* Ensure that the number of layers is valid. */ + if (cp->tcp.numlyrs > 16384) { + fprintf(stderr, "too many layers\n"); + goto error; + } + + /* There must be at least one resolution level. */ + if (cp->tccp.maxrlvls < 1) { + fprintf(stderr, "must be at least one resolution level\n"); + goto error; + } + + /* Ensure that the number of guard bits is valid. */ + if (cp->tccp.numgbits > 8) { + fprintf(stderr, "invalid number of guard bits\n"); + goto error; + } + + /* Ensure that the rate is within the legal range. */ + if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) { + fprintf(stderr, "warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize); + } + + /* Ensure that the intermediate layer rates are valid. */ + if (tcp->numlyrs > 1) { + /* The intermediate layers rates must increase monotonically. */ + for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) { + if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) { + fprintf(stderr, "intermediate layer rates must increase monotonically\n"); + goto error; + } + } + /* The intermediate layer rates must be less than the overall rate. */ + if (cp->totalsize != UINT_FAST32_MAX) { + for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) { + if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize) + / cp->rawsize) { + fprintf(stderr, "warning: intermediate layer rates must be less than overall rate\n"); + goto error; + } + } + } + } + + if (ilyrrates) { + jas_free(ilyrrates); + } + + return cp; + +error: + + if (ilyrrates) { + jas_free(ilyrrates); + } + if (tvp) { + jas_tvparser_destroy(tvp); + } + if (cp) { + jpc_enc_cp_destroy(cp); + } + return 0; +} + +void jpc_enc_cp_destroy(jpc_enc_cp_t *cp) +{ + if (cp->ccps) { + if (cp->tcp.ilyrrates) { + jas_free(cp->tcp.ilyrrates); + } + jas_free(cp->ccps); + } + jas_free(cp); +} + +int ratestrtosize(char *s, uint_fast32_t rawsize, uint_fast32_t *size) +{ + char *cp; + jpc_flt_t f; + + /* Note: This function must not modify output size on failure. */ + if ((cp = strchr(s, 'B'))) { + *size = atoi(s); + } else { + f = atof(s); + if (f < 0) { + *size = 0; + } else if (f > 1.0) { + *size = rawsize + 1; + } else { + *size = (unsigned int)(f * rawsize); + } + } + return 0; +} + +/******************************************************************************\ +* Encoder constructor and destructor. +\******************************************************************************/ + +jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image) +{ + jpc_enc_t *enc; + + enc = 0; + + if (!(enc = jas_malloc(sizeof(jpc_enc_t)))) { + goto error; + } + + enc->image = image; + enc->out = out; + enc->cp = cp; + enc->cstate = 0; + enc->tmpstream = 0; + enc->mrk = 0; + enc->curtile = 0; + + if (!(enc->cstate = jpc_cstate_create())) { + goto error; + } + enc->len = 0; + enc->mainbodysize = 0; + + return enc; + +error: + + if (enc) { + jpc_enc_destroy(enc); + } + return 0; +} + +void jpc_enc_destroy(jpc_enc_t *enc) +{ + /* The image object (i.e., enc->image) and output stream object + (i.e., enc->out) are created outside of the encoder. + Therefore, they must not be destroyed here. */ + + if (enc->curtile) { + jpc_enc_tile_destroy(enc->curtile); + } + if (enc->cp) { + jpc_enc_cp_destroy(enc->cp); + } + if (enc->cstate) { + jpc_cstate_destroy(enc->cstate); + } + if (enc->tmpstream) { + jas_stream_close(enc->tmpstream); + } + + jas_free(enc); +} + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +static int jpc_calcssmant(jpc_fix_t stepsize) +{ + int n; + int e; + int m; + + n = jpc_firstone(stepsize); + e = n - JPC_FIX_FRACBITS; + if (n >= 11) { + m = (stepsize >> (n - 11)) & 0x7ff; + } else { + m = (stepsize & ((1 << n) - 1)) << (11 - n); + } + return m; +} + +static int jpc_calcssexp(jpc_fix_t stepsize) +{ + return jpc_firstone(stepsize) - JPC_FIX_FRACBITS; +} + +static int jpc_enc_encodemainhdr(jpc_enc_t *enc) +{ + jpc_siz_t *siz; + jpc_cod_t *cod; + jpc_qcd_t *qcd; + int i; +long startoff; +long mainhdrlen; + jpc_enc_cp_t *cp; + jpc_qcc_t *qcc; + jpc_enc_tccp_t *tccp; + uint_fast16_t cmptno; + jpc_tsfb_band_t bandinfos[JPC_MAXBANDS]; + jpc_fix_t mctsynweight; + jpc_enc_tcp_t *tcp; + jpc_tsfb_t *tsfb; + jpc_tsfb_band_t *bandinfo; + uint_fast16_t numbands; + uint_fast16_t bandno; + uint_fast16_t rlvlno; + uint_fast16_t analgain; + jpc_fix_t absstepsize; + char buf[1024]; + jpc_com_t *com; + + cp = enc->cp; + +startoff = jas_stream_getrwcount(enc->out); + + /* Write SOC marker segment. */ + if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) { + return -1; + } + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { + fprintf(stderr, "cannot write SOC marker\n"); + return -1; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + + /* Write SIZ marker segment. */ + if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) { + return -1; + } + siz = &enc->mrk->parms.siz; + siz->caps = 0; + siz->xoff = cp->imgareatlx; + siz->yoff = cp->imgareatly; + siz->width = cp->refgrdwidth; + siz->height = cp->refgrdheight; + siz->tilexoff = cp->tilegrdoffx; + siz->tileyoff = cp->tilegrdoffy; + siz->tilewidth = cp->tilewidth; + siz->tileheight = cp->tileheight; + siz->numcomps = cp->numcmpts; + siz->comps = jas_malloc(siz->numcomps * sizeof(jpc_sizcomp_t)); + assert(siz->comps); + for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) { + siz->comps[i].prec = cp->ccps[i].prec; + siz->comps[i].sgnd = cp->ccps[i].sgnd; + siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx; + siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy; + } + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { + fprintf(stderr, "cannot write SIZ marker\n"); + return -1; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + + if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) { + return -1; + } + sprintf(buf, "Creator: JasPer Version %s", jas_getversion()); + com = &enc->mrk->parms.com; + com->len = strlen(buf); + com->regid = JPC_COM_LATIN; + if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) { + abort(); + } + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { + fprintf(stderr, "cannot write COM marker\n"); + return -1; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + +#if 0 + if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) { + return -1; + } + crg = &enc->mrk->parms.crg; + crg->comps = jas_malloc(crg->numcomps * sizeof(jpc_crgcomp_t)); + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { + fprintf(stderr, "cannot write CRG marker\n"); + return -1; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; +#endif + + tcp = &cp->tcp; + tccp = &cp->tccp; + for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) { + tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1); + jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls, + bandinfos); + jpc_tsfb_destroy(tsfb); + mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno); + numbands = 3 * tccp->maxrlvls - 2; + for (bandno = 0, bandinfo = bandinfos; bandno < numbands; + ++bandno, ++bandinfo) { + rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0; + analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls, + rlvlno, bandinfo->orient); + if (!tcp->intmode) { + absstepsize = jpc_fix_div(jpc_inttofix(1 << + (analgain + 1)), bandinfo->synenergywt); + } else { + absstepsize = jpc_inttofix(1); + } + cp->ccps[cmptno].stepsizes[bandno] = + jpc_abstorelstepsize(absstepsize, + cp->ccps[cmptno].prec + analgain); + } + cp->ccps[cmptno].numstepsizes = numbands; + } + + if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { + return -1; + } + cod = &enc->mrk->parms.cod; + cod->csty = cp->tccp.csty | cp->tcp.csty; + cod->compparms.csty = cp->tccp.csty | cp->tcp.csty; + cod->compparms.numdlvls = cp->tccp.maxrlvls - 1; + cod->compparms.numrlvls = cp->tccp.maxrlvls; + cod->prg = cp->tcp.prg; + cod->numlyrs = cp->tcp.numlyrs; + cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn); + cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn); + cod->compparms.cblksty = cp->tccp.cblksty; + cod->compparms.qmfbid = cp->tccp.qmfbid; + cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE); + if (tccp->csty & JPC_COX_PRT) { + for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { + cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno]; + cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno]; + } + } + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { + fprintf(stderr, "cannot write COD marker\n"); + return -1; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + + if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) { + return -1; + } + qcd = &enc->mrk->parms.qcd; + qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? + JPC_QCX_SEQNT : JPC_QCX_NOQNT; + qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes; + qcd->compparms.numguard = cp->tccp.numgbits; + qcd->compparms.stepsizes = cp->ccps[0].stepsizes; + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { + return -1; + } + /* We do not want the step size array to be freed! */ + qcd->compparms.stepsizes = 0; + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + + tccp = &cp->tccp; + for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) { + if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { + return -1; + } + qcc = &enc->mrk->parms.qcc; + qcc->compno = cmptno; + qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? + JPC_QCX_SEQNT : JPC_QCX_NOQNT; + qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes; + qcc->compparms.numguard = cp->tccp.numgbits; + qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes; + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { + return -1; + } + /* We do not want the step size array to be freed! */ + qcc->compparms.stepsizes = 0; + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + } + +#define MAINTLRLEN 2 + mainhdrlen = jas_stream_getrwcount(enc->out) - startoff; + enc->len += mainhdrlen; + if (enc->cp->totalsize != UINT_FAST32_MAX) { + uint_fast32_t overhead; + overhead = mainhdrlen + MAINTLRLEN; + enc->mainbodysize = (enc->cp->totalsize >= overhead) ? + (enc->cp->totalsize - overhead) : 0; + } else { + enc->mainbodysize = UINT_FAST32_MAX; + } + + return 0; +} + +static int jpc_enc_encodemainbody(jpc_enc_t *enc) +{ + int tileno; + int tilex; + int tiley; + int i; + jpc_sot_t *sot; + jpc_enc_tcmpt_t *comp; + jpc_enc_tcmpt_t *endcomps; + jpc_enc_band_t *band; + jpc_enc_band_t *endbands; + jpc_enc_rlvl_t *lvl; + int rlvlno; + jpc_qcc_t *qcc; + jpc_cod_t *cod; + int adjust; + int j; + int absbandno; + long numbytes; + long tilehdrlen; + long tilelen; + jpc_enc_tile_t *tile; + jpc_enc_cp_t *cp; + double rho; + int lyrno; + int cmptno; + int samestepsizes; + jpc_enc_ccp_t *ccps; + jpc_enc_tccp_t *tccp; +int bandno; +uint_fast32_t x; +uint_fast32_t y; +int mingbits; +int actualnumbps; +jpc_fix_t mxmag; +jpc_fix_t mag; +int numgbits; + + cp = enc->cp; + + /* Avoid compile warnings. */ + numbytes = 0; + + for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) { + tilex = tileno % cp->numhtiles; + tiley = tileno / cp->numhtiles; + + if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno))) { + abort(); + } + + tile = enc->curtile; + + if (jas_getdbglevel() >= 10) { + jpc_enc_dump(enc); + } + + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) { + if (!cp->ccps[cmptno].sgnd) { + adjust = 1 << (cp->ccps[cmptno].prec - 1); + for (i = 0; i < jas_matrix_numrows(comp->data); ++i) { + for (j = 0; j < jas_matrix_numcols(comp->data); ++j) { + *jas_matrix_getref(comp->data, i, j) -= adjust; + } + } + } + } + + if (!tile->intmode) { + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + jas_matrix_asl(comp->data, JPC_FIX_FRACBITS); + } + } + + switch (tile->mctid) { + case JPC_MCT_RCT: +assert(jas_image_numcmpts(enc->image) == 3); + jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data, + tile->tcmpts[2].data); + break; + case JPC_MCT_ICT: +assert(jas_image_numcmpts(enc->image) == 3); + jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data, + tile->tcmpts[2].data); + break; + default: + break; + } + + for (i = 0; i < jas_image_numcmpts(enc->image); ++i) { + comp = &tile->tcmpts[i]; + jpc_tsfb_analyze(comp->tsfb, ((comp->qmfbid == JPC_COX_RFT) ? JPC_TSFB_RITIMODE : 0), comp->data); + + } + + + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) { + mingbits = 0; + absbandno = 0; + /* All bands must have a corresponding quantizer step size, + even if they contain no samples and are never coded. */ + /* Some bands may not be hit by the loop below, so we must + initialize all of the step sizes to a sane value. */ + memset(comp->stepsizes, 0, sizeof(comp->stepsizes)); + for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) { + if (!lvl->bands) { + absbandno += rlvlno ? 3 : 1; + continue; + } + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + ++absbandno; + continue; + } + actualnumbps = 0; + mxmag = 0; + for (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) { + for (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) { + mag = abs(jas_matrix_get(band->data, y, x)); + if (mag > mxmag) { + mxmag = mag; + } + } + } + if (tile->intmode) { + actualnumbps = jpc_firstone(mxmag) + 1; + } else { + actualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS; + } + numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 + + band->analgain); +#if 0 +fprintf(stderr, "%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits); +#endif + if (numgbits > mingbits) { + mingbits = numgbits; + } + if (!tile->intmode) { + band->absstepsize = jpc_fix_div(jpc_inttofix(1 + << (band->analgain + 1)), + band->synweight); + } else { + band->absstepsize = jpc_inttofix(1); + } + band->stepsize = jpc_abstorelstepsize( + band->absstepsize, cp->ccps[cmptno].prec + + band->analgain); + band->numbps = cp->tccp.numgbits + + JPC_QCX_GETEXPN(band->stepsize) - 1; + + if ((!tile->intmode) && band->data) { + quantize(band->data, band->absstepsize); + } + + comp->stepsizes[absbandno] = band->stepsize; + ++absbandno; + } + } + + assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS); + if (!tile->intmode) { + jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS); + } else { + jas_matrix_asl(comp->data, JPC_NUMEXTRABITS); + } + +#if 0 +fprintf(stderr, "mingbits %d\n", mingbits); +#endif + if (mingbits > cp->tccp.numgbits) { + fprintf(stderr, "error: too few guard bits (need at least %d)\n", + mingbits); + return -1; + } + } + + if (!(enc->tmpstream = jas_stream_memopen(0, 0))) { + fprintf(stderr, "cannot open tmp file\n"); + return -1; + } + + /* Write the tile header. */ + if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) { + return -1; + } + sot = &enc->mrk->parms.sot; + sot->len = 0; + sot->tileno = tileno; + sot->partno = 0; + sot->numparts = 1; + if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { + fprintf(stderr, "cannot write SOT marker\n"); + return -1; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + +/************************************************************************/ +/************************************************************************/ +/************************************************************************/ + + tccp = &cp->tccp; + for (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) { + comp = &tile->tcmpts[cmptno]; + if (comp->numrlvls != tccp->maxrlvls) { + if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { + return -1; + } +/* XXX = this is not really correct. we are using comp #0's precint sizes +and other characteristics */ + comp = &tile->tcmpts[0]; + cod = &enc->mrk->parms.cod; + cod->compparms.csty = 0; + cod->compparms.numdlvls = comp->numrlvls - 1; + cod->prg = tile->prg; + cod->numlyrs = tile->numlyrs; + cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn); + cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn); + cod->compparms.cblksty = comp->cblksty; + cod->compparms.qmfbid = comp->qmfbid; + cod->mctrans = (tile->mctid != JPC_MCT_NONE); + for (i = 0; i < comp->numrlvls; ++i) { + cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn; + cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn; + } + if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { + return -1; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + } + } + + for (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, ++comp) { + ccps = &cp->ccps[cmptno]; + if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) { + samestepsizes = 1; + for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes); ++bandno) { + if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) { + samestepsizes = 0; + break; + } + } + } else { + samestepsizes = 0; + } + if (!samestepsizes) { + if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { + return -1; + } + qcc = &enc->mrk->parms.qcc; + qcc->compno = cmptno; + qcc->compparms.numguard = cp->tccp.numgbits; + qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ? + JPC_QCX_SEQNT : JPC_QCX_NOQNT; + qcc->compparms.numstepsizes = comp->numstepsizes; + qcc->compparms.stepsizes = comp->stepsizes; + if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { + return -1; + } + qcc->compparms.stepsizes = 0; + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; + } + } + + /* Write a SOD marker to indicate the end of the tile header. */ + if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) { + return -1; + } + if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { + fprintf(stderr, "cannot write SOD marker\n"); + return -1; + } + jpc_ms_destroy(enc->mrk); + enc->mrk = 0; +tilehdrlen = jas_stream_getrwcount(enc->tmpstream); + +/************************************************************************/ +/************************************************************************/ +/************************************************************************/ + +if (jpc_enc_enccblks(enc)) { + abort(); + return -1; +} + + cp = enc->cp; + rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) / + ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight - + cp->imgareatly)); + tile->rawsize = (unsigned int)(cp->rawsize * rho); + + for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) { + tile->lyrsizes[lyrno] = (unsigned int)(tile->rawsize * jpc_fixtodbl( + cp->tcp.ilyrrates[lyrno])); + } + tile->lyrsizes[tile->numlyrs - 1] = (cp->totalsize != UINT_FAST32_MAX) ? + (unsigned int)(rho * enc->mainbodysize) : UINT_FAST32_MAX; + for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) { + if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) { + if (tilehdrlen <= JAS_CAST(long, tile->lyrsizes[lyrno])) { + tile->lyrsizes[lyrno] -= tilehdrlen; + } else { + tile->lyrsizes[lyrno] = 0; + } + } + } + + if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) { + return -1; + } + +#if 0 +fprintf(stderr, "ENCODE TILE DATA\n"); +#endif + if (jpc_enc_encodetiledata(enc)) { + fprintf(stderr, "dotile failed\n"); + return -1; + } + +/************************************************************************/ +/************************************************************************/ +/************************************************************************/ + +/************************************************************************/ +/************************************************************************/ +/************************************************************************/ + + tilelen = jas_stream_tell(enc->tmpstream); + + if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) { + return -1; + } + jpc_putuint32(enc->tmpstream, tilelen); + + if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) { + return -1; + } + if (jpc_putdata(enc->out, enc->tmpstream, -1)) { + return -1; + } + enc->len += tilelen; + + jas_stream_close(enc->tmpstream); + enc->tmpstream = 0; + + jpc_enc_tile_destroy(enc->curtile); + enc->curtile = 0; + + } + + return 0; +} + +int jpc_enc_encodetiledata(jpc_enc_t *enc) +{ +assert(enc->tmpstream); + if (jpc_enc_encpkts(enc, enc->tmpstream)) { + return -1; + } + return 0; +} + +int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk) +{ + jpc_enc_pass_t *pass; + int i; + jas_stream_memobj_t *smo; + + smo = cblk->stream->obj_; + + pass = passes; + for (i = 0; i < numpasses; ++i) { + fprintf(stderr, "start=%d end=%d type=%d term=%d lyrno=%d firstchar=%02x size=%ld pos=%ld\n", + (int)pass->start, (int)pass->end, (int)pass->type, (int)pass->term, (int)pass->lyrno, + smo->buf_[pass->start], (long)smo->len_, (long)smo->pos_); +#if 0 + jas_memdump(stderr, &smo->buf_[pass->start], pass->end - pass->start); +#endif + ++pass; + } + return 0; +} + +void quantize(jas_matrix_t *data, jpc_fix_t stepsize) +{ + int i; + int j; + jpc_fix_t t; + + if (stepsize == jpc_inttofix(1)) { + return; + } + + for (i = 0; i < jas_matrix_numrows(data); ++i) { + for (j = 0; j < jas_matrix_numcols(data); ++j) { + t = jas_matrix_get(data, i, j); + +{ + if (t < 0) { + t = jpc_fix_neg(jpc_fix_div(jpc_fix_neg(t), stepsize)); + } else { + t = jpc_fix_div(t, stepsize); + } +} + + jas_matrix_set(data, i, j, t); + } + } +} + +void calcrdslopes(jpc_enc_cblk_t *cblk) +{ + jpc_enc_pass_t *endpasses; + jpc_enc_pass_t *pass0; + jpc_enc_pass_t *pass1; + jpc_enc_pass_t *pass2; + jpc_flt_t slope0; + jpc_flt_t slope; + jpc_flt_t dd; + long dr; + + endpasses = &cblk->passes[cblk->numpasses]; + pass2 = cblk->passes; + slope0 = 0; + while (pass2 != endpasses) { + pass0 = 0; + for (pass1 = cblk->passes; pass1 != endpasses; ++pass1) { + dd = pass1->cumwmsedec; + dr = pass1->end; + if (pass0) { + dd -= pass0->cumwmsedec; + dr -= pass0->end; + } + if (dd <= 0) { + pass1->rdslope = JPC_BADRDSLOPE; + if (pass1 >= pass2) { + pass2 = &pass1[1]; + } + continue; + } + if (pass1 < pass2 && pass1->rdslope <= 0) { + continue; + } + if (!dr) { + assert(pass0); + pass0->rdslope = 0; + break; + } + slope = dd / dr; + if (pass0 && slope >= slope0) { + pass0->rdslope = 0; + break; + } + pass1->rdslope = slope; + if (pass1 >= pass2) { + pass2 = &pass1[1]; + } + pass0 = pass1; + slope0 = slope; + } + } + +#if 0 + for (pass0 = cblk->passes; pass0 != endpasses; ++pass0) { +if (pass0->rdslope > 0.0) { + fprintf(stderr, "pass %02d nmsedec=%lf dec=%lf end=%d %lf\n", pass0 - cblk->passes, + fixtodbl(pass0->nmsedec), pass0->wmsedec, pass0->end, pass0->rdslope); +} + } +#endif +} + +void dump_layeringinfo(jpc_enc_t *enc) +{ + + jpc_enc_tcmpt_t *tcmpt; + int tcmptno; + jpc_enc_rlvl_t *rlvl; + int rlvlno; + jpc_enc_band_t *band; + int bandno; + jpc_enc_prc_t *prc; + int prcno; + jpc_enc_cblk_t *cblk; + int cblkno; + jpc_enc_pass_t *pass; + int passno; + int lyrno; + jpc_enc_tile_t *tile; + + tile = enc->curtile; + + for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) { + fprintf(stderr, "lyrno = %02d\n", lyrno); + for (tcmptno = 0, tcmpt = tile->tcmpts; tcmptno < tile->numtcmpts; + ++tcmptno, ++tcmpt) { + for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls; + ++rlvlno, ++rlvl) { + if (!rlvl->bands) { + continue; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (!band->data) { + continue; + } + for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; + ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + for (cblkno = 0, cblk = prc->cblks; cblkno < + prc->numcblks; ++cblkno, ++cblk) { + for (passno = 0, pass = cblk->passes; passno < + cblk->numpasses && pass->lyrno == lyrno; + ++passno, ++pass) { + fprintf(stderr, "lyrno=%02d cmptno=%02d rlvlno=%02d bandno=%02d prcno=%02d cblkno=%03d passno=%03d\n", lyrno, tcmptno, rlvlno, bandno, prcno, cblkno, passno); + } + } + } + } + } + } + } +} + +int rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens) +{ + jpc_flt_t lo; + jpc_flt_t hi; + jas_stream_t *out; + long cumlen; + int lyrno; + jpc_flt_t thresh; + jpc_flt_t goodthresh; + int success; + long pos; + long oldpos; + int numiters; + + jpc_enc_tcmpt_t *comp; + jpc_enc_tcmpt_t *endcomps; + jpc_enc_rlvl_t *lvl; + jpc_enc_rlvl_t *endlvls; + jpc_enc_band_t *band; + jpc_enc_band_t *endbands; + jpc_enc_cblk_t *cblk; + jpc_enc_cblk_t *endcblks; + jpc_enc_pass_t *pass; + jpc_enc_pass_t *endpasses; + jpc_enc_pass_t *pass1; + jpc_flt_t mxrdslope; + jpc_flt_t mnrdslope; + jpc_enc_tile_t *tile; + jpc_enc_prc_t *prc; + int prcno; + + tile = enc->curtile; + + for (lyrno = 1; lyrno < numlyrs - 1; ++lyrno) { + if (cumlens[lyrno - 1] > cumlens[lyrno]) { + abort(); + } + } + + if (!(out = jas_stream_memopen(0, 0))) { + return -1; + } + + + /* Find minimum and maximum R-D slope values. */ + mnrdslope = DBL_MAX; + mxrdslope = 0; + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + endlvls = &comp->rlvls[comp->numrlvls]; + for (lvl = comp->rlvls; lvl != endlvls; ++lvl) { + if (!lvl->bands) { + continue; + } + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + calcrdslopes(cblk); + endpasses = &cblk->passes[cblk->numpasses]; + for (pass = cblk->passes; pass != endpasses; ++pass) { + if (pass->rdslope > 0) { + if (pass->rdslope < mnrdslope) { + mnrdslope = pass->rdslope; + } + if (pass->rdslope > mxrdslope) { + mxrdslope = pass->rdslope; + } + } + } + } + } + } + } + } +if (jas_getdbglevel()) { + fprintf(stderr, "min rdslope = %f max rdslope = %f\n", mnrdslope, mxrdslope); +} + + jpc_init_t2state(enc, 1); + + for (lyrno = 0; lyrno < numlyrs; ++lyrno) { + + lo = mnrdslope; + hi = mxrdslope; + + success = 0; + goodthresh = 0; + numiters = 0; + + do { + + cumlen = cumlens[lyrno]; + if (cumlen == UINT_FAST32_MAX) { + /* Only the last layer can be free of a rate + constraint (e.g., for lossless coding). */ + assert(lyrno == numlyrs - 1); + goodthresh = -1; + success = 1; + break; + } + + thresh = (lo + hi) / 2; + + /* Save the tier 2 coding state. */ + jpc_save_t2state(enc); + oldpos = jas_stream_tell(out); + assert(oldpos >= 0); + + /* Assign all passes with R-D slopes greater than or + equal to the current threshold to this layer. */ + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + endlvls = &comp->rlvls[comp->numrlvls]; + for (lvl = comp->rlvls; lvl != endlvls; ++lvl) { + if (!lvl->bands) { + continue; + } + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + if (cblk->curpass) { + endpasses = &cblk->passes[cblk->numpasses]; + pass1 = cblk->curpass; + for (pass = cblk->curpass; pass != endpasses; ++pass) { + if (pass->rdslope >= thresh) { + pass1 = &pass[1]; + } + } + for (pass = cblk->curpass; pass != pass1; ++pass) { + pass->lyrno = lyrno; + } + for (; pass != endpasses; ++pass) { + pass->lyrno = -1; + } + } + } + } + } + } + } + + /* Perform tier 2 coding. */ + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + endlvls = &comp->rlvls[comp->numrlvls]; + for (lvl = comp->rlvls; lvl != endlvls; ++lvl) { + if (!lvl->bands) { + continue; + } + for (prcno = 0; prcno < lvl->numprcs; ++prcno) { + if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) { + return -1; + } + } + } + } + + pos = jas_stream_tell(out); + + /* Check the rate constraint. */ + assert(pos >= 0); + if (pos > cumlen) { + /* The rate is too high. */ + lo = thresh; + } else if (pos <= cumlen) { + /* The rate is low enough, so try higher. */ + hi = thresh; + if (!success || thresh < goodthresh) { + goodthresh = thresh; + success = 1; + } + } + + /* Save the tier 2 coding state. */ + jpc_restore_t2state(enc); + if (jas_stream_seek(out, oldpos, SEEK_SET) < 0) { + abort(); + } + +if (jas_getdbglevel()) { +fprintf(stderr, "maxlen=%08ld actuallen=%08ld thresh=%f\n", cumlen, pos, thresh); +} + + ++numiters; + } while (lo < hi - 1e-3 && numiters < 32); + + if (!success) { + fprintf(stderr, "warning: empty layer generated\n"); + } + +if (jas_getdbglevel()) { +fprintf(stderr, "success %d goodthresh %f\n", success, goodthresh); +} + + /* Assign all passes with R-D slopes greater than or + equal to the selected threshold to this layer. */ + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + endlvls = &comp->rlvls[comp->numrlvls]; + for (lvl = comp->rlvls; lvl != endlvls; ++lvl) { +if (!lvl->bands) { + continue; +} + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + if (cblk->curpass) { + endpasses = &cblk->passes[cblk->numpasses]; + pass1 = cblk->curpass; + if (success) { + for (pass = cblk->curpass; pass != endpasses; ++pass) { + if (pass->rdslope >= goodthresh) { + pass1 = &pass[1]; + } + } + } + for (pass = cblk->curpass; pass != pass1; ++pass) { + pass->lyrno = lyrno; + } + for (; pass != endpasses; ++pass) { + pass->lyrno = -1; + } + } + } + } + } + } + } + + /* Perform tier 2 coding. */ + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + endlvls = &comp->rlvls[comp->numrlvls]; + for (lvl = comp->rlvls; lvl != endlvls; ++lvl) { + if (!lvl->bands) { + continue; + } + for (prcno = 0; prcno < lvl->numprcs; ++prcno) { + if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) { + return -1; + } + } + } + } + } + + if (jas_getdbglevel() >= 5) { + dump_layeringinfo(enc); + } + + jas_stream_close(out); + + JAS_DBGLOG(10, ("done doing rateallocation\n")); +#if 0 +fprintf(stderr, "DONE RATE ALLOCATE\n"); +#endif + + return 0; +} + +/******************************************************************************\ +* Tile constructors and destructors. +\******************************************************************************/ + +jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno) +{ + jpc_enc_tile_t *tile; + uint_fast32_t htileno; + uint_fast32_t vtileno; + uint_fast16_t lyrno; + uint_fast16_t cmptno; + jpc_enc_tcmpt_t *tcmpt; + + if (!(tile = jas_malloc(sizeof(jpc_enc_tile_t)))) { + goto error; + } + + /* Initialize a few members used in error recovery. */ + tile->tcmpts = 0; + tile->lyrsizes = 0; + tile->numtcmpts = cp->numcmpts; + tile->pi = 0; + + tile->tileno = tileno; + htileno = tileno % cp->numhtiles; + vtileno = tileno / cp->numhtiles; + + /* Calculate the coordinates of the top-left and bottom-right + corners of the tile. */ + tile->tlx = JAS_MAX(cp->tilegrdoffx + htileno * cp->tilewidth, + cp->imgareatlx); + tile->tly = JAS_MAX(cp->tilegrdoffy + vtileno * cp->tileheight, + cp->imgareatly); + tile->brx = JAS_MIN(cp->tilegrdoffx + (htileno + 1) * cp->tilewidth, + cp->refgrdwidth); + tile->bry = JAS_MIN(cp->tilegrdoffy + (vtileno + 1) * cp->tileheight, + cp->refgrdheight); + + /* Initialize some tile coding parameters. */ + tile->intmode = cp->tcp.intmode; + tile->csty = cp->tcp.csty; + tile->prg = cp->tcp.prg; + tile->mctid = cp->tcp.mctid; + + tile->numlyrs = cp->tcp.numlyrs; + if (!(tile->lyrsizes = jas_malloc(tile->numlyrs * + sizeof(uint_fast32_t)))) { + goto error; + } + for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) { + tile->lyrsizes[lyrno] = 0; + } + + /* Allocate an array for the per-tile-component information. */ + if (!(tile->tcmpts = jas_malloc(cp->numcmpts * sizeof(jpc_enc_tcmpt_t)))) { + goto error; + } + /* Initialize a few members critical for error recovery. */ + for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts; + ++cmptno, ++tcmpt) { + tcmpt->rlvls = 0; + tcmpt->tsfb = 0; + tcmpt->data = 0; + } + /* Initialize the per-tile-component information. */ + for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts; + ++cmptno, ++tcmpt) { + if (!tcmpt_create(tcmpt, cp, image, tile)) { + goto error; + } + } + + /* Initialize the synthesis weights for the MCT. */ + switch (tile->mctid) { + case JPC_MCT_RCT: + tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0)); + tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(0.6875)); + tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(0.6875)); + break; + case JPC_MCT_ICT: + tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0000)); + tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(3.2584)); + tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(2.4755)); + break; + default: + case JPC_MCT_NONE: + for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts; + ++cmptno, ++tcmpt) { + tcmpt->synweight = JPC_FIX_ONE; + } + break; + } + + if (!(tile->pi = jpc_enc_pi_create(cp, tile))) { + goto error; + } + + return tile; + +error: + + if (tile) { + jpc_enc_tile_destroy(tile); + } + return 0; +} + +void jpc_enc_tile_destroy(jpc_enc_tile_t *tile) +{ + jpc_enc_tcmpt_t *tcmpt; + uint_fast16_t cmptno; + + if (tile->tcmpts) { + for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < + tile->numtcmpts; ++cmptno, ++tcmpt) { + tcmpt_destroy(tcmpt); + } + jas_free(tile->tcmpts); + } + if (tile->lyrsizes) { + jas_free(tile->lyrsizes); + } + if (tile->pi) { + jpc_pi_destroy(tile->pi); + } + jas_free(tile); +} + +static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp, + jas_image_t *image, jpc_enc_tile_t *tile) +{ + uint_fast16_t cmptno; + uint_fast16_t rlvlno; + jpc_enc_rlvl_t *rlvl; + uint_fast32_t tlx; + uint_fast32_t tly; + uint_fast32_t brx; + uint_fast32_t bry; + uint_fast32_t cmpttlx; + uint_fast32_t cmpttly; + jpc_enc_ccp_t *ccp; + jpc_tsfb_band_t bandinfos[JPC_MAXBANDS]; + + tcmpt->tile = tile; + tcmpt->tsfb = 0; + tcmpt->data = 0; + tcmpt->rlvls = 0; + + /* Deduce the component number. */ + cmptno = tcmpt - tile->tcmpts; + + ccp = &cp->ccps[cmptno]; + + /* Compute the coordinates of the top-left and bottom-right + corners of this tile-component. */ + tlx = JPC_CEILDIV(tile->tlx, ccp->sampgrdstepx); + tly = JPC_CEILDIV(tile->tly, ccp->sampgrdstepy); + brx = JPC_CEILDIV(tile->brx, ccp->sampgrdstepx); + bry = JPC_CEILDIV(tile->bry, ccp->sampgrdstepy); + + /* Create a sequence to hold the tile-component sample data. */ + if (!(tcmpt->data = jas_seq2d_create(tlx, tly, brx, bry))) { + goto error; + } + + /* Get the image data associated with this tile-component. */ + cmpttlx = JPC_CEILDIV(cp->imgareatlx, ccp->sampgrdstepx); + cmpttly = JPC_CEILDIV(cp->imgareatly, ccp->sampgrdstepy); + if (jas_image_readcmpt(image, cmptno, tlx - cmpttlx, tly - cmpttly, + brx - tlx, bry - tly, tcmpt->data)) { + goto error; + } + + tcmpt->synweight = 0; + tcmpt->qmfbid = cp->tccp.qmfbid; + tcmpt->numrlvls = cp->tccp.maxrlvls; + tcmpt->numbands = 3 * tcmpt->numrlvls - 2; + if (!(tcmpt->tsfb = jpc_cod_gettsfb(tcmpt->qmfbid, tcmpt->numrlvls - 1))) { + goto error; + } + + for (rlvlno = 0; rlvlno < tcmpt->numrlvls; ++rlvlno) { + tcmpt->prcwidthexpns[rlvlno] = cp->tccp.prcwidthexpns[rlvlno]; + tcmpt->prcheightexpns[rlvlno] = cp->tccp.prcheightexpns[rlvlno]; + } + tcmpt->cblkwidthexpn = cp->tccp.cblkwidthexpn; + tcmpt->cblkheightexpn = cp->tccp.cblkheightexpn; + tcmpt->cblksty = cp->tccp.cblksty; + tcmpt->csty = cp->tccp.csty; + + tcmpt->numstepsizes = tcmpt->numbands; + assert(tcmpt->numstepsizes <= JPC_MAXBANDS); + memset(tcmpt->stepsizes, 0, sizeof(tcmpt->numstepsizes * + sizeof(uint_fast16_t))); + + /* Retrieve information about the various bands. */ + jpc_tsfb_getbands(tcmpt->tsfb, jas_seq2d_xstart(tcmpt->data), + jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data), + jas_seq2d_yend(tcmpt->data), bandinfos); + + if (!(tcmpt->rlvls = jas_malloc(tcmpt->numrlvls * sizeof(jpc_enc_rlvl_t)))) { + goto error; + } + for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls; + ++rlvlno, ++rlvl) { + rlvl->bands = 0; + rlvl->tcmpt = tcmpt; + } + for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls; + ++rlvlno, ++rlvl) { + if (!rlvl_create(rlvl, cp, tcmpt, bandinfos)) { + goto error; + } + } + + return tcmpt; + +error: + + tcmpt_destroy(tcmpt); + return 0; + +} + +static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt) +{ + jpc_enc_rlvl_t *rlvl; + uint_fast16_t rlvlno; + + if (tcmpt->rlvls) { + for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls; + ++rlvlno, ++rlvl) { + rlvl_destroy(rlvl); + } + jas_free(tcmpt->rlvls); + } + + if (tcmpt->data) { + jas_seq2d_destroy(tcmpt->data); + } + if (tcmpt->tsfb) { + jpc_tsfb_destroy(tcmpt->tsfb); + } +} + +static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp, + jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos) +{ + uint_fast16_t rlvlno; + uint_fast32_t tlprctlx; + uint_fast32_t tlprctly; + uint_fast32_t brprcbrx; + uint_fast32_t brprcbry; + uint_fast16_t bandno; + jpc_enc_band_t *band; + + /* Deduce the resolution level. */ + rlvlno = rlvl - tcmpt->rlvls; + + /* Initialize members required for error recovery. */ + rlvl->bands = 0; + rlvl->tcmpt = tcmpt; + + /* Compute the coordinates of the top-left and bottom-right + corners of the tile-component at this resolution. */ + rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + + if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) { + rlvl->numhprcs = 0; + rlvl->numvprcs = 0; + rlvl->numprcs = 0; + return rlvl; + } + + rlvl->numbands = (!rlvlno) ? 1 : 3; + rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno]; + rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno]; + if (!rlvlno) { + rlvl->cbgwidthexpn = rlvl->prcwidthexpn; + rlvl->cbgheightexpn = rlvl->prcheightexpn; + } else { + rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; + rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; + } + rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn); + rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn); + + /* Compute the number of precincts. */ + tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn); + tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn); + brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn); + brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn); + rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn); + rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn); + rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; + + if (!(rlvl->bands = jas_malloc(rlvl->numbands * sizeof(jpc_enc_band_t)))) { + goto error; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + band->prcs = 0; + band->data = 0; + band->rlvl = rlvl; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (!band_create(band, cp, rlvl, bandinfos)) { + goto error; + } + } + + return rlvl; +error: + + rlvl_destroy(rlvl); + return 0; +} + +static void rlvl_destroy(jpc_enc_rlvl_t *rlvl) +{ + jpc_enc_band_t *band; + uint_fast16_t bandno; + + if (rlvl->bands) { + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + band_destroy(band); + } + jas_free(rlvl->bands); + } +} + +static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp, + jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos) +{ + uint_fast16_t bandno; + uint_fast16_t gblbandno; + uint_fast16_t rlvlno; + jpc_tsfb_band_t *bandinfo; + jpc_enc_tcmpt_t *tcmpt; + uint_fast32_t prcno; + jpc_enc_prc_t *prc; + + tcmpt = rlvl->tcmpt; + band->data = 0; + band->prcs = 0; + band->rlvl = rlvl; + + /* Deduce the resolution level and band number. */ + rlvlno = rlvl - rlvl->tcmpt->rlvls; + bandno = band - rlvl->bands; + gblbandno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1); + + bandinfo = &bandinfos[gblbandno]; + +if (bandinfo->xstart != bandinfo->xend && bandinfo->ystart != bandinfo->yend) { + if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { + goto error; + } + jas_seq2d_bindsub(band->data, tcmpt->data, bandinfo->locxstart, + bandinfo->locystart, bandinfo->locxend, bandinfo->locyend); + jas_seq2d_setshift(band->data, bandinfo->xstart, bandinfo->ystart); +} + band->orient = bandinfo->orient; + band->analgain = JPC_NOMINALGAIN(cp->tccp.qmfbid, tcmpt->numrlvls, rlvlno, + band->orient); + band->numbps = 0; + band->absstepsize = 0; + band->stepsize = 0; + band->synweight = bandinfo->synenergywt; + +if (band->data) { + if (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_enc_prc_t)))) { + goto error; + } + for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, + ++prc) { + prc->cblks = 0; + prc->incltree = 0; + prc->nlibtree = 0; + prc->savincltree = 0; + prc->savnlibtree = 0; + prc->band = band; + } + for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, + ++prc) { + if (!prc_create(prc, cp, band)) { + goto error; + } + } +} + + return band; + +error: + band_destroy(band); + return 0; +} + +static void band_destroy(jpc_enc_band_t *band) +{ + jpc_enc_prc_t *prc; + jpc_enc_rlvl_t *rlvl; + uint_fast32_t prcno; + + if (band->prcs) { + rlvl = band->rlvl; + for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; + ++prcno, ++prc) { + prc_destroy(prc); + } + jas_free(band->prcs); + } + if (band->data) { + jas_seq2d_destroy(band->data); + } +} + +static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band) +{ + uint_fast32_t prcno; + uint_fast32_t prcxind; + uint_fast32_t prcyind; + uint_fast32_t cbgtlx; + uint_fast32_t cbgtly; + uint_fast32_t tlprctlx; + uint_fast32_t tlprctly; + uint_fast32_t tlcbgtlx; + uint_fast32_t tlcbgtly; + uint_fast16_t rlvlno; + jpc_enc_rlvl_t *rlvl; + uint_fast32_t tlcblktlx; + uint_fast32_t tlcblktly; + uint_fast32_t brcblkbrx; + uint_fast32_t brcblkbry; + uint_fast32_t cblkno; + jpc_enc_cblk_t *cblk; + jpc_enc_tcmpt_t *tcmpt; + + prc->cblks = 0; + prc->incltree = 0; + prc->savincltree = 0; + prc->nlibtree = 0; + prc->savnlibtree = 0; + + rlvl = band->rlvl; + tcmpt = rlvl->tcmpt; +rlvlno = rlvl - tcmpt->rlvls; + prcno = prc - band->prcs; + prcxind = prcno % rlvl->numhprcs; + prcyind = prcno / rlvl->numhprcs; + prc->band = band; + +tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn); +tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn); +if (!rlvlno) { + tlcbgtlx = tlprctlx; + tlcbgtly = tlprctly; +} else { + tlcbgtlx = JPC_CEILDIVPOW2(tlprctlx, 1); + tlcbgtly = JPC_CEILDIVPOW2(tlprctly, 1); +} + + /* Compute the coordinates of the top-left and bottom-right + corners of the precinct. */ + cbgtlx = tlcbgtlx + (prcxind << rlvl->cbgwidthexpn); + cbgtly = tlcbgtly + (prcyind << rlvl->cbgheightexpn); + prc->tlx = JAS_MAX(jas_seq2d_xstart(band->data), cbgtlx); + prc->tly = JAS_MAX(jas_seq2d_ystart(band->data), cbgtly); + prc->brx = JAS_MIN(jas_seq2d_xend(band->data), cbgtlx + + (1 << rlvl->cbgwidthexpn)); + prc->bry = JAS_MIN(jas_seq2d_yend(band->data), cbgtly + + (1 << rlvl->cbgheightexpn)); + + if (prc->tlx < prc->brx && prc->tly < prc->bry) { + /* The precinct contains at least one code block. */ + + tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn); + tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn); + brcblkbrx = JPC_CEILTOMULTPOW2(prc->brx, rlvl->cblkwidthexpn); + brcblkbry = JPC_CEILTOMULTPOW2(prc->bry, rlvl->cblkheightexpn); + prc->numhcblks = JPC_FLOORDIVPOW2(brcblkbrx - tlcblktlx, + rlvl->cblkwidthexpn); + prc->numvcblks = JPC_FLOORDIVPOW2(brcblkbry - tlcblktly, + rlvl->cblkheightexpn); + prc->numcblks = prc->numhcblks * prc->numvcblks; + + if (!(prc->incltree = jpc_tagtree_create(prc->numhcblks, + prc->numvcblks))) { + goto error; + } + if (!(prc->nlibtree = jpc_tagtree_create(prc->numhcblks, + prc->numvcblks))) { + goto error; + } + if (!(prc->savincltree = jpc_tagtree_create(prc->numhcblks, + prc->numvcblks))) { + goto error; + } + if (!(prc->savnlibtree = jpc_tagtree_create(prc->numhcblks, + prc->numvcblks))) { + goto error; + } + + if (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_enc_cblk_t)))) { + goto error; + } + for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; + ++cblkno, ++cblk) { + cblk->passes = 0; + cblk->stream = 0; + cblk->mqenc = 0; + cblk->data = 0; + cblk->flags = 0; + cblk->prc = prc; + } + for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; + ++cblkno, ++cblk) { + if (!cblk_create(cblk, cp, prc)) { + goto error; + } + } + } else { + /* The precinct does not contain any code blocks. */ + prc->tlx = prc->brx; + prc->tly = prc->bry; + prc->numcblks = 0; + prc->numhcblks = 0; + prc->numvcblks = 0; + prc->cblks = 0; + prc->incltree = 0; + prc->nlibtree = 0; + prc->savincltree = 0; + prc->savnlibtree = 0; + } + + return prc; + +error: + prc_destroy(prc); + return 0; +} + +static void prc_destroy(jpc_enc_prc_t *prc) +{ + jpc_enc_cblk_t *cblk; + uint_fast32_t cblkno; + + if (prc->cblks) { + for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; + ++cblkno, ++cblk) { + cblk_destroy(cblk); + } + jas_free(prc->cblks); + } + if (prc->incltree) { + jpc_tagtree_destroy(prc->incltree); + } + if (prc->nlibtree) { + jpc_tagtree_destroy(prc->nlibtree); + } + if (prc->savincltree) { + jpc_tagtree_destroy(prc->savincltree); + } + if (prc->savnlibtree) { + jpc_tagtree_destroy(prc->savnlibtree); + } +} + +static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp, jpc_enc_prc_t *prc) +{ + jpc_enc_band_t *band; + uint_fast32_t cblktlx; + uint_fast32_t cblktly; + uint_fast32_t cblkbrx; + uint_fast32_t cblkbry; + jpc_enc_rlvl_t *rlvl; + uint_fast32_t cblkxind; + uint_fast32_t cblkyind; + uint_fast32_t cblkno; + uint_fast32_t tlcblktlx; + uint_fast32_t tlcblktly; + + cblkno = cblk - prc->cblks; + cblkxind = cblkno % prc->numhcblks; + cblkyind = cblkno / prc->numhcblks; + rlvl = prc->band->rlvl; + cblk->prc = prc; + + cblk->numpasses = 0; + cblk->passes = 0; + cblk->numencpasses = 0; + cblk->numimsbs = 0; + cblk->numlenbits = 0; + cblk->stream = 0; + cblk->mqenc = 0; + cblk->flags = 0; + cblk->numbps = 0; + cblk->curpass = 0; + cblk->data = 0; + cblk->savedcurpass = 0; + cblk->savednumlenbits = 0; + cblk->savednumencpasses = 0; + + band = prc->band; + tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn); + tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn); + cblktlx = JAS_MAX(tlcblktlx + (cblkxind << rlvl->cblkwidthexpn), prc->tlx); + cblktly = JAS_MAX(tlcblktly + (cblkyind << rlvl->cblkheightexpn), prc->tly); + cblkbrx = JAS_MIN(tlcblktlx + ((cblkxind + 1) << rlvl->cblkwidthexpn), + prc->brx); + cblkbry = JAS_MIN(tlcblktly + ((cblkyind + 1) << rlvl->cblkheightexpn), + prc->bry); + + assert(cblktlx < cblkbrx && cblktly < cblkbry); + if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) { + goto error; + } + jas_seq2d_bindsub(cblk->data, band->data, cblktlx, cblktly, cblkbrx, cblkbry); + + return cblk; + +error: + cblk_destroy(cblk); + return 0; +} + +static void cblk_destroy(jpc_enc_cblk_t *cblk) +{ + uint_fast16_t passno; + jpc_enc_pass_t *pass; + if (cblk->passes) { + for (passno = 0, pass = cblk->passes; passno < cblk->numpasses; + ++passno, ++pass) { + pass_destroy(pass); + } + jas_free(cblk->passes); + } + if (cblk->stream) { + jas_stream_close(cblk->stream); + } + if (cblk->mqenc) { + jpc_mqenc_destroy(cblk->mqenc); + } + if (cblk->data) { + jas_seq2d_destroy(cblk->data); + } + if (cblk->flags) { + jas_seq2d_destroy(cblk->flags); + } +} + +static void pass_destroy(jpc_enc_pass_t *pass) +{ + /* XXX - need to free resources here */ +} + +void jpc_enc_dump(jpc_enc_t *enc) +{ + jpc_enc_tile_t *tile; + jpc_enc_tcmpt_t *tcmpt; + jpc_enc_rlvl_t *rlvl; + jpc_enc_band_t *band; + jpc_enc_prc_t *prc; + jpc_enc_cblk_t *cblk; + uint_fast16_t cmptno; + uint_fast16_t rlvlno; + uint_fast16_t bandno; + uint_fast32_t prcno; + uint_fast32_t cblkno; + + tile = enc->curtile; + + for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, + ++tcmpt) { + fprintf(stderr, " tcmpt %5d %5d %5d %5d\n", jas_seq2d_xstart(tcmpt->data), jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data), jas_seq2d_yend(tcmpt->data)); + for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls; + ++rlvlno, ++rlvl) { + fprintf(stderr, " rlvl %5d %5d %5d %5d\n", rlvl->tlx, rlvl->tly, rlvl->brx, rlvl->bry); + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (!band->data) { + continue; + } + fprintf(stderr, " band %5d %5d %5d %5d\n", jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data), jas_seq2d_yend(band->data)); + for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; + ++prcno, ++prc) { + fprintf(stderr, " prc %5d %5d %5d %5d (%5d %5d)\n", prc->tlx, prc->tly, prc->brx, prc->bry, prc->brx - prc->tlx, prc->bry - prc->tly); + if (!prc->cblks) { + continue; + } + for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; + ++cblkno, ++cblk) { + fprintf(stderr, " cblk %5d %5d %5d %5d\n", jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data), jas_seq2d_yend(cblk->data)); + } + } + } + } + } +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_enc.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_enc.h new file mode 100644 index 0000000..e0f7599 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_enc.h @@ -0,0 +1,695 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * $Id$ + */ + +#ifndef JPC_ENC_H +#define JPC_ENC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_seq.h" + +#include "jpc_t2cod.h" +#include "jpc_mqenc.h" +#include "jpc_cod.h" +#include "jpc_tagtree.h" +#include "jpc_cs.h" +#include "jpc_flt.h" +#include "jpc_tsfb.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* The number of bits used in various lookup tables. */ +#define JPC_NUMEXTRABITS JPC_NMSEDEC_FRACBITS + +/* An invalid R-D slope value. */ +#define JPC_BADRDSLOPE (-1) + +/******************************************************************************\ +* Coding parameters types. +\******************************************************************************/ + +/* Per-component coding paramters. */ + +typedef struct { + + /* The horizontal sampling period. */ + uint_fast8_t sampgrdstepx; + + /* The vertical sampling period. */ + uint_fast8_t sampgrdstepy; + + /* The sample alignment horizontal offset. */ + uint_fast8_t sampgrdsubstepx; + + /* The sample alignment vertical offset. */ + uint_fast8_t sampgrdsubstepy; + + /* The precision of the samples. */ + uint_fast8_t prec; + + /* The signedness of the samples. */ + bool sgnd; + + /* The number of step sizes. */ + uint_fast16_t numstepsizes; + + /* The quantizer step sizes. */ + uint_fast16_t stepsizes[JPC_MAXBANDS]; + +} jpc_enc_ccp_t; + +/* Per-tile coding parameters. */ + +typedef struct { + + /* The coding mode. */ + bool intmode; + + /* The coding style (i.e., SOP, EPH). */ + uint_fast8_t csty; + + /* The progression order. */ + uint_fast8_t prg; + + /* The multicomponent transform. */ + uint_fast8_t mctid; + + /* The number of layers. */ + uint_fast16_t numlyrs; + + /* The normalized bit rates associated with the various + intermediate layers. */ + jpc_fix_t *ilyrrates; + +} jpc_enc_tcp_t; + +/* Per tile-component coding parameters. */ + +typedef struct { + + /* The coding style (i.e., explicit precinct sizes). */ + uint_fast8_t csty; + + /* The maximum number of resolution levels allowed. */ + uint_fast8_t maxrlvls; + + /* The exponent for the nominal code block width. */ + uint_fast16_t cblkwidthexpn; + + /* The exponent for the nominal code block height. */ + uint_fast16_t cblkheightexpn; + + /* The code block style parameters (e.g., lazy, terminate all, + segmentation symbols, causal, reset probability models). */ + uint_fast8_t cblksty; + + /* The QMFB. */ + uint_fast8_t qmfbid; + + /* The precinct width values. */ + uint_fast16_t prcwidthexpns[JPC_MAXRLVLS]; + + /* The precinct height values. */ + uint_fast16_t prcheightexpns[JPC_MAXRLVLS]; + + /* The number of guard bits. */ + uint_fast8_t numgbits; + +} jpc_enc_tccp_t; + +/* Coding parameters. */ + +typedef struct { + + /* The debug level. */ + int debug; + + /* The horizontal offset from the origin of the reference grid to the + left edge of the image area. */ + uint_fast32_t imgareatlx; + + /* The vertical offset from the origin of the reference grid to the + top edge of the image area. */ + uint_fast32_t imgareatly; + + /* The horizontal offset from the origin of the reference grid to the + right edge of the image area (plus one). */ + uint_fast32_t refgrdwidth; + + /* The vertical offset from the origin of the reference grid to the + bottom edge of the image area (plus one). */ + uint_fast32_t refgrdheight; + + /* The horizontal offset from the origin of the tile grid to the + origin of the reference grid. */ + uint_fast32_t tilegrdoffx; + + /* The vertical offset from the origin of the tile grid to the + origin of the reference grid. */ + uint_fast32_t tilegrdoffy; + + /* The nominal tile width in units of the image reference grid. */ + uint_fast32_t tilewidth; + + /* The nominal tile height in units of the image reference grid. */ + uint_fast32_t tileheight; + + /* The number of tiles spanning the image area in the horizontal + direction. */ + uint_fast32_t numhtiles; + + /* The number of tiles spanning the image area in the vertical + direction. */ + uint_fast32_t numvtiles; + + /* The number of tiles. */ + uint_fast32_t numtiles; + + /* The number of components. */ + uint_fast16_t numcmpts; + + /* The per-component coding parameters. */ + jpc_enc_ccp_t *ccps; + + /* The per-tile coding parameters. */ + jpc_enc_tcp_t tcp; + + /* The per-tile-component coding parameters. */ + jpc_enc_tccp_t tccp; + + /* The target code stream length in bytes. */ + uint_fast32_t totalsize; + + /* The raw (i.e., uncompressed) size of the image in bytes. */ + uint_fast32_t rawsize; + +} jpc_enc_cp_t; + +/******************************************************************************\ +* Encoder class. +\******************************************************************************/ + +/* Encoder per-coding-pass state information. */ + +typedef struct { + + /* The starting offset for this pass. */ + int start; + + /* The ending offset for this pass. */ + int end; + + /* The type of data in this pass (i.e., MQ or raw). */ + int type; + + /* Flag indicating that this pass is terminated. */ + int term; + + /* The entropy coder state after coding this pass. */ + jpc_mqencstate_t mqencstate; + + /* The layer to which this pass has been assigned. */ + int lyrno; + + /* The R-D slope for this pass. */ + jpc_flt_t rdslope; + + /* The weighted MSE reduction associated with this pass. */ + jpc_flt_t wmsedec; + + /* The cumulative weighted MSE reduction. */ + jpc_flt_t cumwmsedec; + + /* The normalized MSE reduction. */ + long nmsedec; + +} jpc_enc_pass_t; + +/* Encoder per-code-block state information. */ + +typedef struct { + + /* The number of passes. */ + int numpasses; + + /* The per-pass information. */ + jpc_enc_pass_t *passes; + + /* The number of passes encoded so far. */ + int numencpasses; + + /* The number of insignificant MSBs. */ + int numimsbs; + + /* The number of bits used to encode pass data lengths. */ + int numlenbits; + + /* The byte stream for this code block. */ + jas_stream_t *stream; + + /* The entropy encoder. */ + jpc_mqenc_t *mqenc; + + /* The data for this code block. */ + jas_matrix_t *data; + + /* The state for this code block. */ + jas_matrix_t *flags; + + /* The number of bit planes required for this code block. */ + int numbps; + + /* The next pass to be encoded. */ + jpc_enc_pass_t *curpass; + + /* The per-code-block-group state information. */ + struct jpc_enc_prc_s *prc; + + /* The saved current pass. */ + /* This is used by the rate control code. */ + jpc_enc_pass_t *savedcurpass; + + /* The saved length indicator size. */ + /* This is used by the rate control code. */ + int savednumlenbits; + + /* The saved number of encoded passes. */ + /* This is used by the rate control code. */ + int savednumencpasses; + +} jpc_enc_cblk_t; + +/* Encoder per-code-block-group state information. */ + +typedef struct jpc_enc_prc_s { + + /* The x-coordinate of the top-left corner of the precinct. */ + uint_fast32_t tlx; + + /* The y-coordinate of the top-left corner of the precinct. */ + uint_fast32_t tly; + + /* The x-coordinate of the bottom-right corner of the precinct + (plus one). */ + uint_fast32_t brx; + + /* The y-coordinate of the bottom-right corner of the precinct + (plus one). */ + uint_fast32_t bry; + + /* The number of code blocks spanning the precinct in the horizontal + direction. */ + int numhcblks; + + /* The number of code blocks spanning the precinct in the vertical + direction. */ + int numvcblks; + + /* The total number of code blocks. */ + int numcblks; + + /* The per-code-block information. */ + jpc_enc_cblk_t *cblks; + + /* The inclusion tag tree. */ + jpc_tagtree_t *incltree; + + /* The insignifcant MSBs tag tree. */ + jpc_tagtree_t *nlibtree; + + /* The per-band information. */ + struct jpc_enc_band_s *band; + + /* The saved inclusion tag tree. */ + /* This is used by rate control. */ + jpc_tagtree_t *savincltree; + + /* The saved leading-insignificant-bit-planes tag tree. */ + /* This is used by rate control. */ + jpc_tagtree_t *savnlibtree; + +} jpc_enc_prc_t; + +/* Encoder per-band state information. */ + +typedef struct jpc_enc_band_s { + + /* The per precinct information. */ + jpc_enc_prc_t *prcs; + + /* The coefficient data for this band. */ + jas_matrix_t *data; + + /* The orientation of this band (i.e., LL, LH, HL, or HH). */ + int orient; + + /* The number of bit planes associated with this band. */ + int numbps; + + /* The quantizer step size. */ + jpc_fix_t absstepsize; + + /* The encoded quantizer step size. */ + int stepsize; + + /* The L2 norm of the synthesis basis functions associated with + this band. (The MCT is not considered in this value.) */ + jpc_fix_t synweight; + + /* The analysis gain for this band. */ + int analgain; + + /* The per-resolution-level information. */ + struct jpc_enc_rlvl_s *rlvl; + +} jpc_enc_band_t; + +/* Encoder per-resolution-level state information. */ + +typedef struct jpc_enc_rlvl_s { + + /* The x-coordinate of the top-left corner of the tile-component + at this resolution. */ + uint_fast32_t tlx; + + /* The y-coordinate of the top-left corner of the tile-component + at this resolution. */ + uint_fast32_t tly; + + /* The x-coordinate of the bottom-right corner of the tile-component + at this resolution (plus one). */ + uint_fast32_t brx; + + /* The y-coordinate of the bottom-right corner of the tile-component + at this resolution (plus one). */ + uint_fast32_t bry; + + /* The exponent value for the nominal precinct width measured + relative to the associated LL band. */ + int prcwidthexpn; + + /* The exponent value for the nominal precinct height measured + relative to the associated LL band. */ + int prcheightexpn; + + /* The number of precincts spanning the resolution level in the + horizontal direction. */ + int numhprcs; + + /* The number of precincts spanning the resolution level in the + vertical direction. */ + int numvprcs; + + /* The total number of precincts. */ + int numprcs; + + /* The exponent value for the nominal code block group width. + This quantity is associated with the next lower resolution level + (assuming that there is one). */ + int cbgwidthexpn; + + /* The exponent value for the nominal code block group height. + This quantity is associated with the next lower resolution level + (assuming that there is one). */ + int cbgheightexpn; + + /* The exponent value for the code block width. */ + uint_fast16_t cblkwidthexpn; + + /* The exponent value for the code block height. */ + uint_fast16_t cblkheightexpn; + + /* The number of bands associated with this resolution level. */ + int numbands; + + /* The per-band information. */ + jpc_enc_band_t *bands; + + /* The parent tile-component. */ + struct jpc_enc_tcmpt_s *tcmpt; + +} jpc_enc_rlvl_t; + +/* Encoder per-tile-component state information. */ + +typedef struct jpc_enc_tcmpt_s { + + /* The number of resolution levels. */ + int numrlvls; + + /* The per-resolution-level information. */ + jpc_enc_rlvl_t *rlvls; + + /* The tile-component data. */ + jas_matrix_t *data; + + /* The QMFB. */ + int qmfbid; + + /* The number of bands. */ + int numbands; + + /* The TSFB. */ + jpc_tsfb_t *tsfb; + + /* The synthesis energy weight (for the MCT). */ + jpc_fix_t synweight; + + /* The precinct width exponents. */ + int prcwidthexpns[JPC_MAXRLVLS]; + + /* The precinct height exponents. */ + int prcheightexpns[JPC_MAXRLVLS]; + + /* The code block width exponent. */ + int cblkwidthexpn; + + /* The code block height exponent. */ + int cblkheightexpn; + + /* Coding style (i.e., explicit precinct sizes). */ + int csty; + + /* Code block style. */ + int cblksty; + + /* The number of quantizer step sizes. */ + int numstepsizes; + + /* The encoded quantizer step sizes. */ + uint_fast16_t stepsizes[JPC_MAXBANDS]; + + /* The parent tile. */ + struct jpc_enc_tile_s *tile; + +} jpc_enc_tcmpt_t; + +/* Encoder per-tile state information. */ + +typedef struct jpc_enc_tile_s { + + /* The tile number. */ + uint_fast32_t tileno; + + /* The x-coordinate of the top-left corner of the tile measured with + respect to the reference grid. */ + uint_fast32_t tlx; + + /* The y-coordinate of the top-left corner of the tile measured with + respect to the reference grid. */ + uint_fast32_t tly; + + /* The x-coordinate of the bottom-right corner of the tile measured + with respect to the reference grid (plus one). */ + uint_fast32_t brx; + + /* The y-coordinate of the bottom-right corner of the tile measured + with respect to the reference grid (plus one). */ + uint_fast32_t bry; + + /* The coding style. */ + uint_fast8_t csty; + + /* The progression order. */ + uint_fast8_t prg; + + /* The number of layers. */ + int numlyrs; + + /* The MCT to employ (if any). */ + uint_fast8_t mctid; + + /* The packet iterator (used to determine the order of packet + generation). */ + jpc_pi_t *pi; + + /* The coding mode (i.e., integer or real). */ + bool intmode; + + /* The number of bytes to allocate to the various layers. */ + uint_fast32_t *lyrsizes; + + /* The number of tile-components. */ + int numtcmpts; + + /* The per tile-component information. */ + jpc_enc_tcmpt_t *tcmpts; + + /* The raw (i.e., uncompressed) size of this tile. */ + uint_fast32_t rawsize; + +} jpc_enc_tile_t; + +/* Encoder class. */ + +typedef struct jpc_enc_s { + + /* The image being encoded. */ + jas_image_t *image; + + /* The output stream. */ + jas_stream_t *out; + + /* The coding parameters. */ + jpc_enc_cp_t *cp; + + /* The tile currently being processed. */ + jpc_enc_tile_t *curtile; + + /* The code stream state. */ + jpc_cstate_t *cstate; + + /* The number of bytes output so far. */ + uint_fast32_t len; + + /* The number of bytes available for the main body of the code stream. */ + /* This is used for rate allocation purposes. */ + uint_fast32_t mainbodysize; + + /* The marker segment currently being processed. */ + /* This member is a convenience for making cleanup easier. */ + jpc_ms_t *mrk; + + /* The stream used to temporarily hold tile-part data. */ + jas_stream_t *tmpstream; + +} jpc_enc_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_fix.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_fix.h new file mode 100644 index 0000000..a084d8b --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_fix.h @@ -0,0 +1,193 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Fixed-Point Number Class + * + * $Id$ + */ + +#ifndef JPC_FIX_H +#define JPC_FIX_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" +#include "jasper/jas_fix.h" + +/******************************************************************************\ +* Basic parameters of the fixed-point type. +\******************************************************************************/ + +/* The integral type used to represent a fixed-point number. This + type must be capable of representing values from -(2^31) to 2^31-1 + (inclusive). */ +typedef int_fast32_t jpc_fix_t; + +/* The integral type used to respresent higher-precision intermediate results. + This type should be capable of representing values from -(2^63) to 2^63-1 + (inclusive). */ +typedef int_fast64_t jpc_fix_big_t; + +/* The number of bits used for the fractional part of a fixed-point number. */ +#define JPC_FIX_FRACBITS 13 + +/******************************************************************************\ +* Instantiations of the generic fixed-point number macros for the +* parameters given above. (Too bad C does not support templates, eh?) +* The purpose of these macros is self-evident if one examines the +* corresponding macros in the jasper/jas_fix.h header file. +\******************************************************************************/ + +#define JPC_FIX_ZERO JAS_FIX_ZERO(jpc_fix_t, JPC_FIX_FRACBITS) +#define JPC_FIX_ONE JAS_FIX_ONE(jpc_fix_t, JPC_FIX_FRACBITS) +#define JPC_FIX_HALF JAS_FIX_HALF(jpc_fix_t, JPC_FIX_FRACBITS) + +#define jpc_inttofix(x) JAS_INTTOFIX(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_fixtoint(x) JAS_FIXTOINT(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_fixtodbl(x) JAS_FIXTODBL(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_dbltofix(x) JAS_DBLTOFIX(jpc_fix_t, JPC_FIX_FRACBITS, x) + +#define jpc_fix_add(x, y) JAS_FIX_ADD(jpc_fix_t, JPC_FIX_FRACBITS, x, y) +#define jpc_fix_sub(x, y) JAS_FIX_SUB(jpc_fix_t, JPC_FIX_FRACBITS, x, y) +#define jpc_fix_mul(x, y) \ + JAS_FIX_MUL(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y) +#define jpc_fix_mulbyint(x, y) \ + JAS_FIX_MULBYINT(jpc_fix_t, JPC_FIX_FRACBITS, x, y) +#define jpc_fix_div(x, y) \ + JAS_FIX_DIV(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y) +#define jpc_fix_neg(x) JAS_FIX_NEG(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_fix_asl(x, n) JAS_FIX_ASL(jpc_fix_t, JPC_FIX_FRACBITS, x, n) +#define jpc_fix_asr(x, n) JAS_FIX_ASR(jpc_fix_t, JPC_FIX_FRACBITS, x, n) + +#define jpc_fix_pluseq(x, y) JAS_FIX_PLUSEQ(jpc_fix_t, JPC_FIX_FRACBITS, x, y) +#define jpc_fix_minuseq(x, y) JAS_FIX_MINUSEQ(jpc_fix_t, JPC_FIX_FRACBITS, x, y) +#define jpc_fix_muleq(x, y) \ + JAS_FIX_MULEQ(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y) + +#define jpc_fix_abs(x) JAS_FIX_ABS(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_fix_isint(x) JAS_FIX_ISINT(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_fix_sgn(x) JAS_FIX_SGN(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_fix_round(x) JAS_FIX_ROUND(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_fix_floor(x) JAS_FIX_FLOOR(jpc_fix_t, JPC_FIX_FRACBITS, x) +#define jpc_fix_trunc(x) JAS_FIX_TRUNC(jpc_fix_t, JPC_FIX_FRACBITS, x) + +/******************************************************************************\ +* Extra macros for convenience. +\******************************************************************************/ + +/* Compute the sum of three fixed-point numbers. */ +#define jpc_fix_add3(x, y, z) jpc_fix_add(jpc_fix_add(x, y), z) + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_flt.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_flt.h new file mode 100644 index 0000000..eeb0c0f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_flt.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Floating-Point Class + * + * $Id$ + */ + +#ifndef JPC_FLT_H +#define JPC_FLT_H + +#include + +/* The code ought to be modified so this type is not used at all. */ +/* Very few places in the code rely on floating-point arithmetic, aside + from conversions in printf's. */ +typedef double jpc_flt_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_math.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_math.c new file mode 100644 index 0000000..504e774 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_math.c @@ -0,0 +1,170 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Math Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes +\******************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include "jpc_math.h" + +/******************************************************************************\ +* Miscellaneous Functions +\******************************************************************************/ + +/* Calculate the integer quantity floor(log2(x)), where x is a positive + integer. */ +int jpc_floorlog2(int x) +{ + int y; + + /* The argument must be positive. */ + assert(x > 0); + + y = 0; + while (x > 1) { + x >>= 1; + ++y; + } + return y; +} + +/* Calculate the bit position of the first leading one in a nonnegative + integer. */ +/* This function is the basically the same as ceillog2(x), except that the + allowable range for x is slightly different. */ +int jpc_firstone(int x) +{ + int n; + + /* The argument must be nonnegative. */ + assert(x >= 0); + + n = -1; + while (x > 0) { + x >>= 1; + ++n; + } + return n; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_math.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_math.h new file mode 100644 index 0000000..0373532 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_math.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JPC_MATH_H +#define JPC_MATH_H + +/******************************************************************************\ +* Includes +\******************************************************************************/ + +#include + +/******************************************************************************\ +* Macros +\******************************************************************************/ + +/* Compute the floor of the quotient of two integers. */ +#define JPC_FLOORDIV(x, y) ((x) / (y)) + +/* Compute the ceiling of the quotient of two integers. */ +#define JPC_CEILDIV(x, y) (((x) + (y) - 1) / (y)) + +/* Compute the floor of (x / 2^y). */ +#define JPC_FLOORDIVPOW2(x, y) ((x) >> (y)) + +/* Compute the ceiling of (x / 2^y). */ +#define JPC_CEILDIVPOW2(x, y) (((x) + (1 << (y)) - 1) >> (y)) + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Calculate the bit position of the first leading one in a nonnegative + integer. */ +int jpc_firstone(int x); + +/* Calculate the integer quantity floor(log2(x)), where x is a positive + integer. */ +int jpc_floorlog2(int x); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mct.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mct.c new file mode 100644 index 0000000..0301f57 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mct.c @@ -0,0 +1,340 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Multicomponent Transform Code + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_seq.h" + +#include "jpc_fix.h" +#include "jpc_mct.h" + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +/* Compute the forward RCT. */ + +void jpc_rct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2) +{ + int numrows; + int numcols; + int i; + int j; + jpc_fix_t *c0p; + jpc_fix_t *c1p; + jpc_fix_t *c2p; + + numrows = jas_matrix_numrows(c0); + numcols = jas_matrix_numcols(c0); + + /* All three matrices must have the same dimensions. */ + assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols + && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols); + + for (i = 0; i < numrows; i++) { + c0p = jas_matrix_getref(c0, i, 0); + c1p = jas_matrix_getref(c1, i, 0); + c2p = jas_matrix_getref(c2, i, 0); + for (j = numcols; j > 0; --j) { + int r; + int g; + int b; + int y; + int u; + int v; + r = *c0p; + g = *c1p; + b = *c2p; + y = (r + (g << 1) + b) >> 2; + u = b - g; + v = r - g; + *c0p++ = y; + *c1p++ = u; + *c2p++ = v; + } + } +} + +/* Compute the inverse RCT. */ + +void jpc_irct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2) +{ + int numrows; + int numcols; + int i; + int j; + jpc_fix_t *c0p; + jpc_fix_t *c1p; + jpc_fix_t *c2p; + + numrows = jas_matrix_numrows(c0); + numcols = jas_matrix_numcols(c0); + + /* All three matrices must have the same dimensions. */ + assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols + && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols); + + for (i = 0; i < numrows; i++) { + c0p = jas_matrix_getref(c0, i, 0); + c1p = jas_matrix_getref(c1, i, 0); + c2p = jas_matrix_getref(c2, i, 0); + for (j = numcols; j > 0; --j) { + int r; + int g; + int b; + int y; + int u; + int v; + y = *c0p; + u = *c1p; + v = *c2p; + g = y - ((u + v) >> 2); + r = v + g; + b = u + g; + *c0p++ = r; + *c1p++ = g; + *c2p++ = b; + } + } +} + +void jpc_ict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2) +{ + int numrows; + int numcols; + int i; + int j; + jpc_fix_t r; + jpc_fix_t g; + jpc_fix_t b; + jpc_fix_t y; + jpc_fix_t u; + jpc_fix_t v; + jpc_fix_t *c0p; + jpc_fix_t *c1p; + jpc_fix_t *c2p; + + numrows = jas_matrix_numrows(c0); + assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows); + numcols = jas_matrix_numcols(c0); + assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols); + for (i = 0; i < numrows; ++i) { + c0p = jas_matrix_getref(c0, i, 0); + c1p = jas_matrix_getref(c1, i, 0); + c2p = jas_matrix_getref(c2, i, 0); + for (j = numcols; j > 0; --j) { + r = *c0p; + g = *c1p; + b = *c2p; + y = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.299), r), jpc_fix_mul(jpc_dbltofix(0.587), g), + jpc_fix_mul(jpc_dbltofix(0.114), b)); + u = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(-0.16875), r), jpc_fix_mul(jpc_dbltofix(-0.33126), g), + jpc_fix_mul(jpc_dbltofix(0.5), b)); + v = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.5), r), jpc_fix_mul(jpc_dbltofix(-0.41869), g), + jpc_fix_mul(jpc_dbltofix(-0.08131), b)); + *c0p++ = y; + *c1p++ = u; + *c2p++ = v; + } + } +} + +void jpc_iict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2) +{ + int numrows; + int numcols; + int i; + int j; + jpc_fix_t r; + jpc_fix_t g; + jpc_fix_t b; + jpc_fix_t y; + jpc_fix_t u; + jpc_fix_t v; + jpc_fix_t *c0p; + jpc_fix_t *c1p; + jpc_fix_t *c2p; + + numrows = jas_matrix_numrows(c0); + assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows); + numcols = jas_matrix_numcols(c0); + assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols); + for (i = 0; i < numrows; ++i) { + c0p = jas_matrix_getref(c0, i, 0); + c1p = jas_matrix_getref(c1, i, 0); + c2p = jas_matrix_getref(c2, i, 0); + for (j = numcols; j > 0; --j) { + y = *c0p; + u = *c1p; + v = *c2p; + r = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.402), v)); + g = jpc_fix_add3(y, jpc_fix_mul(jpc_dbltofix(-0.34413), u), + jpc_fix_mul(jpc_dbltofix(-0.71414), v)); + b = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.772), u)); + *c0p++ = r; + *c1p++ = g; + *c2p++ = b; + } + } +} + +jpc_fix_t jpc_mct_getsynweight(int mctid, int cmptno) +{ + jpc_fix_t synweight; + + synweight = JPC_FIX_ONE; + switch (mctid) { + case JPC_MCT_RCT: + switch (cmptno) { + case 0: + synweight = jpc_dbltofix(sqrt(3.0)); + break; + case 1: + synweight = jpc_dbltofix(sqrt(0.6875)); + break; + case 2: + synweight = jpc_dbltofix(sqrt(0.6875)); + break; + } + break; + case JPC_MCT_ICT: + switch (cmptno) { + case 0: + synweight = jpc_dbltofix(sqrt(3.0000)); + break; + case 1: + synweight = jpc_dbltofix(sqrt(3.2584)); + break; + case 2: + synweight = jpc_dbltofix(sqrt(2.4755)); + break; + } + break; +#if 0 + default: + synweight = JPC_FIX_ONE; + break; +#endif + } + + return synweight; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mct.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mct.h new file mode 100644 index 0000000..10f3336 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mct.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Multicomponent Transform Code + * + * $Id$ + */ + +#ifndef JPC_MCT_H +#define JPC_MCT_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_seq.h" +#include "jasper/jas_fix.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* + * Multicomponent transform IDs. + */ + +#define JPC_MCT_NONE 0 +#define JPC_MCT_ICT 1 +#define JPC_MCT_RCT 2 + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Calculate the forward RCT. */ +void jpc_rct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2); + +/* Calculate the inverse RCT. */ +void jpc_irct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2); + +/* Calculate the forward ICT. */ +void jpc_ict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2); + +/* Calculate the inverse ICT. */ +void jpc_iict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2); + +/* Get the synthesis weight associated with a particular component. */ +jpc_fix_t jpc_mct_getsynweight(int mctid, int cmptno); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqcod.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqcod.c new file mode 100644 index 0000000..e590dd0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqcod.c @@ -0,0 +1,228 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * MQ Arithmetic Coder + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_malloc.h" + +#include "jpc_mqcod.h" + +/******************************************************************************\ +* Data. +\******************************************************************************/ + +/* MQ coder per-state information. */ + +jpc_mqstate_t jpc_mqstates[47 * 2] = { + {0x5601, 0, &jpc_mqstates[ 2], &jpc_mqstates[ 3]}, + {0x5601, 1, &jpc_mqstates[ 3], &jpc_mqstates[ 2]}, + {0x3401, 0, &jpc_mqstates[ 4], &jpc_mqstates[12]}, + {0x3401, 1, &jpc_mqstates[ 5], &jpc_mqstates[13]}, + {0x1801, 0, &jpc_mqstates[ 6], &jpc_mqstates[18]}, + {0x1801, 1, &jpc_mqstates[ 7], &jpc_mqstates[19]}, + {0x0ac1, 0, &jpc_mqstates[ 8], &jpc_mqstates[24]}, + {0x0ac1, 1, &jpc_mqstates[ 9], &jpc_mqstates[25]}, + {0x0521, 0, &jpc_mqstates[10], &jpc_mqstates[58]}, + {0x0521, 1, &jpc_mqstates[11], &jpc_mqstates[59]}, + {0x0221, 0, &jpc_mqstates[76], &jpc_mqstates[66]}, + {0x0221, 1, &jpc_mqstates[77], &jpc_mqstates[67]}, + {0x5601, 0, &jpc_mqstates[14], &jpc_mqstates[13]}, + {0x5601, 1, &jpc_mqstates[15], &jpc_mqstates[12]}, + {0x5401, 0, &jpc_mqstates[16], &jpc_mqstates[28]}, + {0x5401, 1, &jpc_mqstates[17], &jpc_mqstates[29]}, + {0x4801, 0, &jpc_mqstates[18], &jpc_mqstates[28]}, + {0x4801, 1, &jpc_mqstates[19], &jpc_mqstates[29]}, + {0x3801, 0, &jpc_mqstates[20], &jpc_mqstates[28]}, + {0x3801, 1, &jpc_mqstates[21], &jpc_mqstates[29]}, + {0x3001, 0, &jpc_mqstates[22], &jpc_mqstates[34]}, + {0x3001, 1, &jpc_mqstates[23], &jpc_mqstates[35]}, + {0x2401, 0, &jpc_mqstates[24], &jpc_mqstates[36]}, + {0x2401, 1, &jpc_mqstates[25], &jpc_mqstates[37]}, + {0x1c01, 0, &jpc_mqstates[26], &jpc_mqstates[40]}, + {0x1c01, 1, &jpc_mqstates[27], &jpc_mqstates[41]}, + {0x1601, 0, &jpc_mqstates[58], &jpc_mqstates[42]}, + {0x1601, 1, &jpc_mqstates[59], &jpc_mqstates[43]}, + {0x5601, 0, &jpc_mqstates[30], &jpc_mqstates[29]}, + {0x5601, 1, &jpc_mqstates[31], &jpc_mqstates[28]}, + {0x5401, 0, &jpc_mqstates[32], &jpc_mqstates[28]}, + {0x5401, 1, &jpc_mqstates[33], &jpc_mqstates[29]}, + {0x5101, 0, &jpc_mqstates[34], &jpc_mqstates[30]}, + {0x5101, 1, &jpc_mqstates[35], &jpc_mqstates[31]}, + {0x4801, 0, &jpc_mqstates[36], &jpc_mqstates[32]}, + {0x4801, 1, &jpc_mqstates[37], &jpc_mqstates[33]}, + {0x3801, 0, &jpc_mqstates[38], &jpc_mqstates[34]}, + {0x3801, 1, &jpc_mqstates[39], &jpc_mqstates[35]}, + {0x3401, 0, &jpc_mqstates[40], &jpc_mqstates[36]}, + {0x3401, 1, &jpc_mqstates[41], &jpc_mqstates[37]}, + {0x3001, 0, &jpc_mqstates[42], &jpc_mqstates[38]}, + {0x3001, 1, &jpc_mqstates[43], &jpc_mqstates[39]}, + {0x2801, 0, &jpc_mqstates[44], &jpc_mqstates[38]}, + {0x2801, 1, &jpc_mqstates[45], &jpc_mqstates[39]}, + {0x2401, 0, &jpc_mqstates[46], &jpc_mqstates[40]}, + {0x2401, 1, &jpc_mqstates[47], &jpc_mqstates[41]}, + {0x2201, 0, &jpc_mqstates[48], &jpc_mqstates[42]}, + {0x2201, 1, &jpc_mqstates[49], &jpc_mqstates[43]}, + {0x1c01, 0, &jpc_mqstates[50], &jpc_mqstates[44]}, + {0x1c01, 1, &jpc_mqstates[51], &jpc_mqstates[45]}, + {0x1801, 0, &jpc_mqstates[52], &jpc_mqstates[46]}, + {0x1801, 1, &jpc_mqstates[53], &jpc_mqstates[47]}, + {0x1601, 0, &jpc_mqstates[54], &jpc_mqstates[48]}, + {0x1601, 1, &jpc_mqstates[55], &jpc_mqstates[49]}, + {0x1401, 0, &jpc_mqstates[56], &jpc_mqstates[50]}, + {0x1401, 1, &jpc_mqstates[57], &jpc_mqstates[51]}, + {0x1201, 0, &jpc_mqstates[58], &jpc_mqstates[52]}, + {0x1201, 1, &jpc_mqstates[59], &jpc_mqstates[53]}, + {0x1101, 0, &jpc_mqstates[60], &jpc_mqstates[54]}, + {0x1101, 1, &jpc_mqstates[61], &jpc_mqstates[55]}, + {0x0ac1, 0, &jpc_mqstates[62], &jpc_mqstates[56]}, + {0x0ac1, 1, &jpc_mqstates[63], &jpc_mqstates[57]}, + {0x09c1, 0, &jpc_mqstates[64], &jpc_mqstates[58]}, + {0x09c1, 1, &jpc_mqstates[65], &jpc_mqstates[59]}, + {0x08a1, 0, &jpc_mqstates[66], &jpc_mqstates[60]}, + {0x08a1, 1, &jpc_mqstates[67], &jpc_mqstates[61]}, + {0x0521, 0, &jpc_mqstates[68], &jpc_mqstates[62]}, + {0x0521, 1, &jpc_mqstates[69], &jpc_mqstates[63]}, + {0x0441, 0, &jpc_mqstates[70], &jpc_mqstates[64]}, + {0x0441, 1, &jpc_mqstates[71], &jpc_mqstates[65]}, + {0x02a1, 0, &jpc_mqstates[72], &jpc_mqstates[66]}, + {0x02a1, 1, &jpc_mqstates[73], &jpc_mqstates[67]}, + {0x0221, 0, &jpc_mqstates[74], &jpc_mqstates[68]}, + {0x0221, 1, &jpc_mqstates[75], &jpc_mqstates[69]}, + {0x0141, 0, &jpc_mqstates[76], &jpc_mqstates[70]}, + {0x0141, 1, &jpc_mqstates[77], &jpc_mqstates[71]}, + {0x0111, 0, &jpc_mqstates[78], &jpc_mqstates[72]}, + {0x0111, 1, &jpc_mqstates[79], &jpc_mqstates[73]}, + {0x0085, 0, &jpc_mqstates[80], &jpc_mqstates[74]}, + {0x0085, 1, &jpc_mqstates[81], &jpc_mqstates[75]}, + {0x0049, 0, &jpc_mqstates[82], &jpc_mqstates[76]}, + {0x0049, 1, &jpc_mqstates[83], &jpc_mqstates[77]}, + {0x0025, 0, &jpc_mqstates[84], &jpc_mqstates[78]}, + {0x0025, 1, &jpc_mqstates[85], &jpc_mqstates[79]}, + {0x0015, 0, &jpc_mqstates[86], &jpc_mqstates[80]}, + {0x0015, 1, &jpc_mqstates[87], &jpc_mqstates[81]}, + {0x0009, 0, &jpc_mqstates[88], &jpc_mqstates[82]}, + {0x0009, 1, &jpc_mqstates[89], &jpc_mqstates[83]}, + {0x0005, 0, &jpc_mqstates[90], &jpc_mqstates[84]}, + {0x0005, 1, &jpc_mqstates[91], &jpc_mqstates[85]}, + {0x0001, 0, &jpc_mqstates[90], &jpc_mqstates[86]}, + {0x0001, 1, &jpc_mqstates[91], &jpc_mqstates[87]}, + {0x5601, 0, &jpc_mqstates[92], &jpc_mqstates[92]}, + {0x5601, 1, &jpc_mqstates[93], &jpc_mqstates[93]}, +}; diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqcod.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqcod.h new file mode 100644 index 0000000..33a58a5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqcod.h @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * MQ Arithmetic Coder + * + * $Id$ + */ + +#ifndef JPC_MQCOD_H +#define JPC_MQCOD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* + * MQ coder context information. + */ + +typedef struct { + + /* The most probable symbol (MPS). */ + int mps; + + /* The state index. */ + int_fast16_t ind; + +} jpc_mqctx_t; + +/* + * MQ coder state table entry. + */ + +typedef struct jpc_mqstate_s { + + /* The Qe value. */ + uint_fast16_t qeval; + + /* The MPS. */ + int mps; + + /* The NMPS state. */ + struct jpc_mqstate_s *nmps; + + /* The NLPS state. */ + struct jpc_mqstate_s *nlps; + +} jpc_mqstate_t; + +/******************************************************************************\ +* Data. +\******************************************************************************/ + +/* The state table for the MQ coder. */ +extern jpc_mqstate_t jpc_mqstates[]; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqdec.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqdec.c new file mode 100644 index 0000000..301e7c2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqdec.c @@ -0,0 +1,355 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * MQ Arithmetic Decoder + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" +#include "jasper/jas_debug.h" + +#include "jpc_mqdec.h" + +/******************************************************************************\ +* Local macros. +\******************************************************************************/ + +#if defined(DEBUG) +#define MQDEC_CALL(n, x) \ + ((jas_getdbglevel() >= (n)) ? ((void)(x)) : ((void)0)) +#else +#define MQDEC_CALL(n, x) +#endif + +/******************************************************************************\ +* Local function prototypes. +\******************************************************************************/ + +static void jpc_mqdec_bytein(jpc_mqdec_t *mqdec); + +/******************************************************************************\ +* Code for creation and destruction of a MQ decoder. +\******************************************************************************/ + +/* Create a MQ decoder. */ +jpc_mqdec_t *jpc_mqdec_create(int maxctxs, jas_stream_t *in) +{ + jpc_mqdec_t *mqdec; + + /* There must be at least one context. */ + assert(maxctxs > 0); + + /* Allocate memory for the MQ decoder. */ + if (!(mqdec = jas_malloc(sizeof(jpc_mqdec_t)))) { + goto error; + } + mqdec->in = in; + mqdec->maxctxs = maxctxs; + /* Allocate memory for the per-context state information. */ + if (!(mqdec->ctxs = jas_malloc(mqdec->maxctxs * sizeof(jpc_mqstate_t *)))) { + goto error; + } + /* Set the current context to the first context. */ + mqdec->curctx = mqdec->ctxs; + + /* If an input stream has been associated with the MQ decoder, + initialize the decoder state from the stream. */ + if (mqdec->in) { + jpc_mqdec_init(mqdec); + } + /* Initialize the per-context state information. */ + jpc_mqdec_setctxs(mqdec, 0, 0); + + return mqdec; + +error: + /* Oops... Something has gone wrong. */ + if (mqdec) { + jpc_mqdec_destroy(mqdec); + } + return 0; +} + +/* Destroy a MQ decoder. */ +void jpc_mqdec_destroy(jpc_mqdec_t *mqdec) +{ + if (mqdec->ctxs) { + jas_free(mqdec->ctxs); + } + jas_free(mqdec); +} + +/******************************************************************************\ +* Code for initialization of a MQ decoder. +\******************************************************************************/ + +/* Initialize the state of a MQ decoder. */ + +void jpc_mqdec_init(jpc_mqdec_t *mqdec) +{ + int c; + + mqdec->eof = 0; + mqdec->creg = 0; + /* Get the next byte from the input stream. */ + if ((c = jas_stream_getc(mqdec->in)) == EOF) { + /* We have encountered an I/O error or EOF. */ + c = 0xff; + mqdec->eof = 1; + } + mqdec->inbuffer = c; + mqdec->creg += mqdec->inbuffer << 16; + jpc_mqdec_bytein(mqdec); + mqdec->creg <<= 7; + mqdec->ctreg -= 7; + mqdec->areg = 0x8000; +} + +/* Set the input stream for a MQ decoder. */ + +void jpc_mqdec_setinput(jpc_mqdec_t *mqdec, jas_stream_t *in) +{ + mqdec->in = in; +} + +/* Initialize one or more contexts. */ + +void jpc_mqdec_setctxs(jpc_mqdec_t *mqdec, int numctxs, jpc_mqctx_t *ctxs) +{ + jpc_mqstate_t **ctx; + int n; + + ctx = mqdec->ctxs; + n = JAS_MIN(mqdec->maxctxs, numctxs); + while (--n >= 0) { + *ctx = &jpc_mqstates[2 * ctxs->ind + ctxs->mps]; + ++ctx; + ++ctxs; + } + n = mqdec->maxctxs - numctxs; + while (--n >= 0) { + *ctx = &jpc_mqstates[0]; + ++ctx; + } +} + +/* Initialize a context. */ + +void jpc_mqdec_setctx(jpc_mqdec_t *mqdec, int ctxno, jpc_mqctx_t *ctx) +{ + jpc_mqstate_t **ctxi; + ctxi = &mqdec->ctxs[ctxno]; + *ctxi = &jpc_mqstates[2 * ctx->ind + ctx->mps]; +} + +/******************************************************************************\ +* Code for decoding a bit. +\******************************************************************************/ + +/* Decode a bit. */ + +int jpc_mqdec_getbit_func(register jpc_mqdec_t *mqdec) +{ + int bit; + JAS_DBGLOG(100, ("jpc_mqdec_getbit_func(%p)\n", mqdec)); + MQDEC_CALL(100, jpc_mqdec_dump(mqdec, stderr)); + bit = jpc_mqdec_getbit_macro(mqdec); + MQDEC_CALL(100, jpc_mqdec_dump(mqdec, stderr)); + JAS_DBGLOG(100, ("ctx = %d, decoded %d\n", mqdec->curctx - + mqdec->ctxs, bit)); + return bit; +} + +/* Apply MPS_EXCHANGE algorithm (with RENORMD). */ +int jpc_mqdec_mpsexchrenormd(register jpc_mqdec_t *mqdec) +{ + int ret; + register jpc_mqstate_t *state = *mqdec->curctx; + jpc_mqdec_mpsexchange(mqdec->areg, state->qeval, mqdec->curctx, ret); + jpc_mqdec_renormd(mqdec->areg, mqdec->creg, mqdec->ctreg, mqdec->in, + mqdec->eof, mqdec->inbuffer); + return ret; +} + +/* Apply LPS_EXCHANGE algorithm (with RENORMD). */ +int jpc_mqdec_lpsexchrenormd(register jpc_mqdec_t *mqdec) +{ + int ret; + register jpc_mqstate_t *state = *mqdec->curctx; + jpc_mqdec_lpsexchange(mqdec->areg, state->qeval, mqdec->curctx, ret); + jpc_mqdec_renormd(mqdec->areg, mqdec->creg, mqdec->ctreg, mqdec->in, + mqdec->eof, mqdec->inbuffer); + return ret; +} + +/******************************************************************************\ +* Support code. +\******************************************************************************/ + +/* Apply the BYTEIN algorithm. */ +static void jpc_mqdec_bytein(jpc_mqdec_t *mqdec) +{ + int c; + unsigned char prevbuf; + + if (!mqdec->eof) { + if ((c = jas_stream_getc(mqdec->in)) == EOF) { + mqdec->eof = 1; + c = 0xff; + } + prevbuf = mqdec->inbuffer; + mqdec->inbuffer = c; + if (prevbuf == 0xff) { + if (c > 0x8f) { + mqdec->creg += 0xff00; + mqdec->ctreg = 8; + } else { + mqdec->creg += c << 9; + mqdec->ctreg = 7; + } + } else { + mqdec->creg += c << 8; + mqdec->ctreg = 8; + } + } else { + mqdec->creg += 0xff00; + mqdec->ctreg = 8; + } +} + +/******************************************************************************\ +* Code for debugging. +\******************************************************************************/ + +/* Dump a MQ decoder to a stream for debugging. */ + +void jpc_mqdec_dump(jpc_mqdec_t *mqdec, FILE *out) +{ + fprintf(out, "MQDEC A = %08lx, C = %08lx, CT=%08lx, ", + (unsigned long) mqdec->areg, (unsigned long) mqdec->creg, + (unsigned long) mqdec->ctreg); + fprintf(out, "CTX = %d, ", mqdec->curctx - mqdec->ctxs); + fprintf(out, "IND %d, MPS %d, QEVAL %x\n", *mqdec->curctx - + jpc_mqstates, (*mqdec->curctx)->mps, (*mqdec->curctx)->qeval); +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqdec.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqdec.h new file mode 100644 index 0000000..8539506 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqdec.h @@ -0,0 +1,320 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * MQ Arithmetic Decoder + * + * $Id$ + */ + +#ifndef JPC_MQDEC_H +#define JPC_MQDEC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" +#include "jasper/jas_stream.h" + +#include "jpc_mqcod.h" + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* MQ arithmetic decoder. */ + +typedef struct { + + /* The C register. */ + uint_fast32_t creg; + + /* The A register. */ + uint_fast32_t areg; + + /* The CT register. */ + uint_fast32_t ctreg; + + /* The current context. */ + jpc_mqstate_t **curctx; + + /* The per-context information. */ + jpc_mqstate_t **ctxs; + + /* The maximum number of contexts. */ + int maxctxs; + + /* The stream from which to read data. */ + jas_stream_t *in; + + /* The last character read. */ + uchar inbuffer; + + /* The EOF indicator. */ + int eof; + +} jpc_mqdec_t; + +/******************************************************************************\ +* Functions/macros for construction and destruction. +\******************************************************************************/ + +/* Create a MQ decoder. */ +jpc_mqdec_t *jpc_mqdec_create(int maxctxs, jas_stream_t *in); + +/* Destroy a MQ decoder. */ +void jpc_mqdec_destroy(jpc_mqdec_t *dec); + +/******************************************************************************\ +* Functions/macros for initialization. +\******************************************************************************/ + +/* Set the input stream associated with a MQ decoder. */ +void jpc_mqdec_setinput(jpc_mqdec_t *dec, jas_stream_t *in); + +/* Initialize a MQ decoder. */ +void jpc_mqdec_init(jpc_mqdec_t *dec); + +/******************************************************************************\ +* Functions/macros for manipulating contexts. +\******************************************************************************/ + +/* Set the current context for a MQ decoder. */ +#define jpc_mqdec_setcurctx(dec, ctxno) \ + ((mqdec)->curctx = &(mqdec)->ctxs[ctxno]); + +/* Set the state information for a particular context of a MQ decoder. */ +void jpc_mqdec_setctx(jpc_mqdec_t *dec, int ctxno, jpc_mqctx_t *ctx); + +/* Set the state information for all contexts of a MQ decoder. */ +void jpc_mqdec_setctxs(jpc_mqdec_t *dec, int numctxs, jpc_mqctx_t *ctxs); + +/******************************************************************************\ +* Functions/macros for decoding bits. +\******************************************************************************/ + +/* Decode a symbol. */ +#if !defined(DEBUG) +#define jpc_mqdec_getbit(dec) \ + jpc_mqdec_getbit_macro(dec) +#else +#define jpc_mqdec_getbit(dec) \ + jpc_mqdec_getbit_func(dec) +#endif + +/* Decode a symbol (assuming an unskewed probability distribution). */ +#if !defined(DEBUG) +#define jpc_mqdec_getbitnoskew(dec) \ + jpc_mqdec_getbit_macro(dec) +#else +#define jpc_mqdec_getbitnoskew(dec) \ + jpc_mqdec_getbit_func(dec) +#endif + +/******************************************************************************\ +* Functions/macros for debugging. +\******************************************************************************/ + +/* Dump the MQ decoder state for debugging. */ +void jpc_mqdec_dump(jpc_mqdec_t *dec, FILE *out); + +/******************************************************************************\ +* EVERYTHING BELOW THIS POINT IS IMPLEMENTATION SPECIFIC AND NOT PART OF THE +* APPLICATION INTERFACE. DO NOT RELY ON ANY OF THE INTERNAL FUNCTIONS/MACROS +* GIVEN BELOW. +\******************************************************************************/ + +#define jpc_mqdec_getbit_macro(dec) \ + ((((dec)->areg -= (*(dec)->curctx)->qeval), \ + (dec)->creg >> 16 >= (*(dec)->curctx)->qeval) ? \ + ((((dec)->creg -= (*(dec)->curctx)->qeval << 16), \ + (dec)->areg & 0x8000) ? (*(dec)->curctx)->mps : \ + jpc_mqdec_mpsexchrenormd(dec)) : \ + jpc_mqdec_lpsexchrenormd(dec)) + +#define jpc_mqdec_mpsexchange(areg, delta, curctx, bit) \ +{ \ + if ((areg) < (delta)) { \ + register jpc_mqstate_t *state = *(curctx); \ + /* LPS decoded. */ \ + (bit) = state->mps ^ 1; \ + *(curctx) = state->nlps; \ + } else { \ + register jpc_mqstate_t *state = *(curctx); \ + /* MPS decoded. */ \ + (bit) = state->mps; \ + *(curctx) = state->nmps; \ + } \ +} + +#define jpc_mqdec_lpsexchange(areg, delta, curctx, bit) \ +{ \ + if ((areg) >= (delta)) { \ + register jpc_mqstate_t *state = *(curctx); \ + (areg) = (delta); \ + (bit) = state->mps ^ 1; \ + *(curctx) = state->nlps; \ + } else { \ + register jpc_mqstate_t *state = *(curctx); \ + (areg) = (delta); \ + (bit) = state->mps; \ + *(curctx) = state->nmps; \ + } \ +} + +#define jpc_mqdec_renormd(areg, creg, ctreg, in, eof, inbuf) \ +{ \ + do { \ + if (!(ctreg)) { \ + jpc_mqdec_bytein2(creg, ctreg, in, eof, inbuf); \ + } \ + (areg) <<= 1; \ + (creg) <<= 1; \ + --(ctreg); \ + } while (!((areg) & 0x8000)); \ +} + +#define jpc_mqdec_bytein2(creg, ctreg, in, eof, inbuf) \ +{ \ + int c; \ + unsigned char prevbuf; \ + if (!(eof)) { \ + if ((c = jas_stream_getc(in)) == EOF) { \ + (eof) = 1; \ + c = 0xff; \ + } \ + prevbuf = (inbuf); \ + (inbuf) = c; \ + if (prevbuf == 0xff) { \ + if (c > 0x8f) { \ + (creg) += 0xff00; \ + (ctreg) = 8; \ + } else { \ + (creg) += c << 9; \ + (ctreg) = 7; \ + } \ + } else { \ + (creg) += c << 8; \ + (ctreg) = 8; \ + } \ + } else { \ + (creg) += 0xff00; \ + (ctreg) = 8; \ + } \ +} + +int jpc_mqdec_getbit_func(jpc_mqdec_t *dec); +int jpc_mqdec_mpsexchrenormd(jpc_mqdec_t *dec); +int jpc_mqdec_lpsexchrenormd(jpc_mqdec_t *dec); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqenc.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqenc.c new file mode 100644 index 0000000..3aa5471 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqenc.c @@ -0,0 +1,441 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * MQ Arithmetic Encoder + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#include "jasper/jas_stream.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" +#include "jasper/jas_debug.h" + +#include "jpc_mqenc.h" + +/******************************************************************************\ +* Macros +\******************************************************************************/ + +#if defined(DEBUG) +#define JPC_MQENC_CALL(n, x) \ + ((jas_getdbglevel() >= (n)) ? ((void)(x)) : ((void)0)) +#else +#define JPC_MQENC_CALL(n, x) +#endif + +#define jpc_mqenc_codemps9(areg, creg, ctreg, curctx, enc) \ +{ \ + jpc_mqstate_t *state = *(curctx); \ + (areg) -= state->qeval; \ + if (!((areg) & 0x8000)) { \ + if ((areg) < state->qeval) { \ + (areg) = state->qeval; \ + } else { \ + (creg) += state->qeval; \ + } \ + *(curctx) = state->nmps; \ + jpc_mqenc_renorme((areg), (creg), (ctreg), (enc)); \ + } else { \ + (creg) += state->qeval; \ + } \ +} + +#define jpc_mqenc_codelps2(areg, creg, ctreg, curctx, enc) \ +{ \ + jpc_mqstate_t *state = *(curctx); \ + (areg) -= state->qeval; \ + if ((areg) < state->qeval) { \ + (creg) += state->qeval; \ + } else { \ + (areg) = state->qeval; \ + } \ + *(curctx) = state->nlps; \ + jpc_mqenc_renorme((areg), (creg), (ctreg), (enc)); \ +} + +#define jpc_mqenc_renorme(areg, creg, ctreg, enc) \ +{ \ + do { \ + (areg) <<= 1; \ + (creg) <<= 1; \ + if (!--(ctreg)) { \ + jpc_mqenc_byteout((areg), (creg), (ctreg), (enc)); \ + } \ + } while (!((areg) & 0x8000)); \ +} + +#define jpc_mqenc_byteout(areg, creg, ctreg, enc) \ +{ \ + if ((enc)->outbuf != 0xff) { \ + if ((creg) & 0x8000000) { \ + if (++((enc)->outbuf) == 0xff) { \ + (creg) &= 0x7ffffff; \ + jpc_mqenc_byteout2(enc); \ + enc->outbuf = ((creg) >> 20) & 0xff; \ + (creg) &= 0xfffff; \ + (ctreg) = 7; \ + } else { \ + jpc_mqenc_byteout2(enc); \ + enc->outbuf = ((creg) >> 19) & 0xff; \ + (creg) &= 0x7ffff; \ + (ctreg) = 8; \ + } \ + } else { \ + jpc_mqenc_byteout2(enc); \ + (enc)->outbuf = ((creg) >> 19) & 0xff; \ + (creg) &= 0x7ffff; \ + (ctreg) = 8; \ + } \ + } else { \ + jpc_mqenc_byteout2(enc); \ + (enc)->outbuf = ((creg) >> 20) & 0xff; \ + (creg) &= 0xfffff; \ + (ctreg) = 7; \ + } \ +} + +#define jpc_mqenc_byteout2(enc) \ +{ \ + if (enc->outbuf >= 0) { \ + if (jas_stream_putc(enc->out, (unsigned char)enc->outbuf) == EOF) { \ + enc->err |= 1; \ + } \ + } \ + enc->lastbyte = enc->outbuf; \ +} + +/******************************************************************************\ +* Local function protoypes. +\******************************************************************************/ + +static void jpc_mqenc_setbits(jpc_mqenc_t *mqenc); + +/******************************************************************************\ +* Code for creation and destruction of encoder. +\******************************************************************************/ + +/* Create a MQ encoder. */ + +jpc_mqenc_t *jpc_mqenc_create(int maxctxs, jas_stream_t *out) +{ + jpc_mqenc_t *mqenc; + + /* Allocate memory for the MQ encoder. */ + if (!(mqenc = jas_malloc(sizeof(jpc_mqenc_t)))) { + goto error; + } + mqenc->out = out; + mqenc->maxctxs = maxctxs; + + /* Allocate memory for the per-context state information. */ + if (!(mqenc->ctxs = jas_malloc(mqenc->maxctxs * sizeof(jpc_mqstate_t *)))) { + goto error; + } + + /* Set the current context to the first one. */ + mqenc->curctx = mqenc->ctxs; + + jpc_mqenc_init(mqenc); + + /* Initialize the per-context state information to something sane. */ + jpc_mqenc_setctxs(mqenc, 0, 0); + + return mqenc; + +error: + if (mqenc) { + jpc_mqenc_destroy(mqenc); + } + return 0; +} + +/* Destroy a MQ encoder. */ + +void jpc_mqenc_destroy(jpc_mqenc_t *mqenc) +{ + if (mqenc->ctxs) { + jas_free(mqenc->ctxs); + } + jas_free(mqenc); +} + +/******************************************************************************\ +* State initialization code. +\******************************************************************************/ + +/* Initialize the coding state of a MQ encoder. */ + +void jpc_mqenc_init(jpc_mqenc_t *mqenc) +{ + mqenc->areg = 0x8000; + mqenc->outbuf = -1; + mqenc->creg = 0; + mqenc->ctreg = 12; + mqenc->lastbyte = -1; + mqenc->err = 0; +} + +/* Initialize one or more contexts. */ + +void jpc_mqenc_setctxs(jpc_mqenc_t *mqenc, int numctxs, jpc_mqctx_t *ctxs) +{ + jpc_mqstate_t **ctx; + int n; + + ctx = mqenc->ctxs; + n = JAS_MIN(mqenc->maxctxs, numctxs); + while (--n >= 0) { + *ctx = &jpc_mqstates[2 * ctxs->ind + ctxs->mps]; + ++ctx; + ++ctxs; + } + n = mqenc->maxctxs - numctxs; + while (--n >= 0) { + *ctx = &jpc_mqstates[0]; + ++ctx; + } + +} + +/* Get the coding state for a MQ encoder. */ + +void jpc_mqenc_getstate(jpc_mqenc_t *mqenc, jpc_mqencstate_t *state) +{ + state->areg = mqenc->areg; + state->creg = mqenc->creg; + state->ctreg = mqenc->ctreg; + state->lastbyte = mqenc->lastbyte; +} + +/******************************************************************************\ +* Code for coding symbols. +\******************************************************************************/ + +/* Encode a bit. */ + +int jpc_mqenc_putbit_func(jpc_mqenc_t *mqenc, int bit) +{ + const jpc_mqstate_t *state; + JAS_DBGLOG(100, ("jpc_mqenc_putbit(%p, %d)\n", mqenc, bit)); + JPC_MQENC_CALL(100, jpc_mqenc_dump(mqenc, stderr)); + + state = *(mqenc->curctx); + + if (state->mps == bit) { + /* Apply the CODEMPS algorithm as defined in the standard. */ + mqenc->areg -= state->qeval; + if (!(mqenc->areg & 0x8000)) { + jpc_mqenc_codemps2(mqenc); + } else { + mqenc->creg += state->qeval; + } + } else { + /* Apply the CODELPS algorithm as defined in the standard. */ + jpc_mqenc_codelps2(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc->curctx, mqenc); + } + + return jpc_mqenc_error(mqenc) ? (-1) : 0; +} + +int jpc_mqenc_codemps2(jpc_mqenc_t *mqenc) +{ + /* Note: This function only performs part of the work associated with + the CODEMPS algorithm from the standard. Some of the work is also + performed by the caller. */ + + jpc_mqstate_t *state = *(mqenc->curctx); + if (mqenc->areg < state->qeval) { + mqenc->areg = state->qeval; + } else { + mqenc->creg += state->qeval; + } + *mqenc->curctx = state->nmps; + jpc_mqenc_renorme(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc); + return jpc_mqenc_error(mqenc) ? (-1) : 0; +} + +int jpc_mqenc_codelps(jpc_mqenc_t *mqenc) +{ + jpc_mqenc_codelps2(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc->curctx, mqenc); + return jpc_mqenc_error(mqenc) ? (-1) : 0; +} + +/******************************************************************************\ +* Miscellaneous code. +\******************************************************************************/ + +/* Terminate the code word. */ + +int jpc_mqenc_flush(jpc_mqenc_t *mqenc, int termmode) +{ + int_fast16_t k; + + switch (termmode) { + case JPC_MQENC_PTERM: + k = 11 - mqenc->ctreg + 1; + while (k > 0) { + mqenc->creg <<= mqenc->ctreg; + mqenc->ctreg = 0; + jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, + mqenc); + k -= mqenc->ctreg; + } + if (mqenc->outbuf != 0xff) { + jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc); + } + break; + case JPC_MQENC_DEFTERM: + jpc_mqenc_setbits(mqenc); + mqenc->creg <<= mqenc->ctreg; + jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc); + mqenc->creg <<= mqenc->ctreg; + jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc); + if (mqenc->outbuf != 0xff) { + jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc); + } + break; + default: + abort(); + break; + } + return 0; +} + +static void jpc_mqenc_setbits(jpc_mqenc_t *mqenc) +{ + uint_fast32_t tmp = mqenc->creg + mqenc->areg; + mqenc->creg |= 0xffff; + if (mqenc->creg >= tmp) { + mqenc->creg -= 0x8000; + } +} + +/* Dump a MQ encoder to a stream for debugging. */ + +int jpc_mqenc_dump(jpc_mqenc_t *mqenc, FILE *out) +{ + fprintf(out, "AREG = %08x, CREG = %08x, CTREG = %d\n", + mqenc->areg, mqenc->creg, mqenc->ctreg); + fprintf(out, "IND = %02d, MPS = %d, QEVAL = %04x\n", + *mqenc->curctx - jpc_mqstates, (*mqenc->curctx)->mps, + (*mqenc->curctx)->qeval); + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqenc.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqenc.h new file mode 100644 index 0000000..7d3603a --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_mqenc.h @@ -0,0 +1,285 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * MQ Arithmetic Encoder + * + * $Id$ + */ + +#ifndef JPC_MQENC_H +#define JPC_MQENC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" +#include "jasper/jas_stream.h" + +#include "jpc_mqcod.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* + * Termination modes. + */ + +#define JPC_MQENC_DEFTERM 0 /* default termination */ +#define JPC_MQENC_PTERM 1 /* predictable termination */ + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* MQ arithmetic encoder class. */ + +typedef struct { + + /* The C register. */ + uint_fast32_t creg; + + /* The A register. */ + uint_fast32_t areg; + + /* The CT register. */ + uint_fast32_t ctreg; + + /* The maximum number of contexts. */ + int maxctxs; + + /* The per-context information. */ + jpc_mqstate_t **ctxs; + + /* The current context. */ + jpc_mqstate_t **curctx; + + /* The stream for encoder output. */ + jas_stream_t *out; + + /* The byte buffer (i.e., the B variable in the standard). */ + int_fast16_t outbuf; + + /* The last byte output. */ + int_fast16_t lastbyte; + + /* The error indicator. */ + int err; + +} jpc_mqenc_t; + +/* MQ arithmetic encoder state information. */ + +typedef struct { + + /* The A register. */ + unsigned areg; + + /* The C register. */ + unsigned creg; + + /* The CT register. */ + unsigned ctreg; + + /* The last byte output by the encoder. */ + int lastbyte; + +} jpc_mqencstate_t; + +/******************************************************************************\ +* Functions/macros for construction and destruction. +\******************************************************************************/ + +/* Create a MQ encoder. */ +jpc_mqenc_t *jpc_mqenc_create(int maxctxs, jas_stream_t *out); + +/* Destroy a MQ encoder. */ +void jpc_mqenc_destroy(jpc_mqenc_t *enc); + +/******************************************************************************\ +* Functions/macros for initialization. +\******************************************************************************/ + +/* Initialize a MQ encoder. */ +void jpc_mqenc_init(jpc_mqenc_t *enc); + +/******************************************************************************\ +* Functions/macros for context manipulation. +\******************************************************************************/ + +/* Set the current context. */ +#define jpc_mqenc_setcurctx(enc, ctxno) \ + ((enc)->curctx = &(enc)->ctxs[ctxno]); + +/* Set the state information for a particular context. */ +void jpc_mqenc_setctx(jpc_mqenc_t *enc, int ctxno, jpc_mqctx_t *ctx); + +/* Set the state information for multiple contexts. */ +void jpc_mqenc_setctxs(jpc_mqenc_t *enc, int numctxs, jpc_mqctx_t *ctxs); + +/******************************************************************************\ +* Miscellaneous functions/macros. +\******************************************************************************/ + +/* Get the error state of a MQ encoder. */ +#define jpc_mqenc_error(enc) \ + ((enc)->err) + +/* Get the current encoder state. */ +void jpc_mqenc_getstate(jpc_mqenc_t *enc, jpc_mqencstate_t *state); + +/* Terminate the code. */ +int jpc_mqenc_flush(jpc_mqenc_t *enc, int termmode); + +/******************************************************************************\ +* Functions/macros for encoding bits. +\******************************************************************************/ + +/* Encode a bit. */ +#if !defined(DEBUG) +#define jpc_mqenc_putbit(enc, bit) jpc_mqenc_putbit_macro(enc, bit) +#else +#define jpc_mqenc_putbit(enc, bit) jpc_mqenc_putbit_func(enc, bit) +#endif + +/******************************************************************************\ +* Functions/macros for debugging. +\******************************************************************************/ + +int jpc_mqenc_dump(jpc_mqenc_t *mqenc, FILE *out); + +/******************************************************************************\ +* Implementation-specific details. +\******************************************************************************/ + +/* Note: This macro is included only to satisfy the needs of + the mqenc_putbit macro. */ +#define jpc_mqenc_putbit_macro(enc, bit) \ + (((*((enc)->curctx))->mps == (bit)) ? \ + (((enc)->areg -= (*(enc)->curctx)->qeval), \ + ((!((enc)->areg & 0x8000)) ? (jpc_mqenc_codemps2(enc)) : \ + ((enc)->creg += (*(enc)->curctx)->qeval))) : \ + jpc_mqenc_codelps(enc)) + +/* Note: These function prototypes are included only to satisfy the + needs of the mqenc_putbit_macro macro. Do not call any of these + functions directly. */ +int jpc_mqenc_codemps2(jpc_mqenc_t *enc); +int jpc_mqenc_codelps(jpc_mqenc_t *enc); + +/* Note: This function prototype is included only to satisfy the needs of + the mqenc_putbit macro. */ +int jpc_mqenc_putbit_func(jpc_mqenc_t *enc, int bit); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_qmfb.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_qmfb.c new file mode 100644 index 0000000..19e492d --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_qmfb.c @@ -0,0 +1,1171 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Quadrature Mirror-Image Filter Bank (QMFB) Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_fix.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" + +#include "jpc_qmfb.h" +#include "jpc_tsfb.h" +#include "jpc_math.h" + +/******************************************************************************\ +* +\******************************************************************************/ + +static jpc_qmfb1d_t *jpc_qmfb1d_create(void); + +static int jpc_ft_getnumchans(jpc_qmfb1d_t *qmfb); +static int jpc_ft_getanalfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters); +static int jpc_ft_getsynfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters); +static void jpc_ft_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x); +static void jpc_ft_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x); + +static int jpc_ns_getnumchans(jpc_qmfb1d_t *qmfb); +static int jpc_ns_getanalfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters); +static int jpc_ns_getsynfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters); +static void jpc_ns_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x); +static void jpc_ns_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x); + +/******************************************************************************\ +* +\******************************************************************************/ + +jpc_qmfb1dops_t jpc_ft_ops = { + jpc_ft_getnumchans, + jpc_ft_getanalfilters, + jpc_ft_getsynfilters, + jpc_ft_analyze, + jpc_ft_synthesize +}; + +jpc_qmfb1dops_t jpc_ns_ops = { + jpc_ns_getnumchans, + jpc_ns_getanalfilters, + jpc_ns_getsynfilters, + jpc_ns_analyze, + jpc_ns_synthesize +}; + +/******************************************************************************\ +* +\******************************************************************************/ + +static void jpc_qmfb1d_setup(jpc_fix_t *startptr, int startind, int endind, + int intrastep, jpc_fix_t **lstartptr, int *lstartind, int *lendind, + jpc_fix_t **hstartptr, int *hstartind, int *hendind) +{ + *lstartind = JPC_CEILDIVPOW2(startind, 1); + *lendind = JPC_CEILDIVPOW2(endind, 1); + *hstartind = JPC_FLOORDIVPOW2(startind, 1); + *hendind = JPC_FLOORDIVPOW2(endind, 1); + *lstartptr = startptr; + *hstartptr = &startptr[(*lendind - *lstartind) * intrastep]; +} + +static void jpc_qmfb1d_split(jpc_fix_t *startptr, int startind, int endind, + register int step, jpc_fix_t *lstartptr, int lstartind, int lendind, + jpc_fix_t *hstartptr, int hstartind, int hendind) +{ + int bufsize = JPC_CEILDIVPOW2(endind - startind, 2); +#if defined(WIN32) +#define QMFB_SPLITBUFSIZE 4096 + jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE]; +#else + jpc_fix_t splitbuf[bufsize]; +#endif + jpc_fix_t *buf = splitbuf; + int llen; + int hlen; + int twostep; + jpc_fix_t *tmpptr; + register jpc_fix_t *ptr; + register jpc_fix_t *hptr; + register jpc_fix_t *lptr; + register int n; + int state; + + twostep = step << 1; + llen = lendind - lstartind; + hlen = hendind - hstartind; + +#if defined(WIN32) + /* Get a buffer. */ + if (bufsize > QMFB_SPLITBUFSIZE) { + if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) { + /* We have no choice but to commit suicide in this case. */ + abort(); + } + } +#endif + + if (hstartind < lstartind) { + /* The first sample in the input signal is to appear + in the highpass subband signal. */ + /* Copy the appropriate samples into the lowpass subband + signal, saving any samples destined for the highpass subband + signal as they are overwritten. */ + tmpptr = buf; + ptr = &startptr[step]; + lptr = lstartptr; + n = llen; + state = 1; + while (n-- > 0) { + if (state) { + *tmpptr = *lptr; + ++tmpptr; + } + *lptr = *ptr; + ptr += twostep; + lptr += step; + state ^= 1; + } + /* Copy the appropriate samples into the highpass subband + signal. */ + /* Handle the nonoverwritten samples. */ + hptr = &hstartptr[(hlen - 1) * step]; + ptr = &startptr[(((llen + hlen - 1) >> 1) << 1) * step]; + n = hlen - (tmpptr - buf); + while (n-- > 0) { + *hptr = *ptr; + hptr -= step; + ptr -= twostep; + } + /* Handle the overwritten samples. */ + n = tmpptr - buf; + while (n-- > 0) { + --tmpptr; + *hptr = *tmpptr; + hptr -= step; + } + } else { + /* The first sample in the input signal is to appear + in the lowpass subband signal. */ + /* Copy the appropriate samples into the lowpass subband + signal, saving any samples for the highpass subband + signal as they are overwritten. */ + state = 0; + ptr = startptr; + lptr = lstartptr; + tmpptr = buf; + n = llen; + while (n-- > 0) { + if (state) { + *tmpptr = *lptr; + ++tmpptr; + } + *lptr = *ptr; + ptr += twostep; + lptr += step; + state ^= 1; + } + /* Copy the appropriate samples into the highpass subband + signal. */ + /* Handle the nonoverwritten samples. */ + ptr = &startptr[((((llen + hlen) >> 1) << 1) - 1) * step]; + hptr = &hstartptr[(hlen - 1) * step]; + n = hlen - (tmpptr - buf); + while (n-- > 0) { + *hptr = *ptr; + ptr -= twostep; + hptr -= step; + } + /* Handle the overwritten samples. */ + n = tmpptr - buf; + while (n-- > 0) { + --tmpptr; + *hptr = *tmpptr; + hptr -= step; + } + } + +#if defined(WIN32) + /* If the split buffer was allocated on the heap, free this memory. */ + if (buf != splitbuf) { + jas_free(buf); + } +#endif +} + +static void jpc_qmfb1d_join(jpc_fix_t *startptr, int startind, int endind, + register int step, jpc_fix_t *lstartptr, int lstartind, int lendind, + jpc_fix_t *hstartptr, int hstartind, int hendind) +{ + int bufsize = JPC_CEILDIVPOW2(endind - startind, 2); +#if defined(WIN32) +#define QMFB_JOINBUFSIZE 4096 + jpc_fix_t joinbuf[QMFB_JOINBUFSIZE]; +#else + jpc_fix_t joinbuf[bufsize]; +#endif + jpc_fix_t *buf = joinbuf; + int llen; + int hlen; + int twostep; + jpc_fix_t *tmpptr; + register jpc_fix_t *ptr; + register jpc_fix_t *hptr; + register jpc_fix_t *lptr; + register int n; + int state; + +#if defined(WIN32) + /* Allocate memory for the join buffer from the heap. */ + if (bufsize > QMFB_JOINBUFSIZE) { + if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) { + /* We have no choice but to commit suicide. */ + abort(); + } + } +#endif + + twostep = step << 1; + llen = lendind - lstartind; + hlen = hendind - hstartind; + + if (hstartind < lstartind) { + /* The first sample in the highpass subband signal is to + appear first in the output signal. */ + /* Copy the appropriate samples into the first phase of the + output signal. */ + tmpptr = buf; + hptr = hstartptr; + ptr = startptr; + n = (llen + 1) >> 1; + while (n-- > 0) { + *tmpptr = *ptr; + *ptr = *hptr; + ++tmpptr; + ptr += twostep; + hptr += step; + } + n = hlen - ((llen + 1) >> 1); + while (n-- > 0) { + *ptr = *hptr; + ptr += twostep; + hptr += step; + } + /* Copy the appropriate samples into the second phase of + the output signal. */ + ptr -= (lendind > hendind) ? (step) : (step + twostep); + state = !((llen - 1) & 1); + lptr = &lstartptr[(llen - 1) * step]; + n = llen; + while (n-- > 0) { + if (state) { + --tmpptr; + *ptr = *tmpptr; + } else { + *ptr = *lptr; + } + lptr -= step; + ptr -= twostep; + state ^= 1; + } + } else { + /* The first sample in the lowpass subband signal is to + appear first in the output signal. */ + /* Copy the appropriate samples into the first phase of the + output signal (corresponding to even indexed samples). */ + lptr = &lstartptr[(llen - 1) * step]; + ptr = &startptr[((llen - 1) << 1) * step]; + n = llen >> 1; + tmpptr = buf; + while (n-- > 0) { + *tmpptr = *ptr; + *ptr = *lptr; + ++tmpptr; + ptr -= twostep; + lptr -= step; + } + n = llen - (llen >> 1); + while (n-- > 0) { + *ptr = *lptr; + ptr -= twostep; + lptr -= step; + } + /* Copy the appropriate samples into the second phase of + the output signal (corresponding to odd indexed + samples). */ + ptr = &startptr[step]; + hptr = hstartptr; + state = !(llen & 1); + n = hlen; + while (n-- > 0) { + if (state) { + --tmpptr; + *ptr = *tmpptr; + } else { + *ptr = *hptr; + } + hptr += step; + ptr += twostep; + state ^= 1; + } + } + +#if defined(WIN32) + /* If the join buffer was allocated on the heap, free this memory. */ + if (buf != joinbuf) { + jas_free(buf); + } +#endif +} + +/******************************************************************************\ +* Code for 5/3 transform. +\******************************************************************************/ + +static int jpc_ft_getnumchans(jpc_qmfb1d_t *qmfb) +{ + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + + return 2; +} + +static int jpc_ft_getanalfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters) +{ + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + len = 0; + filters = 0; + abort(); + return -1; +} + +static int jpc_ft_getsynfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters) +{ + jas_seq_t *lf; + jas_seq_t *hf; + + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + + lf = 0; + hf = 0; + + if (len > 1 || (!len)) { + if (!(lf = jas_seq_create(-1, 2))) { + goto error; + } + jas_seq_set(lf, -1, jpc_dbltofix(0.5)); + jas_seq_set(lf, 0, jpc_dbltofix(1.0)); + jas_seq_set(lf, 1, jpc_dbltofix(0.5)); + if (!(hf = jas_seq_create(-1, 4))) { + goto error; + } + jas_seq_set(hf, -1, jpc_dbltofix(-0.125)); + jas_seq_set(hf, 0, jpc_dbltofix(-0.25)); + jas_seq_set(hf, 1, jpc_dbltofix(0.75)); + jas_seq_set(hf, 2, jpc_dbltofix(-0.25)); + jas_seq_set(hf, 3, jpc_dbltofix(-0.125)); + } else if (len == 1) { + if (!(lf = jas_seq_create(0, 1))) { + goto error; + } + jas_seq_set(lf, 0, jpc_dbltofix(1.0)); + if (!(hf = jas_seq_create(0, 1))) { + goto error; + } + jas_seq_set(hf, 0, jpc_dbltofix(2.0)); + } else { + abort(); + } + + filters[0] = lf; + filters[1] = hf; + + return 0; + +error: + if (lf) { + jas_seq_destroy(lf); + } + if (hf) { + jas_seq_destroy(hf); + } + return -1; +} + +#define NFT_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pluseq) \ +{ \ + register jpc_fix_t *lptr = (lstartptr); \ + register jpc_fix_t *hptr = (hstartptr); \ + register int n = (hendind) - (hstartind); \ + if ((hstartind) < (lstartind)) { \ + pluseq(*hptr, *lptr); \ + hptr += (step); \ + --n; \ + } \ + if ((hendind) >= (lendind)) { \ + --n; \ + } \ + while (n-- > 0) { \ + pluseq(*hptr, jpc_fix_asr(jpc_fix_add(*lptr, lptr[(step)]), 1)); \ + hptr += (step); \ + lptr += (step); \ + } \ + if ((hendind) >= (lendind)) { \ + pluseq(*hptr, *lptr); \ + } \ +} + +#define NFT_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pluseq) \ +{ \ + register jpc_fix_t *lptr = (lstartptr); \ + register jpc_fix_t *hptr = (hstartptr); \ + register int n = (lendind) - (lstartind); \ + if ((hstartind) >= (lstartind)) { \ + pluseq(*lptr, *hptr); \ + lptr += (step); \ + --n; \ + } \ + if ((lendind) > (hendind)) { \ + --n; \ + } \ + while (n-- > 0) { \ + pluseq(*lptr, jpc_fix_asr(jpc_fix_add(*hptr, hptr[(step)]), 2)); \ + lptr += (step); \ + hptr += (step); \ + } \ + if ((lendind) > (hendind)) { \ + pluseq(*lptr, *hptr); \ + } \ +} + +#define RFT_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pmeqop) \ +{ \ + register jpc_fix_t *lptr = (lstartptr); \ + register jpc_fix_t *hptr = (hstartptr); \ + register int n = (hendind) - (hstartind); \ + if ((hstartind) < (lstartind)) { \ + *hptr pmeqop *lptr; \ + hptr += (step); \ + --n; \ + } \ + if ((hendind) >= (lendind)) { \ + --n; \ + } \ + while (n-- > 0) { \ + *hptr pmeqop (*lptr + lptr[(step)]) >> 1; \ + hptr += (step); \ + lptr += (step); \ + } \ + if ((hendind) >= (lendind)) { \ + *hptr pmeqop *lptr; \ + } \ +} + +#define RFT_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pmeqop) \ +{ \ + register jpc_fix_t *lptr = (lstartptr); \ + register jpc_fix_t *hptr = (hstartptr); \ + register int n = (lendind) - (lstartind); \ + if ((hstartind) >= (lstartind)) { \ + *lptr pmeqop ((*hptr << 1) + 2) >> 2; \ + lptr += (step); \ + --n; \ + } \ + if ((lendind) > (hendind)) { \ + --n; \ + } \ + while (n-- > 0) { \ + *lptr pmeqop ((*hptr + hptr[(step)]) + 2) >> 2; \ + lptr += (step); \ + hptr += (step); \ + } \ + if ((lendind) > (hendind)) { \ + *lptr pmeqop ((*hptr << 1) + 2) >> 2; \ + } \ +} + +static void jpc_ft_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x) +{ + jpc_fix_t *startptr; + int startind; + int endind; + jpc_fix_t * lstartptr; + int lstartind; + int lendind; + jpc_fix_t * hstartptr; + int hstartind; + int hendind; + int interstep; + int intrastep; + int numseq; + + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + + if (flags & JPC_QMFB1D_VERT) { + interstep = 1; + intrastep = jas_seq2d_rowstep(x); + numseq = jas_seq2d_width(x); + startind = jas_seq2d_ystart(x); + endind = jas_seq2d_yend(x); + } else { + interstep = jas_seq2d_rowstep(x); + intrastep = 1; + numseq = jas_seq2d_height(x); + startind = jas_seq2d_xstart(x); + endind = jas_seq2d_xend(x); + } + + assert(startind < endind); + + startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x)); + if (flags & JPC_QMFB1D_RITIMODE) { + while (numseq-- > 0) { + jpc_qmfb1d_setup(startptr, startind, endind, intrastep, + &lstartptr, &lstartind, &lendind, &hstartptr, + &hstartind, &hendind); + if (endind - startind > 1) { + jpc_qmfb1d_split(startptr, startind, endind, + intrastep, lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind); + RFT_LIFT0(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, -=); + RFT_LIFT1(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, +=); + } else { + if (lstartind == lendind) { + *startptr <<= 1; + } + } + startptr += interstep; + } + } else { + while (numseq-- > 0) { + jpc_qmfb1d_setup(startptr, startind, endind, intrastep, + &lstartptr, &lstartind, &lendind, &hstartptr, + &hstartind, &hendind); + if (endind - startind > 1) { + jpc_qmfb1d_split(startptr, startind, endind, + intrastep, lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind); + NFT_LIFT0(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_fix_minuseq); + NFT_LIFT1(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_fix_pluseq); + } else { + if (lstartind == lendind) { + *startptr = jpc_fix_asl(*startptr, 1); + } + } + startptr += interstep; + } + } +} + +static void jpc_ft_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x) +{ + jpc_fix_t *startptr; + int startind; + int endind; + jpc_fix_t *lstartptr; + int lstartind; + int lendind; + jpc_fix_t *hstartptr; + int hstartind; + int hendind; + int interstep; + int intrastep; + int numseq; + + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + + if (flags & JPC_QMFB1D_VERT) { + interstep = 1; + intrastep = jas_seq2d_rowstep(x); + numseq = jas_seq2d_width(x); + startind = jas_seq2d_ystart(x); + endind = jas_seq2d_yend(x); + } else { + interstep = jas_seq2d_rowstep(x); + intrastep = 1; + numseq = jas_seq2d_height(x); + startind = jas_seq2d_xstart(x); + endind = jas_seq2d_xend(x); + } + + assert(startind < endind); + + startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x)); + if (flags & JPC_QMFB1D_RITIMODE) { + while (numseq-- > 0) { + jpc_qmfb1d_setup(startptr, startind, endind, intrastep, + &lstartptr, &lstartind, &lendind, &hstartptr, + &hstartind, &hendind); + if (endind - startind > 1) { + RFT_LIFT1(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, -=); + RFT_LIFT0(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, +=); + jpc_qmfb1d_join(startptr, startind, endind, + intrastep, lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind); + } else { + if (lstartind == lendind) { + *startptr >>= 1; + } + } + startptr += interstep; + } + } else { + while (numseq-- > 0) { + jpc_qmfb1d_setup(startptr, startind, endind, intrastep, + &lstartptr, &lstartind, &lendind, &hstartptr, + &hstartind, &hendind); + if (endind - startind > 1) { + NFT_LIFT1(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_fix_minuseq); + NFT_LIFT0(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_fix_pluseq); + jpc_qmfb1d_join(startptr, startind, endind, + intrastep, lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind); + } else { + if (lstartind == lendind) { + *startptr = jpc_fix_asr(*startptr, 1); + } + } + startptr += interstep; + } + } +} + +/******************************************************************************\ +* Code for 9/7 transform. +\******************************************************************************/ + +static int jpc_ns_getnumchans(jpc_qmfb1d_t *qmfb) +{ + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + + return 2; +} + +static int jpc_ns_getanalfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters) +{ + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + len = 0; + filters = 0; + + abort(); + return -1; +} + +static int jpc_ns_getsynfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters) +{ + jas_seq_t *lf; + jas_seq_t *hf; + + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + + lf = 0; + hf = 0; + + if (len > 1 || (!len)) { + if (!(lf = jas_seq_create(-3, 4))) { + goto error; + } + jas_seq_set(lf, -3, jpc_dbltofix(-0.09127176311424948)); + jas_seq_set(lf, -2, jpc_dbltofix(-0.05754352622849957)); + jas_seq_set(lf, -1, jpc_dbltofix(0.5912717631142470)); + jas_seq_set(lf, 0, jpc_dbltofix(1.115087052456994)); + jas_seq_set(lf, 1, jpc_dbltofix(0.5912717631142470)); + jas_seq_set(lf, 2, jpc_dbltofix(-0.05754352622849957)); + jas_seq_set(lf, 3, jpc_dbltofix(-0.09127176311424948)); + if (!(hf = jas_seq_create(-3, 6))) { + goto error; + } + jas_seq_set(hf, -3, jpc_dbltofix(-0.02674875741080976 * 2.0)); + jas_seq_set(hf, -2, jpc_dbltofix(-0.01686411844287495 * 2.0)); + jas_seq_set(hf, -1, jpc_dbltofix(0.07822326652898785 * 2.0)); + jas_seq_set(hf, 0, jpc_dbltofix(0.2668641184428723 * 2.0)); + jas_seq_set(hf, 1, jpc_dbltofix(-0.6029490182363579 * 2.0)); + jas_seq_set(hf, 2, jpc_dbltofix(0.2668641184428723 * 2.0)); + jas_seq_set(hf, 3, jpc_dbltofix(0.07822326652898785 * 2.0)); + jas_seq_set(hf, 4, jpc_dbltofix(-0.01686411844287495 * 2.0)); + jas_seq_set(hf, 5, jpc_dbltofix(-0.02674875741080976 * 2.0)); + } else if (len == 1) { + if (!(lf = jas_seq_create(0, 1))) { + goto error; + } + jas_seq_set(lf, 0, jpc_dbltofix(1.0)); + if (!(hf = jas_seq_create(0, 1))) { + goto error; + } + jas_seq_set(hf, 0, jpc_dbltofix(2.0)); + } else { + abort(); + } + + filters[0] = lf; + filters[1] = hf; + + return 0; + +error: + if (lf) { + jas_seq_destroy(lf); + } + if (hf) { + jas_seq_destroy(hf); + } + return -1; +} + +#define NNS_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, alpha) \ +{ \ + register jpc_fix_t *lptr = (lstartptr); \ + register jpc_fix_t *hptr = (hstartptr); \ + register int n = (hendind) - (hstartind); \ + jpc_fix_t twoalpha = jpc_fix_mulbyint(alpha, 2); \ + if ((hstartind) < (lstartind)) { \ + jpc_fix_pluseq(*hptr, jpc_fix_mul(*lptr, (twoalpha))); \ + hptr += (step); \ + --n; \ + } \ + if ((hendind) >= (lendind)) { \ + --n; \ + } \ + while (n-- > 0) { \ + jpc_fix_pluseq(*hptr, jpc_fix_mul(jpc_fix_add(*lptr, lptr[(step)]), (alpha))); \ + hptr += (step); \ + lptr += (step); \ + } \ + if ((hendind) >= (lendind)) { \ + jpc_fix_pluseq(*hptr, jpc_fix_mul(*lptr, (twoalpha))); \ + } \ +} + +#define NNS_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, alpha) \ +{ \ + register jpc_fix_t *lptr = (lstartptr); \ + register jpc_fix_t *hptr = (hstartptr); \ + register int n = (lendind) - (lstartind); \ + int twoalpha = jpc_fix_mulbyint(alpha, 2); \ + if ((hstartind) >= (lstartind)) { \ + jpc_fix_pluseq(*lptr, jpc_fix_mul(*hptr, (twoalpha))); \ + lptr += (step); \ + --n; \ + } \ + if ((lendind) > (hendind)) { \ + --n; \ + } \ + while (n-- > 0) { \ + jpc_fix_pluseq(*lptr, jpc_fix_mul(jpc_fix_add(*hptr, hptr[(step)]), (alpha))); \ + lptr += (step); \ + hptr += (step); \ + } \ + if ((lendind) > (hendind)) { \ + jpc_fix_pluseq(*lptr, jpc_fix_mul(*hptr, (twoalpha))); \ + } \ +} + +#define NNS_SCALE(startptr, startind, endind, step, alpha) \ +{ \ + register jpc_fix_t *ptr = (startptr); \ + register int n = (endind) - (startind); \ + while (n-- > 0) { \ + jpc_fix_muleq(*ptr, alpha); \ + ptr += (step); \ + } \ +} + +static void jpc_ns_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x) +{ + jpc_fix_t *startptr; + int startind; + int endind; + jpc_fix_t *lstartptr; + int lstartind; + int lendind; + jpc_fix_t *hstartptr; + int hstartind; + int hendind; + int interstep; + int intrastep; + int numseq; + + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + + if (flags & JPC_QMFB1D_VERT) { + interstep = 1; + intrastep = jas_seq2d_rowstep(x); + numseq = jas_seq2d_width(x); + startind = jas_seq2d_ystart(x); + endind = jas_seq2d_yend(x); + } else { + interstep = jas_seq2d_rowstep(x); + intrastep = 1; + numseq = jas_seq2d_height(x); + startind = jas_seq2d_xstart(x); + endind = jas_seq2d_xend(x); + } + + assert(startind < endind); + + startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x)); + if (!(flags & JPC_QMFB1D_RITIMODE)) { + while (numseq-- > 0) { + jpc_qmfb1d_setup(startptr, startind, endind, intrastep, + &lstartptr, &lstartind, &lendind, &hstartptr, + &hstartind, &hendind); + if (endind - startind > 1) { + jpc_qmfb1d_split(startptr, startind, endind, + intrastep, lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind); + NNS_LIFT0(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_dbltofix(-1.586134342)); + NNS_LIFT1(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_dbltofix(-0.052980118)); + NNS_LIFT0(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_dbltofix(0.882911075)); + NNS_LIFT1(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_dbltofix(0.443506852)); + NNS_SCALE(lstartptr, lstartind, lendind, + intrastep, jpc_dbltofix(1.0/1.23017410558578)); + NNS_SCALE(hstartptr, hstartind, hendind, + intrastep, jpc_dbltofix(1.0/1.62578613134411)); + } else { +#if 0 + if (lstartind == lendind) { + *startptr = jpc_fix_asl(*startptr, 1); + } +#endif + } + startptr += interstep; + } + } else { + /* The reversible integer-to-integer mode is not supported + for this transform. */ + abort(); + } +} + +static void jpc_ns_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x) +{ + jpc_fix_t *startptr; + int startind; + int endind; + jpc_fix_t *lstartptr; + int lstartind; + int lendind; + jpc_fix_t *hstartptr; + int hstartind; + int hendind; + int interstep; + int intrastep; + int numseq; + + /* Avoid compiler warnings about unused parameters. */ + qmfb = 0; + + if (flags & JPC_QMFB1D_VERT) { + interstep = 1; + intrastep = jas_seq2d_rowstep(x); + numseq = jas_seq2d_width(x); + startind = jas_seq2d_ystart(x); + endind = jas_seq2d_yend(x); + } else { + interstep = jas_seq2d_rowstep(x); + intrastep = 1; + numseq = jas_seq2d_height(x); + startind = jas_seq2d_xstart(x); + endind = jas_seq2d_xend(x); + } + + assert(startind < endind); + + startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x)); + if (!(flags & JPC_QMFB1D_RITIMODE)) { + while (numseq-- > 0) { + jpc_qmfb1d_setup(startptr, startind, endind, intrastep, + &lstartptr, &lstartind, &lendind, &hstartptr, + &hstartind, &hendind); + if (endind - startind > 1) { + NNS_SCALE(lstartptr, lstartind, lendind, + intrastep, jpc_dbltofix(1.23017410558578)); + NNS_SCALE(hstartptr, hstartind, hendind, + intrastep, jpc_dbltofix(1.62578613134411)); + NNS_LIFT1(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_dbltofix(-0.443506852)); + NNS_LIFT0(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_dbltofix(-0.882911075)); + NNS_LIFT1(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_dbltofix(0.052980118)); + NNS_LIFT0(lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind, intrastep, + jpc_dbltofix(1.586134342)); + jpc_qmfb1d_join(startptr, startind, endind, + intrastep, lstartptr, lstartind, lendind, + hstartptr, hstartind, hendind); + } else { +#if 0 + if (lstartind == lendind) { + *startptr = jpc_fix_asr(*startptr, 1); + } +#endif + } + startptr += interstep; + } + } else { + /* The reversible integer-to-integer mode is not supported + for this transform. */ + abort(); + } +} + +/******************************************************************************\ +* +\******************************************************************************/ + +jpc_qmfb1d_t *jpc_qmfb1d_make(int qmfbid) +{ + jpc_qmfb1d_t *qmfb; + if (!(qmfb = jpc_qmfb1d_create())) { + return 0; + } + switch (qmfbid) { + case JPC_QMFB1D_FT: + qmfb->ops = &jpc_ft_ops; + break; + case JPC_QMFB1D_NS: + qmfb->ops = &jpc_ns_ops; + break; + default: + jpc_qmfb1d_destroy(qmfb); + return 0; + break; + } + return qmfb; +} + +static jpc_qmfb1d_t *jpc_qmfb1d_create() +{ + jpc_qmfb1d_t *qmfb; + if (!(qmfb = jas_malloc(sizeof(jpc_qmfb1d_t)))) { + return 0; + } + qmfb->ops = 0; + return qmfb; +} + +jpc_qmfb1d_t *jpc_qmfb1d_copy(jpc_qmfb1d_t *qmfb) +{ + jpc_qmfb1d_t *newqmfb; + + if (!(newqmfb = jpc_qmfb1d_create())) { + return 0; + } + newqmfb->ops = qmfb->ops; + return newqmfb; +} + +void jpc_qmfb1d_destroy(jpc_qmfb1d_t *qmfb) +{ + jas_free(qmfb); +} + +/******************************************************************************\ +* +\******************************************************************************/ + +void jpc_qmfb1d_getbands(jpc_qmfb1d_t *qmfb, int flags, uint_fast32_t xstart, + uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend, int maxbands, + int *numbandsptr, jpc_qmfb1dband_t *bands) +{ + int start; + int end; + + assert(maxbands >= 2); + + if (flags & JPC_QMFB1D_VERT) { + start = ystart; + end = yend; + } else { + start = xstart; + end = xend; + } + assert(jpc_qmfb1d_getnumchans(qmfb) == 2); + assert(start <= end); + bands[0].start = JPC_CEILDIVPOW2(start, 1); + bands[0].end = JPC_CEILDIVPOW2(end, 1); + bands[0].locstart = start; + bands[0].locend = start + bands[0].end - bands[0].start; + bands[1].start = JPC_FLOORDIVPOW2(start, 1); + bands[1].end = JPC_FLOORDIVPOW2(end, 1); + bands[1].locstart = bands[0].locend; + bands[1].locend = bands[1].locstart + bands[1].end - bands[1].start; + assert(bands[1].locend == end); + *numbandsptr = 2; +} + +/******************************************************************************\ +* +\******************************************************************************/ + +int jpc_qmfb1d_getnumchans(jpc_qmfb1d_t *qmfb) +{ + return (*qmfb->ops->getnumchans)(qmfb); +} + +int jpc_qmfb1d_getanalfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters) +{ + return (*qmfb->ops->getanalfilters)(qmfb, len, filters); +} + +int jpc_qmfb1d_getsynfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters) +{ + return (*qmfb->ops->getsynfilters)(qmfb, len, filters); +} + +void jpc_qmfb1d_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x) +{ + (*qmfb->ops->analyze)(qmfb, flags, x); +} + +void jpc_qmfb1d_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x) +{ + (*qmfb->ops->synthesize)(qmfb, flags, x); +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_qmfb.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_qmfb.h new file mode 100644 index 0000000..8ee3799 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_qmfb.h @@ -0,0 +1,235 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Quadrature Mirror-Image Filter Bank (QMFB) Routines + * + * $Id$ + */ + +#ifndef JPC_QMFB_H +#define JPC_QMFB_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_seq.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* The maximum number of channels for a QMF bank. */ +#define JPC_QMFB1D_MAXCHANS 2 + +/* Select reversible integer-to-integer mode. */ +#define JPC_QMFB1D_RITIMODE 1 + +/* Vertical filtering. */ +#define JPC_QMFB1D_VERT 0x10000 + +/* QMFB IDs. */ +#define JPC_QMFB1D_FT 1 /* 5/3 */ +#define JPC_QMFB1D_NS 2 /* 9/7 */ + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* Forward declaration. */ +struct jpc_qmfb1dops_s; + +/* Band information. */ + +typedef struct { + + /* The starting index for the band in the downsampled domain. */ + int start; + + /* The ending index for the band in the downsampled domain. */ + int end; + + /* The location of the start of the band. */ + int locstart; + + /* The location of the end of the band. */ + int locend; + +} jpc_qmfb1dband_t; + +/* QMF bank */ + +typedef struct { + + /* The operations for this QMFB. */ + struct jpc_qmfb1dops_s *ops; + +} jpc_qmfb1d_t; + +/* QMFB operations. */ + +typedef struct jpc_qmfb1dops_s { + + /* The number of channels in the QMFB. */ + int (*getnumchans)(jpc_qmfb1d_t *qmfb); + + /* Get the analysis filters for this QMFB. */ + int (*getanalfilters)(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters); + + /* Get the synthesis filters for this QMFB. */ + int (*getsynfilters)(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters); + + /* Do analysis. */ + void (*analyze)(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x); + + /* Do synthesis. */ + void (*synthesize)(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x); + +} jpc_qmfb1dops_t; + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Create a QMFB from a QMFB ID. */ +jpc_qmfb1d_t *jpc_qmfb1d_make(int qmfbid); + +/* Create a copy of a QMFB. */ +jpc_qmfb1d_t *jpc_qmfb1d_copy(jpc_qmfb1d_t *qmfb); + +/* Destroy a QMFB. */ +void jpc_qmfb1d_destroy(jpc_qmfb1d_t *qmfb); + +/* Get the number of channels for a QMFB. */ +int jpc_qmfb1d_getnumchans(jpc_qmfb1d_t *qmfb); + +/* Get the analysis filters for a QMFB. */ +int jpc_qmfb1d_getanalfilters(jpc_qmfb1d_t *qmfb, int len, + jas_seq2d_t **filters); + +/* Get the synthesis filters for a QMFB. */ +int jpc_qmfb1d_getsynfilters(jpc_qmfb1d_t *qmfb, int len, + jas_seq2d_t **filters); + +/* Get the bands for a QMFB. */ +void jpc_qmfb1d_getbands(jpc_qmfb1d_t *qmfb, int flags, uint_fast32_t xstart, + uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend, int maxbands, + int *numbandsptr, jpc_qmfb1dband_t *bands); + +/* Perform analysis. */ +void jpc_qmfb1d_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x); + +/* Perform synthesis. */ +void jpc_qmfb1d_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1cod.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1cod.c new file mode 100644 index 0000000..d8f617f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1cod.c @@ -0,0 +1,546 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_math.h" + +#include "jpc_bs.h" +#include "jpc_dec.h" +#include "jpc_cs.h" +#include "jpc_mqcod.h" +#include "jpc_t1cod.h" +#include "jpc_tsfb.h" + +double jpc_pow2i(int n); + +/******************************************************************************\ +* Global data. +\******************************************************************************/ + +int jpc_zcctxnolut[4 * 256]; +int jpc_spblut[256]; +int jpc_scctxnolut[256]; +int jpc_magctxnolut[4096]; + +jpc_fix_t jpc_signmsedec[1 << JPC_NMSEDEC_BITS]; +jpc_fix_t jpc_refnmsedec[1 << JPC_NMSEDEC_BITS]; +jpc_fix_t jpc_signmsedec0[1 << JPC_NMSEDEC_BITS]; +jpc_fix_t jpc_refnmsedec0[1 << JPC_NMSEDEC_BITS]; + +jpc_mqctx_t jpc_mqctxs[JPC_NUMCTXS]; + +/******************************************************************************\ +* +\******************************************************************************/ + +void jpc_initmqctxs(void); + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +int JPC_PASSTYPE(int passno) +{ + int passtype; + switch (passno % 3) { + case 0: + passtype = JPC_CLNPASS; + break; + case 1: + passtype = JPC_SIGPASS; + break; + case 2: + passtype = JPC_REFPASS; + break; + default: + passtype = -1; + assert(0); + break; + } + return passtype; +} + +int JPC_NOMINALGAIN(int qmfbid, int numlvls, int lvlno, int orient) +{ + /* Avoid compiler warnings about unused parameters. */ + numlvls = 0; + +if (qmfbid == JPC_COX_INS) { + return 0; +} + assert(qmfbid == JPC_COX_RFT); + if (lvlno == 0) { + assert(orient == JPC_TSFB_LL); + return 0; + } else { + switch (orient) { + case JPC_TSFB_LH: + case JPC_TSFB_HL: + return 1; + break; + case JPC_TSFB_HH: + return 2; + break; + } + } + abort(); +} + +/******************************************************************************\ +* Coding pass related functions. +\******************************************************************************/ + +int JPC_SEGTYPE(int passno, int firstpassno, int bypass) +{ + int passtype; + if (bypass) { + passtype = JPC_PASSTYPE(passno); + if (passtype == JPC_CLNPASS) { + return JPC_SEG_MQ; + } + return ((passno < firstpassno + 10) ? JPC_SEG_MQ : JPC_SEG_RAW); + } else { + return JPC_SEG_MQ; + } +} + +int JPC_SEGPASSCNT(int passno, int firstpassno, int numpasses, int bypass, int termall) +{ + int ret; + int passtype; + + if (termall) { + ret = 1; + } else if (bypass) { + if (passno < firstpassno + 10) { + ret = 10 - (passno - firstpassno); + } else { + passtype = JPC_PASSTYPE(passno); + switch (passtype) { + case JPC_SIGPASS: + ret = 2; + break; + case JPC_REFPASS: + ret = 1; + break; + case JPC_CLNPASS: + ret = 1; + break; + default: + ret = -1; + assert(0); + break; + } + } + } else { + ret = JPC_PREC * 3 - 2; + } + ret = JAS_MIN(ret, numpasses - passno); + return ret; +} + +int JPC_ISTERMINATED(int passno, int firstpassno, int numpasses, int termall, + int lazy) +{ + int ret; + int n; + if (passno - firstpassno == numpasses - 1) { + ret = 1; + } else { + n = JPC_SEGPASSCNT(passno, firstpassno, numpasses, lazy, termall); + ret = (n <= 1) ? 1 : 0; + } + + return ret; +} + +/******************************************************************************\ +* Lookup table code. +\******************************************************************************/ + +void jpc_initluts() +{ + int i; + int orient; + int refine; + float u; + float v; + float t; + +/* XXX - hack */ +jpc_initmqctxs(); + + for (orient = 0; orient < 4; ++orient) { + for (i = 0; i < 256; ++i) { + jpc_zcctxnolut[(orient << 8) | i] = jpc_getzcctxno(i, orient); + } + } + + for (i = 0; i < 256; ++i) { + jpc_spblut[i] = jpc_getspb(i << 4); + } + + for (i = 0; i < 256; ++i) { + jpc_scctxnolut[i] = jpc_getscctxno(i << 4); + } + + for (refine = 0; refine < 2; ++refine) { + for (i = 0; i < 2048; ++i) { + jpc_magctxnolut[(refine << 11) + i] = jpc_getmagctxno((refine ? JPC_REFINE : 0) | i); + } + } + + for (i = 0; i < (1 << JPC_NMSEDEC_BITS); ++i) { + t = i * jpc_pow2i(-JPC_NMSEDEC_FRACBITS); + u = t; + v = t - 1.5; + jpc_signmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS)); +/* XXX - this calc is not correct */ + jpc_signmsedec0[i] = jpc_dbltofix(floor((u * u) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS)); + u = t - 1.0; + if (i & (1 << (JPC_NMSEDEC_BITS - 1))) { + v = t - 1.5; + } else { + v = t - 0.5; + } + jpc_refnmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS)); +/* XXX - this calc is not correct */ + jpc_refnmsedec0[i] = jpc_dbltofix(floor((u * u) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS)); + } +} + +jpc_fix_t jpc_getsignmsedec_func(jpc_fix_t x, int bitpos) +{ + jpc_fix_t y; + assert(!(x & (~JAS_ONES(bitpos + 1)))); + y = jpc_getsignmsedec_macro(x, bitpos); + return y; +} + +int jpc_getzcctxno(int f, int orient) +{ + int h; + int v; + int d; + int n; + int t; + int hv; + + /* Avoid compiler warning. */ + n = 0; + + h = ((f & JPC_WSIG) != 0) + ((f & JPC_ESIG) != 0); + v = ((f & JPC_NSIG) != 0) + ((f & JPC_SSIG) != 0); + d = ((f & JPC_NWSIG) != 0) + ((f & JPC_NESIG) != 0) + ((f & JPC_SESIG) != 0) + ((f & JPC_SWSIG) != 0); + switch (orient) { + case JPC_TSFB_HL: + t = h; + h = v; + v = t; + case JPC_TSFB_LL: + case JPC_TSFB_LH: + if (!h) { + if (!v) { + if (!d) { + n = 0; + } else if (d == 1) { + n = 1; + } else { + n = 2; + } + } else if (v == 1) { + n = 3; + } else { + n = 4; + } + } else if (h == 1) { + if (!v) { + if (!d) { + n = 5; + } else { + n = 6; + } + } else { + n = 7; + } + } else { + n = 8; + } + break; + case JPC_TSFB_HH: + hv = h + v; + if (!d) { + if (!hv) { + n = 0; + } else if (hv == 1) { + n = 1; + } else { + n = 2; + } + } else if (d == 1) { + if (!hv) { + n = 3; + } else if (hv == 1) { + n = 4; + } else { + n = 5; + } + } else if (d == 2) { + if (!hv) { + n = 6; + } else { + n = 7; + } + } else { + n = 8; + } + break; + } + assert(n < JPC_NUMZCCTXS); + return JPC_ZCCTXNO + n; +} + +int jpc_getspb(int f) +{ + int hc; + int vc; + int n; + + hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG), 1) - + JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) + ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1); + vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG), 1) - + JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) + ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1); + if (!hc && !vc) { + n = 0; + } else { + n = (!(hc > 0 || (!hc && vc > 0))); + } + return n; +} + +int jpc_getscctxno(int f) +{ + int hc; + int vc; + int n; + + /* Avoid compiler warning. */ + n = 0; + + hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG), + 1) - JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) + + ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1); + vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG), + 1) - JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) + + ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1); + assert(hc >= -1 && hc <= 1 && vc >= -1 && vc <= 1); + if (hc < 0) { + hc = -hc; + vc = -vc; + } + if (!hc) { + if (vc == -1) { + n = 1; + } else if (!vc) { + n = 0; + } else { + n = 1; + } + } else if (hc == 1) { + if (vc == -1) { + n = 2; + } else if (!vc) { + n = 3; + } else { + n = 4; + } + } + assert(n < JPC_NUMSCCTXS); + return JPC_SCCTXNO + n; +} + +int jpc_getmagctxno(int f) +{ + int n; + + if (!(f & JPC_REFINE)) { + n = (f & (JPC_OTHSIGMSK)) ? 1 : 0; + } else { + n = 2; + } + + assert(n < JPC_NUMMAGCTXS); + return JPC_MAGCTXNO + n; +} + +void jpc_initctxs(jpc_mqctx_t *ctxs) +{ + jpc_mqctx_t *ctx; + int i; + + ctx = ctxs; + for (i = 0; i < JPC_NUMCTXS; ++i) { + ctx->mps = 0; + switch (i) { + case JPC_UCTXNO: + ctx->ind = 46; + break; + case JPC_ZCCTXNO: + ctx->ind = 4; + break; + case JPC_AGGCTXNO: + ctx->ind = 3; + break; + default: + ctx->ind = 0; + break; + } + ++ctx; + } +} + +void jpc_initmqctxs() +{ + jpc_initctxs(jpc_mqctxs); +} + +/* Calculate the real quantity exp2(n), where x is an integer. */ +double jpc_pow2i(int n) +{ + double x; + double a; + + x = 1.0; + if (n < 0) { + a = 0.5; + n = -n; + } else { + a = 2.0; + } + while (--n >= 0) { + x *= a; + } + return x; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1cod.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1cod.h new file mode 100644 index 0000000..dd422aa --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1cod.h @@ -0,0 +1,344 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * $Id$ + */ + +#ifndef JPC_T1COD_H +#define JPC_T1COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_fix.h" +#include "jasper/jas_math.h" + +#include "jpc_mqcod.h" +#include "jpc_tsfb.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* The number of bits used to index into various lookup tables. */ +#define JPC_NMSEDEC_BITS 7 +#define JPC_NMSEDEC_FRACBITS (JPC_NMSEDEC_BITS - 1) + +/* + * Segment types. + */ + +/* Invalid. */ +#define JPC_SEG_INVALID 0 +/* MQ. */ +#define JPC_SEG_MQ 1 +/* Raw. */ +#define JPC_SEG_RAW 2 + +/* The nominal word size. */ +#define JPC_PREC 32 + +/* Tier-1 coding pass types. */ +#define JPC_SIGPASS 0 /* significance */ +#define JPC_REFPASS 1 /* refinement */ +#define JPC_CLNPASS 2 /* cleanup */ + +/* + * Per-sample state information for tier-1 coding. + */ + +/* The northeast neighbour has been found to be significant. */ +#define JPC_NESIG 0x0001 +/* The southeast neighbour has been found to be significant. */ +#define JPC_SESIG 0x0002 +/* The southwest neighbour has been found to be significant. */ +#define JPC_SWSIG 0x0004 +/* The northwest neighbour has been found to be significant. */ +#define JPC_NWSIG 0x0008 +/* The north neighbour has been found to be significant. */ +#define JPC_NSIG 0x0010 +/* The east neighbour has been found to be significant. */ +#define JPC_ESIG 0x0020 +/* The south neighbour has been found to be significant. */ +#define JPC_SSIG 0x0040 +/* The west neighbour has been found to be significant. */ +#define JPC_WSIG 0x0080 +/* The significance mask for 8-connected neighbours. */ +#define JPC_OTHSIGMSK \ + (JPC_NSIG | JPC_NESIG | JPC_ESIG | JPC_SESIG | JPC_SSIG | JPC_SWSIG | JPC_WSIG | JPC_NWSIG) +/* The significance mask for 4-connected neighbours. */ +#define JPC_PRIMSIGMSK (JPC_NSIG | JPC_ESIG | JPC_SSIG | JPC_WSIG) + +/* The north neighbour is negative in value. */ +#define JPC_NSGN 0x0100 +/* The east neighbour is negative in value. */ +#define JPC_ESGN 0x0200 +/* The south neighbour is negative in value. */ +#define JPC_SSGN 0x0400 +/* The west neighbour is negative in value. */ +#define JPC_WSGN 0x0800 +/* The sign mask for 4-connected neighbours. */ +#define JPC_SGNMSK (JPC_NSGN | JPC_ESGN | JPC_SSGN | JPC_WSGN) + +/* This sample has been found to be significant. */ +#define JPC_SIG 0x1000 +/* The sample has been refined. */ +#define JPC_REFINE 0x2000 +/* This sample has been processed during the significance pass. */ +#define JPC_VISIT 0x4000 + +/* The number of aggregation contexts. */ +#define JPC_NUMAGGCTXS 1 +/* The number of zero coding contexts. */ +#define JPC_NUMZCCTXS 9 +/* The number of magnitude contexts. */ +#define JPC_NUMMAGCTXS 3 +/* The number of sign coding contexts. */ +#define JPC_NUMSCCTXS 5 +/* The number of uniform contexts. */ +#define JPC_NUMUCTXS 1 + +/* The context ID for the first aggregation context. */ +#define JPC_AGGCTXNO 0 +/* The context ID for the first zero coding context. */ +#define JPC_ZCCTXNO (JPC_AGGCTXNO + JPC_NUMAGGCTXS) +/* The context ID for the first magnitude context. */ +#define JPC_MAGCTXNO (JPC_ZCCTXNO + JPC_NUMZCCTXS) +/* The context ID for the first sign coding context. */ +#define JPC_SCCTXNO (JPC_MAGCTXNO + JPC_NUMMAGCTXS) +/* The context ID for the first uniform context. */ +#define JPC_UCTXNO (JPC_SCCTXNO + JPC_NUMSCCTXS) +/* The total number of contexts. */ +#define JPC_NUMCTXS (JPC_UCTXNO + JPC_NUMUCTXS) + +/******************************************************************************\ +* External data. +\******************************************************************************/ + +/* These lookup tables are used by various macros/functions. */ +/* Do not access these lookup tables directly. */ +extern int jpc_zcctxnolut[]; +extern int jpc_spblut[]; +extern int jpc_scctxnolut[]; +extern int jpc_magctxnolut[]; +extern jpc_fix_t jpc_refnmsedec[]; +extern jpc_fix_t jpc_signmsedec[]; +extern jpc_fix_t jpc_refnmsedec0[]; +extern jpc_fix_t jpc_signmsedec0[]; + +/* The initial settings for the MQ contexts. */ +extern jpc_mqctx_t jpc_mqctxs[]; + +/******************************************************************************\ +* Functions and macros. +\******************************************************************************/ + +/* Initialize the MQ contexts. */ +void jpc_initctxs(jpc_mqctx_t *ctxs); + +/* Get the zero coding context. */ +int jpc_getzcctxno(int f, int orient); +#define JPC_GETZCCTXNO(f, orient) \ + (jpc_zcctxnolut[((orient) << 8) | ((f) & JPC_OTHSIGMSK)]) + +/* Get the sign prediction bit. */ +int jpc_getspb(int f); +#define JPC_GETSPB(f) \ + (jpc_spblut[((f) & (JPC_PRIMSIGMSK | JPC_SGNMSK)) >> 4]) + +/* Get the sign coding context. */ +int jpc_getscctxno(int f); +#define JPC_GETSCCTXNO(f) \ + (jpc_scctxnolut[((f) & (JPC_PRIMSIGMSK | JPC_SGNMSK)) >> 4]) + +/* Get the magnitude context. */ +int jpc_getmagctxno(int f); +#define JPC_GETMAGCTXNO(f) \ + (jpc_magctxnolut[((f) & JPC_OTHSIGMSK) | ((((f) & JPC_REFINE) != 0) << 11)]) + +/* Get the normalized MSE reduction for significance passes. */ +#define JPC_GETSIGNMSEDEC(x, bitpos) jpc_getsignmsedec_macro(x, bitpos) +jpc_fix_t jpc_getsignmsedec_func(jpc_fix_t x, int bitpos); +#define jpc_getsignmsedec_macro(x, bitpos) \ + ((bitpos > JPC_NMSEDEC_FRACBITS) ? jpc_signmsedec[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)] : \ + (jpc_signmsedec0[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)])) + +/* Get the normalized MSE reduction for refinement passes. */ +#define JPC_GETREFNMSEDEC(x, bitpos) jpc_getrefnmsedec_macro(x, bitpos) +jpc_fix_t jpc_refsignmsedec_func(jpc_fix_t x, int bitpos); +#define jpc_getrefnmsedec_macro(x, bitpos) \ + ((bitpos > JPC_NMSEDEC_FRACBITS) ? jpc_refnmsedec[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)] : \ + (jpc_refnmsedec0[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)])) + +/* Arithmetic shift right (with ability to shift left also). */ +#define JPC_ASR(x, n) \ + (((n) >= 0) ? ((x) >> (n)) : ((x) << (-(n)))) + +/* Update the per-sample state information. */ +#define JPC_UPDATEFLAGS4(fp, rowstep, s, vcausalflag) \ +{ \ + register jpc_fix_t *np = (fp) - (rowstep); \ + register jpc_fix_t *sp = (fp) + (rowstep); \ + if ((vcausalflag)) { \ + sp[-1] |= JPC_NESIG; \ + sp[1] |= JPC_NWSIG; \ + if (s) { \ + *sp |= JPC_NSIG | JPC_NSGN; \ + (fp)[-1] |= JPC_ESIG | JPC_ESGN; \ + (fp)[1] |= JPC_WSIG | JPC_WSGN; \ + } else { \ + *sp |= JPC_NSIG; \ + (fp)[-1] |= JPC_ESIG; \ + (fp)[1] |= JPC_WSIG; \ + } \ + } else { \ + np[-1] |= JPC_SESIG; \ + np[1] |= JPC_SWSIG; \ + sp[-1] |= JPC_NESIG; \ + sp[1] |= JPC_NWSIG; \ + if (s) { \ + *np |= JPC_SSIG | JPC_SSGN; \ + *sp |= JPC_NSIG | JPC_NSGN; \ + (fp)[-1] |= JPC_ESIG | JPC_ESGN; \ + (fp)[1] |= JPC_WSIG | JPC_WSGN; \ + } else { \ + *np |= JPC_SSIG; \ + *sp |= JPC_NSIG; \ + (fp)[-1] |= JPC_ESIG; \ + (fp)[1] |= JPC_WSIG; \ + } \ + } \ +} + +/* Initialize the lookup tables used by the codec. */ +void jpc_initluts(void); + +/* Get the nominal gain associated with a particular band. */ +int JPC_NOMINALGAIN(int qmfbid, int numlvls, int lvlno, int orient); + +/* Get the coding pass type. */ +int JPC_PASSTYPE(int passno); + +/* Get the segment type. */ +int JPC_SEGTYPE(int passno, int firstpassno, int bypass); + +/* Get the number of coding passess in the segment. */ +int JPC_SEGPASSCNT(int passno, int firstpassno, int numpasses, int bypass, + int termall); + +/* Is the coding pass terminated? */ +int JPC_ISTERMINATED(int passno, int firstpassno, int numpasses, int termall, + int lazy); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1dec.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1dec.c new file mode 100644 index 0000000..9649b0f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1dec.c @@ -0,0 +1,971 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier 1 Decoder + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_fix.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_math.h" + +#include "jpc_bs.h" +#include "jpc_mqdec.h" +#include "jpc_t1dec.h" +#include "jpc_t1cod.h" +#include "jpc_dec.h" + +/******************************************************************************\ +* +\******************************************************************************/ + +static int jpc_dec_decodecblk(jpc_dec_t *dec, jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band, + jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs); +static int dec_sigpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int orient, + int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data); +static int dec_rawsigpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos, + int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data); +static int dec_refpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int vcausalflag, + jas_matrix_t *flags, jas_matrix_t *data); +static int dec_rawrefpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos, + int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data); +static int dec_clnpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int orient, + int vcausalflag, int segsymflag, jas_matrix_t *flags, jas_matrix_t *data); + +#if defined(DEBUG) +static long t1dec_cnt = 0; +#endif + +#if !defined(DEBUG) +#define JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) \ + ((v) = jpc_mqdec_getbit(mqdec)) +#else +#define JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) \ +{ \ + (v) = jpc_mqdec_getbit(mqdec); \ + if (jas_getdbglevel() >= 100) { \ + fprintf(stderr, "index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v); \ + ++t1dec_cnt; \ + } \ +} +#endif +#define JPC_T1D_GETBITNOSKEW(mqdec, v, passtypename, symtypename) \ + JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) + +#if !defined(DEBUG) +#define JPC_T1D_RAWGETBIT(bitstream, v, passtypename, symtypename) \ + ((v) = jpc_bitstream_getbit(bitstream)) +#else +#define JPC_T1D_RAWGETBIT(bitstream, v, passtypename, symtypename) \ +{ \ + (v) = jpc_bitstream_getbit(bitstream); \ + if (jas_getdbglevel() >= 100) { \ + fprintf(stderr, "index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v); \ + ++t1dec_cnt; \ + } \ +} +#endif + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +int jpc_dec_decodecblks(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + jpc_dec_tcomp_t *tcomp; + int compcnt; + jpc_dec_rlvl_t *rlvl; + int rlvlcnt; + jpc_dec_band_t *band; + int bandcnt; + jpc_dec_prc_t *prc; + int prccnt; + jpc_dec_cblk_t *cblk; + int cblkcnt; + + for (compcnt = dec->numcomps, tcomp = tile->tcomps; compcnt > 0; + --compcnt, ++tcomp) { + for (rlvlcnt = tcomp->numrlvls, rlvl = tcomp->rlvls; + rlvlcnt > 0; --rlvlcnt, ++rlvl) { + if (!rlvl->bands) { + continue; + } + for (bandcnt = rlvl->numbands, band = rlvl->bands; + bandcnt > 0; --bandcnt, ++band) { + if (!band->data) { + continue; + } + for (prccnt = rlvl->numprcs, prc = band->prcs; + prccnt > 0; --prccnt, ++prc) { + if (!prc->cblks) { + continue; + } + for (cblkcnt = prc->numcblks, + cblk = prc->cblks; cblkcnt > 0; + --cblkcnt, ++cblk) { + if (jpc_dec_decodecblk(dec, tile, tcomp, + band, cblk, 1, JPC_MAXLYRS)) { + return -1; + } + } + } + + } + } + } + + return 0; +} + +static int jpc_dec_decodecblk(jpc_dec_t *dec, jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band, + jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs) +{ + jpc_dec_seg_t *seg; + int i; + int bpno; + int passtype; + int ret; + int compno; + int filldata; + int fillmask; + jpc_dec_ccp_t *ccp; + + compno = tcomp - tile->tcomps; + + if (!cblk->flags) { + /* Note: matrix is assumed to be zeroed */ + if (!(cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + + 2, jas_matrix_numcols(cblk->data) + 2))) { + return -1; + } + } + + seg = cblk->segs.head; + while (seg && (seg != cblk->curseg || dopartial) && (maxlyrs < 0 || + seg->lyrno < maxlyrs)) { + assert(seg->numpasses >= seg->maxpasses || dopartial); + assert(seg->stream); + jas_stream_rewind(seg->stream); + jas_stream_setrwcount(seg->stream, 0); + if (seg->type == JPC_SEG_MQ) { + if (!cblk->mqdec) { + if (!(cblk->mqdec = jpc_mqdec_create(JPC_NUMCTXS, 0))) { + return -1; + } + jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs); + } + jpc_mqdec_setinput(cblk->mqdec, seg->stream); + jpc_mqdec_init(cblk->mqdec); + } else { + assert(seg->type == JPC_SEG_RAW); + if (!cblk->nulldec) { + if (!(cblk->nulldec = jpc_bitstream_sopen(seg->stream, "r"))) { + assert(0); + } + } + } + + + for (i = 0; i < seg->numpasses; ++i) { + if (cblk->numimsbs > band->numbps) { + ccp = &tile->cp->ccps[compno]; + if (ccp->roishift <= 0) { + fprintf(stderr, "warning: corrupt code stream\n"); + } else { + if (cblk->numimsbs < ccp->roishift - band->numbps) { + fprintf(stderr, "warning: corrupt code stream\n"); + } + } + } + bpno = band->roishift + band->numbps - 1 - (cblk->numimsbs + + (seg->passno + i - cblk->firstpassno + 2) / 3); +if (bpno < 0) { + goto premature_exit; +} +#if 1 + passtype = (seg->passno + i + 2) % 3; +#else + passtype = JPC_PASSTYPE(seg->passno + i + 2); +#endif + assert(bpno >= 0 && bpno < 31); + switch (passtype) { + case JPC_SIGPASS: + ret = (seg->type == JPC_SEG_MQ) ? dec_sigpass(dec, + cblk->mqdec, bpno, band->orient, + (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, + cblk->flags, cblk->data) : + dec_rawsigpass(dec, cblk->nulldec, bpno, + (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, + cblk->flags, cblk->data); + break; + case JPC_REFPASS: + ret = (seg->type == JPC_SEG_MQ) ? + dec_refpass(dec, cblk->mqdec, bpno, + (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, + cblk->flags, cblk->data) : + dec_rawrefpass(dec, cblk->nulldec, bpno, + (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, + cblk->flags, cblk->data); + break; + case JPC_CLNPASS: + assert(seg->type == JPC_SEG_MQ); + ret = dec_clnpass(dec, cblk->mqdec, bpno, + band->orient, (tile->cp->ccps[compno].cblkctx & + JPC_COX_VSC) != 0, (tile->cp->ccps[compno].cblkctx & + JPC_COX_SEGSYM) != 0, cblk->flags, + cblk->data); + break; + default: + ret = -1; + break; + } + /* Do we need to reset after each coding pass? */ + if (tile->cp->ccps[compno].cblkctx & JPC_COX_RESET) { + jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs); + } + + if (ret) { + fprintf(stderr, "coding pass failed passtype=%d segtype=%d\n", passtype, seg->type); + return -1; + } + + } + + if (seg->type == JPC_SEG_MQ) { +/* Note: dont destroy mq decoder because context info will be lost */ + } else { + assert(seg->type == JPC_SEG_RAW); + if (tile->cp->ccps[compno].cblkctx & JPC_COX_PTERM) { + fillmask = 0x7f; + filldata = 0x2a; + } else { + fillmask = 0; + filldata = 0; + } + if ((ret = jpc_bitstream_inalign(cblk->nulldec, fillmask, + filldata)) < 0) { + return -1; + } else if (ret > 0) { + fprintf(stderr, "warning: bad termination pattern detected\n"); + } + jpc_bitstream_close(cblk->nulldec); + cblk->nulldec = 0; + } + + cblk->curseg = seg->next; + jpc_seglist_remove(&cblk->segs, seg); + jpc_seg_destroy(seg); + seg = cblk->curseg; + } + + assert(dopartial ? (!cblk->curseg) : 1); + +premature_exit: + return 0; +} + +/******************************************************************************\ +* Code for significance pass. +\******************************************************************************/ + +#define jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf, orient, mqdec, vcausalflag) \ +{ \ + int f; \ + int v; \ + f = *(fp); \ + if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \ + jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO(f, (orient))); \ + JPC_T1D_GETBIT((mqdec), v, "SIG", "ZC"); \ + if (v) { \ + jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \ + JPC_T1D_GETBIT((mqdec), v, "SIG", "SC"); \ + v ^= JPC_GETSPB(f); \ + JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \ + *(fp) |= JPC_SIG; \ + *(dp) = (v) ? (-(oneplushalf)) : (oneplushalf); \ + } \ + *(fp) |= JPC_VISIT; \ + } \ +} + +static int dec_sigpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos, int orient, + int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data) +{ + int i; + int j; + int one; + int half; + int oneplushalf; + int vscanlen; + int width; + int height; + jpc_fix_t *fp; + int frowstep; + int fstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *fvscanstart; + jpc_fix_t *dp; + int drowstep; + int dstripestep; + jpc_fix_t *dstripestart; + jpc_fix_t *dvscanstart; + int k; + + /* Avoid compiler warning about unused parameters. */ + dec = 0; + + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << bitpos; + half = one >> 1; + oneplushalf = one | half; + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + + /* Process first sample in vertical scan. */ + jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf, + orient, mqdec, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process second sample in vertical scan. */ + jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf, + orient, mqdec, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process third sample in vertical scan. */ + jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf, + orient, mqdec, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process fourth sample in vertical scan. */ + jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf, + orient, mqdec, 0); + } + } + return 0; +} + +#define jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, in, vcausalflag) \ +{ \ + jpc_fix_t f = *(fp); \ + jpc_fix_t v; \ + if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \ + JPC_T1D_RAWGETBIT(in, v, "SIG", "ZC"); \ + if (v < 0) { \ + return -1; \ + } \ + if (v) { \ + JPC_T1D_RAWGETBIT(in, v, "SIG", "SC"); \ + if (v < 0) { \ + return -1; \ + } \ + JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \ + *(fp) |= JPC_SIG; \ + *(dp) = v ? (-oneplushalf) : (oneplushalf); \ + } \ + *(fp) |= JPC_VISIT; \ + } \ +} + +static int dec_rawsigpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos, int vcausalflag, + jas_matrix_t *flags, jas_matrix_t *data) +{ + int i; + int j; + int k; + int one; + int half; + int oneplushalf; + int vscanlen; + int width; + int height; + jpc_fix_t *fp; + int frowstep; + int fstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *fvscanstart; + jpc_fix_t *dp; + int drowstep; + int dstripestep; + jpc_fix_t *dstripestart; + jpc_fix_t *dvscanstart; + + /* Avoid compiler warning about unused parameters. */ + dec = 0; + + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << bitpos; + half = one >> 1; + oneplushalf = one | half; + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + + /* Process first sample in vertical scan. */ + jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, + in, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process second sample in vertical scan. */ + jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, + in, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process third sample in vertical scan. */ + jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, + in, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process fourth sample in vertical scan. */ + jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, + in, 0); + + } + } + return 0; +} + +/******************************************************************************\ +* Code for refinement pass. +\******************************************************************************/ + +#define jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, vcausalflag) \ +{ \ + int v; \ + int t; \ + if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \ + jpc_mqdec_setcurctx((mqdec), JPC_GETMAGCTXNO(*(fp))); \ + JPC_T1D_GETBITNOSKEW((mqdec), v, "REF", "MR"); \ + t = (v ? (poshalf) : (neghalf)); \ + *(dp) += (*(dp) < 0) ? (-t) : t; \ + *(fp) |= JPC_REFINE; \ + } \ +} + +static int dec_refpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos, + int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data) +{ + int i; + int j; + int vscanlen; + int width; + int height; + int one; + int poshalf; + int neghalf; + jpc_fix_t *fp; + int frowstep; + int fstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *fvscanstart; + jpc_fix_t *dp; + int drowstep; + int dstripestep; + jpc_fix_t *dstripestart; + jpc_fix_t *dvscanstart; + int k; + + /* Avoid compiler warning about unused parameters. */ + dec = 0; + vcausalflag = 0; + + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << bitpos; + poshalf = one >> 1; + neghalf = (bitpos > 0) ? (-poshalf) : (-1); + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + + /* Process first sample in vertical scan. */ + jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, + vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process second sample in vertical scan. */ + jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process third sample in vertical scan. */ + jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process fourth sample in vertical scan. */ + jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0); + } + } + + return 0; +} + +#define jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, vcausalflag) \ +{ \ + jpc_fix_t v; \ + jpc_fix_t t; \ + if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \ + JPC_T1D_RAWGETBIT(in, v, "REF", "MAGREF"); \ + if (v < 0) { \ + return -1; \ + } \ + t = (v ? poshalf : neghalf); \ + *(dp) += (*(dp) < 0) ? (-t) : t; \ + *(fp) |= JPC_REFINE; \ + } \ +} + +static int dec_rawrefpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos, int vcausalflag, + jas_matrix_t *flags, jas_matrix_t *data) +{ + int i; + int j; + int k; + int vscanlen; + int width; + int height; + int one; + int poshalf; + int neghalf; + jpc_fix_t *fp; + int frowstep; + int fstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *fvscanstart; + jpc_fix_t *dp; + int drowstep; + int dstripestep; + jpc_fix_t *dstripestart; + jpc_fix_t *dvscanstart; + + /* Avoid compiler warning about unused parameters. */ + dec = 0; + vcausalflag = 0; + + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << bitpos; + poshalf = one >> 1; + neghalf = (bitpos > 0) ? (-poshalf) : (-1); + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + + /* Process first sample in vertical scan. */ + jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, + vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process second sample in vertical scan. */ + jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process third sample in vertical scan. */ + jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process fourth sample in vertical scan. */ + jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0); + } + } + return 0; +} + +/******************************************************************************\ +* Code for cleanup pass. +\******************************************************************************/ + +#define jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, mqdec, flabel, plabel, vcausalflag) \ +{ \ + int v; \ +flabel \ + if (!((f) & (JPC_SIG | JPC_VISIT))) { \ + jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO((f), (orient))); \ + JPC_T1D_GETBIT((mqdec), v, "CLN", "ZC"); \ + if (v) { \ +plabel \ + /* Coefficient is significant. */ \ + jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \ + JPC_T1D_GETBIT((mqdec), v, "CLN", "SC"); \ + v ^= JPC_GETSPB(f); \ + *(dp) = (v) ? (-(oneplushalf)) : (oneplushalf); \ + JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \ + *(fp) |= JPC_SIG; \ + } \ + } \ + /* XXX - Is this correct? Can aggregation cause some VISIT bits not to be reset? Check. */ \ + *(fp) &= ~JPC_VISIT; \ +} + +static int dec_clnpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos, int orient, + int vcausalflag, int segsymflag, jas_matrix_t *flags, jas_matrix_t *data) +{ + int i; + int j; + int k; + int vscanlen; + int v; + int half; + int runlen; + int f; + int width; + int height; + int one; + int oneplushalf; + + jpc_fix_t *fp; + int frowstep; + int fstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *fvscanstart; + + jpc_fix_t *dp; + int drowstep; + int dstripestep; + jpc_fix_t *dstripestart; + jpc_fix_t *dvscanstart; + + /* Avoid compiler warning about unused parameters. */ + dec = 0; + + one = 1 << bitpos; + half = one >> 1; + oneplushalf = one | half; + + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = 0; i < height; i += 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(4, height - i); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + if (vscanlen >= 4 && (!((*fp) & (JPC_SIG | JPC_VISIT | + JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) & (JPC_SIG | + JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) & + (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, + !((*fp) & (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK)))) { + + jpc_mqdec_setcurctx(mqdec, JPC_AGGCTXNO); + JPC_T1D_GETBIT(mqdec, v, "CLN", "AGG"); + if (!v) { + continue; + } + jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO); + JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "RL"); + runlen = v; + JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "RL"); + runlen = (runlen << 1) | v; + f = *(fp = fvscanstart + frowstep * runlen); + dp = dvscanstart + drowstep * runlen; + k = vscanlen - runlen; + switch (runlen) { + case 0: + goto clnpass_partial0; + break; + case 1: + goto clnpass_partial1; + break; + case 2: + goto clnpass_partial2; + break; + case 3: + goto clnpass_partial3; + break; + } + } else { + f = *(fp = fvscanstart); + dp = dvscanstart; + k = vscanlen; + goto clnpass_full0; + } + + /* Process first sample in vertical scan. */ + jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, + mqdec, clnpass_full0:, clnpass_partial0:, + vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process second sample in vertical scan. */ + f = *fp; + jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, + mqdec, ;, clnpass_partial1:, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process third sample in vertical scan. */ + f = *fp; + jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, + mqdec, ;, clnpass_partial2:, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + /* Process fourth sample in vertical scan. */ + f = *fp; + jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, + mqdec, ;, clnpass_partial3:, 0); + } + } + + if (segsymflag) { + int segsymval; + segsymval = 0; + jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO); + JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM"); + segsymval = (segsymval << 1) | (v & 1); + JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM"); + segsymval = (segsymval << 1) | (v & 1); + JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM"); + segsymval = (segsymval << 1) | (v & 1); + JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM"); + segsymval = (segsymval << 1) | (v & 1); + if (segsymval != 0xa) { + fprintf(stderr, "warning: bad segmentation symbol\n"); + } + } + + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1dec.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1dec.h new file mode 100644 index 0000000..eb233af --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1dec.h @@ -0,0 +1,137 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier 1 Decoder + * + * $Id$ + */ + +#ifndef JPC_T1DEC_H +#define JPC_T1DEC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jpc_dec.h" +#include "jpc_mqdec.h" +#include "jpc_t1cod.h" + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Decode all of the code blocks for a particular tile. */ +int jpc_dec_decodecblks(jpc_dec_t *dec, jpc_dec_tile_t *tile); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1enc.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1enc.c new file mode 100644 index 0000000..2e46161 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1enc.c @@ -0,0 +1,1008 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier 1 Encoder + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_fix.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" + +#include "jpc_t1enc.h" +#include "jpc_t1cod.h" +#include "jpc_enc.h" +#include "jpc_cod.h" +#include "jpc_math.h" + +static int jpc_encsigpass(jpc_mqenc_t *mqenc, int bitpos, int orient, int, + jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec); + +static int jpc_encrefpass(jpc_mqenc_t *mqenc, int bitpos, int, jas_matrix_t *flags, + jas_matrix_t *data, int term, long *nmsedec); + +static int jpc_encclnpass(jpc_mqenc_t *mqenc, int bitpos, int orient, int, + int, jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec); + +static int jpc_encrawsigpass(jpc_bitstream_t *out, int bitpos, int, + jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec); + +static int jpc_encrawrefpass(jpc_bitstream_t *out, int bitpos, int, + jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec); + +/******************************************************************************\ +* Code for encoding code blocks. +\******************************************************************************/ + +/* Encode all of the code blocks associated with the current tile. */ +int jpc_enc_enccblks(jpc_enc_t *enc) +{ + jpc_enc_tcmpt_t *tcmpt; + jpc_enc_tcmpt_t *endcomps; + jpc_enc_rlvl_t *lvl; + jpc_enc_rlvl_t *endlvls; + jpc_enc_band_t *band; + jpc_enc_band_t *endbands; + jpc_enc_cblk_t *cblk; + jpc_enc_cblk_t *endcblks; + int i; + int j; + int mx; + int bmx; + int v; + jpc_enc_tile_t *tile; + uint_fast32_t prcno; + jpc_enc_prc_t *prc; + + tile = enc->curtile; + + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (tcmpt = tile->tcmpts; tcmpt != endcomps; ++tcmpt) { + endlvls = &tcmpt->rlvls[tcmpt->numrlvls]; + for (lvl = tcmpt->rlvls; lvl != endlvls; ++lvl) { + if (!lvl->bands) { + continue; + } + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + bmx = 0; + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + mx = 0; + for (i = 0; i < jas_matrix_numrows(cblk->data); ++i) { + for (j = 0; j < jas_matrix_numcols(cblk->data); ++j) { + v = abs(jas_matrix_get(cblk->data, i, j)); + if (v > mx) { + mx = v; + } + } + } + if (mx > bmx) { + bmx = mx; + } + cblk->numbps = JAS_MAX(jpc_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0); + } + + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + cblk->numimsbs = band->numbps - cblk->numbps; + assert(cblk->numimsbs >= 0); + } + + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + if (jpc_enc_enccblk(enc, cblk->stream, tcmpt, band, cblk)) { + return -1; + } + } + } + } + } + } + return 0; +} + +int getthebyte(jas_stream_t *in, long off) +{ + int c; + long oldpos; + oldpos = jas_stream_tell(in); + assert(oldpos >= 0); + jas_stream_seek(in, off, SEEK_SET); + c = jas_stream_peekc(in); + jas_stream_seek(in, oldpos, SEEK_SET); + return c; +} + +/* Encode a single code block. */ +int jpc_enc_enccblk(jpc_enc_t *enc, jas_stream_t *out, jpc_enc_tcmpt_t *tcmpt, jpc_enc_band_t *band, jpc_enc_cblk_t *cblk) +{ + jpc_enc_pass_t *pass; + jpc_enc_pass_t *endpasses; + int bitpos; + int n; + int adjust; + int ret; + int passtype; + int t; + jpc_bitstream_t *bout; + jpc_enc_pass_t *termpass; + jpc_enc_rlvl_t *rlvl; + int vcausal; + int segsym; + int termmode; + int c; + + bout = 0; + rlvl = band->rlvl; + + cblk->stream = jas_stream_memopen(0, 0); + assert(cblk->stream); + cblk->mqenc = jpc_mqenc_create(JPC_NUMCTXS, cblk->stream); + assert(cblk->mqenc); + jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs); + + cblk->numpasses = (cblk->numbps > 0) ? (3 * cblk->numbps - 2) : 0; + if (cblk->numpasses > 0) { + cblk->passes = jas_malloc(cblk->numpasses * sizeof(jpc_enc_pass_t)); + assert(cblk->passes); + } else { + cblk->passes = 0; + } + endpasses = &cblk->passes[cblk->numpasses]; + for (pass = cblk->passes; pass != endpasses; ++pass) { + pass->start = 0; + pass->end = 0; + pass->term = JPC_ISTERMINATED(pass - cblk->passes, 0, cblk->numpasses, (tcmpt->cblksty & JPC_COX_TERMALL) != 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0); + pass->type = JPC_SEGTYPE(pass - cblk->passes, 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0); + pass->lyrno = -1; +if (pass == endpasses - 1) { +assert(pass->term == 1); + pass->term = 1; +} + } + + cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + 2, + jas_matrix_numcols(cblk->data) + 2); + assert(cblk->flags); + + + bitpos = cblk->numbps - 1; + pass = cblk->passes; + n = cblk->numpasses; + while (--n >= 0) { + + if (pass->type == JPC_SEG_MQ) { + /* NOP */ + } else { + assert(pass->type == JPC_SEG_RAW); + if (!bout) { + bout = jpc_bitstream_sopen(cblk->stream, "w"); + assert(bout); + } + } + +#if 1 + passtype = (pass - cblk->passes + 2) % 3; +#else + passtype = JPC_PASSTYPE(pass - cblk->passes + 2); +#endif + pass->start = jas_stream_tell(cblk->stream); +#if 0 +assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream)); +#endif + assert(bitpos >= 0); + vcausal = (tcmpt->cblksty & JPC_COX_VSC) != 0; + segsym = (tcmpt->cblksty & JPC_COX_SEGSYM) != 0; + if (pass->term) { + termmode = ((tcmpt->cblksty & JPC_COX_PTERM) ? + JPC_MQENC_PTERM : JPC_MQENC_DEFTERM) + 1; + } else { + termmode = 0; + } + switch (passtype) { + case JPC_SIGPASS: + ret = (pass->type == JPC_SEG_MQ) ? jpc_encsigpass(cblk->mqenc, + bitpos, band->orient, vcausal, cblk->flags, + cblk->data, termmode, &pass->nmsedec) : + jpc_encrawsigpass(bout, bitpos, vcausal, cblk->flags, + cblk->data, termmode, &pass->nmsedec); + break; + case JPC_REFPASS: + ret = (pass->type == JPC_SEG_MQ) ? jpc_encrefpass(cblk->mqenc, + bitpos, vcausal, cblk->flags, cblk->data, termmode, + &pass->nmsedec) : jpc_encrawrefpass(bout, bitpos, + vcausal, cblk->flags, cblk->data, termmode, + &pass->nmsedec); + break; + case JPC_CLNPASS: + assert(pass->type == JPC_SEG_MQ); + ret = jpc_encclnpass(cblk->mqenc, bitpos, band->orient, + vcausal, segsym, cblk->flags, cblk->data, termmode, + &pass->nmsedec); + break; + default: + assert(0); + break; + } + + if (pass->type == JPC_SEG_MQ) { + if (pass->term) { + jpc_mqenc_init(cblk->mqenc); + } + jpc_mqenc_getstate(cblk->mqenc, &pass->mqencstate); + pass->end = jas_stream_tell(cblk->stream); + if (tcmpt->cblksty & JPC_COX_RESET) { + jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs); + } + } else { + if (pass->term) { + if (jpc_bitstream_pending(bout)) { + jpc_bitstream_outalign(bout, 0x2a); + } + jpc_bitstream_close(bout); + bout = 0; + pass->end = jas_stream_tell(cblk->stream); + } else { + pass->end = jas_stream_tell(cblk->stream) + + jpc_bitstream_pending(bout); +/* NOTE - This will not work. need to adjust by # of pending output bytes */ + } + } +#if 0 +/* XXX - This assertion fails sometimes when various coding modes are used. +This seems to be harmless, but why does it happen at all? */ +assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream)); +#endif + + pass->wmsedec = jpc_fixtodbl(band->rlvl->tcmpt->synweight) * + jpc_fixtodbl(band->rlvl->tcmpt->synweight) * + jpc_fixtodbl(band->synweight) * + jpc_fixtodbl(band->synweight) * + jpc_fixtodbl(band->absstepsize) * jpc_fixtodbl(band->absstepsize) * + ((double) (1 << bitpos)) * ((double)(1 << bitpos)) * + jpc_fixtodbl(pass->nmsedec); + pass->cumwmsedec = pass->wmsedec; + if (pass != cblk->passes) { + pass->cumwmsedec += pass[-1].cumwmsedec; + } + if (passtype == JPC_CLNPASS) { + --bitpos; + } + ++pass; + } + +#if 0 +dump_passes(cblk->passes, cblk->numpasses, cblk); +#endif + + n = 0; + endpasses = &cblk->passes[cblk->numpasses]; + for (pass = cblk->passes; pass != endpasses; ++pass) { + if (pass->start < n) { + pass->start = n; + } + if (pass->end < n) { + pass->end = n; + } + if (!pass->term) { + termpass = pass; + while (termpass - pass < cblk->numpasses && + !termpass->term) { + ++termpass; + } + if (pass->type == JPC_SEG_MQ) { + t = (pass->mqencstate.lastbyte == 0xff) ? 1 : 0; + if (pass->mqencstate.ctreg >= 5) { + adjust = 4 + t; + } else { + adjust = 5 + t; + } + pass->end += adjust; + } + if (pass->end > termpass->end) { + pass->end = termpass->end; + } + if ((c = getthebyte(cblk->stream, pass->end - 1)) == EOF) { + abort(); + } + if (c == 0xff) { + ++pass->end; + } + n = JAS_MAX(n, pass->end); + } else { + n = JAS_MAX(n, pass->end); + } + } + +#if 0 +dump_passes(cblk->passes, cblk->numpasses, cblk); +#endif + + if (bout) { + jpc_bitstream_close(bout); + } + + return 0; +} + +/******************************************************************************\ +* Code for significance pass. +\******************************************************************************/ + +#define sigpass_step(fp, frowstep, dp, bitpos, one, nmsedec, orient, mqenc, vcausalflag) \ +{ \ + int f; \ + int v; \ + f = *(fp); \ + if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \ + v = (abs(*(dp)) & (one)) ? 1 : 0; \ + jpc_mqenc_setcurctx(mqenc, JPC_GETZCCTXNO(f, (orient))); \ + jpc_mqenc_putbit(mqenc, v); \ + if (v) { \ + *(nmsedec) += JPC_GETSIGNMSEDEC(abs(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \ + v = ((*(dp) < 0) ? 1 : 0); \ + jpc_mqenc_setcurctx(mqenc, JPC_GETSCCTXNO(f)); \ + jpc_mqenc_putbit(mqenc, v ^ JPC_GETSPB(f)); \ + JPC_UPDATEFLAGS4(fp, frowstep, v, vcausalflag); \ + *(fp) |= JPC_SIG; \ + } \ + *(fp) |= JPC_VISIT; \ + } \ +} + +static int jpc_encsigpass(jpc_mqenc_t *mqenc, int bitpos, int orient, int vcausalflag, + jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec) +{ + int i; + int j; + int one; + int vscanlen; + int width; + int height; + int frowstep; + int drowstep; + int fstripestep; + int dstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *dstripestart; + jpc_fix_t *fp; + jpc_fix_t *dp; + jpc_fix_t *fvscanstart; + jpc_fix_t *dvscanstart; + int k; + + *nmsedec = 0; + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << (bitpos + JPC_NUMEXTRABITS); + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + + sigpass_step(fp, frowstep, dp, bitpos, one, + nmsedec, orient, mqenc, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + sigpass_step(fp, frowstep, dp, bitpos, one, + nmsedec, orient, mqenc, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + sigpass_step(fp, frowstep, dp, bitpos, one, + nmsedec, orient, mqenc, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + sigpass_step(fp, frowstep, dp, bitpos, one, + nmsedec, orient, mqenc, 0); + + } + } + + if (term) { + jpc_mqenc_flush(mqenc, term - 1); + } + + return jpc_mqenc_error(mqenc) ? (-1) : 0; +} + +#define rawsigpass_step(fp, frowstep, dp, bitpos, one, nmsedec, out, vcausalflag) \ +{ \ + jpc_fix_t f = *(fp); \ + jpc_fix_t v; \ + if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \ + v = (abs(*(dp)) & (one)) ? 1 : 0; \ + if ((jpc_bitstream_putbit((out), v)) == EOF) { \ + return -1; \ + } \ + if (v) { \ + *(nmsedec) += JPC_GETSIGNMSEDEC(abs(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \ + v = ((*(dp) < 0) ? 1 : 0); \ + if (jpc_bitstream_putbit(out, v) == EOF) { \ + return -1; \ + } \ + JPC_UPDATEFLAGS4(fp, frowstep, v, vcausalflag); \ + *(fp) |= JPC_SIG; \ + } \ + *(fp) |= JPC_VISIT; \ + } \ +} + +static int jpc_encrawsigpass(jpc_bitstream_t *out, int bitpos, int vcausalflag, jas_matrix_t *flags, + jas_matrix_t *data, int term, long *nmsedec) +{ + int i; + int j; + int k; + int one; + int vscanlen; + int width; + int height; + int frowstep; + int drowstep; + int fstripestep; + int dstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *dstripestart; + jpc_fix_t *fp; + jpc_fix_t *dp; + jpc_fix_t *fvscanstart; + jpc_fix_t *dvscanstart; + + *nmsedec = 0; + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << (bitpos + JPC_NUMEXTRABITS); + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + + rawsigpass_step(fp, frowstep, dp, bitpos, one, + nmsedec, out, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + rawsigpass_step(fp, frowstep, dp, bitpos, one, + nmsedec, out, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + rawsigpass_step(fp, frowstep, dp, bitpos, one, + nmsedec, out, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + rawsigpass_step(fp, frowstep, dp, bitpos, one, + nmsedec, out, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + + } + } + + if (term) { + jpc_bitstream_outalign(out, 0x2a); + } + + return 0; +} + +/******************************************************************************\ +* Code for refinement pass. +\******************************************************************************/ + +#define refpass_step(fp, dp, bitpos, one, nmsedec, mqenc, vcausalflag) \ +{ \ + int v; \ + if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \ + (d) = *(dp); \ + *(nmsedec) += JPC_GETREFNMSEDEC(abs(d), (bitpos) + JPC_NUMEXTRABITS); \ + jpc_mqenc_setcurctx((mqenc), JPC_GETMAGCTXNO(*(fp))); \ + v = (abs(d) & (one)) ? 1 : 0; \ + jpc_mqenc_putbit((mqenc), v); \ + *(fp) |= JPC_REFINE; \ + } \ +} + +static int jpc_encrefpass(jpc_mqenc_t *mqenc, int bitpos, int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data, + int term, long *nmsedec) +{ + int i; + int j; + int one; + int vscanlen; + int d; + int width; + int height; + int frowstep; + int drowstep; + int fstripestep; + int dstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *dstripestart; + jpc_fix_t *fvscanstart; + jpc_fix_t *dvscanstart; + jpc_fix_t *dp; + jpc_fix_t *fp; +int k; + + *nmsedec = 0; + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << (bitpos + JPC_NUMEXTRABITS); + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + + refpass_step(fp, dp, bitpos, one, nmsedec, + mqenc, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + refpass_step(fp, dp, bitpos, one, nmsedec, + mqenc, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + refpass_step(fp, dp, bitpos, one, nmsedec, + mqenc, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + refpass_step(fp, dp, bitpos, one, nmsedec, + mqenc, 0); + + } + } + + if (term) { + jpc_mqenc_flush(mqenc, term - 1); + } + + return jpc_mqenc_error(mqenc) ? (-1) : 0; +} + +#define rawrefpass_step(fp, dp, bitpos, one, nmsedec, out, vcausalflag) \ +{ \ + jpc_fix_t d; \ + jpc_fix_t v; \ + if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \ + d = *(dp); \ + *(nmsedec) += JPC_GETREFNMSEDEC(abs(d), (bitpos) + JPC_NUMEXTRABITS); \ + v = (abs(d) & (one)) ? 1 : 0; \ + if (jpc_bitstream_putbit((out), v) == EOF) { \ + return -1; \ + } \ + *(fp) |= JPC_REFINE; \ + } \ +} + +static int jpc_encrawrefpass(jpc_bitstream_t *out, int bitpos, int vcausalflag, jas_matrix_t *flags, + jas_matrix_t *data, int term, long *nmsedec) +{ + int i; + int j; + int k; + int one; + int vscanlen; + int width; + int height; + int frowstep; + int drowstep; + int fstripestep; + int dstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *dstripestart; + jpc_fix_t *fvscanstart; + jpc_fix_t *dvscanstart; + jpc_fix_t *dp; + jpc_fix_t *fp; + + *nmsedec = 0; + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << (bitpos + JPC_NUMEXTRABITS); + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + + rawrefpass_step(fp, dp, bitpos, one, nmsedec, + out, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + rawrefpass_step(fp, dp, bitpos, one, nmsedec, + out, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + rawrefpass_step(fp, dp, bitpos, one, nmsedec, + out, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + rawrefpass_step(fp, dp, bitpos, one, nmsedec, + out, vcausalflag); + + } + } + + if (term) { + jpc_bitstream_outalign(out, 0x2a); + } + + return 0; +} + +/******************************************************************************\ +* Code for cleanup pass. +\******************************************************************************/ + +#define clnpass_step(fp, frowstep, dp, bitpos, one, orient, nmsedec, mqenc, label1, label2, vcausalflag) \ +{ \ + int f; \ + int v; \ +label1 \ + f = *(fp); \ + if (!(f & (JPC_SIG | JPC_VISIT))) { \ + jpc_mqenc_setcurctx(mqenc, JPC_GETZCCTXNO(f, (orient))); \ + v = (abs(*(dp)) & (one)) ? 1 : 0; \ + jpc_mqenc_putbit((mqenc), v); \ + if (v) { \ +label2 \ + f = *(fp); \ + /* Coefficient is significant. */ \ + *(nmsedec) += JPC_GETSIGNMSEDEC(abs(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \ + jpc_mqenc_setcurctx((mqenc), JPC_GETSCCTXNO(f)); \ + v = ((*(dp) < 0) ? 1 : 0); \ + jpc_mqenc_putbit((mqenc), v ^ JPC_GETSPB(f)); \ + JPC_UPDATEFLAGS4((fp), (frowstep), v, vcausalflag); \ + *(fp) |= JPC_SIG; \ + } \ + } \ + *(fp) &= ~JPC_VISIT; \ +} + +static int jpc_encclnpass(jpc_mqenc_t *mqenc, int bitpos, int orient, int vcausalflag, int segsymflag, jas_matrix_t *flags, + jas_matrix_t *data, int term, long *nmsedec) +{ + int i; + int j; + int k; + int vscanlen; + int v; + int runlen; + jpc_fix_t *fp; + int width; + int height; + jpc_fix_t *dp; + int one; + int frowstep; + int drowstep; + int fstripestep; + int dstripestep; + jpc_fix_t *fstripestart; + jpc_fix_t *dstripestart; + jpc_fix_t *fvscanstart; + jpc_fix_t *dvscanstart; + + *nmsedec = 0; + width = jas_matrix_numcols(data); + height = jas_matrix_numrows(data); + frowstep = jas_matrix_rowstep(flags); + drowstep = jas_matrix_rowstep(data); + fstripestep = frowstep << 2; + dstripestep = drowstep << 2; + + one = 1 << (bitpos + JPC_NUMEXTRABITS); + + fstripestart = jas_matrix_getref(flags, 1, 1); + dstripestart = jas_matrix_getref(data, 0, 0); + for (i = height; i > 0; i -= 4, fstripestart += fstripestep, + dstripestart += dstripestep) { + fvscanstart = fstripestart; + dvscanstart = dstripestart; + vscanlen = JAS_MIN(i, 4); + for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) { + + fp = fvscanstart; + if (vscanlen >= 4 && !((*fp) & (JPC_SIG | JPC_VISIT | + JPC_OTHSIGMSK)) && (fp += frowstep, !((*fp) & (JPC_SIG | + JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) & + (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, + !((*fp) & (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK)))) { + dp = dvscanstart; + for (k = 0; k < vscanlen; ++k) { + v = (abs(*dp) & one) ? 1 : 0; + if (v) { + break; + } + dp += drowstep; + } + runlen = k; + if (runlen >= 4) { + jpc_mqenc_setcurctx(mqenc, JPC_AGGCTXNO); + jpc_mqenc_putbit(mqenc, 0); + continue; + } + jpc_mqenc_setcurctx(mqenc, JPC_AGGCTXNO); + jpc_mqenc_putbit(mqenc, 1); + jpc_mqenc_setcurctx(mqenc, JPC_UCTXNO); + jpc_mqenc_putbit(mqenc, runlen >> 1); + jpc_mqenc_putbit(mqenc, runlen & 1); + fp = fvscanstart + frowstep * runlen; + dp = dvscanstart + drowstep * runlen; + k = vscanlen - runlen; + switch (runlen) { + case 0: + goto clnpass_partial0; + break; + case 1: + goto clnpass_partial1; + break; + case 2: + goto clnpass_partial2; + break; + case 3: + goto clnpass_partial3; + break; + } + } else { + runlen = 0; + fp = fvscanstart; + dp = dvscanstart; + k = vscanlen; + goto clnpass_full0; + } + clnpass_step(fp, frowstep, dp, bitpos, one, + orient, nmsedec, mqenc, clnpass_full0:, clnpass_partial0:, vcausalflag); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + clnpass_step(fp, frowstep, dp, bitpos, one, + orient, nmsedec, mqenc, ;, clnpass_partial1:, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + clnpass_step(fp, frowstep, dp, bitpos, one, + orient, nmsedec, mqenc, ;, clnpass_partial2:, 0); + if (--k <= 0) { + continue; + } + fp += frowstep; + dp += drowstep; + clnpass_step(fp, frowstep, dp, bitpos, one, + orient, nmsedec, mqenc, ;, clnpass_partial3:, 0); + } + } + + if (segsymflag) { + jpc_mqenc_setcurctx(mqenc, JPC_UCTXNO); + jpc_mqenc_putbit(mqenc, 1); + jpc_mqenc_putbit(mqenc, 0); + jpc_mqenc_putbit(mqenc, 1); + jpc_mqenc_putbit(mqenc, 0); + } + + if (term) { + jpc_mqenc_flush(mqenc, term - 1); + } + + return jpc_mqenc_error(mqenc) ? (-1) : 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1enc.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1enc.h new file mode 100644 index 0000000..ffc5cf3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t1enc.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier 1 Encoder + * + * $Id$ + */ + +#ifndef JPC_T1ENC_H +#define JPC_T1ENC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_seq.h" + +#include "jpc_enc.h" +#include "jpc_t1cod.h" + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Encode all of the code blocks. */ +int jpc_enc_enccblks(jpc_enc_t *enc); + +/* Encode a single code block. */ +int jpc_enc_enccblk(jpc_enc_t *enc, jas_stream_t *out, jpc_enc_tcmpt_t *comp, + jpc_enc_band_t *band, jpc_enc_cblk_t *cblk); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2cod.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2cod.c new file mode 100644 index 0000000..10e0a4f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2cod.c @@ -0,0 +1,733 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier-2 Coding Library + * + * $Id$ + */ + +#include "jasper/jas_math.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" + +#include "jpc_cs.h" +#include "jpc_t2cod.h" +#include "jpc_math.h" + +static int jpc_pi_nextlrcp(jpc_pi_t *pi); +static int jpc_pi_nextrlcp(jpc_pi_t *pi); +static int jpc_pi_nextrpcl(jpc_pi_t *pi); +static int jpc_pi_nextpcrl(jpc_pi_t *pi); +static int jpc_pi_nextcprl(jpc_pi_t *pi); + +int jpc_pi_next(jpc_pi_t *pi) +{ + jpc_pchg_t *pchg; + int ret; + + + for (;;) { + + pi->valid = false; + + if (!pi->pchg) { + ++pi->pchgno; + pi->compno = 0; + pi->rlvlno = 0; + pi->prcno = 0; + pi->lyrno = 0; + pi->prgvolfirst = true; + if (pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) { + pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno); + } else if (pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) { + pi->pchg = &pi->defaultpchg; + } else { + return 1; + } + } + + pchg = pi->pchg; + switch (pchg->prgord) { + case JPC_COD_LRCPPRG: + ret = jpc_pi_nextlrcp(pi); + break; + case JPC_COD_RLCPPRG: + ret = jpc_pi_nextrlcp(pi); + break; + case JPC_COD_RPCLPRG: + ret = jpc_pi_nextrpcl(pi); + break; + case JPC_COD_PCRLPRG: + ret = jpc_pi_nextpcrl(pi); + break; + case JPC_COD_CPRLPRG: + ret = jpc_pi_nextcprl(pi); + break; + default: + ret = -1; + break; + } + if (!ret) { + pi->valid = true; + ++pi->pktno; + return 0; + } + pi->pchg = 0; + } +} + +static int jpc_pi_nextlrcp(register jpc_pi_t *pi) +{ + jpc_pchg_t *pchg; + int *prclyrno; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + goto skip; + } else { + pi->prgvolfirst = false; + } + + for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < + JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && + pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { + for (pi->compno = pchg->compnostart, pi->picomp = + &pi->picomps[pi->compno]; pi->compno < pi->numcomps + && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, + ++pi->picomp) { + if (pi->rlvlno >= pi->picomp->numrlvls) { + continue; + } + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + for (pi->prcno = 0, prclyrno = + pi->pirlvl->prclyrnos; pi->prcno < + pi->pirlvl->numprcs; ++pi->prcno, + ++prclyrno) { + if (pi->lyrno >= *prclyrno) { + *prclyrno = pi->lyrno; + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + return 1; +} + +static int jpc_pi_nextrlcp(register jpc_pi_t *pi) +{ + jpc_pchg_t *pchg; + int *prclyrno; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + assert(pi->prcno < pi->pirlvl->numprcs); + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + goto skip; + } else { + pi->prgvolfirst = 0; + } + + for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && + pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { + for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < + JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + for (pi->compno = pchg->compnostart, pi->picomp = + &pi->picomps[pi->compno]; pi->compno < pi->numcomps && + pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { + if (pi->rlvlno >= pi->picomp->numrlvls) { + continue; + } + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; + pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { + if (pi->lyrno >= *prclyrno) { + *prclyrno = pi->lyrno; + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + return 1; +} + +static int jpc_pi_nextrpcl(register jpc_pi_t *pi) +{ + int rlvlno; + jpc_pirlvl_t *pirlvl; + jpc_pchg_t *pchg; + int prchind; + int prcvind; + int *prclyrno; + int compno; + jpc_picomp_t *picomp; + int xstep; + int ystep; + uint_fast32_t r; + uint_fast32_t rpx; + uint_fast32_t rpy; + uint_fast32_t trx0; + uint_fast32_t try0; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + goto skip; + } else { + pi->xstep = 0; + pi->ystep = 0; + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + + picomp->numrlvls - rlvlno - 1)); + ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + + picomp->numrlvls - rlvlno - 1)); + pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); + pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); + } + } + pi->prgvolfirst = 0; + } + + for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && + pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { + for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += + pi->ystep - (pi->y % pi->ystep)) { + for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += + pi->xstep - (pi->x % pi->xstep)) { + for (pi->compno = pchg->compnostart, + pi->picomp = &pi->picomps[pi->compno]; + pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < + pi->numcomps; ++pi->compno, ++pi->picomp) { + if (pi->rlvlno >= pi->picomp->numrlvls) { + continue; + } + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + if (pi->pirlvl->numprcs == 0) { + continue; + } + r = pi->picomp->numrlvls - 1 - pi->rlvlno; + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; + trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) + || !(pi->x % (1 << rpx))) && + ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) + || !(pi->y % (1 << rpy)))) { + prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp + << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, + pi->pirlvl->prcwidthexpn); + prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp + << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, + pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; + + assert(pi->prcno < pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < + pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + } + } + return 1; +} + +static int jpc_pi_nextpcrl(register jpc_pi_t *pi) +{ + int rlvlno; + jpc_pirlvl_t *pirlvl; + jpc_pchg_t *pchg; + int prchind; + int prcvind; + int *prclyrno; + int compno; + jpc_picomp_t *picomp; + int xstep; + int ystep; + uint_fast32_t trx0; + uint_fast32_t try0; + uint_fast32_t r; + uint_fast32_t rpx; + uint_fast32_t rpy; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + goto skip; + } else { + pi->xstep = 0; + pi->ystep = 0; + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + xstep = picomp->hsamp * (1 << + (pirlvl->prcwidthexpn + picomp->numrlvls - + rlvlno - 1)); + ystep = picomp->vsamp * (1 << + (pirlvl->prcheightexpn + picomp->numrlvls - + rlvlno - 1)); + pi->xstep = (!pi->xstep) ? xstep : + JAS_MIN(pi->xstep, xstep); + pi->ystep = (!pi->ystep) ? ystep : + JAS_MIN(pi->ystep, ystep); + } + } + pi->prgvolfirst = 0; + } + + for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - + (pi->y % pi->ystep)) { + for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - + (pi->x % pi->xstep)) { + for (pi->compno = pchg->compnostart, pi->picomp = + &pi->picomps[pi->compno]; pi->compno < pi->numcomps + && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, + ++pi->picomp) { + for (pi->rlvlno = pchg->rlvlnostart, + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + pi->rlvlno < pi->picomp->numrlvls && + pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, + ++pi->pirlvl) { + if (pi->pirlvl->numprcs == 0) { + continue; + } + r = pi->picomp->numrlvls - 1 - pi->rlvlno; + trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; + if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || + !(pi->x % (pi->picomp->hsamp << rpx))) && + ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || + !(pi->y % (pi->picomp->vsamp << rpy)))) { + prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp + << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, + pi->pirlvl->prcwidthexpn); + prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp + << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, + pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; + assert(pi->prcno < pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && + pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + } + } + return 1; +} + +static int jpc_pi_nextcprl(register jpc_pi_t *pi) +{ + int rlvlno; + jpc_pirlvl_t *pirlvl; + jpc_pchg_t *pchg; + int prchind; + int prcvind; + int *prclyrno; + uint_fast32_t trx0; + uint_fast32_t try0; + uint_fast32_t r; + uint_fast32_t rpx; + uint_fast32_t rpy; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + goto skip; + } else { + pi->prgvolfirst = 0; + } + + for (pi->compno = pchg->compnostart, pi->picomp = + &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, + ++pi->picomp) { + pirlvl = pi->picomp->pirlvls; + pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn + + pi->picomp->numrlvls - 1)); + pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn + + pi->picomp->numrlvls - 1)); + for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1]; + rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) { + pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 << + (pirlvl->prcwidthexpn + pi->picomp->numrlvls - + rlvlno - 1))); + pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 << + (pirlvl->prcheightexpn + pi->picomp->numrlvls - + rlvlno - 1))); + } + for (pi->y = pi->ystart; pi->y < pi->yend; + pi->y += pi->ystep - (pi->y % pi->ystep)) { + for (pi->x = pi->xstart; pi->x < pi->xend; + pi->x += pi->xstep - (pi->x % pi->xstep)) { + for (pi->rlvlno = pchg->rlvlnostart, + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < + pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { + if (pi->pirlvl->numprcs == 0) { + continue; + } + r = pi->picomp->numrlvls - 1 - pi->rlvlno; + trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; + if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || + !(pi->x % (pi->picomp->hsamp << rpx))) && + ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || + !(pi->y % (pi->picomp->vsamp << rpy)))) { + prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp + << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, + pi->pirlvl->prcwidthexpn); + prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp + << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, + pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * + pi->pirlvl->numhprcs + + prchind; + assert(pi->prcno < + pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < + pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + } + } + return 1; +} + +static void pirlvl_destroy(jpc_pirlvl_t *rlvl) +{ + if (rlvl->prclyrnos) { + jas_free(rlvl->prclyrnos); + } +} + +static void jpc_picomp_destroy(jpc_picomp_t *picomp) +{ + int rlvlno; + jpc_pirlvl_t *pirlvl; + if (picomp->pirlvls) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + pirlvl_destroy(pirlvl); + } + jas_free(picomp->pirlvls); + } +} + +void jpc_pi_destroy(jpc_pi_t *pi) +{ + jpc_picomp_t *picomp; + int compno; + if (pi->picomps) { + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; + ++compno, ++picomp) { + jpc_picomp_destroy(picomp); + } + jas_free(pi->picomps); + } + if (pi->pchglist) { + jpc_pchglist_destroy(pi->pchglist); + } + jas_free(pi); +} + +jpc_pi_t *jpc_pi_create0() +{ + jpc_pi_t *pi; + if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) { + return 0; + } + pi->picomps = 0; + pi->pchgno = 0; + if (!(pi->pchglist = jpc_pchglist_create())) { + jas_free(pi); + return 0; + } + return pi; +} + +int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg) +{ + return jpc_pchglist_insert(pi->pchglist, -1, pchg); +} + +jpc_pchglist_t *jpc_pchglist_create() +{ + jpc_pchglist_t *pchglist; + if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) { + return 0; + } + pchglist->numpchgs = 0; + pchglist->maxpchgs = 0; + pchglist->pchgs = 0; + return pchglist; +} + +int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg) +{ + int i; + int newmaxpchgs; + jpc_pchg_t **newpchgs; + if (pchgno < 0) { + pchgno = pchglist->numpchgs; + } + if (pchglist->numpchgs >= pchglist->maxpchgs) { + newmaxpchgs = pchglist->maxpchgs + 128; + if (!(newpchgs = jas_realloc(pchglist->pchgs, newmaxpchgs * sizeof(jpc_pchg_t *)))) { + return -1; + } + pchglist->maxpchgs = newmaxpchgs; + pchglist->pchgs = newpchgs; + } + for (i = pchglist->numpchgs; i > pchgno; --i) { + pchglist->pchgs[i] = pchglist->pchgs[i - 1]; + } + pchglist->pchgs[pchgno] = pchg; + ++pchglist->numpchgs; + return 0; +} + +jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno) +{ + int i; + jpc_pchg_t *pchg; + assert(pchgno < pchglist->numpchgs); + pchg = pchglist->pchgs[pchgno]; + for (i = pchgno + 1; i < pchglist->numpchgs; ++i) { + pchglist->pchgs[i - 1] = pchglist->pchgs[i]; + } + --pchglist->numpchgs; + return pchg; +} + +jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg) +{ + jpc_pchg_t *newpchg; + if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) { + return 0; + } + *newpchg = *pchg; + return newpchg; +} + +jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist) +{ + jpc_pchglist_t *newpchglist; + jpc_pchg_t *newpchg; + int pchgno; + if (!(newpchglist = jpc_pchglist_create())) { + return 0; + } + for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { + if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) || + jpc_pchglist_insert(newpchglist, -1, newpchg)) { + jpc_pchglist_destroy(newpchglist); + return 0; + } + } + return newpchglist; +} + +void jpc_pchglist_destroy(jpc_pchglist_t *pchglist) +{ + int pchgno; + if (pchglist->pchgs) { + for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { + jpc_pchg_destroy(pchglist->pchgs[pchgno]); + } + jas_free(pchglist->pchgs); + } + jas_free(pchglist); +} + +void jpc_pchg_destroy(jpc_pchg_t *pchg) +{ + jas_free(pchg); +} + +jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno) +{ + return pchglist->pchgs[pchgno]; +} + +int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist) +{ + return pchglist->numpchgs; +} + +int jpc_pi_init(jpc_pi_t *pi) +{ + int compno; + int rlvlno; + int prcno; + jpc_picomp_t *picomp; + jpc_pirlvl_t *pirlvl; + int *prclyrno; + + pi->prgvolfirst = 0; + pi->valid = 0; + pi->pktno = -1; + pi->pchgno = -1; + pi->pchg = 0; + + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + for (prcno = 0, prclyrno = pirlvl->prclyrnos; + prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { + *prclyrno = 0; + } + } + } + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2cod.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2cod.h new file mode 100644 index 0000000..61d540d --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2cod.h @@ -0,0 +1,348 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier-2 Coding Library + * + * $Id$ + */ + +#ifndef JPC_T2COD_H +#define JPC_T2COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jpc_cs.h" + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* Progression change list. */ + +typedef struct { + + /* The number of progression changes. */ + int numpchgs; + + /* The maximum number of progression changes that can be accomodated + without growing the progression change array. */ + int maxpchgs; + + /* The progression changes. */ + jpc_pchg_t **pchgs; + +} jpc_pchglist_t; + +/* Packet iterator per-resolution-level information. */ + +typedef struct { + + /* The number of precincts. */ + int numprcs; + + /* The last layer processed for each precinct. */ + int *prclyrnos; + + /* The precinct width exponent. */ + int prcwidthexpn; + + /* The precinct height exponent. */ + int prcheightexpn; + + /* The number of precincts spanning the resolution level in the horizontal + direction. */ + int numhprcs; + +} jpc_pirlvl_t; + +/* Packet iterator per-component information. */ + +typedef struct { + + /* The number of resolution levels. */ + int numrlvls; + + /* The per-resolution-level information. */ + jpc_pirlvl_t *pirlvls; + + /* The horizontal sampling period. */ + int hsamp; + + /* The vertical sampling period. */ + int vsamp; + +} jpc_picomp_t; + +/* Packet iterator class. */ + +typedef struct { + + /* The number of layers. */ + int numlyrs; + + /* The number of resolution levels. */ + int maxrlvls; + + /* The number of components. */ + int numcomps; + + /* The per-component information. */ + jpc_picomp_t *picomps; + + /* The current component. */ + jpc_picomp_t *picomp; + + /* The current resolution level. */ + jpc_pirlvl_t *pirlvl; + + /* The number of the current component. */ + int compno; + + /* The number of the current resolution level. */ + int rlvlno; + + /* The number of the current precinct. */ + int prcno; + + /* The number of the current layer. */ + int lyrno; + + /* The x-coordinate of the current position. */ + int x; + + /* The y-coordinate of the current position. */ + int y; + + /* The horizontal step size. */ + int xstep; + + /* The vertical step size. */ + int ystep; + + /* The x-coordinate of the top-left corner of the tile on the reference + grid. */ + int xstart; + + /* The y-coordinate of the top-left corner of the tile on the reference + grid. */ + int ystart; + + /* The x-coordinate of the bottom-right corner of the tile on the + reference grid (plus one). */ + int xend; + + /* The y-coordinate of the bottom-right corner of the tile on the + reference grid (plus one). */ + int yend; + + /* The current progression change. */ + jpc_pchg_t *pchg; + + /* The progression change list. */ + jpc_pchglist_t *pchglist; + + /* The progression to use in the absense of explicit specification. */ + jpc_pchg_t defaultpchg; + + /* The current progression change number. */ + int pchgno; + + /* Is this the first time in the current progression volume? */ + bool prgvolfirst; + + /* Is the current iterator value valid? */ + bool valid; + + /* The current packet number. */ + int pktno; + +} jpc_pi_t; + +/******************************************************************************\ +* Functions/macros for packet iterators. +\******************************************************************************/ + +/* Create a packet iterator. */ +jpc_pi_t *jpc_pi_create0(void); + +/* Destroy a packet iterator. */ +void jpc_pi_destroy(jpc_pi_t *pi); + +/* Add a progression change to a packet iterator. */ +int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg); + +/* Prepare a packet iterator for iteration. */ +int jpc_pi_init(jpc_pi_t *pi); + +/* Set the iterator to the first packet. */ +int jpc_pi_begin(jpc_pi_t *pi); + +/* Proceed to the next packet in sequence. */ +int jpc_pi_next(jpc_pi_t *pi); + +/* Get the index of the current packet. */ +#define jpc_pi_getind(pi) ((pi)->pktno) + +/* Get the component number of the current packet. */ +#define jpc_pi_cmptno(pi) (assert(pi->valid), (pi)->compno) + +/* Get the resolution level of the current packet. */ +#define jpc_pi_rlvlno(pi) (assert(pi->valid), (pi)->rlvlno) + +/* Get the layer number of the current packet. */ +#define jpc_pi_lyrno(pi) (assert(pi->valid), (pi)->lyrno) + +/* Get the precinct number of the current packet. */ +#define jpc_pi_prcno(pi) (assert(pi->valid), (pi)->prcno) + +/* Get the progression order for the current packet. */ +#define jpc_pi_prg(pi) (assert(pi->valid), (pi)->pchg->prgord) + +/******************************************************************************\ +* Functions/macros for progression change lists. +\******************************************************************************/ + +/* Create a progression change list. */ +jpc_pchglist_t *jpc_pchglist_create(void); + +/* Destroy a progression change list. */ +void jpc_pchglist_destroy(jpc_pchglist_t *pchglist); + +/* Insert a new element into a progression change list. */ +int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg); + +/* Remove an element from a progression change list. */ +jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno); + +/* Get an element from a progression change list. */ +jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno); + +/* Copy a progression change list. */ +jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist); + +/* Get the number of elements in a progression change list. */ +int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist); + +/******************************************************************************\ +* Functions/macros for progression changes. +\******************************************************************************/ + +/* Destroy a progression change. */ +void jpc_pchg_destroy(jpc_pchg_t *pchg); + +/* Copy a progression change. */ +jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2dec.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2dec.c new file mode 100644 index 0000000..9456a6a --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2dec.c @@ -0,0 +1,630 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier 2 Decoder + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_fix.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_debug.h" + +#include "jpc_bs.h" +#include "jpc_dec.h" +#include "jpc_cs.h" +#include "jpc_mqdec.h" +#include "jpc_t2dec.h" +#include "jpc_t1cod.h" +#include "jpc_math.h" + +/******************************************************************************\ +* +\******************************************************************************/ + +long jpc_dec_lookahead(jas_stream_t *in); +static int jpc_getcommacode(jpc_bitstream_t *in); +static int jpc_getnumnewpasses(jpc_bitstream_t *in); +static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int lvlno, + int prcno, int lyrno); + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +static int jpc_getcommacode(jpc_bitstream_t *in) +{ + int n; + int v; + + n = 0; + for (;;) { + if ((v = jpc_bitstream_getbit(in)) < 0) { + return -1; + } + if (jpc_bitstream_eof(in)) { + return -1; + } + if (!v) { + break; + } + ++n; + } + + return n; +} + +static int jpc_getnumnewpasses(jpc_bitstream_t *in) +{ + int n; + + if ((n = jpc_bitstream_getbit(in)) > 0) { + if ((n = jpc_bitstream_getbit(in)) > 0) { + if ((n = jpc_bitstream_getbits(in, 2)) == 3) { + if ((n = jpc_bitstream_getbits(in, 5)) == 31) { + if ((n = jpc_bitstream_getbits(in, 7)) >= 0) { + n += 36 + 1; + } + } else if (n >= 0) { + n += 5 + 1; + } + } else if (n >= 0) { + n += 2 + 1; + } + } else if (!n) { + n += 2; + } + } else if (!n) { + ++n; + } + + return n; +} + +static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno, + int prcno, int lyrno) +{ + jpc_bitstream_t *inb; + jpc_dec_tcomp_t *tcomp; + jpc_dec_rlvl_t *rlvl; + jpc_dec_band_t *band; + jpc_dec_cblk_t *cblk; + int n; + int m; + int i; + jpc_tagtreenode_t *leaf; + int included; + int ret; + int numnewpasses; + jpc_dec_seg_t *seg; + int len; + int present; + int savenumnewpasses; + int mycounter; + jpc_ms_t *ms; + jpc_dec_tile_t *tile; + jpc_dec_ccp_t *ccp; + jpc_dec_cp_t *cp; + int bandno; + jpc_dec_prc_t *prc; + int usedcblkcnt; + int cblkno; + uint_fast32_t bodylen; + bool discard; + int passno; + int maxpasses; + int hdrlen; + int hdroffstart; + int hdroffend; + + /* Avoid compiler warning about possible use of uninitialized + variable. */ + bodylen = 0; + + discard = (lyrno >= dec->maxlyrs); + + tile = dec->curtile; + cp = tile->cp; + ccp = &cp->ccps[compno]; + + /* + * Decode the packet header. + */ + + /* Decode the SOP marker segment if present. */ + if (cp->csty & JPC_COD_SOP) { + if (jpc_dec_lookahead(in) == JPC_MS_SOP) { + if (!(ms = jpc_getms(in, dec->cstate))) { + return -1; + } + if (jpc_ms_gettype(ms) != JPC_MS_SOP) { + jpc_ms_destroy(ms); + fprintf(stderr, "missing SOP marker segment\n"); + return -1; + } + jpc_ms_destroy(ms); + } + } + +hdroffstart = jas_stream_getrwcount(pkthdrstream); + + if (!(inb = jpc_bitstream_sopen(pkthdrstream, "r"))) { + return -1; + } + + if ((present = jpc_bitstream_getbit(inb)) < 0) { + return 1; + } + JAS_DBGLOG(10, ("\n", present)); + JAS_DBGLOG(10, ("present=%d ", present)); + + /* Is the packet non-empty? */ + if (present) { + /* The packet is non-empty. */ + tcomp = &tile->tcomps[compno]; + rlvl = &tcomp->rlvls[rlvlno]; + bodylen = 0; + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (!band->data) { + continue; + } + prc = &band->prcs[prcno]; + if (!prc->cblks) { + continue; + } + usedcblkcnt = 0; + for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; + ++cblkno, ++cblk) { + ++usedcblkcnt; + if (!cblk->numpasses) { + leaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1); + if ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) { + return -1; + } + } else { + if ((included = jpc_bitstream_getbit(inb)) < 0) { + return -1; + } + } + JAS_DBGLOG(10, ("\n")); + JAS_DBGLOG(10, ("included=%d ", included)); + if (!included) { + continue; + } + if (!cblk->numpasses) { + i = 1; + leaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1); + for (;;) { + if ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) { + return -1; + } + if (ret) { + break; + } + ++i; + } + cblk->numimsbs = i - 1; + cblk->firstpassno = cblk->numimsbs * 3; + } + if ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) { + return -1; + } + JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses)); + seg = cblk->curseg; + savenumnewpasses = numnewpasses; + mycounter = 0; + if (numnewpasses > 0) { + if ((m = jpc_getcommacode(inb)) < 0) { + return -1; + } + cblk->numlenbits += m; + JAS_DBGLOG(10, ("increment=%d ", m)); + while (numnewpasses > 0) { + passno = cblk->firstpassno + cblk->numpasses + mycounter; + /* XXX - the maxpasses is not set precisely but this doesn't matter... */ + maxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0); + if (!discard && !seg) { + if (!(seg = jpc_seg_alloc())) { + return -1; + } + jpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg); + if (!cblk->curseg) { + cblk->curseg = seg; + } + seg->passno = passno; + seg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0); + seg->maxpasses = maxpasses; + } + n = JAS_MIN(numnewpasses, maxpasses); + mycounter += n; + numnewpasses -= n; + if ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) { + return -1; + } + JAS_DBGLOG(10, ("len=%d ", len)); + if (!discard) { + seg->lyrno = lyrno; + seg->numpasses += n; + seg->cnt = len; + seg = seg->next; + } + bodylen += len; + } + } + cblk->numpasses += savenumnewpasses; + } + } + + jpc_bitstream_inalign(inb, 0, 0); + + } else { + if (jpc_bitstream_inalign(inb, 0x7f, 0)) { + fprintf(stderr, "alignment failed\n"); + return -1; + } + } + jpc_bitstream_close(inb); + + hdroffend = jas_stream_getrwcount(pkthdrstream); + hdrlen = hdroffend - hdroffstart; + if (jas_getdbglevel() >= 5) { + fprintf(stderr, "hdrlen=%lu bodylen=%lu \n", (unsigned long) hdrlen, + (unsigned long) bodylen); + } + + if (cp->csty & JPC_COD_EPH) { + if (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) { + if (!(ms = jpc_getms(pkthdrstream, dec->cstate))) { + fprintf(stderr, "cannot get (EPH) marker segment\n"); + return -1; + } + if (jpc_ms_gettype(ms) != JPC_MS_EPH) { + jpc_ms_destroy(ms); + fprintf(stderr, "missing EPH marker segment\n"); + return -1; + } + jpc_ms_destroy(ms); + } + } + + /* decode the packet body. */ + + if (jas_getdbglevel() >= 1) { + fprintf(stderr, "packet body offset=%06ld\n", (long) jas_stream_getrwcount(in)); + } + + if (!discard) { + tcomp = &tile->tcomps[compno]; + rlvl = &tcomp->rlvls[rlvlno]; + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (!band->data) { + continue; + } + prc = &band->prcs[prcno]; + if (!prc->cblks) { + continue; + } + for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; + ++cblkno, ++cblk) { + seg = cblk->curseg; + while (seg) { + if (!seg->stream) { + if (!(seg->stream = jas_stream_memopen(0, 0))) { + return -1; + } + } +#if 0 +fprintf(stderr, "lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\n", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs); +#endif + if (seg->cnt > 0) { + if (jpc_getdata(in, seg->stream, seg->cnt) < 0) { + return -1; + } + seg->cnt = 0; + } + if (seg->numpasses >= seg->maxpasses) { + cblk->curseg = seg->next; + } + seg = seg->next; + } + } + } + } else { + if (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) { + return -1; + } + } + return 0; +} + +/********************************************************************************************/ +/********************************************************************************************/ + +int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in) +{ + jpc_dec_tile_t *tile; + jpc_pi_t *pi; + int ret; + + tile = dec->curtile; + pi = tile->pi; + for (;;) { +if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) { + switch (jpc_dec_lookahead(in)) { + case JPC_MS_EOC: + case JPC_MS_SOT: + return 0; + break; + case JPC_MS_SOP: + case JPC_MS_EPH: + case 0: + break; + default: + return -1; + break; + } +} + if ((ret = jpc_pi_next(pi))) { + return ret; + } +if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) { + fprintf(stderr, "warning: stopping decode prematurely as requested\n"); + return 0; +} + if (jas_getdbglevel() >= 1) { + fprintf(stderr, "packet offset=%08ld prg=%d cmptno=%02d " + "rlvlno=%02d prcno=%03d lyrno=%02d\n", (long) + jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi), + jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi)); + } + if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi), + jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) { + return -1; + } +++dec->numpkts; + } + + return 0; +} + +jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + jpc_pi_t *pi; + int compno; + jpc_picomp_t *picomp; + jpc_pirlvl_t *pirlvl; + jpc_dec_tcomp_t *tcomp; + int rlvlno; + jpc_dec_rlvl_t *rlvl; + int prcno; + int *prclyrno; + jpc_dec_cmpt_t *cmpt; + + if (!(pi = jpc_pi_create0())) { + return 0; + } + pi->numcomps = dec->numcomps; + if (!(pi->picomps = jas_malloc(pi->numcomps * sizeof(jpc_picomp_t)))) { + jpc_pi_destroy(pi); + return 0; + } + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, + ++picomp) { + picomp->pirlvls = 0; + } + + for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps; + compno < pi->numcomps; ++compno, ++tcomp, ++picomp) { + picomp->numrlvls = tcomp->numrlvls; + if (!(picomp->pirlvls = jas_malloc(picomp->numrlvls * + sizeof(jpc_pirlvl_t)))) { + jpc_pi_destroy(pi); + return 0; + } + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + pirlvl->prclyrnos = 0; + } + for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls; + rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) { +/* XXX sizeof(long) should be sizeof different type */ + pirlvl->numprcs = rlvl->numprcs; + if (!(pirlvl->prclyrnos = jas_malloc(pirlvl->numprcs * + sizeof(long)))) { + jpc_pi_destroy(pi); + return 0; + } + } + } + + pi->maxrlvls = 0; + for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps, cmpt = + dec->cmpts; compno < pi->numcomps; ++compno, ++tcomp, ++picomp, + ++cmpt) { + picomp->hsamp = cmpt->hstep; + picomp->vsamp = cmpt->vstep; + for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls; + rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) { + pirlvl->prcwidthexpn = rlvl->prcwidthexpn; + pirlvl->prcheightexpn = rlvl->prcheightexpn; + for (prcno = 0, prclyrno = pirlvl->prclyrnos; + prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { + *prclyrno = 0; + } + pirlvl->numhprcs = rlvl->numhprcs; + } + if (pi->maxrlvls < tcomp->numrlvls) { + pi->maxrlvls = tcomp->numrlvls; + } + } + + pi->numlyrs = tile->cp->numlyrs; + pi->xstart = tile->xstart; + pi->ystart = tile->ystart; + pi->xend = tile->xend; + pi->yend = tile->yend; + + pi->picomp = 0; + pi->pirlvl = 0; + pi->x = 0; + pi->y = 0; + pi->compno = 0; + pi->rlvlno = 0; + pi->prcno = 0; + pi->lyrno = 0; + pi->xstep = 0; + pi->ystep = 0; + + pi->pchgno = -1; + + pi->defaultpchg.prgord = tile->cp->prgord; + pi->defaultpchg.compnostart = 0; + pi->defaultpchg.compnoend = pi->numcomps; + pi->defaultpchg.rlvlnostart = 0; + pi->defaultpchg.rlvlnoend = pi->maxrlvls; + pi->defaultpchg.lyrnoend = pi->numlyrs; + pi->pchg = 0; + + pi->valid = 0; + + return pi; +} + +long jpc_dec_lookahead(jas_stream_t *in) +{ + uint_fast16_t x; + if (jpc_getuint16(in, &x)) { + return -1; + } + if (jas_stream_ungetc(in, x & 0xff) == EOF || + jas_stream_ungetc(in, x >> 8) == EOF) { + return -1; + } + if (x >= JPC_MS_INMIN && x <= JPC_MS_INMAX) { + return x; + } + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2dec.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2dec.h new file mode 100644 index 0000000..b58dc29 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2dec.h @@ -0,0 +1,144 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier 2 Decoder + * + * $Id$ + */ + +#ifndef JPC_T2DEC_H +#define JPC_T2DEC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_fix.h" +#include "jasper/jas_stream.h" + +#include "jpc_bs.h" +#include "jpc_dec.h" +#include "jpc_mqdec.h" + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Decode the packets for a tile-part. */ +int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, + jas_stream_t *in); + +/* Create a packet iterator for the decoder. */ +jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2enc.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2enc.c new file mode 100644 index 0000000..b18a855 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2enc.c @@ -0,0 +1,704 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier 2 Encoder + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_fix.h" +#include "jasper/jas_malloc.h" +#include "jasper/jas_math.h" +#include "jasper/jas_debug.h" + +#include "jpc_flt.h" +#include "jpc_t2enc.h" +#include "jpc_t2cod.h" +#include "jpc_tagtree.h" +#include "jpc_enc.h" +#include "jpc_math.h" + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +static int jpc_putcommacode(jpc_bitstream_t *out, int n) +{ + assert(n >= 0); + + while (--n >= 0) { + if (jpc_bitstream_putbit(out, 1) == EOF) { + return -1; + } + } + if (jpc_bitstream_putbit(out, 0) == EOF) { + return -1; + } + return 0; +} + +static int jpc_putnumnewpasses(jpc_bitstream_t *out, int n) +{ + int ret; + + if (n <= 0) { + return -1; + } else if (n == 1) { + ret = jpc_bitstream_putbit(out, 0); + } else if (n == 2) { + ret = jpc_bitstream_putbits(out, 2, 2); + } else if (n <= 5) { + ret = jpc_bitstream_putbits(out, 4, 0xc | (n - 3)); + } else if (n <= 36) { + ret = jpc_bitstream_putbits(out, 9, 0x1e0 | (n - 6)); + } else if (n <= 164) { + ret = jpc_bitstream_putbits(out, 16, 0xff80 | (n - 37)); + } else { + /* The standard has no provision for encoding a larger value. + In practice, however, it is highly unlikely that this + limitation will ever be encountered. */ + return -1; + } + + return (ret != EOF) ? 0 : (-1); +} + +int jpc_enc_encpkts(jpc_enc_t *enc, jas_stream_t *out) +{ + jpc_enc_tile_t *tile; + jpc_pi_t *pi; + + tile = enc->curtile; + + jpc_init_t2state(enc, 0); + pi = tile->pi; + jpc_pi_init(pi); + + if (!jpc_pi_next(pi)) { + for (;;) { + if (jpc_enc_encpkt(enc, out, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi), + jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) { + return -1; + } + if (jpc_pi_next(pi)) { + break; + } + } + } + + return 0; +} + +int jpc_enc_encpkt(jpc_enc_t *enc, jas_stream_t *out, int compno, int lvlno, int prcno, int lyrno) +{ + jpc_enc_tcmpt_t *comp; + jpc_enc_rlvl_t *lvl; + jpc_enc_band_t *band; + jpc_enc_band_t *endbands; + jpc_enc_cblk_t *cblk; + jpc_enc_cblk_t *endcblks; + jpc_bitstream_t *outb; + jpc_enc_pass_t *pass; + jpc_enc_pass_t *startpass; + jpc_enc_pass_t *lastpass; + jpc_enc_pass_t *endpass; + jpc_enc_pass_t *endpasses; + int i; + int included; + int ret; + jpc_tagtreenode_t *leaf; + int n; + int t1; + int t2; + int adjust; + int maxadjust; + int datalen; + int numnewpasses; + int passcount; + jpc_enc_tile_t *tile; + jpc_enc_prc_t *prc; + jpc_enc_cp_t *cp; + jpc_ms_t *ms; + + tile = enc->curtile; + cp = enc->cp; + + if (cp->tcp.csty & JPC_COD_SOP) { + if (!(ms = jpc_ms_create(JPC_MS_SOP))) { + return -1; + } + ms->parms.sop.seqno = jpc_pi_getind(tile->pi); + if (jpc_putms(out, enc->cstate, ms)) { + return -1; + } + jpc_ms_destroy(ms); + } + + outb = jpc_bitstream_sopen(out, "w+"); + assert(outb); + + if (jpc_bitstream_putbit(outb, 1) == EOF) { + return -1; + } + JAS_DBGLOG(10, ("\n")); + JAS_DBGLOG(10, ("present. ")); + + comp = &tile->tcmpts[compno]; + lvl = &comp->rlvls[lvlno]; + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + prc = &band->prcs[prcno]; + if (!prc->cblks) { + continue; + } + + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + if (!lyrno) { + leaf = jpc_tagtree_getleaf(prc->nlibtree, cblk - prc->cblks); + jpc_tagtree_setvalue(prc->nlibtree, leaf, cblk->numimsbs); + } + pass = cblk->curpass; + included = (pass && pass->lyrno == lyrno); + if (included && (!cblk->numencpasses)) { + assert(pass->lyrno == lyrno); + leaf = jpc_tagtree_getleaf(prc->incltree, + cblk - prc->cblks); + jpc_tagtree_setvalue(prc->incltree, leaf, pass->lyrno); + } + } + + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + pass = cblk->curpass; + included = (pass && pass->lyrno == lyrno); + if (!cblk->numencpasses) { + leaf = jpc_tagtree_getleaf(prc->incltree, + cblk - prc->cblks); + if (jpc_tagtree_encode(prc->incltree, leaf, lyrno + + 1, outb) < 0) { + return -1; + } + } else { + if (jpc_bitstream_putbit(outb, included) == EOF) { + return -1; + } + } + JAS_DBGLOG(10, ("included=%d ", included)); + if (!included) { + continue; + } + if (!cblk->numencpasses) { + i = 1; + leaf = jpc_tagtree_getleaf(prc->nlibtree, cblk - prc->cblks); + for (;;) { + if ((ret = jpc_tagtree_encode(prc->nlibtree, leaf, i, outb)) < 0) { + return -1; + } + if (ret) { + break; + } + ++i; + } + assert(leaf->known_ && i == leaf->value_ + 1); + } + + endpasses = &cblk->passes[cblk->numpasses]; + startpass = pass; + endpass = startpass; + while (endpass != endpasses && endpass->lyrno == lyrno){ + ++endpass; + } + numnewpasses = endpass - startpass; + if (jpc_putnumnewpasses(outb, numnewpasses)) { + return -1; + } + JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses)); + + lastpass = endpass - 1; + n = startpass->start; + passcount = 1; + maxadjust = 0; + for (pass = startpass; pass != endpass; ++pass) { + if (pass->term || pass == lastpass) { + datalen = pass->end - n; + t1 = jpc_firstone(datalen) + 1; + t2 = cblk->numlenbits + jpc_floorlog2(passcount); + adjust = JAS_MAX(t1 - t2, 0); + maxadjust = JAS_MAX(adjust, maxadjust); + n += datalen; + passcount = 1; + } else { + ++passcount; + } + } + if (jpc_putcommacode(outb, maxadjust)) { + return -1; + } + cblk->numlenbits += maxadjust; + + lastpass = endpass - 1; + n = startpass->start; + passcount = 1; + for (pass = startpass; pass != endpass; ++pass) { + if (pass->term || pass == lastpass) { + datalen = pass->end - n; +assert(jpc_firstone(datalen) < cblk->numlenbits + jpc_floorlog2(passcount)); + if (jpc_bitstream_putbits(outb, cblk->numlenbits + jpc_floorlog2(passcount), datalen) == EOF) { + return -1; + } + n += datalen; + passcount = 1; + } else { + ++passcount; + } + } + } + } + + jpc_bitstream_outalign(outb, 0); + jpc_bitstream_close(outb); + + if (cp->tcp.csty & JPC_COD_EPH) { + if (!(ms = jpc_ms_create(JPC_MS_EPH))) { + return -1; + } + jpc_putms(out, enc->cstate, ms); + jpc_ms_destroy(ms); + } + + comp = &tile->tcmpts[compno]; + lvl = &comp->rlvls[lvlno]; + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + prc = &band->prcs[prcno]; + if (!prc->cblks) { + continue; + } + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + pass = cblk->curpass; + + if (!pass) { + continue; + } + if (pass->lyrno != lyrno) { + assert(pass->lyrno < 0 || pass->lyrno > lyrno); + continue; + } + + endpasses = &cblk->passes[cblk->numpasses]; + startpass = pass; + endpass = startpass; + while (endpass != endpasses && endpass->lyrno == lyrno){ + ++endpass; + } + lastpass = endpass - 1; + numnewpasses = endpass - startpass; + + jas_stream_seek(cblk->stream, startpass->start, SEEK_SET); + assert(jas_stream_tell(cblk->stream) == startpass->start); + if (jas_stream_copy(out, cblk->stream, lastpass->end - startpass->start)) { + return -1; + } + cblk->curpass = (endpass != endpasses) ? endpass : 0; + cblk->numencpasses += numnewpasses; + + } + } + + return 0; +} + +void jpc_save_t2state(jpc_enc_t *enc) +{ +/* stream pos in embedded T1 stream may be wrong since not saved/restored! */ + + jpc_enc_tcmpt_t *comp; + jpc_enc_tcmpt_t *endcomps; + jpc_enc_rlvl_t *lvl; + jpc_enc_rlvl_t *endlvls; + jpc_enc_band_t *band; + jpc_enc_band_t *endbands; + jpc_enc_cblk_t *cblk; + jpc_enc_cblk_t *endcblks; + jpc_enc_tile_t *tile; + int prcno; + jpc_enc_prc_t *prc; + + tile = enc->curtile; + + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + endlvls = &comp->rlvls[comp->numrlvls]; + for (lvl = comp->rlvls; lvl != endlvls; ++lvl) { + if (!lvl->bands) { + continue; + } + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + jpc_tagtree_copy(prc->savincltree, prc->incltree); + jpc_tagtree_copy(prc->savnlibtree, prc->nlibtree); + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + cblk->savedcurpass = cblk->curpass; + cblk->savednumencpasses = cblk->numencpasses; + cblk->savednumlenbits = cblk->numlenbits; + } + } + } + } + } + +} + +void jpc_restore_t2state(jpc_enc_t *enc) +{ + + jpc_enc_tcmpt_t *comp; + jpc_enc_tcmpt_t *endcomps; + jpc_enc_rlvl_t *lvl; + jpc_enc_rlvl_t *endlvls; + jpc_enc_band_t *band; + jpc_enc_band_t *endbands; + jpc_enc_cblk_t *cblk; + jpc_enc_cblk_t *endcblks; + jpc_enc_tile_t *tile; + int prcno; + jpc_enc_prc_t *prc; + + tile = enc->curtile; + + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + endlvls = &comp->rlvls[comp->numrlvls]; + for (lvl = comp->rlvls; lvl != endlvls; ++lvl) { + if (!lvl->bands) { + continue; + } + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + jpc_tagtree_copy(prc->incltree, prc->savincltree); + jpc_tagtree_copy(prc->nlibtree, prc->savnlibtree); + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + cblk->curpass = cblk->savedcurpass; + cblk->numencpasses = cblk->savednumencpasses; + cblk->numlenbits = cblk->savednumlenbits; + } + } + } + } + } +} + +void jpc_init_t2state(jpc_enc_t *enc, int raflag) +{ +/* It is assumed that band->numbps and cblk->numbps precomputed */ + + jpc_enc_tcmpt_t *comp; + jpc_enc_tcmpt_t *endcomps; + jpc_enc_rlvl_t *lvl; + jpc_enc_rlvl_t *endlvls; + jpc_enc_band_t *band; + jpc_enc_band_t *endbands; + jpc_enc_cblk_t *cblk; + jpc_enc_cblk_t *endcblks; + jpc_enc_pass_t *pass; + jpc_enc_pass_t *endpasses; + jpc_tagtreenode_t *leaf; + jpc_enc_tile_t *tile; + int prcno; + jpc_enc_prc_t *prc; + + tile = enc->curtile; + + endcomps = &tile->tcmpts[tile->numtcmpts]; + for (comp = tile->tcmpts; comp != endcomps; ++comp) { + endlvls = &comp->rlvls[comp->numrlvls]; + for (lvl = comp->rlvls; lvl != endlvls; ++lvl) { + if (!lvl->bands) { + continue; + } + endbands = &lvl->bands[lvl->numbands]; + for (band = lvl->bands; band != endbands; ++band) { + if (!band->data) { + continue; + } + for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + jpc_tagtree_reset(prc->incltree); + jpc_tagtree_reset(prc->nlibtree); + endcblks = &prc->cblks[prc->numcblks]; + for (cblk = prc->cblks; cblk != endcblks; ++cblk) { + if (jas_stream_rewind(cblk->stream)) { + assert(0); + } + cblk->curpass = (cblk->numpasses > 0) ? cblk->passes : 0; + cblk->numencpasses = 0; + cblk->numlenbits = 3; + cblk->numimsbs = band->numbps - cblk->numbps; + assert(cblk->numimsbs >= 0); + leaf = jpc_tagtree_getleaf(prc->nlibtree, cblk - prc->cblks); + jpc_tagtree_setvalue(prc->nlibtree, leaf, cblk->numimsbs); + + if (raflag) { + endpasses = &cblk->passes[cblk->numpasses]; + for (pass = cblk->passes; pass != endpasses; ++pass) { + pass->lyrno = -1; + pass->lyrno = 0; + } + } + } + } + } + } + } + +} + +jpc_pi_t *jpc_enc_pi_create(jpc_enc_cp_t *cp, jpc_enc_tile_t *tile) +{ + jpc_pi_t *pi; + int compno; + jpc_picomp_t *picomp; + jpc_pirlvl_t *pirlvl; + jpc_enc_tcmpt_t *tcomp; + int rlvlno; + jpc_enc_rlvl_t *rlvl; + int prcno; + int *prclyrno; + + if (!(pi = jpc_pi_create0())) { + return 0; + } + pi->pktno = -1; + pi->numcomps = cp->numcmpts; + if (!(pi->picomps = jas_malloc(pi->numcomps * sizeof(jpc_picomp_t)))) { + jpc_pi_destroy(pi); + return 0; + } + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, + ++picomp) { + picomp->pirlvls = 0; + } + + for (compno = 0, tcomp = tile->tcmpts, picomp = pi->picomps; + compno < pi->numcomps; ++compno, ++tcomp, ++picomp) { + picomp->numrlvls = tcomp->numrlvls; + if (!(picomp->pirlvls = jas_malloc(picomp->numrlvls * + sizeof(jpc_pirlvl_t)))) { + jpc_pi_destroy(pi); + return 0; + } + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + pirlvl->prclyrnos = 0; + } + for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls; + rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) { +/* XXX sizeof(long) should be sizeof different type */ + pirlvl->numprcs = rlvl->numprcs; + if (rlvl->numprcs) { + if (!(pirlvl->prclyrnos = jas_malloc(pirlvl->numprcs * + sizeof(long)))) { + jpc_pi_destroy(pi); + return 0; + } + } else { + pirlvl->prclyrnos = 0; + } + } + } + + pi->maxrlvls = 0; + for (compno = 0, tcomp = tile->tcmpts, picomp = pi->picomps; + compno < pi->numcomps; ++compno, ++tcomp, ++picomp) { + picomp->hsamp = cp->ccps[compno].sampgrdstepx; + picomp->vsamp = cp->ccps[compno].sampgrdstepy; + for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls; + rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) { + pirlvl->prcwidthexpn = rlvl->prcwidthexpn; + pirlvl->prcheightexpn = rlvl->prcheightexpn; + for (prcno = 0, prclyrno = pirlvl->prclyrnos; + prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { + *prclyrno = 0; + } + pirlvl->numhprcs = rlvl->numhprcs; + } + if (pi->maxrlvls < tcomp->numrlvls) { + pi->maxrlvls = tcomp->numrlvls; + } + } + + pi->numlyrs = tile->numlyrs; + pi->xstart = tile->tlx; + pi->ystart = tile->tly; + pi->xend = tile->brx; + pi->yend = tile->bry; + + pi->picomp = 0; + pi->pirlvl = 0; + pi->x = 0; + pi->y = 0; + pi->compno = 0; + pi->rlvlno = 0; + pi->prcno = 0; + pi->lyrno = 0; + pi->xstep = 0; + pi->ystep = 0; + + pi->pchgno = -1; + + pi->defaultpchg.prgord = tile->prg; + pi->defaultpchg.compnostart = 0; + pi->defaultpchg.compnoend = pi->numcomps; + pi->defaultpchg.rlvlnostart = 0; + pi->defaultpchg.rlvlnoend = pi->maxrlvls; + pi->defaultpchg.lyrnoend = pi->numlyrs; + pi->pchg = 0; + + pi->valid = 0; + + return pi; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2enc.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2enc.h new file mode 100644 index 0000000..1ac7ec0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_t2enc.h @@ -0,0 +1,155 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tier 2 Encoder + * + * $Id$ + */ + +#ifndef JPC_T2ENC_H +#define JPC_T2ENC_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jpc_enc.h" + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Encode the packets for a tile. */ +int jpc_enc_encpkts(jpc_enc_t *enc, jas_stream_t *out); + +/* Encode the specified packet. */ +int jpc_enc_encpkt(jpc_enc_t *enc, jas_stream_t *out, int compno, int lvlno, + int prcno, int lyrno); + +/* Save the tier-2 coding state. */ +void jpc_save_t2state(jpc_enc_t *enc); + +/* Restore the tier-2 coding state. */ +void jpc_restore_t2state(jpc_enc_t *enc); + +/* Initialize the tier-2 coding state. */ +void jpc_init_t2state(jpc_enc_t *enc, int raflag); + +/* Create a packet iterator for the encoder. */ +jpc_pi_t *jpc_enc_pi_create(jpc_enc_cp_t *cp, jpc_enc_tile_t *tile); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tagtree.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tagtree.c new file mode 100644 index 0000000..97fc4b1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tagtree.c @@ -0,0 +1,442 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tag Tree Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include + +#include "jasper/jas_malloc.h" + +#include "jpc_tagtree.h" + +/******************************************************************************\ +* Prototypes. +\******************************************************************************/ + +static jpc_tagtree_t *jpc_tagtree_alloc(void); + +/******************************************************************************\ +* Code for creating and destroying tag trees. +\******************************************************************************/ + +/* Create a tag tree. */ + +jpc_tagtree_t *jpc_tagtree_create(int numleafsh, int numleafsv) +{ + int nplh[JPC_TAGTREE_MAXDEPTH]; + int nplv[JPC_TAGTREE_MAXDEPTH]; + jpc_tagtreenode_t *node; + jpc_tagtreenode_t *parentnode; + jpc_tagtreenode_t *parentnode0; + jpc_tagtree_t *tree; + int i; + int j; + int k; + int numlvls; + int n; + + assert(numleafsh > 0 && numleafsv > 0); + + if (!(tree = jpc_tagtree_alloc())) { + return 0; + } + tree->numleafsh_ = numleafsh; + tree->numleafsv_ = numleafsv; + + numlvls = 0; + nplh[0] = numleafsh; + nplv[0] = numleafsv; + do { + n = nplh[numlvls] * nplv[numlvls]; + nplh[numlvls + 1] = (nplh[numlvls] + 1) / 2; + nplv[numlvls + 1] = (nplv[numlvls] + 1) / 2; + tree->numnodes_ += n; + ++numlvls; + } while (n > 1); + + if (!(tree->nodes_ = jas_malloc(tree->numnodes_ * sizeof(jpc_tagtreenode_t)))) { + return 0; + } + + /* Initialize the parent links for all nodes in the tree. */ + + node = tree->nodes_; + parentnode = &tree->nodes_[tree->numleafsh_ * tree->numleafsv_]; + parentnode0 = parentnode; + + for (i = 0; i < numlvls - 1; ++i) { + for (j = 0; j < nplv[i]; ++j) { + k = nplh[i]; + while (--k >= 0) { + node->parent_ = parentnode; + ++node; + if (--k >= 0) { + node->parent_ = parentnode; + ++node; + } + ++parentnode; + } + if ((j & 1) || j == nplv[i] - 1) { + parentnode0 = parentnode; + } else { + parentnode = parentnode0; + parentnode0 += nplh[i]; + } + } + } + node->parent_ = 0; + + /* Initialize the data values to something sane. */ + + jpc_tagtree_reset(tree); + + return tree; +} + +/* Destroy a tag tree. */ + +void jpc_tagtree_destroy(jpc_tagtree_t *tree) +{ + if (tree->nodes_) { + jas_free(tree->nodes_); + } + jas_free(tree); +} + +static jpc_tagtree_t *jpc_tagtree_alloc() +{ + jpc_tagtree_t *tree; + + if (!(tree = jas_malloc(sizeof(jpc_tagtree_t)))) { + return 0; + } + tree->numleafsh_ = 0; + tree->numleafsv_ = 0; + tree->numnodes_ = 0; + tree->nodes_ = 0; + + return tree; +} + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +/* Copy state information from one tag tree to another. */ + +void jpc_tagtree_copy(jpc_tagtree_t *dsttree, jpc_tagtree_t *srctree) +{ + int n; + jpc_tagtreenode_t *srcnode; + jpc_tagtreenode_t *dstnode; + + /* The two tag trees must have similar sizes. */ + assert(srctree->numleafsh_ == dsttree->numleafsh_ && + srctree->numleafsv_ == dsttree->numleafsv_); + + n = srctree->numnodes_; + srcnode = srctree->nodes_; + dstnode = dsttree->nodes_; + while (--n >= 0) { + dstnode->value_ = srcnode->value_; + dstnode->low_ = srcnode->low_; + dstnode->known_ = srcnode->known_; + ++dstnode; + ++srcnode; + } +} + +/* Reset all of the state information associated with a tag tree. */ + +void jpc_tagtree_reset(jpc_tagtree_t *tree) +{ + int n; + jpc_tagtreenode_t *node; + + n = tree->numnodes_; + node = tree->nodes_; + + while (--n >= 0) { + node->value_ = INT_MAX; + node->low_ = 0; + node->known_ = 0; + ++node; + } +} + +/* Set the value associated with the specified leaf node, updating +the other nodes as necessary. */ + +void jpc_tagtree_setvalue(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, + int value) +{ + jpc_tagtreenode_t *node; + + /* Avoid compiler warnings about unused parameters. */ + tree = 0; + + assert(value >= 0); + + node = leaf; + while (node && node->value_ > value) { + node->value_ = value; + node = node->parent_; + } +} + +/* Get a particular leaf node. */ + +jpc_tagtreenode_t *jpc_tagtree_getleaf(jpc_tagtree_t *tree, int n) +{ + return &tree->nodes_[n]; +} + +/* Invoke the tag tree encoding procedure. */ + +int jpc_tagtree_encode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, + int threshold, jpc_bitstream_t *out) +{ + jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1]; + jpc_tagtreenode_t **stkptr; + jpc_tagtreenode_t *node; + int low; + + /* Avoid compiler warnings about unused parameters. */ + tree = 0; + + assert(leaf); + assert(threshold >= 0); + + /* Traverse to the root of the tree, recording the path taken. */ + stkptr = stk; + node = leaf; + while (node->parent_) { + *stkptr++ = node; + node = node->parent_; + } + + low = 0; + for (;;) { + if (low > node->low_) { + /* Deferred propagation of the lower bound downward in + the tree. */ + node->low_ = low; + } else { + low = node->low_; + } + + while (low < threshold) { + if (low >= node->value_) { + if (!node->known_) { + if (jpc_bitstream_putbit(out, 1) == EOF) { + return -1; + } + node->known_ = 1; + } + break; + } + if (jpc_bitstream_putbit(out, 0) == EOF) { + return -1; + } + ++low; + } + node->low_ = low; + if (stkptr == stk) { + break; + } + node = *--stkptr; + + } + return (leaf->low_ < threshold) ? 1 : 0; + +} + +/* Invoke the tag tree decoding procedure. */ + +int jpc_tagtree_decode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, + int threshold, jpc_bitstream_t *in) +{ + jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1]; + jpc_tagtreenode_t **stkptr; + jpc_tagtreenode_t *node; + int low; + int ret; + + /* Avoid compiler warnings about unused parameters. */ + tree = 0; + + assert(threshold >= 0); + + /* Traverse to the root of the tree, recording the path taken. */ + stkptr = stk; + node = leaf; + while (node->parent_) { + *stkptr++ = node; + node = node->parent_; + } + + low = 0; + for (;;) { + if (low > node->low_) { + node->low_ = low; + } else { + low = node->low_; + } + while (low < threshold && low < node->value_) { + if ((ret = jpc_bitstream_getbit(in)) < 0) { + return -1; + } + if (ret) { + node->value_ = low; + } else { + ++low; + } + } + node->low_ = low; + if (stkptr == stk) { + break; + } + node = *--stkptr; + } + + return (node->value_ < threshold) ? 1 : 0; +} + +/******************************************************************************\ +* Code for debugging. +\******************************************************************************/ + +void jpc_tagtree_dump(jpc_tagtree_t *tree, FILE *out) +{ + jpc_tagtreenode_t *node; + int n; + + node = tree->nodes_; + n = tree->numnodes_; + while (--n >= 0) { + fprintf(out, "node %p, parent %p, value %d, lower %d, known %d\n", + (void *) node, (void *) node->parent_, node->value_, node->low_, + node->known_); + ++node; + } +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tagtree.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tagtree.h new file mode 100644 index 0000000..a6d7f7c --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tagtree.h @@ -0,0 +1,216 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tag Tree Library + * + * $Id$ + */ + +#ifndef JPC_TAGTREE_H +#define JPC_TAGTREE_H + +/******************************************************************************\ +* Includes +\******************************************************************************/ + +#include +#include + +#include "jpc_bs.h" + +/******************************************************************************\ +* Constants +\******************************************************************************/ + +/* The maximum allowable depth for a tag tree. */ +#define JPC_TAGTREE_MAXDEPTH 32 + +/******************************************************************************\ +* Types +\******************************************************************************/ + +/* + * Tag tree node. + */ + +typedef struct jpc_tagtreenode_ { + + /* The parent of this node. */ + struct jpc_tagtreenode_ *parent_; + + /* The value associated with this node. */ + int value_; + + /* The lower bound on the value associated with this node. */ + int low_; + + /* A flag indicating if the value is known exactly. */ + int known_; + +} jpc_tagtreenode_t; + +/* + * Tag tree. + */ + +typedef struct { + + /* The number of leaves in the horizontal direction. */ + int numleafsh_; + + /* The number of leaves in the vertical direction. */ + int numleafsv_; + + /* The total number of nodes in the tree. */ + int numnodes_; + + /* The nodes. */ + jpc_tagtreenode_t *nodes_; + +} jpc_tagtree_t; + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Create a tag tree. */ +jpc_tagtree_t *jpc_tagtree_create(int numleafsh, int numleafsv); + +/* Destroy a tag tree. */ +void jpc_tagtree_destroy(jpc_tagtree_t *tree); + +/* Copy data from one tag tree to another. */ +void jpc_tagtree_copy(jpc_tagtree_t *dsttree, jpc_tagtree_t *srctree); + +/* Reset the tag tree state. */ +void jpc_tagtree_reset(jpc_tagtree_t *tree); + +/* Set the value associated with a particular leaf node of a tag tree. */ +void jpc_tagtree_setvalue(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, + int value); + +/* Get a pointer to a particular leaf node. */ +jpc_tagtreenode_t *jpc_tagtree_getleaf(jpc_tagtree_t *tree, int n); + +/* Invoke the tag tree decoding procedure. */ +int jpc_tagtree_decode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, + int threshold, jpc_bitstream_t *in); + +/* Invoke the tag tree encoding procedure. */ +int jpc_tagtree_encode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, + int threshold, jpc_bitstream_t *out); + +/* Dump a tag tree (for debugging purposes). */ +void jpc_tagtree_dump(jpc_tagtree_t *tree, FILE *out); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tsfb.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tsfb.c new file mode 100644 index 0000000..fba4ad6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tsfb.c @@ -0,0 +1,663 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tree-Structured Filter Bank (TSFB) Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_malloc.h" +#include "jasper/jas_seq.h" + +#include "jpc_tsfb.h" +#include "jpc_cod.h" +#include "jpc_cs.h" +#include "jpc_util.h" + +/******************************************************************************\ +* +\******************************************************************************/ + +#define bandnotovind(tsfbnode, x) ((x) / (tsfbnode)->numhchans) +#define bandnotohind(tsfbnode, x) ((x) % (tsfbnode)->numhchans) + +static jpc_tsfb_t *jpc_tsfb_create(void); +static jpc_tsfbnode_t *jpc_tsfbnode_create(void); +static void jpc_tsfbnode_destroy(jpc_tsfbnode_t *node); +static void jpc_tsfbnode_synthesize(jpc_tsfbnode_t *node, int flags, jas_seq2d_t *x); +static void jpc_tsfbnode_analyze(jpc_tsfbnode_t *node, int flags, jas_seq2d_t *x); +static void qmfb2d_getbands(jpc_qmfb1d_t *hqmfb, jpc_qmfb1d_t *vqmfb, + uint_fast32_t xstart, uint_fast32_t ystart, uint_fast32_t xend, + uint_fast32_t yend, int maxbands, int *numbandsptr, jpc_tsfbnodeband_t *bands); +static void jpc_tsfbnode_getbandstree(jpc_tsfbnode_t *node, uint_fast32_t posxstart, + uint_fast32_t posystart, uint_fast32_t xstart, uint_fast32_t ystart, + uint_fast32_t xend, uint_fast32_t yend, jpc_tsfb_band_t **bands); +static int jpc_tsfbnode_findchild(jpc_tsfbnode_t *parnode, jpc_tsfbnode_t *cldnode); +static int jpc_tsfbnode_getequivfilters(jpc_tsfbnode_t *tsfbnode, int cldind, + int width, int height, jas_seq_t **vfilter, jas_seq_t **hfilter); + +/******************************************************************************\ +* +\******************************************************************************/ + +jpc_tsfb_t *jpc_tsfb_wavelet(jpc_qmfb1d_t *hqmfb, jpc_qmfb1d_t *vqmfb, int numdlvls) +{ + jpc_tsfb_t *tsfb; + int dlvlno; + jpc_tsfbnode_t *curnode; + jpc_tsfbnode_t *prevnode; + int childno; + if (!(tsfb = jpc_tsfb_create())) { + return 0; + } + prevnode = 0; + for (dlvlno = 0; dlvlno < numdlvls; ++dlvlno) { + if (!(curnode = jpc_tsfbnode_create())) { + jpc_tsfb_destroy(tsfb); + return 0; + } + if (prevnode) { + prevnode->children[0] = curnode; + ++prevnode->numchildren; + curnode->parent = prevnode; + } else { + tsfb->root = curnode; + curnode->parent = 0; + } + if (hqmfb) { + curnode->numhchans = jpc_qmfb1d_getnumchans(hqmfb); + if (!(curnode->hqmfb = jpc_qmfb1d_copy(hqmfb))) { + jpc_tsfb_destroy(tsfb); + return 0; + } + } else { + curnode->hqmfb = 0; + curnode->numhchans = 1; + } + if (vqmfb) { + curnode->numvchans = jpc_qmfb1d_getnumchans(vqmfb); + if (!(curnode->vqmfb = jpc_qmfb1d_copy(vqmfb))) { + jpc_tsfb_destroy(tsfb); + return 0; + } + } else { + curnode->vqmfb = 0; + curnode->numvchans = 1; + } + curnode->maxchildren = curnode->numhchans * curnode->numvchans; + for (childno = 0; childno < curnode->maxchildren; + ++childno) { + curnode->children[childno] = 0; + } + prevnode = curnode; + } + return tsfb; +} + +static jpc_tsfb_t *jpc_tsfb_create() +{ + jpc_tsfb_t *tsfb; + if (!(tsfb = jas_malloc(sizeof(jpc_tsfb_t)))) { + return 0; + } + tsfb->root = 0; + return tsfb; +} + +void jpc_tsfb_destroy(jpc_tsfb_t *tsfb) +{ + if (tsfb->root) { + jpc_tsfbnode_destroy(tsfb->root); + } + jas_free(tsfb); +} + +/******************************************************************************\ +* +\******************************************************************************/ + +void jpc_tsfb_analyze(jpc_tsfb_t *tsfb, int flags, jas_seq2d_t *x) +{ + if (tsfb->root) { + jpc_tsfbnode_analyze(tsfb->root, flags, x); + } +} + +static void jpc_tsfbnode_analyze(jpc_tsfbnode_t *node, int flags, jas_seq2d_t *x) +{ + jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE]; + int numbands; + jas_seq2d_t *y; + int bandno; + jpc_tsfbnodeband_t *band; + + if (node->vqmfb) { + jpc_qmfb1d_analyze(node->vqmfb, flags | JPC_QMFB1D_VERT, x); + } + if (node->hqmfb) { + jpc_qmfb1d_analyze(node->hqmfb, flags, x); + } + if (node->numchildren > 0) { + qmfb2d_getbands(node->hqmfb, node->vqmfb, jas_seq2d_xstart(x), + jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x), + JPC_TSFB_MAXBANDSPERNODE, &numbands, nodebands); + y = jas_seq2d_create(0, 0, 0, 0); + assert(y); + for (bandno = 0, band = nodebands; bandno < numbands; ++bandno, ++band) { + if (node->children[bandno]) { + if (band->xstart != band->xend && band->ystart != band->yend) { + jas_seq2d_bindsub(y, x, band->locxstart, band->locystart, + band->locxend, band->locyend); + jas_seq2d_setshift(y, band->xstart, band->ystart); + jpc_tsfbnode_analyze(node->children[bandno], flags, y); + } + } + } + jas_matrix_destroy(y); + } +} + +void jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, int flags, jas_seq2d_t *x) +{ + if (tsfb->root) { + jpc_tsfbnode_synthesize(tsfb->root, flags, x); + } +} + +static void jpc_tsfbnode_synthesize(jpc_tsfbnode_t *node, int flags, jas_seq2d_t *x) +{ + jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE]; + int numbands; + jas_seq2d_t *y; + int bandno; + jpc_tsfbnodeband_t *band; + + if (node->numchildren > 0) { + qmfb2d_getbands(node->hqmfb, node->vqmfb, jas_seq2d_xstart(x), + jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x), + JPC_TSFB_MAXBANDSPERNODE, &numbands, nodebands); + y = jas_seq2d_create(0, 0, 0, 0); + for (bandno = 0, band = nodebands; bandno < numbands; ++bandno, ++band) { + if (node->children[bandno]) { + if (band->xstart != band->xend && band->ystart != band->yend) { + jas_seq2d_bindsub(y, x, band->locxstart, band->locystart, + band->locxend, band->locyend); + jas_seq2d_setshift(y, band->xstart, band->ystart); + jpc_tsfbnode_synthesize(node->children[bandno], flags, y); + } + } + } + jas_seq2d_destroy(y); + } + if (node->hqmfb) { + jpc_qmfb1d_synthesize(node->hqmfb, flags, x); + } + if (node->vqmfb) { + jpc_qmfb1d_synthesize(node->vqmfb, flags | JPC_QMFB1D_VERT, x); + } +} + +/******************************************************************************\ +* +\******************************************************************************/ + + +int jpc_tsfb_getbands(jpc_tsfb_t *tsfb, uint_fast32_t xstart, uint_fast32_t ystart, + uint_fast32_t xend, uint_fast32_t yend, jpc_tsfb_band_t *bands) +{ + jpc_tsfb_band_t *savbands; + savbands = bands; + if (!tsfb->root) { + bands[0].xstart = xstart; + bands[0].ystart = ystart; + bands[0].xend = xend; + bands[0].yend = yend; + bands[0].locxstart = xstart; + bands[0].locystart = ystart; + bands[0].locxend = xend; + bands[0].locyend = yend; + bands[0].orient = JPC_TSFB_LL; + bands[0].synenergywt = JPC_FIX_ONE; + ++bands; + } else { + jpc_tsfbnode_getbandstree(tsfb->root, xstart, ystart, + xstart, ystart, xend, yend, &bands); + } + return bands - savbands; +} + +static void jpc_tsfbnode_getbandstree(jpc_tsfbnode_t *node, uint_fast32_t posxstart, + uint_fast32_t posystart, uint_fast32_t xstart, uint_fast32_t ystart, + uint_fast32_t xend, uint_fast32_t yend, jpc_tsfb_band_t **bands) +{ + jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE]; + jpc_tsfbnodeband_t *nodeband; + int nodebandno; + int numnodebands; + jpc_tsfb_band_t *band; + jas_seq_t *hfilter; + jas_seq_t *vfilter; + + qmfb2d_getbands(node->hqmfb, node->vqmfb, xstart, ystart, xend, yend, + JPC_TSFB_MAXBANDSPERNODE, &numnodebands, nodebands); + if (node->numchildren > 0) { + for (nodebandno = 0, nodeband = nodebands; + nodebandno < numnodebands; ++nodebandno, ++nodeband) { + if (node->children[nodebandno]) { + jpc_tsfbnode_getbandstree(node->children[ + nodebandno], posxstart + + nodeband->locxstart - xstart, posystart + + nodeband->locystart - ystart, nodeband->xstart, + nodeband->ystart, nodeband->xend, + nodeband->yend, bands); + + } + } + } +assert(numnodebands == 4 || numnodebands == 3); + for (nodebandno = 0, nodeband = nodebands; nodebandno < numnodebands; + ++nodebandno, ++nodeband) { + if (!node->children[nodebandno]) { + band = *bands; + band->xstart = nodeband->xstart; + band->ystart = nodeband->ystart; + band->xend = nodeband->xend; + band->yend = nodeband->yend; + band->locxstart = posxstart + nodeband->locxstart - + xstart; + band->locystart = posystart + nodeband->locystart - + ystart; + band->locxend = band->locxstart + band->xend - + band->xstart; + band->locyend = band->locystart + band->yend - + band->ystart; + if (numnodebands == 4) { + switch (nodebandno) { + case 0: + band->orient = JPC_TSFB_LL; + break; + case 1: + band->orient = JPC_TSFB_HL; + break; + case 2: + band->orient = JPC_TSFB_LH; + break; + case 3: + band->orient = JPC_TSFB_HH; + break; + default: + abort(); + break; + } + } else { + switch (nodebandno) { + case 0: + band->orient = JPC_TSFB_HL; + break; + case 1: + band->orient = JPC_TSFB_LH; + break; + case 2: + band->orient = JPC_TSFB_HH; + break; + default: + abort(); + break; + } + } + jpc_tsfbnode_getequivfilters(node, nodebandno, band->xend - band->xstart, band->yend - band->ystart, &hfilter, &vfilter); + band->synenergywt = jpc_fix_mul(jpc_seq_norm(hfilter), + jpc_seq_norm(vfilter)); + jas_seq_destroy(hfilter); + jas_seq_destroy(vfilter); + ++(*bands); + } + } +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static jpc_tsfbnode_t *jpc_tsfbnode_create() +{ + jpc_tsfbnode_t *node; + if (!(node = jas_malloc(sizeof(jpc_tsfbnode_t)))) { + return 0; + } + node->numhchans = 0; + node->numvchans = 0; + node->numchildren = 0; + node->maxchildren = 0; + node->hqmfb = 0; + node->vqmfb = 0; + node->parent = 0; + return node; +} + +static void jpc_tsfbnode_destroy(jpc_tsfbnode_t *node) +{ + jpc_tsfbnode_t **child; + int childno; + for (childno = 0, child = node->children; childno < node->maxchildren; + ++childno, ++child) { + if (*child) { + jpc_tsfbnode_destroy(*child); + } + } + if (node->hqmfb) { + jpc_qmfb1d_destroy(node->hqmfb); + } + if (node->vqmfb) { + jpc_qmfb1d_destroy(node->vqmfb); + } + jas_free(node); +} + + + + + + + + +static void qmfb2d_getbands(jpc_qmfb1d_t *hqmfb, jpc_qmfb1d_t *vqmfb, + uint_fast32_t xstart, uint_fast32_t ystart, uint_fast32_t xend, + uint_fast32_t yend, int maxbands, int *numbandsptr, jpc_tsfbnodeband_t *bands) +{ + jpc_qmfb1dband_t hbands[JPC_QMFB1D_MAXCHANS]; + jpc_qmfb1dband_t vbands[JPC_QMFB1D_MAXCHANS]; + int numhbands; + int numvbands; + int numbands; + int bandno; + int hbandno; + int vbandno; + jpc_tsfbnodeband_t *band; + + if (hqmfb) { + jpc_qmfb1d_getbands(hqmfb, 0, xstart, ystart, xend, yend, + JPC_QMFB1D_MAXCHANS, &numhbands, hbands); + } else { + numhbands = 1; + hbands[0].start = xstart; + hbands[0].end = xend; + hbands[0].locstart = xstart; + hbands[0].locend = xend; + } + if (vqmfb) { + jpc_qmfb1d_getbands(vqmfb, JPC_QMFB1D_VERT, xstart, ystart, xend, + yend, JPC_QMFB1D_MAXCHANS, &numvbands, vbands); + } else { + numvbands = 1; + vbands[0].start = ystart; + vbands[0].end = yend; + vbands[0].locstart = ystart; + vbands[0].locend = yend; + } + numbands = numhbands * numvbands; + assert(numbands <= maxbands); + *numbandsptr = numbands; + for (bandno = 0, band = bands; bandno < numbands; ++bandno, ++band) { + hbandno = bandno % numhbands; + vbandno = bandno / numhbands; + band->xstart = hbands[hbandno].start; + band->ystart = vbands[vbandno].start; + band->xend = hbands[hbandno].end; + band->yend = vbands[vbandno].end; + band->locxstart = hbands[hbandno].locstart; + band->locystart = vbands[vbandno].locstart; + band->locxend = hbands[hbandno].locend; + band->locyend = vbands[vbandno].locend; + assert(band->xstart <= band->xend && + band->ystart <= band->yend); + if (band->xstart == band->xend) { + band->yend = band->ystart; + band->locyend = band->locystart; + } else if (band->ystart == band->yend) { + band->xend = band->xstart; + band->locxend = band->locxstart; + } + } +} + +static int jpc_tsfbnode_getequivfilters(jpc_tsfbnode_t *tsfbnode, int cldind, + int width, int height, jas_seq_t **hfilter, jas_seq_t **vfilter) +{ + jas_seq_t *hseq; + jas_seq_t *vseq; + jpc_tsfbnode_t *node; + jas_seq2d_t *hfilters[JPC_QMFB1D_MAXCHANS]; + jas_seq2d_t *vfilters[JPC_QMFB1D_MAXCHANS]; + int numhchans; + int numvchans; + jas_seq_t *tmpseq; + + hseq = 0; + vseq = 0; + + if (!(hseq = jas_seq_create(0, 1))) { + goto error; + } + jas_seq_set(hseq, 0, jpc_inttofix(1)); + if (!(vseq = jas_seq_create(0, 1))) { + goto error; + } + jas_seq_set(vseq, 0, jpc_inttofix(1)); + + node = tsfbnode; + while (node) { + if (node->hqmfb) { + numhchans = jpc_qmfb1d_getnumchans(node->hqmfb); + if (jpc_qmfb1d_getsynfilters(node->hqmfb, width, hfilters)) { + goto error; + } + if (!(tmpseq = jpc_seq_upsample(hseq, numhchans))) { + goto error; + } + jas_seq_destroy(hseq); + hseq = tmpseq; + if (!(tmpseq = jpc_seq_conv(hseq, hfilters[bandnotohind(node, cldind)]))) { + goto error; + } + jas_seq_destroy(hfilters[0]); + jas_seq_destroy(hfilters[1]); + jas_seq_destroy(hseq); + hseq = tmpseq; + } + if (node->vqmfb) { + numvchans = jpc_qmfb1d_getnumchans(node->vqmfb); + if (jpc_qmfb1d_getsynfilters(node->vqmfb, height, vfilters)) { + abort(); + } + if (!(tmpseq = jpc_seq_upsample(vseq, numvchans))) { + goto error; + } + jas_seq_destroy(vseq); + vseq = tmpseq; + if (!(tmpseq = jpc_seq_conv(vseq, vfilters[bandnotovind(node, cldind)]))) { + goto error; + } + jas_seq_destroy(vfilters[0]); + jas_seq_destroy(vfilters[1]); + jas_seq_destroy(vseq); + vseq = tmpseq; + } + if (node->parent) { + cldind = jpc_tsfbnode_findchild(node->parent, node); + } + node = node->parent; + } + + *hfilter = hseq; + *vfilter = vseq; + + return 0; + +error: + if (hseq) { + jas_seq_destroy(hseq); + } + if (vseq) { + jas_seq_destroy(vseq); + } + return -1; + +} + +static int jpc_tsfbnode_findchild(jpc_tsfbnode_t *parnode, jpc_tsfbnode_t *cldnode) +{ + int i; + + for (i = 0; i < parnode->maxchildren; i++) { + if (parnode->children[i] == cldnode) + return i; + } + assert(0); + return -1; +} + +jpc_tsfb_t *jpc_cod_gettsfb(int qmfbid, int numlevels) +{ + jpc_tsfb_t *tsfb; + + switch (qmfbid) { + case JPC_COX_RFT: + qmfbid = JPC_QMFB1D_FT; + break; + case JPC_COX_INS: + qmfbid = JPC_QMFB1D_NS; + break; + default: + assert(0); + qmfbid = 10; + break; + } + +{ + jpc_qmfb1d_t *hqmfb; + hqmfb = jpc_qmfb1d_make(qmfbid); + assert(hqmfb); + tsfb = jpc_tsfb_wavelet(hqmfb, hqmfb, numlevels); + assert(tsfb); + jpc_qmfb1d_destroy(hqmfb); +} + + return tsfb; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tsfb.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tsfb.h new file mode 100644 index 0000000..143a318 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_tsfb.h @@ -0,0 +1,222 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Tree-Structured Filter Bank (TSFB) Library + * + * $Id$ + */ + +#ifndef JPC_TSFB_H +#define JPC_TSFB_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_seq.h" + +#include "jpc_fix.h" +#include "jpc_qmfb.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +#define JPC_TSFB_MAXBANDS (JPC_TSFB_MAXDEPTH * 3 + 1) +#define JPC_TSFB_MAXDEPTH 32 +#define JPC_TSFB_RITIMODE JPC_QMFB1D_RITIMODE + +#define JPC_TSFB_MAXBANDSPERNODE (JPC_QMFB1D_MAXCHANS * JPC_QMFB1D_MAXCHANS) + +#define JPC_TSFB_PRUNEVERT 0x01 +#define JPC_TSFB_PRUNEHORZ 0x02 + +#define JPC_TSFB_LL 0 +#define JPC_TSFB_LH 1 +#define JPC_TSFB_HL 2 +#define JPC_TSFB_HH 3 + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +typedef struct { + + int xstart; + int ystart; + int xend; + int yend; + int locxstart; + int locystart; + int locxend; + int locyend; + +} jpc_tsfbnodeband_t; + +typedef struct jpc_tsfbnode_s { + + int numhchans; + int numvchans; + jpc_qmfb1d_t *hqmfb; + jpc_qmfb1d_t *vqmfb; + int maxchildren; + int numchildren; + struct jpc_tsfbnode_s *children[JPC_TSFB_MAXBANDSPERNODE]; + struct jpc_tsfbnode_s *parent; + +} jpc_tsfbnode_t; + +typedef struct { + jpc_tsfbnode_t *root; +} jpc_tsfb_t; + +typedef struct { + int xstart; + int ystart; + int xend; + int yend; + int orient; + int locxstart; + int locystart; + int locxend; + int locyend; + jpc_fix_t synenergywt; +} jpc_tsfb_band_t; + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +/* Create a TSFB. */ +jpc_tsfb_t *jpc_cod_gettsfb(int qmfbid, int numlevels); + +/* Create a wavelet-type TSFB with the specified horizontal and vertical + QMFBs. */ +jpc_tsfb_t *jpc_tsfb_wavelet(jpc_qmfb1d_t *hqmfb, jpc_qmfb1d_t *vqmfb, + int numdlvls); + +/* Destroy a TSFB. */ +void jpc_tsfb_destroy(jpc_tsfb_t *tsfb); + +/* Perform analysis. */ +void jpc_tsfb_analyze(jpc_tsfb_t *tsfb, int flags, jas_seq2d_t *x); + +/* Perform synthesis. */ +void jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, int flags, jas_seq2d_t *x); + +/* Get band information for a TSFB. */ +int jpc_tsfb_getbands(jpc_tsfb_t *tsfb, uint_fast32_t xstart, + uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend, + jpc_tsfb_band_t *bands); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_util.c b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_util.c new file mode 100644 index 0000000..1c68cb8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_util.c @@ -0,0 +1,243 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * $Id$ + */ + +/******************************************************************************\ +* Includes +\******************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include "jasper/jas_math.h" +#include "jasper/jas_malloc.h" + +#include "jpc_fix.h" +#include "jpc_cs.h" +#include "jpc_flt.h" +#include "jpc_util.h" + +/******************************************************************************\ +* Miscellaneous Functions +\******************************************************************************/ + +int jpc_atoaf(char *s, int *numvalues, double **values) +{ + static char delim[] = ", \t\n"; + char buf[4096]; + int n; + double *vs; + char *cp; + + strncpy(buf, s, sizeof(buf)); + buf[sizeof(buf) - 1] = '\0'; + n = 0; + if ((cp = strtok(buf, delim))) { + ++n; + while ((cp = strtok(0, delim))) { + if (cp != '\0') { + ++n; + } + } + } + + if (n) { + if (!(vs = jas_malloc(n * sizeof(double)))) { + return -1; + } + + strncpy(buf, s, sizeof(buf)); + buf[sizeof(buf) - 1] = '\0'; + n = 0; + if ((cp = strtok(buf, delim))) { + vs[n] = atof(cp); + ++n; + while ((cp = strtok(0, delim))) { + if (cp != '\0') { + vs[n] = atof(cp); + ++n; + } + } + } + } else { + vs = 0; + } + + *numvalues = n; + *values = vs; + + return 0; +} + +jas_seq_t *jpc_seq_upsample(jas_seq_t *x, int m) +{ + jas_seq_t *z; + int i; + + if (!(z = jas_seq_create(jas_seq_start(x) * m, (jas_seq_end(x) - 1) * m + 1))) + return 0; + for (i = jas_seq_start(z); i < jas_seq_end(z); i++) { + *jas_seq_getref(z, i) = (!JAS_MOD(i, m)) ? jas_seq_get(x, i / m) : + jpc_inttofix(0); + } + + return z; +} + +jpc_fix_t jpc_seq_norm(jas_seq_t *x) +{ + jpc_fix_t s; + int i; + + s = jpc_inttofix(0); + for (i = jas_seq_start(x); i < jas_seq_end(x); i++) { + s = jpc_fix_add(s, jpc_fix_mul(jas_seq_get(x, i), jas_seq_get(x, i))); + } + + return jpc_dbltofix(sqrt(jpc_fixtodbl(s))); +} + +jas_seq_t *jpc_seq_conv(jas_seq_t *x, jas_seq_t *y) +{ + int i; + int j; + int k; + jas_seq_t *z; + jpc_fix_t s; + jpc_fix_t v; + + z = jas_seq_create(jas_seq_start(x) + jas_seq_start(y), + jas_seq_end(x) + jas_seq_end(y) - 1); + assert(z); + for (i = jas_seq_start(z); i < jas_seq_end(z); i++) { + s = jpc_inttofix(0); + for (j = jas_seq_start(y); j < jas_seq_end(y); j++) { + k = i - j; + if (k < jas_seq_start(x) || k >= jas_seq_end(x)) { + v = JPC_FIX_ZERO; + } else { + v = jas_seq_get(x, k); + } + s = jpc_fix_add(s, jpc_fix_mul(jas_seq_get(y, j), v)); + } + *jas_seq_getref(z, i) = s; + } + + return z; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpc/jpc_util.h b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_util.h new file mode 100644 index 0000000..78b0a2e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpc/jpc_util.h @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JPC_UTIL_H +#define JPC_UTIL_H + +/* Parse a comma separated list of real numbers into an array of doubles. */ +int jpc_atoaf(char *s, int *numvalues, double **values); + +/* Upsample a sequence. */ +jas_seq_t *jpc_seq_upsample(jas_seq_t *seq, int n); + +/* Convolve two sequences. */ +jas_seq_t *jpc_seq_conv(jas_seq_t *seq0, jas_seq_t *seq1); + +/* Compute the norm of a sequence. */ +jpc_fix_t jpc_seq_norm(jas_seq_t *x); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/.gitignore b/SlnkDWFImpl/CxImage/jasper/jpg/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/README b/SlnkDWFImpl/CxImage/jasper/jpg/README new file mode 100644 index 0000000..f2eca1a --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpg/README @@ -0,0 +1,6 @@ +This directory contains code to support the JPEG image format. In order +for the code in this directory to be useful, the free JPEG library from +the Independent JPEG Group (IJG) is needed. For legal reasons, the +IJG JPEG software is not included in the JasPer software distribution. +The IJG JPEG software can be obtained, however, from: + http://www.ijg.org diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/jpg_cod.h b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_cod.h new file mode 100644 index 0000000..6ac819f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_cod.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * JPG Format Library + * + * $Id$ + */ + +#ifndef JPG_COD_H +#define JPG_COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +#define JPG_MAGIC 0xffd8 +#define JPG_MAGICLEN 2 + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/jpg_dec.c b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_dec.c new file mode 100644 index 0000000..f56c2d0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_dec.c @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include + +#include "jasper/jas_tvp.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_string.h" + +#include "jpg_jpeglib.h" +#include "jpg_cod.h" + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* JPEG decoder data sink type. */ + +typedef struct jpg_dest_s { + + /* Initialize output. */ + void (*start_output)(j_decompress_ptr cinfo, struct jpg_dest_s *dinfo); + + /* Output rows of decompressed data. */ + void (*put_pixel_rows)(j_decompress_ptr cinfo, struct jpg_dest_s *dinfo, + JDIMENSION rows_supplied); + + /* Cleanup output. */ + void (*finish_output)(j_decompress_ptr cinfo, struct jpg_dest_s *dinfo); + + /* Output buffer. */ + JSAMPARRAY buffer; + + /* Height of output buffer. */ + JDIMENSION buffer_height; + + /* The current row. */ + JDIMENSION row; + + /* The image used to hold the decompressed sample data. */ + jas_image_t *image; + + /* The row buffer. */ + jas_matrix_t *data; + + /* The error indicator. If this is nonzero, something has gone wrong + during decompression. */ + int error; + +} jpg_dest_t; + +/******************************************************************************\ +* Local functions. +\******************************************************************************/ + +static void jpg_start_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo); +static void jpg_put_pixel_rows(j_decompress_ptr cinfo, jpg_dest_t *dinfo, + JDIMENSION rows_supplied); +static void jpg_finish_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo); +static int jpg_copystreamtofile(FILE *out, jas_stream_t *in); +static jas_image_t *jpg_mkimage(j_decompress_ptr cinfo); + +/******************************************************************************\ +* Code for load operation. +\******************************************************************************/ + +/* Load an image from a stream in the JPG format. */ + +jas_image_t *jpg_decode(jas_stream_t *in, char *optstr) +{ + struct jpeg_decompress_struct cinfo; + struct jpeg_error_mgr jerr; + FILE *input_file; + jpg_dest_t dest_mgr_buf; + jpg_dest_t *dest_mgr = &dest_mgr_buf; + int num_scanlines; + jas_image_t *image; + + /* Avoid compiler warnings about unused parameters. */ + optstr = 0; + + image = 0; + input_file = 0; + if (!(input_file = tmpfile())) { + goto error; + } + if (jpg_copystreamtofile(input_file, in)) { + goto error; + } + rewind(input_file); + + /* Allocate and initialize a JPEG decompression object. */ + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_decompress(&cinfo); + + /* Specify the data source for decompression. */ + jpeg_stdio_src(&cinfo, input_file); + + /* Read the file header to obtain the image information. */ + jpeg_read_header(&cinfo, TRUE); + + /* Start the decompressor. */ + jpeg_start_decompress(&cinfo); + + /* Create an image object to hold the decoded data. */ + if (!(image = jpg_mkimage(&cinfo))) { + goto error; + } + + /* Initialize the data sink object. */ + dest_mgr->image = image; + dest_mgr->data = jas_matrix_create(1, cinfo.output_width); + dest_mgr->start_output = jpg_start_output; + dest_mgr->put_pixel_rows = jpg_put_pixel_rows; + dest_mgr->finish_output = jpg_finish_output; + dest_mgr->buffer = (*cinfo.mem->alloc_sarray) + ((j_common_ptr) &cinfo, JPOOL_IMAGE, + cinfo.output_width * cinfo.output_components, (JDIMENSION) 1); + dest_mgr->buffer_height = 1; + dest_mgr->error = 0; + + /* Process the compressed data. */ + (*dest_mgr->start_output)(&cinfo, dest_mgr); + while (cinfo.output_scanline < cinfo.output_height) { + num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer, + dest_mgr->buffer_height); + (*dest_mgr->put_pixel_rows)(&cinfo, dest_mgr, num_scanlines); + } + (*dest_mgr->finish_output)(&cinfo, dest_mgr); + + /* Complete the decompression process. */ + jpeg_finish_decompress(&cinfo); + + /* Destroy the JPEG decompression object. */ + jpeg_destroy_decompress(&cinfo); + + jas_matrix_destroy(dest_mgr->data); + + fclose(input_file); + + if (dest_mgr->error) { + goto error; + } + + return image; + +error: + if (image) { + jas_image_destroy(image); + } + if (input_file) { + fclose(input_file); + } + return 0; +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static jas_image_t *jpg_mkimage(j_decompress_ptr cinfo) +{ + jas_image_t *image; + int cmptno; + jas_image_cmptparm_t cmptparm; + int numcmpts; + + image = 0; + numcmpts = cinfo->output_components; + if (!(image = jas_image_create0())) { + goto error; + } + for (cmptno = 0; cmptno < numcmpts; ++cmptno) { + cmptparm.tlx = 0; + cmptparm.tly = 0; + cmptparm.hstep = 1; + cmptparm.vstep = 1; + cmptparm.width = cinfo->image_width; + cmptparm.height = cinfo->image_height; + cmptparm.prec = 8; + cmptparm.sgnd = false; + if (jas_image_addcmpt(image, cmptno, &cmptparm)) { + goto error; + } + } + + if (numcmpts == 3) { + jas_image_setclrspc(image, JAS_CLRSPC_SRGB); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); + jas_image_setcmpttype(image, 1, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); + jas_image_setcmpttype(image, 2, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); + } else { + jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); + } + + return image; + +error: + if (image) { + jas_image_destroy(image); + } + return 0; +} + +/******************************************************************************\ +* Data source code. +\******************************************************************************/ + +static int jpg_copystreamtofile(FILE *out, jas_stream_t *in) +{ + int c; + + while ((c = jas_stream_getc(in)) != EOF) { + if (fputc(c, out) == EOF) { + return -1; + } + } + if (jas_stream_error(in)) { + return -1; + } + return 0; +} + +/******************************************************************************\ +* Data sink code. +\******************************************************************************/ + +static void jpg_start_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo) +{ + /* Avoid compiler warnings about unused parameters. */ + cinfo = 0; + + dinfo->row = 0; +} + +static void jpg_put_pixel_rows(j_decompress_ptr cinfo, jpg_dest_t *dinfo, + JDIMENSION rows_supplied) +{ + JSAMPLE *bufptr; + int cmptno; + JDIMENSION x; + uint_fast32_t width; + + if (dinfo->error) { + return; + } + + assert(cinfo->output_components == jas_image_numcmpts(dinfo->image)); + + for (cmptno = 0; cmptno < cinfo->output_components; ++cmptno) { + width = jas_image_cmptwidth(dinfo->image, cmptno); + bufptr = (dinfo->buffer[0]) + cmptno; + for (x = 0; x < width; ++x) { + jas_matrix_set(dinfo->data, 0, x, GETJSAMPLE(*bufptr)); + bufptr += cinfo->output_components; + } + if (jas_image_writecmpt(dinfo->image, cmptno, 0, dinfo->row, width, 1, + dinfo->data)) { + dinfo->error = 1; + } + } + dinfo->row += rows_supplied; +} + +static void jpg_finish_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo) +{ + /* Avoid compiler warnings about unused parameters. */ + cinfo = 0; + dinfo = 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/jpg_dummy.c b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_dummy.c new file mode 100644 index 0000000..f05f255 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_dummy.c @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_tvp.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_string.h" + +#include "jpg_cod.h" + +/******************************************************************************\ +* +\******************************************************************************/ + +#define JPG_IJGINFO \ + "The source code for the IJG JPEG library can be downloaded from:\n" \ + " http://www.ijg.org\n" + +/******************************************************************************\ +* Code for load operation. +\******************************************************************************/ + +/* Load an image from a stream in the JPG format. */ + +jas_image_t *jpg_decode(jas_stream_t *in, char *optstr) +{ + fprintf(stderr, "error: JPEG decoder not available\n"); + fprintf(stderr, + "The IJG JPEG library is required for JPEG decoding support.\n"); + fprintf(stderr, "%s", JPG_IJGINFO); + return 0; +} + +/******************************************************************************\ +* Code for save operation. +\******************************************************************************/ + +/* Save an image to a stream in the the JPG format. */ + +int jpg_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + fprintf(stderr, "error: JPEG encoder not available\n"); + fprintf(stderr, + "The IJG JPEG library is required for JPEG encoding support.\n"); + fprintf(stderr, "%s", JPG_IJGINFO); + return -1; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/jpg_enc.c b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_enc.c new file mode 100644 index 0000000..34843b1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_enc.c @@ -0,0 +1,462 @@ +/* + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include "jasper/jas_types.h" + +#include "jasper/jas_tvp.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_string.h" +#include "jasper/jas_debug.h" + +#include "jpg_jpeglib.h" +#include "jpg_cod.h" +#include "jpg_enc.h" + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +typedef struct jpg_src_s { + + /* Output buffer. */ + JSAMPARRAY buffer; + + /* Height of output buffer. */ + JDIMENSION buffer_height; + + /* The current row. */ + JDIMENSION row; + + /* The image used to hold the decompressed sample data. */ + jas_image_t *image; + + /* The row buffer. */ + jas_matrix_t *data; + + /* The error indicator. If this is nonzero, something has gone wrong + during decompression. */ + int error; + + jpg_enc_t *enc; + +} jpg_src_t; + +typedef struct { + int qual; +} jpg_encopts_t; + +typedef enum { + OPT_QUAL +} jpg_optid_t; + +jas_taginfo_t jpg_opttab[] = { + {OPT_QUAL, "quality"}, + {-1, 0} +}; + +/******************************************************************************\ +* Local prototypes. +\******************************************************************************/ + +static int jpg_copyfiletostream(jas_stream_t *out, FILE *in); +static void jpg_start_input(j_compress_ptr cinfo, struct jpg_src_s *sinfo); +static JDIMENSION jpg_get_pixel_rows(j_compress_ptr cinfo, struct jpg_src_s *sinfo); +static void jpg_finish_input(j_compress_ptr cinfo, struct jpg_src_s *sinfo); +static int tojpgcs(int colorspace); +static int jpg_parseencopts(char *optstr, jpg_encopts_t *encopts); + +/******************************************************************************\ +* +\******************************************************************************/ + +static int jpg_copyfiletostream(jas_stream_t *out, FILE *in) +{ + int c; + while ((c = fgetc(in)) != EOF) { + if (jas_stream_putc(out, c) == EOF) { + return -1; + } + } + return 0; +} + +static void jpg_start_input(j_compress_ptr cinfo, struct jpg_src_s *sinfo) +{ + /* Avoid compiler warnings about unused parameters. */ + cinfo = 0; + + sinfo->row = 0; +} + +static JDIMENSION jpg_get_pixel_rows(j_compress_ptr cinfo, struct jpg_src_s *sinfo) +{ + JSAMPLE *bufptr; + int i; + int cmptno; + int width; + int *cmpts; + + cmpts = sinfo->enc->cmpts; + + width = jas_image_width(sinfo->image); + + if (sinfo->error) { + return 0; + } + for (cmptno = 0; cmptno < cinfo->input_components; ++cmptno) { + if (jas_image_readcmpt(sinfo->image, cmpts[cmptno], 0, sinfo->row, width, 1, sinfo->data)) { + ; + } + bufptr = (sinfo->buffer[0]) + cmptno; + for (i = 0; i < width; ++i) { + *bufptr = jas_matrix_get(sinfo->data, 0, i); + bufptr += cinfo->input_components; + } + } + ++sinfo->row; + return 1; +} + +static void jpg_finish_input(j_compress_ptr cinfo, struct jpg_src_s *sinfo) +{ + /* Avoid compiler warnings about unused parameters. */ + cinfo = 0; + sinfo = 0; +} + +/******************************************************************************\ +* Code for save operation. +\******************************************************************************/ + +/* Save an image to a stream in the the JPG format. */ + +int jpg_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + JDIMENSION numscanlines; + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + jas_image_coord_t width; + jas_image_coord_t height; + jpg_src_t src_mgr_buf; + jpg_src_t *src_mgr = &src_mgr_buf; + FILE *output_file; + int cmptno; + jpg_enc_t encbuf; + jpg_enc_t *enc = &encbuf; + jpg_encopts_t encopts; + + output_file = 0; + + if (jpg_parseencopts(optstr, &encopts)) + goto error; + + switch (jas_clrspc_fam(jas_image_clrspc(image))) { + case JAS_CLRSPC_FAM_RGB: + if (jas_image_clrspc(image) != JAS_CLRSPC_SRGB) + jas_eprintf("warning: inaccurate color\n"); + enc->numcmpts = 3; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 || + (enc->cmpts[1] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 || + (enc->cmpts[2] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) { + jas_eprintf("error: missing color component\n"); + goto error; + } + break; + case JAS_CLRSPC_FAM_YCBCR: + if (jas_image_clrspc(image) != JAS_CLRSPC_SYCBCR) + jas_eprintf("warning: inaccurate color\n"); + enc->numcmpts = 3; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y))) < 0 || + (enc->cmpts[1] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB))) < 0 || + (enc->cmpts[2] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))) < 0) { + jas_eprintf("error: missing color component\n"); + goto error; + } + break; + case JAS_CLRSPC_FAM_GRAY: + if (jas_image_clrspc(image) != JAS_CLRSPC_SGRAY) + jas_eprintf("warning: inaccurate color\n"); + enc->numcmpts = 1; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) { + jas_eprintf("error: missing color component\n"); + goto error; + } + break; + default: + jas_eprintf("error: JPG format does not support color space\n"); + goto error; + break; + } + + width = jas_image_width(image); + height = jas_image_height(image); + + for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) { + if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width || + jas_image_cmptheight(image, enc->cmpts[cmptno]) != height || + jas_image_cmpttlx(image, enc->cmpts[cmptno]) != 0 || + jas_image_cmpttly(image, enc->cmpts[cmptno]) != 0 || + jas_image_cmpthstep(image, enc->cmpts[cmptno]) != 1 || + jas_image_cmptvstep(image, enc->cmpts[cmptno]) != 1 || + jas_image_cmptprec(image, enc->cmpts[cmptno]) != 8 || + jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != false) { + jas_eprintf("error: The JPG encoder cannot handle an image with this geometry.\n"); + goto error; + } + } + + if (!(output_file = tmpfile())) { + goto error; + } + + /* Create a JPEG compression object. */ + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_compress(&cinfo); + + /* Specify data destination for compression */ + jpeg_stdio_dest(&cinfo, output_file); + + cinfo.in_color_space = tojpgcs(jas_image_clrspc(image)); + cinfo.image_width = width; + cinfo.image_height = height; + cinfo.input_components = enc->numcmpts; + jpeg_set_defaults(&cinfo); + + src_mgr->error = 0; + src_mgr->image = image; + src_mgr->data = jas_matrix_create(1, width); + src_mgr->buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, + JPOOL_IMAGE, (JDIMENSION) width * cinfo.input_components, + (JDIMENSION) 1); + src_mgr->buffer_height = 1; + src_mgr->enc = enc; + + /* Read the input file header to obtain file size & colorspace. */ + jpg_start_input(&cinfo, src_mgr); + + if (encopts.qual >= 0) { + jpeg_set_quality(&cinfo, encopts.qual, TRUE); + } + + /* Now that we know input colorspace, fix colorspace-dependent defaults */ + jpeg_default_colorspace(&cinfo); + + /* Start compressor */ + jpeg_start_compress(&cinfo, TRUE); + + /* Process data */ + while (cinfo.next_scanline < cinfo.image_height) { + if ((numscanlines = jpg_get_pixel_rows(&cinfo, src_mgr)) <= 0) { + break; + } + jpeg_write_scanlines(&cinfo, src_mgr->buffer, numscanlines); + } + + /* Finish compression and release memory */ + jpg_finish_input(&cinfo, src_mgr); + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); + + rewind(output_file); + jpg_copyfiletostream(out, output_file); + fclose(output_file); + output_file = 0; + + return 0; + +error: + if (output_file) { + fclose(output_file); + } + return -1; +} + +static int tojpgcs(int colorspace) +{ + switch (jas_clrspc_fam(colorspace)) { + case JAS_CLRSPC_FAM_RGB: + return JCS_RGB; + break; + case JAS_CLRSPC_FAM_YCBCR: + return JCS_YCbCr; + break; + case JAS_CLRSPC_FAM_GRAY: + return JCS_GRAYSCALE; + break; + default: + abort(); + break; + } +} + +/* Parse the encoder options string. */ +static int jpg_parseencopts(char *optstr, jpg_encopts_t *encopts) +{ + jas_tvparser_t *tvp; + char *qual_str; + int ret; + + tvp = 0; + + /* Initialize default values for encoder options. */ + encopts->qual = -1; + + /* Create the tag-value parser. */ + if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { + goto error; + } + + /* Get tag-value pairs, and process as necessary. */ + while (!(ret = jas_tvparser_next(tvp))) { + switch (jas_taginfo_nonull(jas_taginfos_lookup(jpg_opttab, + jas_tvparser_gettag(tvp)))->id) { + case OPT_QUAL: + qual_str = jas_tvparser_getval(tvp); + if (sscanf(qual_str, "%d", &encopts->qual) != 1) { + fprintf(stderr, + "ignoring bad quality specifier %s\n", + jas_tvparser_getval(tvp)); + encopts->qual = -1; + } + break; + default: + fprintf(stderr, "warning: ignoring invalid option %s\n", + jas_tvparser_gettag(tvp)); + break; + } + } + if (ret < 0) { + goto error; + } + + /* Destroy the tag-value parser. */ + jas_tvparser_destroy(tvp); + + return 0; + +error: + if (tvp) { + jas_tvparser_destroy(tvp); + } + return -1; +} diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/jpg_enc.h b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_enc.h new file mode 100644 index 0000000..9ff29bf --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_enc.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JPG_ENC_H +#define JPG_ENC_H + +typedef struct { + int numcmpts; + int cmpts[4]; +} jpg_enc_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/jpg_jpeglib.h b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_jpeglib.h new file mode 100644 index 0000000..c5f2317 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_jpeglib.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef JPG_JPEGLIB_H +#define JPG_JPEGLIB_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include "jasper/jas_types.h" + +/* Note: The jpeglib.h header file does not include definitions of + FILE, size_t, etc. */ +#include + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/jpg/jpg_val.c b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_val.c new file mode 100644 index 0000000..4993c66 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/jpg/jpg_val.c @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" + +#include "jpg_cod.h" + +/******************************************************************************\ +* Code for validate operation. +\******************************************************************************/ + +int jpg_validate(jas_stream_t *in) +{ + uchar buf[JPG_MAGICLEN]; + int i; + int n; + + assert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN); + + /* Read the validation data (i.e., the data used for detecting + the format). */ + if ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) { + return -1; + } + + /* Put the validation data back onto the stream, so that the + stream position will not be changed. */ + for (i = n - 1; i >= 0; --i) { + if (jas_stream_ungetc(in, buf[i]) == EOF) { + return -1; + } + } + + /* Did we read enough data? */ + if (n < JPG_MAGICLEN) { + return -1; + } + + /* Does this look like JPEG? */ + if (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) { + return -1; + } + + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/mif/.gitignore b/SlnkDWFImpl/CxImage/jasper/mif/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/mif/README b/SlnkDWFImpl/CxImage/jasper/mif/README new file mode 100644 index 0000000..6753786 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/mif/README @@ -0,0 +1 @@ +This directory contains the code for support of the MIF format. diff --git a/SlnkDWFImpl/CxImage/jasper/mif/mif_cod.c b/SlnkDWFImpl/CxImage/jasper/mif/mif_cod.c new file mode 100644 index 0000000..7726290 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/mif/mif_cod.c @@ -0,0 +1,800 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_tvp.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_string.h" +#include "jasper/jas_malloc.h" + +#include "mif_cod.h" + +/******************************************************************************\ +* Local types. +\******************************************************************************/ + +typedef enum { + MIF_END = 0, + MIF_CMPT +} mif_tagid2_t; + +typedef enum { + MIF_TLX = 0, + MIF_TLY, + MIF_WIDTH, + MIF_HEIGHT, + MIF_HSAMP, + MIF_VSAMP, + MIF_PREC, + MIF_SGND, + MIF_DATA +} mif_tagid_t; + +/******************************************************************************\ +* Local functions. +\******************************************************************************/ + +static mif_hdr_t *mif_hdr_create(int maxcmpts); +static void mif_hdr_destroy(mif_hdr_t *hdr); +static int mif_hdr_growcmpts(mif_hdr_t *hdr, int maxcmpts); +static mif_hdr_t *mif_hdr_get(jas_stream_t *in); +static int mif_process_cmpt(mif_hdr_t *hdr, char *buf); +static int mif_hdr_put(mif_hdr_t *hdr, jas_stream_t *out); +static int mif_hdr_addcmpt(mif_hdr_t *hdr, int cmptno, mif_cmpt_t *cmpt); +static mif_cmpt_t *mif_cmpt_create(void); +static void mif_cmpt_destroy(mif_cmpt_t *cmpt); +static char *mif_getline(jas_stream_t *jas_stream, char *buf, int bufsize); +static int mif_getc(jas_stream_t *in); +static mif_hdr_t *mif_makehdrfromimage(jas_image_t *image); + +/******************************************************************************\ +* Local data. +\******************************************************************************/ + +jas_taginfo_t mif_tags2[] = { + {MIF_CMPT, "component"}, + {MIF_END, "end"}, + {-1, 0} +}; + +jas_taginfo_t mif_tags[] = { + {MIF_TLX, "tlx"}, + {MIF_TLY, "tly"}, + {MIF_WIDTH, "width"}, + {MIF_HEIGHT, "height"}, + {MIF_HSAMP, "sampperx"}, + {MIF_VSAMP, "samppery"}, + {MIF_PREC, "prec"}, + {MIF_SGND, "sgnd"}, + {MIF_DATA, "data"}, + {-1, 0} +}; + +/******************************************************************************\ +* Code for load operation. +\******************************************************************************/ + +/* Load an image from a stream in the MIF format. */ + +jas_image_t *mif_decode(jas_stream_t *in, char *optstr) +{ + mif_hdr_t *hdr; + jas_image_t *image; + jas_image_t *tmpimage; + jas_stream_t *tmpstream; + int cmptno; + mif_cmpt_t *cmpt; + jas_image_cmptparm_t cmptparm; + jas_seq2d_t *data; + int_fast32_t x; + int_fast32_t y; + int bias; + + /* Avoid warnings about unused parameters. */ + optstr = 0; + + hdr = 0; + image = 0; + tmpimage = 0; + tmpstream = 0; + data = 0; + + if (!(hdr = mif_hdr_get(in))) { + goto error; + } + + if (!(image = jas_image_create0())) { + goto error; + } + + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + cmpt = hdr->cmpts[cmptno]; + tmpstream = cmpt->data ? jas_stream_fopen(cmpt->data, "rb") : in; + if (!tmpstream) { + goto error; + } + if (!(tmpimage = jas_image_decode(tmpstream, -1, 0))) { + goto error; + } + if (tmpstream != in) { + jas_stream_close(tmpstream); + tmpstream = 0; + } + if (!cmpt->width) { + cmpt->width = jas_image_cmptwidth(tmpimage, 0); + } + if (!cmpt->height) { + cmpt->height = jas_image_cmptwidth(tmpimage, 0); + } + if (!cmpt->prec) { + cmpt->prec = jas_image_cmptprec(tmpimage, 0); + } + if (cmpt->sgnd < 0) { + cmpt->sgnd = jas_image_cmptsgnd(tmpimage, 0); + } + cmptparm.tlx = cmpt->tlx; + cmptparm.tly = cmpt->tly; + cmptparm.hstep = cmpt->sampperx; + cmptparm.vstep = cmpt->samppery; + cmptparm.width = cmpt->width; + cmptparm.height = cmpt->height; + cmptparm.prec = cmpt->prec; + cmptparm.sgnd = cmpt->sgnd; + if (jas_image_addcmpt(image, jas_image_numcmpts(image), &cmptparm)) { + goto error; + } + if (!(data = jas_seq2d_create(0, 0, cmpt->width, cmpt->height))) { + goto error; + } + if (jas_image_readcmpt(tmpimage, 0, 0, 0, cmpt->width, cmpt->height, + data)) { + goto error; + } + if (cmpt->sgnd) { + bias = 1 << (cmpt->prec - 1); + for (y = 0; y < cmpt->height; ++y) { + for (x = 0; x < cmpt->width; ++x) { + *jas_seq2d_getref(data, x, y) -= bias; + } + } + } + if (jas_image_writecmpt(image, jas_image_numcmpts(image) - 1, 0, 0, + cmpt->width, cmpt->height, data)) { + goto error; + } + jas_seq2d_destroy(data); + data = 0; + jas_image_destroy(tmpimage); + tmpimage = 0; + } + + mif_hdr_destroy(hdr); + hdr = 0; + return image; + +error: + if (image) { + jas_image_destroy(image); + } + if (hdr) { + mif_hdr_destroy(hdr); + } + if (tmpstream && tmpstream != in) { + jas_stream_close(tmpstream); + } + if (tmpimage) { + jas_image_destroy(tmpimage); + } + if (data) { + jas_seq2d_destroy(data); + } + return 0; +} + +/******************************************************************************\ +* Code for save operation. +\******************************************************************************/ + +/* Save an image to a stream in the the MIF format. */ + +int mif_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + mif_hdr_t *hdr; + jas_image_t *tmpimage; + int fmt; + int cmptno; + mif_cmpt_t *cmpt; + jas_image_cmptparm_t cmptparm; + jas_seq2d_t *data; + int_fast32_t x; + int_fast32_t y; + int bias; + + hdr = 0; + tmpimage = 0; + data = 0; + + if (optstr && *optstr != '\0') { + fprintf(stderr, "warning: ignoring unsupported options\n"); + } + + if ((fmt = jas_image_strtofmt("pnm")) < 0) { + fprintf(stderr, "error: PNM support required\n"); + goto error; + } + + if (!(hdr = mif_makehdrfromimage(image))) { + goto error; + } + if (mif_hdr_put(hdr, out)) { + goto error; + } + + /* Output component data. */ + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + cmpt = hdr->cmpts[cmptno]; + if (!cmpt->data) { + if (!(tmpimage = jas_image_create0())) { + goto error; + } + cmptparm.tlx = 0; + cmptparm.tly = 0; + cmptparm.hstep = cmpt->sampperx; + cmptparm.vstep = cmpt->samppery; + cmptparm.width = cmpt->width; + cmptparm.height = cmpt->height; + cmptparm.prec = cmpt->prec; + cmptparm.sgnd = false; + if (jas_image_addcmpt(tmpimage, jas_image_numcmpts(tmpimage), &cmptparm)) { + goto error; + } + if (!(data = jas_seq2d_create(0, 0, cmpt->width, cmpt->height))) { + goto error; + } + if (jas_image_readcmpt(image, cmptno, 0, 0, cmpt->width, cmpt->height, + data)) { + goto error; + } + if (cmpt->sgnd) { + bias = 1 << (cmpt->prec - 1); + for (y = 0; y < cmpt->height; ++y) { + for (x = 0; x < cmpt->width; ++x) { + *jas_seq2d_getref(data, x, y) += bias; + } + } + } + if (jas_image_writecmpt(tmpimage, 0, 0, 0, cmpt->width, cmpt->height, + data)) { + goto error; + } + jas_seq2d_destroy(data); + data = 0; + if (jas_image_encode(tmpimage, out, fmt, 0)) { + goto error; + } + jas_image_destroy(tmpimage); + tmpimage = 0; + } + } + + mif_hdr_destroy(hdr); + + return 0; + +error: + if (hdr) { + mif_hdr_destroy(hdr); + } + if (tmpimage) { + jas_image_destroy(tmpimage); + } + if (data) { + jas_seq2d_destroy(data); + } + return -1; +} + +/******************************************************************************\ +* Code for validate operation. +\******************************************************************************/ + +int mif_validate(jas_stream_t *in) +{ + uchar buf[MIF_MAGICLEN]; + uint_fast32_t magic; + int i; + int n; + + assert(JAS_STREAM_MAXPUTBACK >= MIF_MAGICLEN); + + /* Read the validation data (i.e., the data used for detecting + the format). */ + if ((n = jas_stream_read(in, buf, MIF_MAGICLEN)) < 0) { + return -1; + } + + /* Put the validation data back onto the stream, so that the + stream position will not be changed. */ + for (i = n - 1; i >= 0; --i) { + if (jas_stream_ungetc(in, buf[i]) == EOF) { + return -1; + } + } + + /* Was enough data read? */ + if (n < MIF_MAGICLEN) { + return -1; + } + + /* Compute the signature value. */ + magic = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; + + /* Ensure that the signature is correct for this format. */ + if (magic != MIF_MAGIC) { + return -1; + } + + return 0; +} + +/******************************************************************************\ +* Code for MIF header class. +\******************************************************************************/ + +static mif_hdr_t *mif_hdr_create(int maxcmpts) +{ + mif_hdr_t *hdr; + if (!(hdr = jas_malloc(sizeof(mif_hdr_t)))) { + return 0; + } + hdr->numcmpts = 0; + hdr->maxcmpts = 0; + hdr->cmpts = 0; + if (mif_hdr_growcmpts(hdr, maxcmpts)) { + mif_hdr_destroy(hdr); + return 0; + } + return hdr; +} + +static void mif_hdr_destroy(mif_hdr_t *hdr) +{ + int cmptno; + if (hdr->cmpts) { + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + mif_cmpt_destroy(hdr->cmpts[cmptno]); + } + jas_free(hdr->cmpts); + } + jas_free(hdr); +} + +static int mif_hdr_growcmpts(mif_hdr_t *hdr, int maxcmpts) +{ + int cmptno; + mif_cmpt_t **newcmpts; + assert(maxcmpts >= hdr->numcmpts); + newcmpts = (!hdr->cmpts) ? jas_malloc(maxcmpts * sizeof(mif_cmpt_t *)) : + jas_realloc(hdr->cmpts, maxcmpts * sizeof(mif_cmpt_t *)); + if (!newcmpts) { + return -1; + } + hdr->maxcmpts = maxcmpts; + hdr->cmpts = newcmpts; + for (cmptno = hdr->numcmpts; cmptno < hdr->maxcmpts; ++cmptno) { + hdr->cmpts[cmptno] = 0; + } + return 0; +} + +static mif_hdr_t *mif_hdr_get(jas_stream_t *in) +{ + uchar magicbuf[MIF_MAGICLEN]; + char buf[4096]; + mif_hdr_t *hdr; + bool done; + jas_tvparser_t *tvp; + int id; + + hdr = 0; + + if (jas_stream_read(in, magicbuf, MIF_MAGICLEN) != MIF_MAGICLEN) { + goto error; + } + if (magicbuf[0] != (MIF_MAGIC >> 24) || magicbuf[1] != ((MIF_MAGIC >> 16) & + 0xff) || magicbuf[2] != ((MIF_MAGIC >> 8) & 0xff) || magicbuf[3] != + (MIF_MAGIC & 0xff)) { + fprintf(stderr, "error: bad signature\n"); + goto error; + } + + if (!(hdr = mif_hdr_create(0))) { + goto error; + } + + done = false; + do { + if (!mif_getline(in, buf, sizeof(buf))) { + goto error; + } + if (buf[0] == '\0') { + continue; + } + if (!(tvp = jas_tvparser_create(buf))) { + goto error; + } + if (jas_tvparser_next(tvp)) { + abort(); + } + id = jas_taginfo_nonull(jas_taginfos_lookup(mif_tags2, jas_tvparser_gettag(tvp)))->id; + jas_tvparser_destroy(tvp); + switch (id) { + case MIF_CMPT: + mif_process_cmpt(hdr, buf); + break; + case MIF_END: + done = 1; + break; + } + } while (!done); + + return hdr; + +error: + if (hdr) { + mif_hdr_destroy(hdr); + } + return 0; +} + +static int mif_process_cmpt(mif_hdr_t *hdr, char *buf) +{ + jas_tvparser_t *tvp; + mif_cmpt_t *cmpt; + int id; + + cmpt = 0; + tvp = 0; + + if (!(cmpt = mif_cmpt_create())) { + goto error; + } + cmpt->tlx = 0; + cmpt->tly = 0; + cmpt->sampperx = 0; + cmpt->samppery = 0; + cmpt->width = 0; + cmpt->height = 0; + cmpt->prec = 0; + cmpt->sgnd = -1; + cmpt->data = 0; + + if (!(tvp = jas_tvparser_create(buf))) { + goto error; + } + while (!(id = jas_tvparser_next(tvp))) { + switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags, + jas_tvparser_gettag(tvp)))->id) { + case MIF_TLX: + cmpt->tlx = atoi(jas_tvparser_getval(tvp)); + break; + case MIF_TLY: + cmpt->tly = atoi(jas_tvparser_getval(tvp)); + break; + case MIF_WIDTH: + cmpt->width = atoi(jas_tvparser_getval(tvp)); + break; + case MIF_HEIGHT: + cmpt->height = atoi(jas_tvparser_getval(tvp)); + break; + case MIF_HSAMP: + cmpt->sampperx = atoi(jas_tvparser_getval(tvp)); + break; + case MIF_VSAMP: + cmpt->samppery = atoi(jas_tvparser_getval(tvp)); + break; + case MIF_PREC: + cmpt->prec = atoi(jas_tvparser_getval(tvp)); + break; + case MIF_SGND: + cmpt->sgnd = atoi(jas_tvparser_getval(tvp)); + break; + case MIF_DATA: + if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) { + return -1; + } + break; + } + } + jas_tvparser_destroy(tvp); + if (!cmpt->sampperx || !cmpt->samppery) { + goto error; + } + if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) { + goto error; + } + return 0; + +error: + if (cmpt) { + mif_cmpt_destroy(cmpt); + } + if (tvp) { + jas_tvparser_destroy(tvp); + } + return -1; +} + +static int mif_hdr_put(mif_hdr_t *hdr, jas_stream_t *out) +{ + int cmptno; + mif_cmpt_t *cmpt; + + /* Output signature. */ + jas_stream_putc(out, (MIF_MAGIC >> 24) & 0xff); + jas_stream_putc(out, (MIF_MAGIC >> 16) & 0xff); + jas_stream_putc(out, (MIF_MAGIC >> 8) & 0xff); + jas_stream_putc(out, MIF_MAGIC & 0xff); + + /* Output component information. */ + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + cmpt = hdr->cmpts[cmptno]; + jas_stream_printf(out, "component tlx=%ld tly=%ld " + "sampperx=%ld samppery=%ld width=%ld height=%ld prec=%d sgnd=%d", + cmpt->tlx, cmpt->tly, cmpt->sampperx, cmpt->samppery, cmpt->width, + cmpt->height, cmpt->prec, cmpt->sgnd); + if (cmpt->data) { + jas_stream_printf(out, " data=%s", cmpt->data); + } + jas_stream_printf(out, "\n"); + } + + /* Output end of header indicator. */ + jas_stream_printf(out, "end\n"); + + return 0; +} + +static int mif_hdr_addcmpt(mif_hdr_t *hdr, int cmptno, mif_cmpt_t *cmpt) +{ + assert(cmptno >= hdr->numcmpts); + if (hdr->numcmpts >= hdr->maxcmpts) { + if (mif_hdr_growcmpts(hdr, hdr->numcmpts + 128)) { + return -1; + } + } + hdr->cmpts[hdr->numcmpts] = cmpt; + ++hdr->numcmpts; + return 0; +} + +/******************************************************************************\ +* Code for MIF component class. +\******************************************************************************/ + +static mif_cmpt_t *mif_cmpt_create() +{ + mif_cmpt_t *cmpt; + if (!(cmpt = jas_malloc(sizeof(mif_cmpt_t)))) { + return 0; + } + memset(cmpt, 0, sizeof(mif_cmpt_t)); + return cmpt; +} + +static void mif_cmpt_destroy(mif_cmpt_t *cmpt) +{ + if (cmpt->data) { + jas_free(cmpt->data); + } + jas_free(cmpt); +} + +/******************************************************************************\ +* MIF parsing code. +\******************************************************************************/ + +static char *mif_getline(jas_stream_t *stream, char *buf, int bufsize) +{ + int c; + char *bufptr; + assert(bufsize > 0); + + bufptr = buf; + while (bufsize > 1) { + if ((c = mif_getc(stream)) == EOF) { + break; + } + *bufptr++ = c; + --bufsize; + if (c == '\n') { + break; + } + } + *bufptr = '\0'; + if (!(bufptr = strchr(buf, '\n'))) { + return 0; + } + *bufptr = '\0'; + return buf; +} + +static int mif_getc(jas_stream_t *in) +{ + int c; + bool done; + + done = false; + do { + switch (c = jas_stream_getc(in)) { + case EOF: + done = 1; + break; + case '#': + for (;;) { + if ((c = jas_stream_getc(in)) == EOF) { + done = 1; + break; + } + if (c == '\n') { + break; + } + } + break; + case '\\': + if (jas_stream_peekc(in) == '\n') { + jas_stream_getc(in); + } + break; + default: + done = 1; + break; + } + } while (!done); + + return c; +} + +/******************************************************************************\ +* Miscellaneous functions. +\******************************************************************************/ + +static mif_hdr_t *mif_makehdrfromimage(jas_image_t *image) +{ + mif_hdr_t *hdr; + int cmptno; + mif_cmpt_t *cmpt; + + if (!(hdr = mif_hdr_create(jas_image_numcmpts(image)))) { + return 0; + } + hdr->magic = MIF_MAGIC; + hdr->numcmpts = jas_image_numcmpts(image); + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + hdr->cmpts[cmptno] = jas_malloc(sizeof(mif_cmpt_t)); + cmpt = hdr->cmpts[cmptno]; + cmpt->tlx = jas_image_cmpttlx(image, cmptno); + cmpt->tly = jas_image_cmpttly(image, cmptno); + cmpt->width = jas_image_cmptwidth(image, cmptno); + cmpt->height = jas_image_cmptheight(image, cmptno); + cmpt->sampperx = jas_image_cmpthstep(image, cmptno); + cmpt->samppery = jas_image_cmptvstep(image, cmptno); + cmpt->prec = jas_image_cmptprec(image, cmptno); + cmpt->sgnd = jas_image_cmptsgnd(image, cmptno); + cmpt->data = 0; + } + return hdr; +} diff --git a/SlnkDWFImpl/CxImage/jasper/mif/mif_cod.h b/SlnkDWFImpl/CxImage/jasper/mif/mif_cod.h new file mode 100644 index 0000000..dde5638 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/mif/mif_cod.h @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef MIF_COD_H +#define MIF_COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +#define MIF_MAGIC 0x4d49460a +/* signature */ + +#define MIF_MAGICLEN 4 +/* length of signature in bytes */ + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* Per-component information. */ + +typedef struct { + + int_fast32_t tlx; + + int_fast32_t tly; + + int_fast32_t width; + + int_fast32_t height; + + int_fast32_t sampperx; + + int_fast32_t samppery; + + int_fast16_t prec; + + int_fast16_t sgnd; + + char *data; + +} mif_cmpt_t; + +/* MIF header. */ + +typedef struct { + + uint_fast32_t magic; + + int numcmpts; + + int maxcmpts; + + mif_cmpt_t **cmpts; + +} mif_hdr_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/pgx/.gitignore b/SlnkDWFImpl/CxImage/jasper/pgx/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/pgx/pgx_cod.c b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_cod.c new file mode 100644 index 0000000..5eabb68 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_cod.c @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "pgx_cod.h" + +/******************************************************************************\ +* +\******************************************************************************/ + +void pgx_dumphdr(FILE *out, pgx_hdr_t *hdr) +{ + fprintf(out, "byteorder=%s sgnd=%s prec=%d width=%d height=%d\n", + hdr->bigendian ? "bigendian" : "littleendian", + hdr->sgnd ? "signed" : "unsigned", + hdr->prec, hdr->width, hdr->height); +} diff --git a/SlnkDWFImpl/CxImage/jasper/pgx/pgx_cod.h b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_cod.h new file mode 100644 index 0000000..bf1e190 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_cod.h @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * PGX Format Library + * + * $Id$ + */ + +#ifndef PGX_COD_H +#define PGX_COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_types.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +#define PGX_MAGIC 0x5047 +#define PGX_MAGICLEN 2 + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +typedef struct { + + uint_fast16_t magic; + /* The signature. */ + + bool bigendian; + /* The byte ordering used. */ + + bool sgnd; + /* The signedness of the samples. */ + + uint_fast32_t prec; + /* The precision of the samples. */ + + uint_fast32_t width; + /* The width of the component. */ + + uint_fast32_t height; + /* The height of the component. */ + +} pgx_hdr_t; + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +void pgx_dumphdr(FILE *out, pgx_hdr_t *hdr); + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/pgx/pgx_dec.c b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_dec.c new file mode 100644 index 0000000..f198e9b --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_dec.c @@ -0,0 +1,463 @@ +/* + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#include "jasper/jas_tvp.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_string.h" + +#include "pgx_cod.h" + +/******************************************************************************\ +* Local prototypes. +\******************************************************************************/ + +static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr); +static int pgx_getdata(jas_stream_t *in, pgx_hdr_t *hdr, jas_image_t *image); +static int_fast32_t pgx_getword(jas_stream_t *in, bool bigendian, int prec); +static int pgx_getsgnd(jas_stream_t *in, bool *sgnd); +static int pgx_getbyteorder(jas_stream_t *in, bool *bigendian); +static int pgx_getc(jas_stream_t *in); +static int pgx_getuint32(jas_stream_t *in, uint_fast32_t *val); +static jas_seqent_t pgx_wordtoint(uint_fast32_t word, int prec, bool sgnd); + +/******************************************************************************\ +* Code for load operation. +\******************************************************************************/ + +/* Load an image from a stream in the PGX format. */ + +jas_image_t *pgx_decode(jas_stream_t *in, char *optstr) +{ + jas_image_t *image; + pgx_hdr_t hdr; + jas_image_cmptparm_t cmptparm; + + /* Avoid compiler warnings about unused parameters. */ + optstr = 0; + + image = 0; + + if (pgx_gethdr(in, &hdr)) { + goto error; + } + +#ifdef PGX_DEBUG + pgx_dumphdr(stderr, &hdr); +#endif + + if (!(image = jas_image_create0())) { + goto error; + } + cmptparm.tlx = 0; + cmptparm.tly = 0; + cmptparm.hstep = 1; + cmptparm.vstep = 1; + cmptparm.width = hdr.width; + cmptparm.height = hdr.height; + cmptparm.prec = hdr.prec; + cmptparm.sgnd = hdr.sgnd; + if (jas_image_addcmpt(image, 0, &cmptparm)) { + goto error; + } + if (pgx_getdata(in, &hdr, image)) { + goto error; + } + + jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); + + return image; + +error: + if (image) { + jas_image_destroy(image); + } + return 0; +} + +/******************************************************************************\ +* Code for validate operation. +\******************************************************************************/ + +int pgx_validate(jas_stream_t *in) +{ + uchar buf[PGX_MAGICLEN]; + uint_fast32_t magic; + int i; + int n; + + assert(JAS_STREAM_MAXPUTBACK >= PGX_MAGICLEN); + + /* Read the validation data (i.e., the data used for detecting + the format). */ + if ((n = jas_stream_read(in, buf, PGX_MAGICLEN)) < 0) { + return -1; + } + + /* Put the validation data back onto the stream, so that the + stream position will not be changed. */ + for (i = n - 1; i >= 0; --i) { + if (jas_stream_ungetc(in, buf[i]) == EOF) { + return -1; + } + } + + /* Did we read enough data? */ + if (n < PGX_MAGICLEN) { + return -1; + } + + /* Compute the signature value. */ + magic = (buf[0] << 8) | buf[1]; + + /* Ensure that the signature is correct for this format. */ + if (magic != PGX_MAGIC) { + return -1; + } + + return 0; +} + +/******************************************************************************\ +* +\******************************************************************************/ + +static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr) +{ + int c; + uchar buf[2]; + + if ((c = jas_stream_getc(in)) == EOF) { + goto error; + } + buf[0] = c; + if ((c = jas_stream_getc(in)) == EOF) { + goto error; + } + buf[1] = c; + hdr->magic = buf[0] << 8 | buf[1]; + if (hdr->magic != PGX_MAGIC) { + goto error; + } + if ((c = pgx_getc(in)) == EOF || !isspace(c)) { + goto error; + } + if (pgx_getbyteorder(in, &hdr->bigendian)) { + goto error; + } + if (pgx_getsgnd(in, &hdr->sgnd)) { + goto error; + } + if (pgx_getuint32(in, &hdr->prec)) { + goto error; + } + if (pgx_getuint32(in, &hdr->width)) { + goto error; + } + if (pgx_getuint32(in, &hdr->height)) { + goto error; + } + return 0; + +error: + return -1; +} + +static int pgx_getdata(jas_stream_t *in, pgx_hdr_t *hdr, jas_image_t *image) +{ + jas_matrix_t *data; + uint_fast32_t x; + uint_fast32_t y; + uint_fast32_t word; + int_fast32_t v; + + data = 0; + + if (!(data = jas_matrix_create(1, hdr->width))) { + goto error; + } + for (y = 0; y < hdr->height; ++y) { + for (x = 0; x < hdr->width; ++x) { + /* Need to adjust signed value. */ + if ((v = pgx_getword(in, hdr->bigendian, hdr->prec)) < 0) { + goto error; + } + word = v; + v = pgx_wordtoint(word, hdr->prec, hdr->sgnd); + jas_matrix_set(data, 0, x, v); + } + if (jas_image_writecmpt(image, 0, 0, y, hdr->width, 1, data)) { + goto error; + } + } + jas_matrix_destroy(data); + return 0; + +error: + if (data) { + jas_matrix_destroy(data); + } + return -1; +} + +static int_fast32_t pgx_getword(jas_stream_t *in, bool bigendian, int prec) +{ + uint_fast32_t val; + int i; + int j; + int c; + int wordsize; + + wordsize = (prec + 7) / 8; + + if (prec > 32) { + goto error; + } + + val = 0; + for (i = 0; i < wordsize; ++i) { + if ((c = jas_stream_getc(in)) == EOF) { + goto error; + } + j = bigendian ? (wordsize - 1 - i) : i; + val = val | ((c & 0xff) << (8 * j)); + } + val &= (1 << prec) - 1; + return val; + +error: + return -1; +} + +static int pgx_getc(jas_stream_t *in) +{ + int c; + for (;;) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + if (c != '#') { + return c; + } + do { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + } while (c != '\n' && c != '\r'); + } +} + +static int pgx_getbyteorder(jas_stream_t *in, bool *bigendian) +{ + int c; + char buf[2]; + + do { + if ((c = pgx_getc(in)) == EOF) { + return -1; + } + } while (isspace(c)); + + buf[0] = c; + if ((c = pgx_getc(in)) == EOF) { + goto error; + } + buf[1] = c; + if (buf[0] == 'M' && buf[1] == 'L') { + *bigendian = true; + } else if (buf[0] == 'L' && buf[1] == 'M') { + *bigendian = false; + } else { + goto error; + } + + while ((c = pgx_getc(in)) != EOF && !isspace(c)) { + ; + } + if (c == EOF) { + goto error; + } + return 0; + +error: + return -1; +} + +static int pgx_getsgnd(jas_stream_t *in, bool *sgnd) +{ + int c; + + do { + if ((c = pgx_getc(in)) == EOF) { + return -1; + } + } while (isspace(c)); + + if (c == '+') { + *sgnd = false; + } else if (c == '-') { + *sgnd = true; + } else { + goto error; + } + while ((c = pgx_getc(in)) != EOF && !isspace(c)) { + ; + } + if (c == EOF) { + goto error; + } + return 0; + +error: + return -1; +} + +static int pgx_getuint32(jas_stream_t *in, uint_fast32_t *val) +{ + int c; + uint_fast32_t v; + + do { + if ((c = pgx_getc(in)) == EOF) { + return -1; + } + } while (isspace(c)); + + v = 0; + while (isdigit(c)) { + v = 10 * v + c - '0'; + if ((c = pgx_getc(in)) < 0) { + return -1; + } + } + if (!isspace(c)) { + return -1; + } + *val = v; + + return 0; +} + +static jas_seqent_t pgx_wordtoint(uint_fast32_t v, int prec, bool sgnd) +{ + jas_seqent_t ret; + v &= (1 << prec) - 1; + ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v; + return ret; +} diff --git a/SlnkDWFImpl/CxImage/jasper/pgx/pgx_enc.c b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_enc.c new file mode 100644 index 0000000..f2eca89 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_enc.c @@ -0,0 +1,279 @@ +/* + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include + +#include "jasper/jas_tvp.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_string.h" +#include "jasper/jas_debug.h" + +#include "pgx_cod.h" +#include "pgx_enc.h" + +/******************************************************************************\ +* Local functions. +\******************************************************************************/ + +static int pgx_puthdr(jas_stream_t *out, pgx_hdr_t *hdr); +static int pgx_putdata(jas_stream_t *out, pgx_hdr_t *hdr, jas_image_t *image, int cmpt); +static int pgx_putword(jas_stream_t *out, bool bigendian, int prec, + uint_fast32_t val); +static uint_fast32_t pgx_inttoword(int_fast32_t val, int prec, bool sgnd); + +/******************************************************************************\ +* Code for save operation. +\******************************************************************************/ + +/* Save an image to a stream in the the PGX format. */ + +int pgx_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + pgx_hdr_t hdr; + uint_fast32_t width; + uint_fast32_t height; + bool sgnd; + int prec; + pgx_enc_t encbuf; + pgx_enc_t *enc = &encbuf; + + /* Avoid compiler warnings about unused parameters. */ + optstr = 0; + + switch (jas_clrspc_fam(jas_image_clrspc(image))) { + case JAS_CLRSPC_FAM_GRAY: + if ((enc->cmpt = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) { + jas_eprintf("error: missing color component\n"); + return -1; + } + break; + default: + jas_eprintf("error: BMP format does not support color space\n"); + return -1; + break; + } + + width = jas_image_cmptwidth(image, enc->cmpt); + height = jas_image_cmptheight(image, enc->cmpt); + prec = jas_image_cmptprec(image, enc->cmpt); + sgnd = jas_image_cmptsgnd(image, enc->cmpt); + + /* The PGX format is quite limited in the set of image geometries + that it can handle. Here, we check to ensure that the image to + be saved can actually be represented reasonably accurately using the + PGX format. */ + /* There must be exactly one component. */ + if (jas_image_numcmpts(image) > 1 || prec > 16) { + fprintf(stderr, "The PNM format cannot be used to represent an image with this geometry.\n"); + return -1; + } + + hdr.magic = PGX_MAGIC; + hdr.bigendian = true; + hdr.sgnd = sgnd; + hdr.prec = prec; + hdr.width = width; + hdr.height = height; + +#ifdef PGX_DEBUG + pgx_dumphdr(stderr, &hdr); +#endif + + if (pgx_puthdr(out, &hdr)) { + return -1; + } + + if (pgx_putdata(out, &hdr, image, enc->cmpt)) { + return -1; + } + + return 0; +} + +/******************************************************************************\ +\******************************************************************************/ + +static int pgx_puthdr(jas_stream_t *out, pgx_hdr_t *hdr) +{ + jas_stream_printf(out, "%c%c", hdr->magic >> 8, hdr->magic & 0xff); + jas_stream_printf(out, " %s %s %d %ld %ld\n", hdr->bigendian ? "ML" : "LM", + hdr->sgnd ? "-" : "+", hdr->prec, (long) hdr->width, (long) hdr->height); + if (jas_stream_error(out)) { + return -1; + } + return 0; +} + +static int pgx_putdata(jas_stream_t *out, pgx_hdr_t *hdr, jas_image_t *image, int cmpt) +{ + jas_matrix_t *data; + uint_fast32_t x; + uint_fast32_t y; + int_fast32_t v; + uint_fast32_t word; + + data = 0; + + if (!(data = jas_matrix_create(1, hdr->width))) { + goto error; + } + for (y = 0; y < hdr->height; ++y) { + if (jas_image_readcmpt(image, cmpt, 0, y, hdr->width, 1, data)) { + goto error; + } + for (x = 0; x < hdr->width; ++x) { + v = jas_matrix_get(data, 0, x); + word = pgx_inttoword(v, hdr->prec, hdr->sgnd); + if (pgx_putword(out, hdr->bigendian, hdr->prec, word)) { + goto error; + } + } + } + jas_matrix_destroy(data); + data = 0; + return 0; + +error: + if (data) { + jas_matrix_destroy(data); + } + return -1; +} + +static int pgx_putword(jas_stream_t *out, bool bigendian, int prec, + uint_fast32_t val) +{ + int i; + int j; + int wordsize; + + val &= (1 << prec) - 1; + wordsize = (prec + 7) /8; + for (i = 0; i < wordsize; ++i) { + j = bigendian ? (wordsize - 1 - i) : i; + if (jas_stream_putc(out, (val >> (8 * j)) & 0xff) == EOF) { + return -1; + } + } + return 0; +} + +static uint_fast32_t pgx_inttoword(jas_seqent_t v, int prec, bool sgnd) +{ + uint_fast32_t ret; + ret = ((sgnd && v < 0) ? ((1 << prec) + v) : v) & ((1 << prec) - 1); + return ret; +} diff --git a/SlnkDWFImpl/CxImage/jasper/pgx/pgx_enc.h b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_enc.h new file mode 100644 index 0000000..7b195fd --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pgx/pgx_enc.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef PGX_ENC_H +#define PGX_ENC_H + +typedef struct { + int cmpt; +} pgx_enc_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/pnm/.gitignore b/SlnkDWFImpl/CxImage/jasper/pnm/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/pnm/pnm_cod.c b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_cod.c new file mode 100644 index 0000000..bb32143 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_cod.c @@ -0,0 +1,195 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Portable Pixmap/Graymap Format Support + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include + +#include "jasper/jas_math.h" + +#include "pnm_cod.h" + +/******************************************************************************\ +* Miscellaneous utilities. +\******************************************************************************/ + +/* Determine the PNM type (i.e., PGM or PPM) from the magic number. */ +int pnm_type(uint_fast16_t magic) +{ + int type; + switch (magic) { + case PNM_MAGIC_TXTPPM: + case PNM_MAGIC_BINPPM: + type = PNM_TYPE_PPM; + break; + case PNM_MAGIC_TXTPGM: + case PNM_MAGIC_BINPGM: + type = PNM_TYPE_PGM; + break; + case PNM_MAGIC_TXTPBM: + case PNM_MAGIC_BINPBM: + type = PNM_TYPE_PBM; + break; + default: + /* This should not happen. */ + abort(); + break; + } + return type; +} + +/* Determine the PNM format (i.e., text or binary) from the magic number. */ +int pnm_fmt(uint_fast16_t magic) +{ + int fmt; + switch (magic) { + case PNM_MAGIC_TXTPBM: + case PNM_MAGIC_TXTPGM: + case PNM_MAGIC_TXTPPM: + fmt = PNM_FMT_TXT; + break; + case PNM_MAGIC_BINPBM: + case PNM_MAGIC_BINPGM: + case PNM_MAGIC_BINPPM: + fmt = PNM_FMT_BIN; + break; + default: + /* This should not happen. */ + abort(); + break; + } + return fmt; +} + +/* Determine the depth (i.e., precision) from the maximum value. */ +int pnm_maxvaltodepth(uint_fast32_t maxval) +{ + int n; + + n = 0; + while (maxval > 0) { + maxval >>= 1; + ++n; + } + return n; +} diff --git a/SlnkDWFImpl/CxImage/jasper/pnm/pnm_cod.h b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_cod.h new file mode 100644 index 0000000..68b741f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_cod.h @@ -0,0 +1,205 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Portable Pixmap/Graymap Format Support + * + * $Id$ + */ + +#ifndef PNM_COD_H +#define PNM_COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +/* Magic numbers. */ +#define PNM_MAGIC_TXTPBM 0x5031 /* Text Portable BitMap (P1) */ +#define PNM_MAGIC_TXTPGM 0x5032 /* Text Portable GrayMap (P2) */ +#define PNM_MAGIC_TXTPPM 0x5033 /* Text Portable PixMap (P3) */ +#define PNM_MAGIC_BINPBM 0x5034 /* Binary Portable BitMap (P4) */ +#define PNM_MAGIC_BINPGM 0x5035 /* Binary Portable GrayMap (P5) */ +#define PNM_MAGIC_BINPPM 0x5036 /* Binary Portable PixMap (P6) */ +#define PNM_MAGIC_PAM 0x5037 /* PAM (P7) */ + +/* Type of image data. */ +#define PNM_TYPE_PPM 0 /* PixMap */ +#define PNM_TYPE_PGM 1 /* GrayMap */ +#define PNM_TYPE_PBM 2 /* BitMap */ + +/* Format of image data. */ +#define PNM_FMT_TXT 0 /* Text */ +#define PNM_FMT_BIN 1 /* Binary */ + +#define PNM_MAXLINELEN 79 + +#define PNM_TUPLETYPE_UNKNOWN 0 +#define PNM_TUPLETYPE_MONO 1 +#define PNM_TUPLETYPE_GRAY 2 +#define PNM_TUPLETYPE_GRAYA 3 +#define PNM_TUPLETYPE_RGB 4 +#define PNM_TUPLETYPE_RGBA 5 + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* File header. */ + +typedef struct { + + int magic; + /* The magic number. */ + + int width; + /* The image width. */ + + int height; + /* The image height. */ + + int numcmpts; + + int maxval; + /* The maximum allowable sample value. */ + +#if 0 + int tupletype; +#endif + + bool sgnd; + /* The sample data is signed. */ + +} pnm_hdr_t; + +/******************************************************************************\ +* Functions. +\******************************************************************************/ + +int pnm_type(uint_fast16_t magic); +/* Determine type (i.e., PGM or PPM) from magic number. */ + +int pnm_fmt(uint_fast16_t magic); +/* Determine format (i.e., text or binary) from magic number. */ + +int pnm_maxvaltodepth(uint_fast32_t maxval); +/* Determine depth (i.e., precision) from maximum value. */ + +#define PNM_ONES(n) \ + (((n) < 32) ? ((1UL << (n)) - 1) : 0xffffffffUL) +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/pnm/pnm_dec.c b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_dec.c new file mode 100644 index 0000000..87f7825 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_dec.c @@ -0,0 +1,609 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Portable Pixmap/Graymap Format Support + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" + +#include "pnm_cod.h" + +/******************************************************************************\ +* Local function prototypes. +\******************************************************************************/ + +static int pnm_gethdr(jas_stream_t *in, pnm_hdr_t *hdr); +static int pnm_getdata(jas_stream_t *in, pnm_hdr_t *hdr, jas_image_t *image); + +static int pnm_getsintstr(jas_stream_t *in, int_fast32_t *val); +static int pnm_getuintstr(jas_stream_t *in, uint_fast32_t *val); +static int pnm_getbitstr(jas_stream_t *in, int *val); +static int pnm_getc(jas_stream_t *in); + +static int pnm_getsint(jas_stream_t *in, int wordsize, int_fast32_t *val); +static int pnm_getuint(jas_stream_t *in, int wordsize, uint_fast32_t *val); +static int pnm_getint16(jas_stream_t *in, int *val); +#define pnm_getuint32(in, val) pnm_getuint(in, 32, val) + +/******************************************************************************\ +* Local data. +\******************************************************************************/ + +static int pnm_allowtrunc = 1; + +/******************************************************************************\ +* Load function. +\******************************************************************************/ + +jas_image_t *pnm_decode(jas_stream_t *in, char *opts) +{ + pnm_hdr_t hdr; + jas_image_t *image; + jas_image_cmptparm_t cmptparms[3]; + jas_image_cmptparm_t *cmptparm; + int i; + + if (opts) { + fprintf(stderr, "warning: ignoring options\n"); + } + + /* Read the file header. */ + if (pnm_gethdr(in, &hdr)) { + return 0; + } + + /* Create an image of the correct size. */ + for (i = 0, cmptparm = cmptparms; i < hdr.numcmpts; ++i, ++cmptparm) { + cmptparm->tlx = 0; + cmptparm->tly = 0; + cmptparm->hstep = 1; + cmptparm->vstep = 1; + cmptparm->width = hdr.width; + cmptparm->height = hdr.height; + cmptparm->prec = pnm_maxvaltodepth(hdr.maxval); + cmptparm->sgnd = hdr.sgnd; + } + if (!(image = jas_image_create(hdr.numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { + return 0; + } + + if (hdr.numcmpts == 3) { + jas_image_setclrspc(image, JAS_CLRSPC_SRGB); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); + jas_image_setcmpttype(image, 1, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); + jas_image_setcmpttype(image, 2, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); + } else { + jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); + } + + /* Read image data from stream into image. */ + if (pnm_getdata(in, &hdr, image)) { + jas_image_destroy(image); + return 0; + } + + return image; +} + +/******************************************************************************\ +* Validation function. +\******************************************************************************/ + +int pnm_validate(jas_stream_t *in) +{ + uchar buf[2]; + int i; + int n; + + assert(JAS_STREAM_MAXPUTBACK >= 2); + + /* Read the first two characters that constitute the signature. */ + if ((n = jas_stream_read(in, buf, 2)) < 0) { + return -1; + } + /* Put these characters back to the stream. */ + for (i = n - 1; i >= 0; --i) { + if (jas_stream_ungetc(in, buf[i]) == EOF) { + return -1; + } + } + /* Did we read enough data? */ + if (n < 2) { + return -1; + } + /* Is this the correct signature for a PNM file? */ + if (buf[0] == 'P' && isdigit(buf[1])) { + return 0; + } + return -1; +} + +/******************************************************************************\ +* Functions for reading the header. +\******************************************************************************/ + +static int pnm_gethdr(jas_stream_t *in, pnm_hdr_t *hdr) +{ + int_fast32_t maxval; + if (pnm_getint16(in, &hdr->magic) || pnm_getsintstr(in, &hdr->width) || + pnm_getsintstr(in, &hdr->height)) { + return -1; + } + if (pnm_type(hdr->magic) != PNM_TYPE_PBM) { + if (pnm_getsintstr(in, &maxval)) { + return -1; + } + } else { + maxval = 1; + } + if (maxval < 0) { + hdr->maxval = -maxval; + hdr->sgnd = true; + } else { + hdr->maxval = maxval; + hdr->sgnd = false; + } + + switch (pnm_type(hdr->magic)) { + case PNM_TYPE_PBM: + case PNM_TYPE_PGM: + hdr->numcmpts = 1; + break; + case PNM_TYPE_PPM: + hdr->numcmpts = 3; + break; + default: + abort(); + break; + } + + return 0; +} + +/******************************************************************************\ +* Functions for processing the sample data. +\******************************************************************************/ + +static int pnm_getdata(jas_stream_t *in, pnm_hdr_t *hdr, jas_image_t *image) +{ + int ret; +#if 0 + int numcmpts; +#endif + int cmptno; + int fmt; + jas_matrix_t *data[3]; + int x; + int y; + int_fast64_t v; + int depth; + int type; + int c; + int n; + + ret = -1; + +#if 0 + numcmpts = jas_image_numcmpts(image); +#endif + fmt = pnm_fmt(hdr->magic); + type = pnm_type(hdr->magic); + depth = pnm_maxvaltodepth(hdr->maxval); + + data[0] = 0; + data[1] = 0; + data[2] = 0; + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + if (!(data[cmptno] = jas_matrix_create(1, hdr->width))) { + goto done; + } + } + + for (y = 0; y < hdr->height; ++y) { + if (type == PNM_TYPE_PBM) { + if (fmt == PNM_FMT_BIN) { + for (x = 0; x < hdr->width;) { + if ((c = jas_stream_getc(in)) == EOF) { + goto done; + } + n = 8; + while (n > 0 && x < hdr->width) { + jas_matrix_set(data[0], 0, x, 1 - ((c >> 7) & 1)); + c <<= 1; + --n; + ++x; + } + } + } else { + for (x = 0; x < hdr->width; ++x) { + int uv; + if (pnm_getbitstr(in, &uv)) { + goto done; + } + jas_matrix_set(data[0], 0, x, 1 - uv); + } + } + } else { + for (x = 0; x < hdr->width; ++x) { + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + if (fmt == PNM_FMT_BIN) { + /* The sample data is in binary format. */ + if (hdr->sgnd) { + /* The sample data is signed. */ + int_fast32_t sv; + if (pnm_getsint(in, depth, &sv)) { + if (!pnm_allowtrunc) { + goto done; + } + sv = 0; + } + v = sv; + } else { + /* The sample data is unsigned. */ + uint_fast32_t uv; + if (pnm_getuint(in, depth, &uv)) { + if (!pnm_allowtrunc) { + goto done; + } + uv = 0; + } + v = uv; + } + } else { + /* The sample data is in text format. */ + if (hdr->sgnd) { + /* The sample data is signed. */ + int_fast32_t sv; + if (pnm_getsintstr(in, &sv)) { + if (!pnm_allowtrunc) { + goto done; + } + sv = 0; + } + v = sv; + } else { + /* The sample data is unsigned. */ + uint_fast32_t uv; + if (pnm_getuintstr(in, &uv)) { + if (!pnm_allowtrunc) { + goto done; + } + uv = 0; + } + v = uv; + } + } + jas_matrix_set(data[cmptno], 0, x, v); + } + } + } + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + if (jas_image_writecmpt(image, cmptno, 0, y, hdr->width, 1, + data[cmptno])) { + goto done; + } + } + } + + ret = 0; + +done: + + for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { + if (data[cmptno]) { + jas_matrix_destroy(data[cmptno]); + } + } + + return ret; +} + +/******************************************************************************\ +* Miscellaneous functions. +\******************************************************************************/ + +static int pnm_getsint(jas_stream_t *in, int wordsize, int_fast32_t *val) +{ + uint_fast32_t tmpval; + + if (pnm_getuint(in, wordsize, &tmpval)) { + return -1; + } + if (val) { + assert((tmpval & (1 << (wordsize - 1))) == 0); + *val = tmpval; + } + + return 0; +} + +static int pnm_getuint(jas_stream_t *in, int wordsize, uint_fast32_t *val) +{ + uint_fast32_t tmpval; + int c; + int n; + + tmpval = 0; + n = (wordsize + 7) / 8; + while (--n >= 0) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + tmpval = (tmpval << 8) | c; + } + tmpval &= (((uint_fast64_t) 1) << wordsize) - 1; + if (val) { + *val = tmpval; + } + + return 0; +} + +static int pnm_getbitstr(jas_stream_t *in, int *val) +{ + int c; + int_fast32_t v; + for (;;) { + if ((c = pnm_getc(in)) == EOF) { + return -1; + } + if (c == '#') { + for (;;) { + if ((c = pnm_getc(in)) == EOF) { + return -1; + } + if (c == '\n') { + break; + } + } + } else if (c == '0' || c == '1') { + v = c - '0'; + break; + } + } + if (val) { + *val = v; + } + return 0; +} + +static int pnm_getuintstr(jas_stream_t *in, uint_fast32_t *val) +{ + uint_fast32_t v; + int c; + + /* Discard any leading whitespace. */ + do { + if ((c = pnm_getc(in)) == EOF) { + return -1; + } + } while (isspace(c)); + + /* Parse the number. */ + v = 0; + while (isdigit(c)) { + v = 10 * v + c - '0'; + if ((c = pnm_getc(in)) < 0) { + return -1; + } + } + + /* The number must be followed by whitespace. */ + if (!isspace(c)) { + return -1; + } + + if (val) { + *val = v; + } + return 0; +} + +static int pnm_getsintstr(jas_stream_t *in, int_fast32_t *val) +{ + int c; + int s; + int_fast32_t v; + + /* Discard any leading whitespace. */ + do { + if ((c = pnm_getc(in)) == EOF) { + return -1; + } + } while (isspace(c)); + + /* Get the number, allowing for a negative sign. */ + s = 1; + if (c == '-') { + s = -1; + if ((c = pnm_getc(in)) == EOF) { + return -1; + } + } else if (c == '+') { + if ((c = pnm_getc(in)) == EOF) { + return -1; + } + } + v = 0; + while (isdigit(c)) { + v = 10 * v + c - '0'; + if ((c = pnm_getc(in)) < 0) { + return -1; + } + } + + /* The number must be followed by whitespace. */ + if (!isspace(c)) { + return -1; + } + + if (val) { + *val = (s >= 0) ? v : (-v); + } + + return 0; +} + +static int pnm_getc(jas_stream_t *in) +{ + int c; + for (;;) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + if (c != '#') { + return c; + } + do { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + } while (c != '\n' && c != '\r'); + } +} + +static int pnm_getint16(jas_stream_t *in, int *val) +{ + int v; + int c; + + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = c & 0xff; + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + v = (v << 8) | (c & 0xff); + *val = v; + + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/pnm/pnm_enc.c b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_enc.c new file mode 100644 index 0000000..c4712cd --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_enc.c @@ -0,0 +1,500 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Portable Pixmap/Graymap Format Support + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include +#include +#include + +#include "jasper/jas_types.h" +#include "jasper/jas_tvp.h" +#include "jasper/jas_image.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_debug.h" + +#include "pnm_cod.h" +#include "pnm_enc.h" + +/******************************************************************************\ +* Local types. +\******************************************************************************/ + +typedef struct { + bool bin; +} pnm_encopts_t; + +typedef enum { + OPT_TEXT +} pnm_optid_t; + +jas_taginfo_t pnm_opttab[] = { + {OPT_TEXT, "text"}, + {-1, 0} +}; + +/******************************************************************************\ +* Local function prototypes. +\******************************************************************************/ + +static int pnm_parseencopts(char *optstr, pnm_encopts_t *encopts); +static int pnm_puthdr(jas_stream_t *out, pnm_hdr_t *hdr); +static int pnm_putdata(jas_stream_t *out, pnm_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts); + +static int pnm_putsint(jas_stream_t *out, int wordsize, int_fast32_t *val); +static int pnm_putuint(jas_stream_t *out, int wordsize, uint_fast32_t *val); +static int pnm_putuint16(jas_stream_t *out, uint_fast16_t val); + +/******************************************************************************\ +* Save function. +\******************************************************************************/ + +int pnm_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + int width; + int height; + int cmptno; + pnm_hdr_t hdr; + pnm_encopts_t encopts; + int prec; + int sgnd; + pnm_enc_t encbuf; + pnm_enc_t *enc = &encbuf; + + /* Parse the encoder option string. */ + if (pnm_parseencopts(optstr, &encopts)) { + fprintf(stderr, "invalid PNM encoder options specified\n"); + return -1; + } + + switch (jas_clrspc_fam(jas_image_clrspc(image))) { + case JAS_CLRSPC_FAM_RGB: + if (jas_image_clrspc(image) != JAS_CLRSPC_SRGB) + jas_eprintf("warning: inaccurate color\n"); + enc->numcmpts = 3; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 || + (enc->cmpts[1] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 || + (enc->cmpts[2] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) { + jas_eprintf("error: missing color component\n"); + return -1; + } + break; + case JAS_CLRSPC_FAM_GRAY: + if (jas_image_clrspc(image) != JAS_CLRSPC_SGRAY) + jas_eprintf("warning: inaccurate color\n"); + enc->numcmpts = 1; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) { + jas_eprintf("error: missing color component\n"); + return -1; + } + break; + default: + jas_eprintf("error: unsupported color space\n"); + return -1; + break; + } + + + width = jas_image_cmptwidth(image, enc->cmpts[0]); + height = jas_image_cmptheight(image, enc->cmpts[0]); + prec = jas_image_cmptprec(image, enc->cmpts[0]); + sgnd = jas_image_cmptsgnd(image, enc->cmpts[0]); + + /* The PNM format is quite limited in the set of image geometries + that it can handle. Here, we check to ensure that the image to + be saved can actually be represented reasonably accurately using the + PNM format. */ + /* All of the components must have the same width and height. */ + /* All of the components must have unsigned samples with the same + precision.*/ + /* All of the components must have their top-left corner located at + the origin. */ + for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) { + if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width || + jas_image_cmptheight(image, enc->cmpts[cmptno]) != height || + jas_image_cmptprec(image, enc->cmpts[cmptno]) != prec || + jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != sgnd || + jas_image_cmpthstep(image, enc->cmpts[cmptno]) != jas_image_cmpthstep(image, 0) || + jas_image_cmptvstep(image, enc->cmpts[cmptno]) != jas_image_cmptvstep(image, 0) || + jas_image_cmpttlx(image, enc->cmpts[cmptno]) != jas_image_cmpttlx(image, 0) || + jas_image_cmpttly(image, enc->cmpts[cmptno]) != jas_image_cmpttly(image, 0)) { + fprintf(stderr, "The PNM format cannot be used to represent an image with this geometry.\n"); + return -1; + } + } + + if (sgnd) { + fprintf(stderr, "warning: support for signed sample data requires use of nonstandard extension to PNM format\n"); + fprintf(stderr, "You may not be able to read or correctly display the resulting PNM data with other software.\n"); + } + + /* Initialize the header. */ + if (enc->numcmpts == 1) { + hdr.magic = encopts.bin ? PNM_MAGIC_BINPGM : PNM_MAGIC_TXTPGM; + } else if (enc->numcmpts == 3) { + hdr.magic = encopts.bin ? PNM_MAGIC_BINPPM : PNM_MAGIC_TXTPPM; + } else { + return -1; + } + hdr.width = width; + hdr.height = height; + hdr.maxval = (1 << prec) - 1; + hdr.sgnd = sgnd; + + /* Write the header. */ + if (pnm_puthdr(out, &hdr)) { + return -1; + } + + /* Write the image data. */ + if (pnm_putdata(out, &hdr, image, enc->numcmpts, enc->cmpts)) { + return -1; + } + + /* Flush the output stream. */ + if (jas_stream_flush(out)) { + return -1; + } + + return 0; +} + +/******************************************************************************\ +* Code for parsing options. +\******************************************************************************/ + +/* Parse the encoder options string. */ +static int pnm_parseencopts(char *optstr, pnm_encopts_t *encopts) +{ + jas_tvparser_t *tvp; + int ret; + + tvp = 0; + + /* Initialize default values for encoder options. */ + encopts->bin = true; + + /* Create the tag-value parser. */ + if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { + goto error; + } + + /* Get tag-value pairs, and process as necessary. */ + while (!(ret = jas_tvparser_next(tvp))) { + switch (jas_taginfo_nonull(jas_taginfos_lookup(pnm_opttab, + jas_tvparser_gettag(tvp)))->id) { + case OPT_TEXT: + encopts->bin = false; + break; + default: + fprintf(stderr, "warning: ignoring invalid option %s\n", + jas_tvparser_gettag(tvp)); + break; + } + } + if (ret < 0) { + goto error; + } + + /* Destroy the tag-value parser. */ + jas_tvparser_destroy(tvp); + + return 0; + +error: + if (tvp) { + jas_tvparser_destroy(tvp); + } + return -1; +} + +/******************************************************************************\ +* Function for writing header. +\******************************************************************************/ + +/* Write the header. */ +static int pnm_puthdr(jas_stream_t *out, pnm_hdr_t *hdr) +{ + int_fast32_t maxval; + + if (pnm_putuint16(out, hdr->magic)) { + return -1; + } + if (hdr->sgnd) { + maxval = -hdr->maxval; + } else { + maxval = hdr->maxval; + } + jas_stream_printf(out, "\n%lu %lu\n%ld\n", (unsigned long) hdr->width, + (unsigned long) hdr->height, (long) maxval); + if (jas_stream_error(out)) { + return -1; + } + return 0; +} + +/******************************************************************************\ +* Functions for processing the sample data. +\******************************************************************************/ + +/* Write the image sample data. */ +static int pnm_putdata(jas_stream_t *out, pnm_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) +{ + int ret; + int cmptno; + int x; + int y; + jas_matrix_t *data[3]; + int fmt; + jas_seqent_t *d[3]; + jas_seqent_t v; + int minval; + int linelen; + int n; + char buf[256]; + int depth; + + ret = -1; + fmt = pnm_fmt(hdr->magic); + minval = -((int) hdr->maxval + 1); + depth = pnm_maxvaltodepth(hdr->maxval); + + data[0] = 0; + data[1] = 0; + data[2] = 0; + for (cmptno = 0; cmptno < numcmpts; ++cmptno) { + if (!(data[cmptno] = jas_matrix_create(1, hdr->width))) { + goto done; + } + } + + for (y = 0; y < hdr->height; ++y) { + for (cmptno = 0; cmptno < numcmpts; ++cmptno) { + if (jas_image_readcmpt(image, cmpts[cmptno], 0, y, hdr->width, 1, + data[cmptno])) { + goto done; + } + d[cmptno] = jas_matrix_getref(data[cmptno], 0, 0); + } + linelen = 0; + for (x = 0; x < hdr->width; ++x) { + for (cmptno = 0; cmptno < numcmpts; ++cmptno) { + v = *d[cmptno]; + if (v < minval) { + v = minval; + } + if (v > ((int) hdr->maxval)) { + v = hdr->maxval; + } + if (fmt == PNM_FMT_BIN) { + if (hdr->sgnd) { + int_fast32_t sv; + sv = v; + if (pnm_putsint(out, depth, &sv)) { + goto done; + } + } else { + uint_fast32_t uv; + uv = v; + if (pnm_putuint(out, depth, &uv)) { + goto done; + } + } + } else { + n = sprintf(buf, "%s%ld", ((!(!x && !cmptno)) ? " " : ""), + (long) v); + if (linelen > 0 && linelen + n > PNM_MAXLINELEN) { + jas_stream_printf(out, "\n"); + linelen = 0; + } + jas_stream_printf(out, "%s", buf); + linelen += n; + } + ++d[cmptno]; + } + } + if (fmt != PNM_FMT_BIN) { + jas_stream_printf(out, "\n"); + linelen = 0; + } + if (jas_stream_error(out)) { + goto done; + } + } + + ret = 0; + +done: + + for (cmptno = 0; cmptno < numcmpts; ++cmptno) { + if (data[cmptno]) { + jas_matrix_destroy(data[cmptno]); + } + } + + return ret; +} + +/******************************************************************************\ +* Miscellaneous functions. +\******************************************************************************/ + +static int pnm_putsint(jas_stream_t *out, int wordsize, int_fast32_t *val) +{ + uint_fast32_t tmpval; + tmpval = (*val < 0) ? + ((~(JAS_CAST(uint_fast32_t, -(*val)) + 1)) & PNM_ONES(wordsize)) : + JAS_CAST(uint_fast32_t, (*val)); + return pnm_putuint(out, wordsize, &tmpval); +} + +static int pnm_putuint(jas_stream_t *out, int wordsize, uint_fast32_t *val) +{ + int n; + uint_fast32_t tmpval; + int c; + + n = (wordsize + 7) / 8; + tmpval &= PNM_ONES(8 * n); + tmpval = (*val) << (8 * (4 - n)); + while (--n >= 0) { + c = (tmpval >> 24) & 0xff; + if (jas_stream_putc(out, c) == EOF) { + return -1; + } + tmpval = (tmpval << 8) & 0xffffffff; + } + return 0; +} + +/* Write a 16-bit unsigned integer to a stream. */ +static int pnm_putuint16(jas_stream_t *out, uint_fast16_t val) +{ + if (jas_stream_putc(out, (unsigned char)(val >> 8)) == EOF || + jas_stream_putc(out, (unsigned char)(val & 0xff)) == EOF) { + return -1; + } + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/pnm/pnm_enc.h b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_enc.h new file mode 100644 index 0000000..b8a6be6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/pnm/pnm_enc.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef PNM_ENC_H +#define PNM_ENC_H + +typedef struct { + int numcmpts; + int cmpts[4]; +} pnm_enc_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/ras/.gitignore b/SlnkDWFImpl/CxImage/jasper/ras/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jasper/ras/ras_cod.c b/SlnkDWFImpl/CxImage/jasper/ras/ras_cod.c new file mode 100644 index 0000000..77973bf --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/ras/ras_cod.c @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Sun Rasterfile Library + * + * $Id$ + */ + +/* Note: There is not currently any code common to both the encoder and + decoder. */ + +/* Keep picky compilers happy. */ +int ras_dummy; diff --git a/SlnkDWFImpl/CxImage/jasper/ras/ras_cod.h b/SlnkDWFImpl/CxImage/jasper/ras/ras_cod.h new file mode 100644 index 0000000..8aad40a --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/ras/ras_cod.h @@ -0,0 +1,213 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Sun Rasterfile Library + * + * $Id$ + */ + +/******************************************************************************\ +* Sun Rasterfile +\******************************************************************************/ + +#ifndef RAS_COD_H +#define RAS_COD_H + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include "jasper/jas_types.h" + +/******************************************************************************\ +* Constants. +\******************************************************************************/ + +#define RAS_MAGIC 0x59a66a95 +#define RAS_MAGICLEN 4 + +#define RAS_TYPE_OLD 0 +#define RAS_TYPE_STD 1 +#define RAS_TYPE_RLE 2 + +#define RAS_MT_NONE 0 +#define RAS_MT_EQUALRGB 1 +#define RAS_MT_RAW 2 + +/******************************************************************************\ +* Types. +\******************************************************************************/ + +/* Sun Rasterfile header. */ +typedef struct { + + int_fast32_t magic; + /* signature */ + + int_fast32_t width; + /* width of image (in pixels) */ + + int_fast32_t height; + /* height of image (in pixels) */ + + int_fast32_t depth; + /* number of bits per pixel */ + + int_fast32_t length; + /* length of image data (in bytes) */ + + int_fast32_t type; + /* format of image data */ + + int_fast32_t maptype; + /* colormap type */ + + int_fast32_t maplength; + /* length of colormap data (in bytes) */ + +} ras_hdr_t; + +#define RAS_CMAP_MAXSIZ 256 + +/* Color map. */ +typedef struct { + + int len; + /* The number of entries in the color map. */ + + int data[RAS_CMAP_MAXSIZ]; + /* The color map data. */ + +} ras_cmap_t; + +/******************************************************************************\ +* Macros. +\******************************************************************************/ + +#define RAS_GETBLUE(x) (((x) >> 16) & 0xff) +#define RAS_GETGREEN(x) (((x) >> 8) & 0xff) +#define RAS_GETRED(x) ((x) & 0xff) + +#define RAS_BLUE(x) (((x) & 0xff) << 16) +#define RAS_GREEN(x) (((x) & 0xff) << 8) +#define RAS_RED(x) ((x) & 0xff) + +#define RAS_ROWSIZE(hdr) \ + ((((hdr)->width * (hdr)->depth + 15) / 16) * 2) +#define RAS_ISRGB(hdr) \ + ((hdr)->depth == 24 || (hdr)->depth == 32) + +#define RAS_ONES(n) \ + (((n) == 32) ? 0xffffffffUL : ((1UL << (n)) - 1)) + +#endif diff --git a/SlnkDWFImpl/CxImage/jasper/ras/ras_dec.c b/SlnkDWFImpl/CxImage/jasper/ras/ras_dec.c new file mode 100644 index 0000000..48a21e5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/ras/ras_dec.c @@ -0,0 +1,447 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Sun Rasterfile Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#include "jasper/jas_stream.h" +#include "jasper/jas_image.h" +#include "jasper/jas_debug.h" + +#include "ras_cod.h" + +/******************************************************************************\ +* Prototypes. +\******************************************************************************/ + +static int ras_gethdr(jas_stream_t *in, ras_hdr_t *hdr); +static int ras_getint(jas_stream_t *in, int_fast32_t *val); + +static int ras_getdata(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap, + jas_image_t *image); +static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap, + jas_image_t *image); +static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap); + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +jas_image_t *ras_decode(jas_stream_t *in, char *optstr) +{ + ras_hdr_t hdr; + ras_cmap_t cmap; + jas_image_t *image; + jas_image_cmptparm_t cmptparms[3]; + jas_image_cmptparm_t *cmptparm; + int clrspc; + int numcmpts; + int i; + + if (optstr) { + fprintf(stderr, "warning: ignoring RAS decoder options\n"); + } + + /* Read the header. */ + if (ras_gethdr(in, &hdr)) { + return 0; + } + + /* Does the header information look reasonably sane? */ + if (hdr.magic != RAS_MAGIC || hdr.width <= 0 || hdr.height <= 0 || + hdr.depth <= 0 || hdr.depth > 32) { + return 0; + } + + /* In the case of the old format, do not rely on the length field + being properly specified. Calculate the quantity from scratch. */ + if (hdr.type == RAS_TYPE_OLD) { + hdr.length = RAS_ROWSIZE(&hdr) * hdr.height; + } + + /* Calculate some quantities needed for creation of the image + object. */ + if (RAS_ISRGB(&hdr)) { + clrspc = JAS_CLRSPC_SRGB; + numcmpts = 3; + } else { + clrspc = JAS_CLRSPC_SGRAY; + numcmpts = 1; + } + for (i = 0, cmptparm = cmptparms; i < numcmpts; ++i, ++cmptparm) { + cmptparm->tlx = 0; + cmptparm->tly = 0; + cmptparm->hstep = 1; + cmptparm->vstep = 1; + cmptparm->width = hdr.width; + cmptparm->height = hdr.height; + cmptparm->prec = RAS_ISRGB(&hdr) ? 8 : hdr.depth; + cmptparm->sgnd = false; + } + /* Create the image object. */ + if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { + return 0; + } + + /* Read the color map (if there is one). */ + if (ras_getcmap(in, &hdr, &cmap)) { + jas_image_destroy(image); + return 0; + } + + /* Read the pixel data. */ + if (ras_getdata(in, &hdr, &cmap, image)) { + jas_image_destroy(image); + return 0; + } + + jas_image_setclrspc(image, clrspc); + if (clrspc == JAS_CLRSPC_SRGB) { + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); + jas_image_setcmpttype(image, 1, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); + jas_image_setcmpttype(image, 2, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); + } else { + jas_image_setcmpttype(image, 0, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); + } + + return image; +} + +int ras_validate(jas_stream_t *in) +{ + uchar buf[RAS_MAGICLEN]; + int i; + int n; + uint_fast32_t magic; + + assert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN); + + /* Read the validation data (i.e., the data used for detecting + the format). */ + if ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) { + return -1; + } + + /* Put the validation data back onto the stream, so that the + stream position will not be changed. */ + for (i = n - 1; i >= 0; --i) { + if (jas_stream_ungetc(in, buf[i]) == EOF) { + return -1; + } + } + + /* Did we read enough data? */ + if (n < RAS_MAGICLEN) { + return -1; + } + + magic = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; + + /* Is the signature correct for the Sun Rasterfile format? */ + if (magic != RAS_MAGIC) { + return -1; + } + return 0; +} + +static int ras_getdata(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap, + jas_image_t *image) +{ + int ret; + + switch (hdr->type) { + case RAS_TYPE_OLD: + case RAS_TYPE_STD: + ret = ras_getdatastd(in, hdr, cmap, image); + break; + case RAS_TYPE_RLE: + jas_eprintf("error: RLE encoding method not supported\n"); + ret = -1; + break; + default: + jas_eprintf("error: encoding method not supported\n"); + ret = -1; + break; + } + return ret; +} + +static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap, + jas_image_t *image) +{ + int pad; + int nz; + int z; + int c; + int y; + int x; + int v; + int i; + jas_matrix_t *data[3]; + +/* Note: This function does not properly handle images with a colormap. */ + /* Avoid compiler warnings about unused parameters. */ + cmap = 0; + + for (i = 0; i < jas_image_numcmpts(image); ++i) { + data[i] = jas_matrix_create(1, jas_image_width(image)); + assert(data[i]); + } + + pad = RAS_ROWSIZE(hdr) - (hdr->width * hdr->depth + 7) / 8; + + for (y = 0; y < hdr->height; y++) { + nz = 0; + z = 0; + for (x = 0; x < hdr->width; x++) { + while (nz < hdr->depth) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + z = (z << 8) | c; + nz += 8; + } + + v = (z >> (nz - hdr->depth)) & RAS_ONES(hdr->depth); + z &= RAS_ONES(nz - hdr->depth); + nz -= hdr->depth; + + if (jas_image_numcmpts(image) == 3) { + jas_matrix_setv(data[0], x, (RAS_GETRED(v))); + jas_matrix_setv(data[1], x, (RAS_GETGREEN(v))); + jas_matrix_setv(data[2], x, (RAS_GETBLUE(v))); + } else { + jas_matrix_setv(data[0], x, (v)); + } + } + if (pad) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + } + for (i = 0; i < jas_image_numcmpts(image); ++i) { + if (jas_image_writecmpt(image, i, 0, y, hdr->width, 1, + data[i])) { + return -1; + } + } + } + + for (i = 0; i < jas_image_numcmpts(image); ++i) { + jas_matrix_destroy(data[i]); + } + + return 0; +} + +static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap) +{ + int i; + int j; + int x; + int c; + int numcolors; + int actualnumcolors; + + switch (hdr->maptype) { + case RAS_MT_NONE: + break; + case RAS_MT_EQUALRGB: + { +fprintf(stderr, "warning: palettized images not fully supported\n"); + numcolors = 1 << hdr->depth; + assert(numcolors <= RAS_CMAP_MAXSIZ); + actualnumcolors = hdr->maplength / 3; + for (i = 0; i < numcolors; i++) { + cmap->data[i] = 0; + } + if ((hdr->maplength % 3) || hdr->maplength < 0 || + hdr->maplength > 3 * numcolors) { + return -1; + } + for (i = 0; i < 3; i++) { + for (j = 0; j < actualnumcolors; j++) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + x = 0; + switch (i) { + case 0: + x = RAS_RED(c); + break; + case 1: + x = RAS_GREEN(c); + break; + case 2: + x = RAS_BLUE(c); + break; + } + cmap->data[j] |= x; + } + } + } + break; + default: + return -1; + break; + } + + return 0; +} + +static int ras_gethdr(jas_stream_t *in, ras_hdr_t *hdr) +{ + if (ras_getint(in, &hdr->magic) || ras_getint(in, &hdr->width) || + ras_getint(in, &hdr->height) || ras_getint(in, &hdr->depth) || + ras_getint(in, &hdr->length) || ras_getint(in, &hdr->type) || + ras_getint(in, &hdr->maptype) || ras_getint(in, &hdr->maplength)) { + return -1; + } + + if (hdr->magic != RAS_MAGIC) { + return -1; + } + + return 0; +} + +static int ras_getint(jas_stream_t *in, int_fast32_t *val) +{ + int x; + int c; + int i; + + x = 0; + for (i = 0; i < 4; i++) { + if ((c = jas_stream_getc(in)) == EOF) { + return -1; + } + x = (x << 8) | (c & 0xff); + } + + *val = x; + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/ras/ras_enc.c b/SlnkDWFImpl/CxImage/jasper/ras/ras_enc.c new file mode 100644 index 0000000..d2401ea --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/ras/ras_enc.c @@ -0,0 +1,367 @@ +/* + * Copyright (c) 1999-2000 Image Power, Inc. and the University of + * British Columbia. + * Copyright (c) 2001-2003 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +/* + * Sun Rasterfile Library + * + * $Id$ + */ + +/******************************************************************************\ +* Includes. +\******************************************************************************/ + +#include +#include + +#include "jasper/jas_image.h" +#include "jasper/jas_stream.h" +#include "jasper/jas_debug.h" + +#include "ras_cod.h" +#include "ras_enc.h" + +/******************************************************************************\ +* Prototypes. +\******************************************************************************/ + +static int ras_puthdr(jas_stream_t *out, ras_hdr_t *hdr); +static int ras_putint(jas_stream_t *out, int val); + +static int ras_putdata(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts); +static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts); + +/******************************************************************************\ +* Code. +\******************************************************************************/ + +int ras_encode(jas_image_t *image, jas_stream_t *out, char *optstr) +{ + int_fast32_t width; + int_fast32_t height; + int_fast32_t depth; + int cmptno; +#if 0 + uint_fast16_t numcmpts; +#endif + int i; + ras_hdr_t hdr; + int rowsize; + ras_enc_t encbuf; + ras_enc_t *enc = &encbuf; + + if (optstr) { + fprintf(stderr, "warning: ignoring RAS encoder options\n"); + } + + switch (jas_clrspc_fam(jas_image_clrspc(image))) { + case JAS_CLRSPC_FAM_RGB: + if (jas_image_clrspc(image) != JAS_CLRSPC_SRGB) + jas_eprintf("warning: inaccurate color\n"); + enc->numcmpts = 3; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 || + (enc->cmpts[1] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 || + (enc->cmpts[2] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) { + jas_eprintf("error: missing color component\n"); + return -1; + } + break; + case JAS_CLRSPC_FAM_GRAY: + if (jas_image_clrspc(image) != JAS_CLRSPC_SGRAY) + jas_eprintf("warning: inaccurate color\n"); + enc->numcmpts = 1; + if ((enc->cmpts[0] = jas_image_getcmptbytype(image, + JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) { + jas_eprintf("error: missing color component\n"); + return -1; + } + break; + default: + jas_eprintf("error: unsupported color space\n"); + return -1; + break; + } + + width = jas_image_cmptwidth(image, enc->cmpts[0]); + height = jas_image_cmptheight(image, enc->cmpts[0]); + depth = jas_image_cmptprec(image, enc->cmpts[0]); + + for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) { + if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width || + jas_image_cmptheight(image, enc->cmpts[cmptno]) != height || + jas_image_cmptprec(image, enc->cmpts[cmptno]) != depth || + jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != false || + jas_image_cmpttlx(image, enc->cmpts[cmptno]) != 0 || + jas_image_cmpttly(image, enc->cmpts[cmptno]) != 0) { + fprintf(stderr, "The RAS format cannot be used to represent an image with this geometry.\n"); + return -1; + } + } + + /* Ensure that the image can be encoded in the desired format. */ + if (enc->numcmpts == 3) { + + /* All three components must have the same subsampling + factor and have a precision of eight bits. */ + if (enc->numcmpts > 1) { + for (i = 0; i < enc->numcmpts; ++i) { + if (jas_image_cmptprec(image, enc->cmpts[i]) != 8) { + return -1; + } + } + } + } else if (enc->numcmpts == 1) { + /* NOP */ + } else { + return -1; + } + + hdr.magic = RAS_MAGIC; + hdr.width = width; + hdr.height = height; + hdr.depth = (enc->numcmpts == 3) ? 24 : depth; + + rowsize = RAS_ROWSIZE(&hdr); + hdr.length = rowsize * hdr.height; + hdr.type = RAS_TYPE_STD; + + hdr.maptype = RAS_MT_NONE; + hdr.maplength = 0; + + if (ras_puthdr(out, &hdr)) { + return -1; + } + + if (ras_putdata(out, &hdr, image, enc->numcmpts, enc->cmpts)) { + return -1; + } + + return 0; +} + +static int ras_putdata(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) +{ + int ret; + + switch (hdr->type) { + case RAS_TYPE_STD: + ret = ras_putdatastd(out, hdr, image, numcmpts, cmpts); + break; + default: + ret = -1; + break; + } + return ret; +} + +static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) +{ + int rowsize; + int pad; + unsigned int z; + int nz; + int c; + int x; + int y; + int v; + jas_matrix_t *data[3]; + int i; + + for (i = 0; i < numcmpts; ++i) { + data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image)); + assert(data[i]); + } + + rowsize = RAS_ROWSIZE(hdr); + pad = rowsize - (hdr->width * hdr->depth + 7) / 8; + + hdr->length = hdr->height * rowsize; + + for (y = 0; y < hdr->height; y++) { + for (i = 0; i < numcmpts; ++i) { + jas_image_readcmpt(image, cmpts[i], 0, y, jas_image_width(image), + 1, data[i]); + } + z = 0; + nz = 0; + for (x = 0; x < hdr->width; x++) { + z <<= hdr->depth; + if (RAS_ISRGB(hdr)) { + v = RAS_RED((jas_matrix_getv(data[0], x))) | + RAS_GREEN((jas_matrix_getv(data[1], x))) | + RAS_BLUE((jas_matrix_getv(data[2], x))); + } else { + v = (jas_matrix_getv(data[0], x)); + } + z |= v & RAS_ONES(hdr->depth); + nz += hdr->depth; + while (nz >= 8) { + c = (z >> (nz - 8)) & 0xff; + if (jas_stream_putc(out, c) == EOF) { + return -1; + } + nz -= 8; + z &= RAS_ONES(nz); + } + } + if (nz > 0) { + c = (z >> (8 - nz)) & RAS_ONES(nz); + if (jas_stream_putc(out, c) == EOF) { + return -1; + } + } + if (pad % 2) { + if (jas_stream_putc(out, 0) == EOF) { + return -1; + } + } + } + + for (i = 0; i < numcmpts; ++i) { + jas_matrix_destroy(data[i]); + } + + return 0; +} + +static int ras_puthdr(jas_stream_t *out, ras_hdr_t *hdr) +{ + if (ras_putint(out, RAS_MAGIC) || ras_putint(out, hdr->width) || + ras_putint(out, hdr->height) || ras_putint(out, hdr->depth) || + ras_putint(out, hdr->length) || ras_putint(out, hdr->type) || + ras_putint(out, hdr->maptype) || ras_putint(out, hdr->maplength)) { + return -1; + } + + return 0; +} + +static int ras_putint(jas_stream_t *out, int val) +{ + int x; + int i; + int c; + + x = val; + for (i = 0; i < 4; i++) { + c = (x >> 24) & 0xff; + if (jas_stream_putc(out, c) == EOF) { + return -1; + } + x <<= 8; + } + + return 0; +} diff --git a/SlnkDWFImpl/CxImage/jasper/ras/ras_enc.h b/SlnkDWFImpl/CxImage/jasper/ras/ras_enc.h new file mode 100644 index 0000000..e9a2272 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jasper/ras/ras_enc.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2002 Michael David Adams. + * All rights reserved. + */ + +/* __START_OF_JASPER_LICENSE__ + * + * JasPer Software License + * + * IMAGE POWER JPEG-2000 PUBLIC LICENSE + * ************************************ + * + * GRANT: + * + * Permission is hereby granted, free of charge, to any person (the "User") + * obtaining a copy of this software and associated documentation, to deal + * in the JasPer Software without restriction, including without limitation + * the right to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the JasPer Software (in source and binary forms), + * and to permit persons to whom the JasPer Software is furnished to do so, + * provided further that the License Conditions below are met. + * + * License Conditions + * ****************** + * + * A. Redistributions of source code must retain the above copyright notice, + * and this list of conditions, and the following disclaimer. + * + * B. Redistributions in binary form must reproduce the above copyright + * notice, and this list of conditions, and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * C. Neither the name of Image Power, Inc. nor any other contributor + * (including, but not limited to, the University of British Columbia and + * Michael David Adams) may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * D. User agrees that it shall not commence any action against Image Power, + * Inc., the University of British Columbia, Michael David Adams, or any + * other contributors (collectively "Licensors") for infringement of any + * intellectual property rights ("IPR") held by the User in respect of any + * technology that User owns or has a right to license or sublicense and + * which is an element required in order to claim compliance with ISO/IEC + * 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property + * rights worldwide arising under statutory or common law, and whether + * or not perfected, including, without limitation, all (i) patents and + * patent applications owned or licensable by User; (ii) rights associated + * with works of authorship including copyrights, copyright applications, + * copyright registrations, mask work rights, mask work applications, + * mask work registrations; (iii) rights relating to the protection of + * trade secrets and confidential information; (iv) any right analogous + * to those set forth in subsections (i), (ii), or (iii) and any other + * proprietary rights relating to intangible property (other than trademark, + * trade dress, or service mark rights); and (v) divisions, continuations, + * renewals, reissues and extensions of the foregoing (as and to the extent + * applicable) now existing, hereafter filed, issued or acquired. + * + * E. If User commences an infringement action against any Licensor(s) then + * such Licensor(s) shall have the right to terminate User's license and + * all sublicenses that have been granted hereunder by User to other parties. + * + * F. This software is for use only in hardware or software products that + * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license + * or right to this Software is granted for products that do not comply + * with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased + * from the ISO. + * + * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. + * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER + * THIS DISCLAIMER. THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND + * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY + * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, + * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, + * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING + * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE + * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING + * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. + * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE + * IS WITH THE USER. SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE + * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY + * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY + * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, + * REPAIR OR CORRECTION. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, + * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE + * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., + * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE + * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO + * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, + * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR + * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF + * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY + * OF SUCH DAMAGES. THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT + * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR + * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING + * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, + * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT + * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY + * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE + * ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS + * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT + * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING + * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS + * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE + * NOTICE SPECIFIED IN THIS SECTION. + * + * __END_OF_JASPER_LICENSE__ + */ + +#ifndef RAS_ENC_H +#define RAS_ENC_H + +typedef struct { + int numcmpts; + int cmpts[4]; +} ras_enc_t; + +#endif diff --git a/SlnkDWFImpl/CxImage/jbig/.gitignore b/SlnkDWFImpl/CxImage/jbig/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/SlnkDWFImpl/CxImage/jbig/Makefile b/SlnkDWFImpl/CxImage/jbig/Makefile new file mode 100644 index 0000000..c4108c9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/Makefile @@ -0,0 +1,30 @@ +# Unix makefile for the JBIG-KIT library +# $Id: Makefile,v 1.9 2004-06-08 15:40:06+01 mgk25 Exp $ + +# Select an ANSI/ISO C compiler here, GNU gcc is recommended +CC = gcc + +# Options for the compiler: A high optimization level is suggested +CFLAGS = -O -Wall -ansi -pedantic + +all: libjbig.a tstcodec + +tstcodec: tstcodec.c jbig.c jbig.h jbig_tab.o + $(CC) $(CFLAGS) -o tstcodec -DTEST_CODEC tstcodec.c jbig.c \ + jbig_tab.o + +libjbig.a: jbig.o jbig_tab.o + rm -f libjbig.a + ar rc libjbig.a jbig.o jbig_tab.o + -ranlib libjbig.a + +jbig.o: jbig.c jbig.h + +test: tstcodec + ./tstcodec + +t82test.pbm: tstcodec + ./tstcodec $@ + +clean: + rm -f *.o *~ core gmon.out dbg_d\=??.pbm tstcodec t82test.pbm diff --git a/SlnkDWFImpl/CxImage/jbig/copying.txt b/SlnkDWFImpl/CxImage/jbig/copying.txt new file mode 100644 index 0000000..9285110 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/copying.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 675 Mass Ave, Cambridge, MA 02139, 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 + + Appendix: 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., 675 Mass Ave, Cambridge, MA 02139, 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. diff --git a/SlnkDWFImpl/CxImage/jbig/jbig.c b/SlnkDWFImpl/CxImage/jbig/jbig.c new file mode 100644 index 0000000..1e1539e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/jbig.c @@ -0,0 +1,3195 @@ +/* + * Portable Free JBIG image compression library + * + * Markus Kuhn -- http://www.cl.cam.ac.uk/~mgk25/ + * + * $Id: jbig.c,v 1.22 2004-06-11 15:17:06+01 mgk25 Exp $ + * + * This module implements a portable standard C encoder and decoder + * using the JBIG lossless bi-level image compression algorithm as + * specified in International Standard ISO 11544:1993 or equivalently + * as specified in ITU-T Recommendation T.82. See the file jbig.doc + * for usage instructions and application examples. + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * If you want to use this program under different license conditions, + * then contact the author for an arrangement. + * + * It is possible that certain products which can be built using this + * software module might form inventions protected by patent rights in + * some countries (e.g., by patents about arithmetic coding algorithms + * owned by IBM and AT&T in the USA). Provision of this software by the + * author does NOT include any licences for any patents. In those + * countries where a patent licence is required for certain applications + * of this software module, you will have to obtain such a licence + * yourself. + */ + +#ifdef DEBUG +#include +#else +#ifndef NDEBUG +#define NDEBUG +#endif +#endif + +#include +#include +#include + +#include "jbig.h" + + +/* optional export of arithmetic coder functions for test purposes */ +#ifdef TEST_CODEC +#define ARITH +#define ARITH_INL +#else +#define ARITH static +#ifdef __GNUC__ +#define ARITH_INL static __inline__ +#else +#define ARITH_INL static +#endif +#endif + +#define MX_MAX 127 /* maximal supported mx offset for + * adaptive template in the encoder */ + +#define TPB2CX 0x195 /* contexts for TP special pixels */ +#define TPB3CX 0x0e5 +#define TPDCX 0xc3f + +/* marker codes */ +#define MARKER_STUFF 0x00 +#define MARKER_RESERVE 0x01 +#define MARKER_SDNORM 0x02 +#define MARKER_SDRST 0x03 +#define MARKER_ABORT 0x04 +#define MARKER_NEWLEN 0x05 +#define MARKER_ATMOVE 0x06 +#define MARKER_COMMENT 0x07 +#define MARKER_ESC 0xff + +/* loop array indices */ +#define STRIPE 0 +#define LAYER 1 +#define PLANE 2 + +/* special jbg_buf pointers (instead of NULL) */ +#define SDE_DONE ((struct jbg_buf *) -1) +#define SDE_TODO ((struct jbg_buf *) 0) + +/* object code version id */ + +const char jbg_version[] = +" JBIG-KIT " JBG_VERSION " -- Markus Kuhn -- " +"$Id: jbig.c,v 1.22 2004-06-11 15:17:06+01 mgk25 Exp $ "; + +/* + * the following array specifies for each combination of the 3 + * ordering bits, which ii[] variable represents which dimension + * of s->sde. + */ +static const int iindex[8][3] = { + { 2, 1, 0 }, /* no ordering bit set */ + { -1, -1, -1}, /* SMID -> illegal combination */ + { 2, 0, 1 }, /* ILEAVE */ + { 1, 0, 2 }, /* SMID + ILEAVE */ + { 0, 2, 1 }, /* SEQ */ + { 1, 2, 0 }, /* SEQ + SMID */ + { 0, 1, 2 }, /* SEQ + ILEAVE */ + { -1, -1, -1 } /* SEQ + SMID + ILEAVE -> illegal combination */ +}; + + +/* + * Array [language][message] with text string error messages that correspond + * to return values from public functions in this library. + */ +#define NEMSG 9 /* number of error codes */ +#define NEMSG_LANG 3 /* number of supported languages */ +static const char *errmsg[NEMSG_LANG][NEMSG] = { + /* English (JBG_EN) */ + { + "Everything is ok", /* JBG_EOK */ + "Reached specified maximum size", /* JBG_EOK_INTR */ + "Unexpected end of data", /* JBG_EAGAIN */ + "Not enough memory available", /* JBG_ENOMEM */ + "ABORT marker found", /* JBG_EABORT */ + "Unknown marker segment encountered", /* JBG_EMARKER */ + "Incremental BIE does not fit to previous one", /* JBG_ENOCONT */ + "Invalid data encountered", /* JBG_EINVAL */ + "Unimplemented features used" /* JBG_EIMPL */ + }, + /* German (JBG_DE_8859_1) */ + { + "Kein Problem aufgetreten", /* JBG_EOK */ + "Angegebene maximale Bildgr\366\337e erreicht", /* JBG_EOK_INTR */ + "Unerwartetes Ende der Daten", /* JBG_EAGAIN */ + "Nicht gen\374gend Speicher vorhanden", /* JBG_ENOMEM */ + "Es wurde eine Abbruch-Sequenz gefunden", /* JBG_EABORT */ + "Eine unbekannte Markierungssequenz wurde gefunden", /* JBG_EMARKER */ + "Neue Daten passen nicht zu vorangegangenen Daten", /* JBG_ENOCONT */ + "Es wurden ung\374ltige Daten gefunden", /* JBG_EINVAL */ + "Noch nicht implementierte Optionen wurden benutzt" /* JBG_EIMPL */ + }, + /* German (JBG_DE_UTF_8) */ + { + "Kein Problem aufgetreten", /* JBG_EOK */ + "Angegebene maximale Bildgr\303\266\303\237e erreicht", /* JBG_EOK_INTR */ + "Unerwartetes Ende der Daten", /* JBG_EAGAIN */ + "Nicht gen\303\274gend Speicher vorhanden", /* JBG_ENOMEM */ + "Es wurde eine Abbruch-Sequenz gefunden", /* JBG_EABORT */ + "Eine unbekannte Markierungssequenz wurde gefunden", /* JBG_EMARKER */ + "Neue Daten passen nicht zu vorangegangenen Daten", /* JBG_ENOCONT */ + "Es wurden ung\303\274ltige Daten gefunden", /* JBG_EINVAL */ + "Noch nicht implementierte Optionen wurden benutzt" /* JBG_EIMPL */ + } +}; + + + +/* + * The following three functions are the only places in this code, were + * C library memory management functions are called. The whole JBIG + * library has been designed in order to allow multi-threaded + * execution. No static or global variables are used, so all fuctions + * are fully reentrant. However if you want to use this multi-thread + * capability and your malloc, realloc and free are not reentrant, + * then simply add the necessary semaphores or mutex primitives below. + * In contrast to C's malloc() and realloc(), but like C's calloc(), + * these functions take two parameters nmemb and size that are multiplied + * before being passed on to the corresponding C function. + * This we can catch all overflows during a size_t multiplication a + * a single place. + */ + +#ifndef SIZE_MAX +#define SIZE_MAX ((size_t) -1) /* largest value of size_t */ +#endif + +static void *checked_malloc(size_t nmemb, size_t size) +{ + void *p; + + /* Full manual exception handling is ugly here for performance + * reasons. If an adequate handling of lack of memory is required, + * then use C++ and throw a C++ exception instead of abort(). */ + + /* assert that nmemb * size <= SIZE_MAX */ + if (size > SIZE_MAX / nmemb) + abort(); + + p = malloc(nmemb * size); + + if (!p) + abort(); + +#if 0 + fprintf(stderr, "%p = malloc(%lu * %lu)\n", p, + (unsigned long) nmemb, (unsigned long) size); +#endif + + return p; +} + + +static void *checked_realloc(void *ptr, size_t nmemb, size_t size) +{ + void *p; + + /* Full manual exception handling is ugly here for performance + * reasons. If an adequate handling of lack of memory is required, + * then use C++ and throw a C++ exception here instead of abort(). */ + + /* assert that nmemb * size <= SIZE_MAX */ + if (size > SIZE_MAX / nmemb) + abort(); + + p = realloc(ptr, nmemb * size); + + if (!p) + abort(); + +#if 0 + fprintf(stderr, "%p = realloc(%p, %lu * %lu)\n", p, ptr, + (unsigned long) nmemb, (unsigned long) size); +#endif + + return p; +} + + +static void checked_free(void *ptr) +{ + free(ptr); + +#if 0 + fprintf(stderr, "free(%p)\n", ptr); +#endif + +} + + + +/* + * The next functions implement the arithmedic encoder and decoder + * required for JBIG. The same algorithm is also used in the arithmetic + * variant of JPEG. + */ + +#ifdef DEBUG +static long encoded_pixels = 0; +#endif + +ARITH void arith_encode_init(struct jbg_arenc_state *s, int reuse_st) +{ + int i; + + if (!reuse_st) + for (i = 0; i < 4096; s->st[i++] = 0); + s->c = 0; + s->a = 0x10000L; + s->sc = 0; + s->ct = 11; + s->buffer = -1; /* empty */ + + return; +} + + +ARITH void arith_encode_flush(struct jbg_arenc_state *s) +{ + unsigned long temp; + +#ifdef DEBUG + fprintf(stderr, " encoded pixels = %ld, a = %05lx, c = %08lx\n", + encoded_pixels, s->a, s->c); +#endif + + /* find the s->c in the coding interval with the largest + * number of trailing zero bits */ + if ((temp = (s->a - 1 + s->c) & 0xffff0000L) < s->c) + s->c = temp + 0x8000; + else + s->c = temp; + /* send remaining bytes to output */ + s->c <<= s->ct; + if (s->c & 0xf8000000L) { + /* one final overflow has to be handled */ + if (s->buffer >= 0) { + s->byte_out(s->buffer + 1, s->file); + if (s->buffer + 1 == MARKER_ESC) + s->byte_out(MARKER_STUFF, s->file); + } + /* output 0x00 bytes only when more non-0x00 will follow */ + if (s->c & 0x7fff800L) + for (; s->sc; --s->sc) + s->byte_out(0x00, s->file); + } else { + if (s->buffer >= 0) + s->byte_out(s->buffer, s->file); + /* T.82 figure 30 says buffer+1 for the above line! Typo? */ + for (; s->sc; --s->sc) { + s->byte_out(0xff, s->file); + s->byte_out(MARKER_STUFF, s->file); + } + } + /* output final bytes only if they are not 0x00 */ + if (s->c & 0x7fff800L) { + s->byte_out((s->c >> 19) & 0xff, s->file); + if (((s->c >> 19) & 0xff) == MARKER_ESC) + s->byte_out(MARKER_STUFF, s->file); + if (s->c & 0x7f800L) { + s->byte_out((s->c >> 11) & 0xff, s->file); + if (((s->c >> 11) & 0xff) == MARKER_ESC) + s->byte_out(MARKER_STUFF, s->file); + } + } + + return; +} + + +ARITH_INL void arith_encode(struct jbg_arenc_state *s, int cx, int pix) +{ + extern short jbg_lsz[]; + extern unsigned char jbg_nmps[], jbg_nlps[]; + register unsigned lsz, ss; + register unsigned char *st; + long temp; + +#ifdef DEBUG + ++encoded_pixels; +#endif + + assert(cx >= 0 && cx < 4096); + st = s->st + cx; + ss = *st & 0x7f; + assert(ss < 113); + lsz = jbg_lsz[ss]; + +#if 0 + fprintf(stderr, "pix = %d, cx = %d, mps = %d, st = %3d, lsz = 0x%04x, " + "a = 0x%05lx, c = 0x%08lx, ct = %2d, buf = 0x%02x\n", + pix, cx, !!(s->st[cx] & 0x80), ss, lsz, s->a, s->c, s->ct, + s->buffer); +#endif + + if (((pix << 7) ^ s->st[cx]) & 0x80) { + /* encode the less probable symbol */ + if ((s->a -= lsz) >= lsz) { + /* If the interval size (lsz) for the less probable symbol (LPS) + * is larger than the interval size for the MPS, then exchange + * the two symbols for coding efficiency, otherwise code the LPS + * as usual: */ + s->c += s->a; + s->a = lsz; + } + /* Check whether MPS/LPS exchange is necessary + * and chose next probability estimator status */ + *st &= 0x80; + *st ^= jbg_nlps[ss]; + } else { + /* encode the more probable symbol */ + if ((s->a -= lsz) & 0xffff8000L) + return; /* A >= 0x8000 -> ready, no renormalization required */ + if (s->a < lsz) { + /* If the interval size (lsz) for the less probable symbol (LPS) + * is larger than the interval size for the MPS, then exchange + * the two symbols for coding efficiency: */ + s->c += s->a; + s->a = lsz; + } + /* chose next probability estimator status */ + *st &= 0x80; + *st |= jbg_nmps[ss]; + } + + /* renormalization of coding interval */ + do { + s->a <<= 1; + s->c <<= 1; + --s->ct; + if (s->ct == 0) { + /* another byte is ready for output */ + temp = s->c >> 19; + if (temp & 0xffffff00L) { + /* handle overflow over all buffered 0xff bytes */ + if (s->buffer >= 0) { + ++s->buffer; + s->byte_out(s->buffer, s->file); + if (s->buffer == MARKER_ESC) + s->byte_out(MARKER_STUFF, s->file); + } + for (; s->sc; --s->sc) + s->byte_out(0x00, s->file); + s->buffer = temp & 0xff; /* new output byte, might overflow later */ + assert(s->buffer != 0xff); + /* can s->buffer really never become 0xff here? */ + } else if (temp == 0xff) { + /* buffer 0xff byte (which might overflow later) */ + ++s->sc; + } else { + /* output all buffered 0xff bytes, they will not overflow any more */ + if (s->buffer >= 0) + s->byte_out(s->buffer, s->file); + for (; s->sc; --s->sc) { + s->byte_out(0xff, s->file); + s->byte_out(MARKER_STUFF, s->file); + } + s->buffer = temp; /* buffer new output byte (can still overflow) */ + } + s->c &= 0x7ffffL; + s->ct = 8; + } + } while (s->a < 0x8000); + + return; +} + + +ARITH void arith_decode_init(struct jbg_ardec_state *s, int reuse_st) +{ + int i; + + if (!reuse_st) + for (i = 0; i < 4096; s->st[i++] = 0); + s->c = 0; + s->a = 1; + s->ct = 0; + s->result = JBG_OK; + s->startup = 1; + return; +} + + +ARITH_INL int arith_decode(struct jbg_ardec_state *s, int cx) +{ + extern short jbg_lsz[]; + extern unsigned char jbg_nmps[], jbg_nlps[]; + register unsigned lsz, ss; + register unsigned char *st; + int pix; + + /* renormalization */ + while (s->a < 0x8000 || s->startup) { + if (s->ct < 1 && s->result != JBG_READY) { + /* first we have to move a new byte into s->c */ + if (s->pscd_ptr >= s->pscd_end) { + s->result = JBG_MORE; + return -1; + } + if (*s->pscd_ptr == 0xff) + if (s->pscd_ptr + 1 >= s->pscd_end) { + s->result = JBG_MARKER; + return -1; + } else { + if (*(s->pscd_ptr + 1) == MARKER_STUFF) { + s->c |= 0xffL << (8 - s->ct); + s->ct += 8; + s->pscd_ptr += 2; + s->result = JBG_OK; + } else + s->result = JBG_READY; + } + else { + s->c |= (long)*(s->pscd_ptr++) << (8 - s->ct); + s->ct += 8; + s->result = JBG_OK; + } + } + s->c <<= 1; + s->a <<= 1; + --s->ct; + if (s->a == 0x10000L) + s->startup = 0; + } + + st = s->st + cx; + ss = *st & 0x7f; + assert(ss < 113); + lsz = jbg_lsz[ss]; + +#if 0 + fprintf(stderr, "cx = %d, mps = %d, st = %3d, lsz = 0x%04x, a = 0x%05lx, " + "c = 0x%08lx, ct = %2d\n", + cx, !!(s->st[cx] & 0x80), ss, lsz, s->a, s->c, s->ct); +#endif + + if ((s->c >> 16) < (s->a -= lsz)) + if (s->a & 0xffff8000L) + return *st >> 7; + else { + /* MPS_EXCHANGE */ + if (s->a < lsz) { + pix = 1 - (*st >> 7); + /* Check whether MPS/LPS exchange is necessary + * and chose next probability estimator status */ + *st &= 0x80; + *st ^= jbg_nlps[ss]; + } else { + pix = *st >> 7; + *st &= 0x80; + *st |= jbg_nmps[ss]; + } + } + else { + /* LPS_EXCHANGE */ + if (s->a < lsz) { + s->c -= s->a << 16; + s->a = lsz; + pix = *st >> 7; + *st &= 0x80; + *st |= jbg_nmps[ss]; + } else { + s->c -= s->a << 16; + s->a = lsz; + pix = 1 - (*st >> 7); + /* Check whether MPS/LPS exchange is necessary + * and chose next probability estimator status */ + *st &= 0x80; + *st ^= jbg_nlps[ss]; + } + } + + return pix; +} + + + +/* + * Memory management for buffers which are used for temporarily + * storing SDEs by the encoder. + * + * The following functions manage a set of struct jbg_buf storage + * containers were each can keep JBG_BUFSIZE bytes. The jbg_buf + * containers can be linked to form linear double-chained lists for + * which a number of operations are provided. Blocks which are + * tempoarily not used any more are returned to a freelist which each + * encoder keeps. Only the destructor of the encoder actually returns + * the block via checked_free() to the stdlib memory management. + */ + + +/* + * Allocate a new buffer block and initialize it. Try to get it from + * the free_list, and if it is empty, call checked_malloc(). + */ +static struct jbg_buf *jbg_buf_init(struct jbg_buf **free_list) +{ + struct jbg_buf *new_block; + + /* Test whether a block from the free list is available */ + if (*free_list) { + new_block = *free_list; + *free_list = new_block->next; + } else { + /* request a new memory block */ + new_block = (struct jbg_buf *) checked_malloc(1, sizeof(struct jbg_buf)); + } + new_block->len = 0; + new_block->next = NULL; + new_block->previous = NULL; + new_block->last = new_block; + new_block->free_list = free_list; + + return new_block; +} + + +/* + * Return an entire free_list to the memory management of stdlib. + * This is only done by jbg_enc_free(). + */ +static void jbg_buf_free(struct jbg_buf **free_list) +{ + struct jbg_buf *tmp; + + while (*free_list) { + tmp = (*free_list)->next; + checked_free(*free_list); + *free_list = tmp; + } + + return; +} + + +/* + * Append a single byte to a single list that starts with the block + * *(struct jbg_buf *) head. The type of *head is void here in order to + * keep the interface of the arithmetic encoder gereric, which uses this + * function as a call-back function in order to deliver single bytes + * for a PSCD. + */ +static void jbg_buf_write(int b, void *head) +{ + struct jbg_buf *now; + + now = ((struct jbg_buf *) head)->last; + if (now->len < JBG_BUFSIZE - 1) { + now->d[now->len++] = b; + return; + } + now->next = jbg_buf_init(((struct jbg_buf *) head)->free_list); + now->next->previous = now; + now->next->d[now->next->len++] = b; + ((struct jbg_buf *) head)->last = now->next; + + return; +} + + +/* + * Remove any trailing zero bytes from the end of a linked jbg_buf list, + * however make sure that no zero byte is removed which directly + * follows a 0xff byte (i.e., keep MARKER_ESC MARKER_STUFF sequences + * intact). This function is used to remove any redundant final zero + * bytes from a PSCD. + */ +static void jbg_buf_remove_zeros(struct jbg_buf *head) +{ + struct jbg_buf *last; + + while (1) { + /* remove trailing 0x00 in last block of list until this block is empty */ + last = head->last; + while (last->len && last->d[last->len - 1] == 0) + last->len--; + /* if block became really empty, remove it in case it is not the + * only remaining block and then loop to next block */ + if (last->previous && !last->len) { + head->last->next = *head->free_list; + *head->free_list = head->last; + head->last = last->previous; + head->last->next = NULL; + } else + break; + } + + /* + * If the final non-zero byte is 0xff (MARKER_ESC), then we just have + * removed a MARKER_STUFF and we will append it again now in order + * to preserve PSCD status of byte stream. + */ + if (head->last->len && head->last->d[head->last->len - 1] == MARKER_ESC) + jbg_buf_write(MARKER_STUFF, head); + + return; +} + + +/* + * The jbg_buf list which starts with block *new_prefix is concatenated + * with the list which starts with block **start and *start will then point + * to the first block of the new list. + */ +static void jbg_buf_prefix(struct jbg_buf *new_prefix, struct jbg_buf **start) +{ + new_prefix->last->next = *start; + new_prefix->last->next->previous = new_prefix->last; + new_prefix->last = new_prefix->last->next->last; + *start = new_prefix; + + return; +} + + +/* + * Send the contents of a jbg_buf list that starts with block **head to + * the call back function data_out and return the blocks of the jbg_buf + * list to the freelist from which these jbg_buf blocks have been taken. + * After the call, *head == NULL. + */ +static void jbg_buf_output(struct jbg_buf **head, + void (*data_out)(unsigned char *start, + size_t len, void *file), + void *file) +{ + struct jbg_buf *tmp; + + while (*head) { + data_out((*head)->d, (*head)->len, file); + tmp = (*head)->next; + (*head)->next = *(*head)->free_list; + *(*head)->free_list = *head; + *head = tmp; + } + + return; +} + + +/* + * Calculate y = ceil(x/2) applied n times, which is equivalent to + * y = ceil(x/(2^n)). This function is used to + * determine the number of pixels per row or column after n resolution + * reductions. E.g. X[d-1] = jbg_ceil_half(X[d], 1) and X[0] = + * jbg_ceil_half(X[d], d) as defined in clause 6.2.3 of T.82. + */ +unsigned long jbg_ceil_half(unsigned long x, int n) +{ + unsigned long mask; + + assert(n >= 0 && n < 32); + mask = (1UL << n) - 1; /* the lowest n bits are 1 here */ + return (x >> n) + ((mask & x) != 0); +} + + +/* + * Set L0 (the number of lines in a stripe at lowest resolution) + * to a default value, such that there are about 35 stripes, as + * suggested in Annex C of ITU-T T.82, without exceeding the + * limit 128/2^D suggested in Annex A. + */ +static void jbg_set_default_l0(struct jbg_enc_state *s) +{ + s->l0 = jbg_ceil_half(s->yd, s->d) / 35; /* 35 stripes/image */ + while ((s->l0 << s->d) > 128) /* but <= 128 lines/stripe */ + --s->l0; + if (s->l0 < 2) s->l0 = 2; +} + + +/* + * Calculate the number of stripes, as defined in clause 6.2.3 of T.82. + */ +static unsigned long jbg_stripes(unsigned long l0, unsigned long yd, + unsigned long d) +{ + unsigned long y0 = jbg_ceil_half(yd, d); + + return y0 / l0 + (y0 % l0 != 0); +} + + +/* + * Initialize the status struct for the encoder. + */ +void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y, + int planes, unsigned char **p, + void (*data_out)(unsigned char *start, size_t len, + void *file), + void *file) +{ + unsigned long l, lx; + int i; + + extern char jbg_resred[], jbg_dptable[]; + + s->xd = x; + s->yd = y; + s->yd1 = y; /* This is the hight initially announced in BIH. To provoke + generation of NEWLEN for T.85 compatibility tests, + overwrite with new value s->yd1 > s->yd */ + s->planes = planes; + s->data_out = data_out; + s->file = file; + + s->d = 0; + s->dl = 0; + s->dh = s->d; + jbg_set_default_l0(s); + s->mx = 8; + s->my = 0; + s->order = JBG_ILEAVE | JBG_SMID; + s->options = JBG_TPBON | JBG_TPDON | JBG_DPON; + s->dppriv = jbg_dptable; + s->res_tab = jbg_resred; + + s->highres = (int *) checked_malloc(planes, sizeof(int)); + s->lhp[0] = p; + s->lhp[1] = (unsigned char **) + checked_malloc(planes, sizeof(unsigned char *)); + for (i = 0; i < planes; i++) { + s->highres[i] = 0; + s->lhp[1][i] = (unsigned char *) + checked_malloc(jbg_ceil_half(y, 1), jbg_ceil_half(x, 1+3)); + } + + s->free_list = NULL; + s->s = (struct jbg_arenc_state *) + checked_malloc(s->planes, sizeof(struct jbg_arenc_state)); + s->tx = (int *) checked_malloc(s->planes, sizeof(int)); + lx = jbg_ceil_half(x, 1); + s->tp = (char *) checked_malloc(lx, sizeof(char)); + for (l = 0; l < lx; s->tp[l++] = 2); + s->sde = NULL; + + return; +} + + +/* + * This function selects the number of differential layers based on + * the maximum size requested for the lowest resolution layer. If + * possible, a number of differential layers is selected, which will + * keep the size of the lowest resolution layer below or equal to the + * given width x and height y. However not more than 6 differential + * resolution layers will be used. In addition, a reasonable value for + * l0 (height of one stripe in the lowest resolution layer) is + * selected, which obeys the recommended limitations for l0 in annex A + * and C of the JBIG standard. The selected number of resolution layers + * is returned. + */ +int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long x, + unsigned long y) +{ + for (s->d = 0; s->d < 6; s->d++) + if (jbg_ceil_half(s->xd, s->d) <= x && jbg_ceil_half(s->yd, s->d) <= y) + break; + s->dl = 0; + s->dh = s->d; + jbg_set_default_l0(s); + return s->d; +} + + +/* + * As an alternative to jbg_enc_lrlmax(), the following function allows + * to specify the number of layers directly. The stripe height and layer + * range is also adjusted automatically here. + */ +void jbg_enc_layers(struct jbg_enc_state *s, int d) +{ + if (d < 0 || d > 31) + return; + s->d = d; + s->dl = 0; + s->dh = s->d; + jbg_set_default_l0(s); + return; +} + + +/* + * Specify the highest and lowest resolution layers which will be + * written to the output file. Call this function not before + * jbg_enc_layers() or jbg_enc_lrlmax(), because these two functions + * reset the lowest and highest resolution layer to default values. + * Negative values are ignored. The total number of layers is returned. + */ +int jbg_enc_lrange(struct jbg_enc_state *s, int dl, int dh) +{ + if (dl >= 0 && dl <= s->d) s->dl = dl; + if (dh >= s->dl && dh <= s->d) s->dh = dh; + + return s->d; +} + + +/* + * The following function allows to specify the bits describing the + * options of the format as well as the maximum AT movement window and + * the number of layer 0 lines per stripes. + */ +void jbg_enc_options(struct jbg_enc_state *s, int order, int options, + unsigned long l0, int mx, int my) +{ + if (order >= 0 && order <= 0x0f) s->order = order; + if (options >= 0) s->options = options; + if (l0 > 0) s->l0 = l0; + if (mx >= 0 && my < 128) s->mx = mx; + if (my >= 0 && my < 256) s->my = my; + + return; +} + + +/* + * This function actually does all the tricky work involved in producing + * a SDE, which is stored in the appropriate s->sde[][][] element + * for later output in the correct order. + */ +static void encode_sde(struct jbg_enc_state *s, + long stripe, int layer, int plane) +{ + unsigned char *hp, *lp1, *lp2, *p0, *p1, *q1, *q2; + unsigned long hl, ll, hx, hy, lx, ly, hbpl, lbpl; + unsigned long line_h0 = 0, line_h1 = 0; + unsigned long line_h2, line_h3, line_l1, line_l2, line_l3; + struct jbg_arenc_state *se; + unsigned long i, j, y; + long o; + unsigned a, p, t; + int ltp, ltp_old, cx; + unsigned long c_all, c[MX_MAX + 1], cmin, cmax, clmin, clmax; + int tmax, at_determined; + int new_tx; + long new_tx_line = -1; + struct jbg_buf *new_jbg_buf; + +#ifdef DEBUG + static long tp_lines, tp_exceptions, tp_pixels, dp_pixels; + static long encoded_pixels; +#endif + + /* return immediately if this stripe has already been encoded */ + if (s->sde[stripe][layer][plane] != SDE_TODO) + return; + +#ifdef DEBUG + if (stripe == 0) + tp_lines = tp_exceptions = tp_pixels = dp_pixels = encoded_pixels = 0; + fprintf(stderr, "encode_sde: s/d/p = %2ld/%2d/%2d\n", + stripe, layer, plane); +#endif + + /* number of lines per stripe in highres image */ + hl = s->l0 << layer; + /* number of lines per stripe in lowres image */ + ll = hl >> 1; + /* current line number in highres image */ + y = stripe * hl; + /* number of pixels in highres image */ + hx = jbg_ceil_half(s->xd, s->d - layer); + hy = jbg_ceil_half(s->yd, s->d - layer); + /* number of pixels in lowres image */ + lx = jbg_ceil_half(hx, 1); + ly = jbg_ceil_half(hy, 1); + /* bytes per line in highres and lowres image */ + hbpl = jbg_ceil_half(hx, 3); + lbpl = jbg_ceil_half(lx, 3); + /* pointer to first image byte of highres stripe */ + hp = s->lhp[s->highres[plane]][plane] + stripe * hl * hbpl; + lp2 = s->lhp[1 - s->highres[plane]][plane] + stripe * ll * lbpl; + lp1 = lp2 + lbpl; + + /* initialize arithmetic encoder */ + se = s->s + plane; + arith_encode_init(se, stripe != 0); + s->sde[stripe][layer][plane] = jbg_buf_init(&s->free_list); + se->byte_out = jbg_buf_write; + se->file = s->sde[stripe][layer][plane]; + + /* initialize adaptive template movement algorithm */ + c_all = 0; + for (t = 0; t <= s->mx; t++) + c[t] = 0; + if (stripe == 0) + s->tx[plane] = 0; + new_tx = -1; + at_determined = 0; /* we haven't yet decided the template move */ + if (s->mx == 0) + at_determined = 1; + + /* initialize typical prediction */ + ltp = 0; + if (stripe == 0) + ltp_old = 0; + else { + ltp_old = 1; + p1 = hp - hbpl; + if (y > 1) { + q1 = p1 - hbpl; + while (p1 < hp && (ltp_old = (*p1++ == *q1++)) != 0); + } else + while (p1 < hp && (ltp_old = (*p1++ == 0)) != 0); + } + + if (layer == 0) { + + /* + * Encode lowest resolution layer + */ + + for (i = 0; i < hl && y < hy; i++, y++) { + + /* check whether it is worth to perform an ATMOVE */ + if (!at_determined && c_all > 2048) { + cmin = clmin = 0xffffffffL; + cmax = clmax = 0; + tmax = 0; + for (t = (s->options & JBG_LRLTWO) ? 5 : 3; t <= s->mx; t++) { + if (c[t] > cmax) cmax = c[t]; + if (c[t] < cmin) cmin = c[t]; + if (c[t] > c[tmax]) tmax = t; + } + clmin = (c[0] < cmin) ? c[0] : cmin; + clmax = (c[0] > cmax) ? c[0] : cmax; + if (c_all - cmax < (c_all >> 3) && + cmax - c[s->tx[plane]] > c_all - cmax && + cmax - c[s->tx[plane]] > (c_all >> 4) && + /* ^ T.82 said < here, fixed in Cor.1/25 */ + cmax - (c_all - c[s->tx[plane]]) > c_all - cmax && + cmax - (c_all - c[s->tx[plane]]) > (c_all >> 4) && + cmax - cmin > (c_all >> 2) && + (s->tx[plane] || clmax - clmin > (c_all >> 3))) { + /* we have decided to perform an ATMOVE */ + new_tx = tmax; + if (!(s->options & JBG_DELAY_AT)) { + new_tx_line = i; + s->tx[plane] = new_tx; + } +#ifdef DEBUG + fprintf(stderr, "ATMOVE: line=%ld, tx=%d, c_all=%ld\n", + i, new_tx, c_all); +#endif + } + at_determined = 1; + } + assert(s->tx[plane] >= 0); /* i.e., tx can safely be cast to unsigned */ + + /* typical prediction */ + if (s->options & JBG_TPBON) { + ltp = 1; + p1 = hp; + if (y > 0) { + q1 = hp - hbpl; + while (q1 < hp && (ltp = (*p1++ == *q1++)) != 0); + } else + while (p1 < hp + hbpl && (ltp = (*p1++ == 0)) != 0); + arith_encode(se, (s->options & JBG_LRLTWO) ? TPB2CX : TPB3CX, + ltp == ltp_old); +#ifdef DEBUG + tp_lines += ltp; +#endif + ltp_old = ltp; + if (ltp) { + /* skip next line */ + hp += hbpl; + continue; + } + } + + /* + * Layout of the variables line_h1, line_h2, line_h3, which contain + * as bits the neighbour pixels of the currently coded pixel X: + * + * 76543210765432107654321076543210 line_h3 + * 76543210765432107654321076543210 line_h2 + * 76543210765432107654321X76543210 line_h1 + */ + + line_h1 = line_h2 = line_h3 = 0; + if (y > 0) line_h2 = (long)*(hp - hbpl) << 8; + if (y > 1) line_h3 = (long)*(hp - hbpl - hbpl) << 8; + + /* encode line */ + for (j = 0; j < hx; hp++) { + line_h1 |= *hp; + if (j < hbpl * 8 - 8 && y > 0) { + line_h2 |= *(hp - hbpl + 1); + if (y > 1) + line_h3 |= *(hp - hbpl - hbpl + 1); + } + if (s->options & JBG_LRLTWO) { + /* two line template */ + do { + line_h1 <<= 1; line_h2 <<= 1; line_h3 <<= 1; + if (s->tx[plane]) { + if ((unsigned) s->tx[plane] > j) + a = 0; + else { + o = (j - s->tx[plane]) - (j & ~7L); + a = (hp[o >> 3] >> (7 - (o & 7))) & 1; + a <<= 4; + } + assert(s->tx[plane] > 23 || + a == ((line_h1 >> (4 + s->tx[plane])) & 0x010)); + arith_encode(se, (((line_h2 >> 10) & 0x3e0) | a | + ((line_h1 >> 9) & 0x00f)), + (line_h1 >> 8) & 1); + } + else + arith_encode(se, (((line_h2 >> 10) & 0x3f0) | + ((line_h1 >> 9) & 0x00f)), + (line_h1 >> 8) & 1); +#ifdef DEBUG + encoded_pixels++; +#endif + /* statistics for adaptive template changes */ + if (!at_determined && j >= s->mx && j < hx-2) { + p = (line_h1 & 0x100) != 0; /* current pixel value */ + c[0] += ((unsigned int)((line_h2 & 0x4000) != 0)) == p; /* default position */ + assert(!(((line_h2 >> 6) ^ line_h1) & 0x100) == + (((line_h2 & 0x4000) != 0) == p)); + for (t = 5; t <= s->mx && t <= j; t++) { + o = (j - t) - (j & ~7L); + a = (hp[o >> 3] >> (7 - (o & 7))) & 1; + assert(t > 23 || + (a == p) == !(((line_h1 >> t) ^ line_h1) & 0x100)); + c[t] += a == p; + } + for (; t <= s->mx; t++) { + c[t] += 0 == p; + } + ++c_all; + } + } while (++j & 7 && j < hx); + } else { + /* three line template */ + do { + line_h1 <<= 1; line_h2 <<= 1; line_h3 <<= 1; + if (s->tx[plane]) { + if ((unsigned) s->tx[plane] > j) + a = 0; + else { + o = (j - s->tx[plane]) - (j & ~7L); + a = (hp[o >> 3] >> (7 - (o & 7))) & 1; + a <<= 2; + } + assert(s->tx[plane] > 23 || + a == ((line_h1 >> (6 + s->tx[plane])) & 0x004)); + arith_encode(se, (((line_h3 >> 8) & 0x380) | + ((line_h2 >> 12) & 0x078) | a | + ((line_h1 >> 9) & 0x003)), + (line_h1 >> 8) & 1); + } else + arith_encode(se, (((line_h3 >> 8) & 0x380) | + ((line_h2 >> 12) & 0x07c) | + ((line_h1 >> 9) & 0x003)), + (line_h1 >> 8) & 1); +#ifdef DEBUG + encoded_pixels++; +#endif + /* statistics for adaptive template changes */ + if (!at_determined && j >= s->mx && j < hx-2) { + p = (line_h1 & 0x100) != 0; /* current pixel value */ + c[0] += ((unsigned int)((line_h2 & 0x4000) != 0)) == p; /* default position */ + assert(!(((line_h2 >> 6) ^ line_h1) & 0x100) == + (((line_h2 & 0x4000) != 0) == p)); + for (t = 3; t <= s->mx && t <= j; t++) { + o = (j - t) - (j & ~7L); + a = (hp[o >> 3] >> (7 - (o & 7))) & 1; + assert(t > 23 || + (a == p) == !(((line_h1 >> t) ^ line_h1) & 0x100)); + c[t] += a == p; + } + for (; t <= s->mx; t++) { + c[t] += 0 == p; + } + ++c_all; + } + } while (++j & 7 && j < hx); + } /* if (s->options & JBG_LRLTWO) */ + } /* for (j = ...) */ + } /* for (i = ...) */ + + } else { + + /* + * Encode differential layer + */ + + for (i = 0; i < hl && y < hy; i++, y++) { + + /* check whether it is worth to perform an ATMOVE */ + if (!at_determined && c_all > 2048) { + cmin = clmin = 0xffffffffL; + cmax = clmax = 0; + tmax = 0; + for (t = 3; t <= s->mx; t++) { + if (c[t] > cmax) cmax = c[t]; + if (c[t] < cmin) cmin = c[t]; + if (c[t] > c[tmax]) tmax = t; + } + clmin = (c[0] < cmin) ? c[0] : cmin; + clmax = (c[0] > cmax) ? c[0] : cmax; + if (c_all - cmax < (c_all >> 3) && + cmax - c[s->tx[plane]] > c_all - cmax && + cmax - c[s->tx[plane]] > (c_all >> 4) && + /* ^ T.82 said < here, fixed in Cor.1/25 */ + cmax - (c_all - c[s->tx[plane]]) > c_all - cmax && + cmax - (c_all - c[s->tx[plane]]) > (c_all >> 4) && + cmax - cmin > (c_all >> 2) && + (s->tx[plane] || clmax - clmin > (c_all >> 3))) { + /* we have decided to perform an ATMOVE */ + new_tx = tmax; + if (!(s->options & JBG_DELAY_AT)) { + new_tx_line = i; + s->tx[plane] = new_tx; + } +#ifdef DEBUG + fprintf(stderr, "ATMOVE: line=%ld, tx=%d, c_all=%ld\n", + i, new_tx, c_all); +#endif + } + at_determined = 1; + } + + if ((i >> 1) >= ll - 1 || (y >> 1) >= ly - 1) + lp1 = lp2; + + /* typical prediction */ + if (s->options & JBG_TPDON && (i & 1) == 0) { + q1 = lp1; q2 = lp2; + p0 = p1 = hp; + if (i < hl - 1 && y < hy - 1) + p0 = hp + hbpl; + if (y > 1) + line_l3 = (long)*(q2 - lbpl) << 8; + else + line_l3 = 0; + line_l2 = (long)*q2 << 8; + line_l1 = (long)*q1 << 8; + ltp = 1; + for (j = 0; j < lx && ltp; q1++, q2++) { + if (j < lbpl * 8 - 8) { + if (y > 1) + line_l3 |= *(q2 - lbpl + 1); + line_l2 |= *(q2 + 1); + line_l1 |= *(q1 + 1); + } + do { + if ((j >> 2) < hbpl) { + line_h1 = *(p1++); + line_h0 = *(p0++); + } + do { + line_l3 <<= 1; + line_l2 <<= 1; + line_l1 <<= 1; + line_h1 <<= 2; + line_h0 <<= 2; + cx = (((line_l3 >> 15) & 0x007) | + ((line_l2 >> 12) & 0x038) | + ((line_l1 >> 9) & 0x1c0)); + if (cx == 0x000) + if ((line_h1 & 0x300) == 0 && (line_h0 & 0x300) == 0) + s->tp[j] = 0; + else { + ltp = 0; +#ifdef DEBUG + tp_exceptions++; +#endif + } + else if (cx == 0x1ff) + if ((line_h1 & 0x300) == 0x300 && (line_h0 & 0x300) == 0x300) + s->tp[j] = 1; + else { + ltp = 0; +#ifdef DEBUG + tp_exceptions++; +#endif + } + else + s->tp[j] = 2; + } while (++j & 3 && j < lx); + } while (j & 7 && j < lx); + } /* for (j = ...) */ + arith_encode(se, TPDCX, !ltp); +#ifdef DEBUG + tp_lines += ltp; +#endif + } + + + /* + * Layout of the variables line_h1, line_h2, line_h3, which contain + * as bits the high resolution neighbour pixels of the currently coded + * highres pixel X: + * + * 76543210 76543210 76543210 76543210 line_h3 + * 76543210 76543210 76543210 76543210 line_h2 + * 76543210 76543210 7654321X 76543210 line_h1 + * + * Layout of the variables line_l1, line_l2, line_l3, which contain + * the low resolution pixels near the currently coded pixel as bits. + * The lowres pixel in which the currently coded highres pixel is + * located is marked as Y: + * + * 76543210 76543210 76543210 76543210 line_l3 + * 76543210 7654321Y 76543210 76543210 line_l2 + * 76543210 76543210 76543210 76543210 line_l1 + */ + + + line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0; + if (y > 0) line_h2 = (long)*(hp - hbpl) << 8; + if (y > 1) { + line_h3 = (long)*(hp - hbpl - hbpl) << 8; + line_l3 = (long)*(lp2 - lbpl) << 8; + } + line_l2 = (long)*lp2 << 8; + line_l1 = (long)*lp1 << 8; + + /* encode line */ + for (j = 0; j < hx; lp1++, lp2++) { + if ((j >> 1) < lbpl * 8 - 8) { + if (y > 1) + line_l3 |= *(lp2 - lbpl + 1); + line_l2 |= *(lp2 + 1); + line_l1 |= *(lp1 + 1); + } + do { /* ... while (j & 15 && j < hx) */ + + assert(hp - (s->lhp[s->highres[plane]][plane] + + (stripe * hl + i) * hbpl) + == (ptrdiff_t) j >> 3); + + assert(lp2 - (s->lhp[1-s->highres[plane]][plane] + + (stripe * ll + (i>>1)) * lbpl) + == (ptrdiff_t) j >> 4); + + line_h1 |= *hp; + if (j < hbpl * 8 - 8) { + if (y > 0) { + line_h2 |= *(hp - hbpl + 1); + if (y > 1) + line_h3 |= *(hp - hbpl - hbpl + 1); + } + } + do { /* ... while (j & 7 && j < hx) */ + line_l1 <<= 1; line_l2 <<= 1; line_l3 <<= 1; + if (ltp && s->tp[j >> 1] < 2) { + /* pixel are typical and have not to be encoded */ + line_h1 <<= 2; line_h2 <<= 2; line_h3 <<= 2; +#ifdef DEBUG + do { + ++tp_pixels; + } while (++j & 1 && j < hx); +#else + j += 2; +#endif + } else + do { /* ... while (++j & 1 && j < hx) */ + line_h1 <<= 1; line_h2 <<= 1; line_h3 <<= 1; + + /* deterministic prediction */ + if (s->options & JBG_DPON) { + if ((y & 1) == 0) { + if ((j & 1) == 0) { + /* phase 0 */ + if (s->dppriv[((line_l3 >> 16) & 0x003) | + ((line_l2 >> 14) & 0x00c) | + ((line_h1 >> 5) & 0x010) | + ((line_h2 >> 10) & 0x0e0)] < 2) { +#ifdef DEBUG + ++dp_pixels; +#endif + continue; + } + } else { + /* phase 1 */ + if (s->dppriv[(((line_l3 >> 16) & 0x003) | + ((line_l2 >> 14) & 0x00c) | + ((line_h1 >> 5) & 0x030) | + ((line_h2 >> 10) & 0x1c0)) + 256] < 2) { +#ifdef DEBUG + ++dp_pixels; +#endif + continue; + } + } + } else { + if ((j & 1) == 0) { + /* phase 2 */ + if (s->dppriv[(((line_l3 >> 16) & 0x003) | + ((line_l2 >> 14) & 0x00c) | + ((line_h1 >> 5) & 0x010) | + ((line_h2 >> 10) & 0x0e0) | + ((line_h3 >> 7) & 0x700)) + 768] < 2) { +#ifdef DEBUG + ++dp_pixels; +#endif + continue; + } + } else { + /* phase 3 */ + if (s->dppriv[(((line_l3 >> 16) & 0x003) | + ((line_l2 >> 14) & 0x00c) | + ((line_h1 >> 5) & 0x030) | + ((line_h2 >> 10) & 0x1c0) | + ((line_h3 >> 7) & 0xe00)) + 2816] < 2) { +#ifdef DEBUG + ++dp_pixels; +#endif + continue; + } + } + } + } + + /* determine context */ + if (s->tx[plane]) { + if ((unsigned) s->tx[plane] > j) + a = 0; + else { + o = (j - s->tx[plane]) - (j & ~7L); + a = (hp[o >> 3] >> (7 - (o & 7))) & 1; + a <<= 4; + } + assert(s->tx[plane] > 23 || + a == ((line_h1 >> (4 + s->tx[plane])) & 0x010)); + cx = (((line_h1 >> 9) & 0x003) | a | + ((line_h2 >> 13) & 0x00c) | + ((line_h3 >> 11) & 0x020)); + } else + cx = (((line_h1 >> 9) & 0x003) | + ((line_h2 >> 13) & 0x01c) | + ((line_h3 >> 11) & 0x020)); + if (j & 1) + cx |= (((line_l2 >> 9) & 0x0c0) | + ((line_l1 >> 7) & 0x300)) | (1UL << 10); + else + cx |= (((line_l2 >> 10) & 0x0c0) | + ((line_l1 >> 8) & 0x300)); + cx |= (y & 1) << 11; + + arith_encode(se, cx, (line_h1 >> 8) & 1); +#ifdef DEBUG + encoded_pixels++; +#endif + + /* statistics for adaptive template changes */ + if (!at_determined && j >= s->mx) { + c[0] += !(((line_h2 >> 6) ^ line_h1) & 0x100); + for (t = 3; t <= s->mx; t++) + c[t] += !(((line_h1 >> t) ^ line_h1) & 0x100); + ++c_all; + } + + } while (++j & 1 && j < hx); + } while (j & 7 && j < hx); + hp++; + } while (j & 15 && j < hx); + } /* for (j = ...) */ + + /* low resolution pixels are used twice */ + if ((i & 1) == 0) { + lp1 -= lbpl; + lp2 -= lbpl; + } + + } /* for (i = ...) */ + } + + arith_encode_flush(se); + jbg_buf_remove_zeros(s->sde[stripe][layer][plane]); + jbg_buf_write(MARKER_ESC, s->sde[stripe][layer][plane]); + jbg_buf_write(MARKER_SDNORM, s->sde[stripe][layer][plane]); + + /* add ATMOVE */ + if (new_tx != -1) { + if (s->options & JBG_DELAY_AT) { + /* ATMOVE will become active at the first line of the next stripe */ + s->tx[plane] = new_tx; + jbg_buf_write(MARKER_ESC, s->sde[stripe][layer][plane]); + jbg_buf_write(MARKER_ATMOVE, s->sde[stripe][layer][plane]); + jbg_buf_write(0, s->sde[stripe][layer][plane]); + jbg_buf_write(0, s->sde[stripe][layer][plane]); + jbg_buf_write(0, s->sde[stripe][layer][plane]); + jbg_buf_write(0, s->sde[stripe][layer][plane]); + jbg_buf_write(s->tx[plane], s->sde[stripe][layer][plane]); + jbg_buf_write(0, s->sde[stripe][layer][plane]); + } else { + /* ATMOVE has already become active during this stripe + * => we have to prefix the SDE data with an ATMOVE marker */ + new_jbg_buf = jbg_buf_init(&s->free_list); + jbg_buf_write(MARKER_ESC, new_jbg_buf); + jbg_buf_write(MARKER_ATMOVE, new_jbg_buf); + jbg_buf_write((new_tx_line >> 24) & 0xff, new_jbg_buf); + jbg_buf_write((new_tx_line >> 16) & 0xff, new_jbg_buf); + jbg_buf_write((new_tx_line >> 8) & 0xff, new_jbg_buf); + jbg_buf_write(new_tx_line & 0xff, new_jbg_buf); + jbg_buf_write(new_tx, new_jbg_buf); + jbg_buf_write(0, new_jbg_buf); + jbg_buf_prefix(new_jbg_buf, &s->sde[stripe][layer][plane]); + } + } + +#if 0 + if (stripe == s->stripes - 1) + fprintf(stderr, "tp_lines = %ld, tp_exceptions = %ld, tp_pixels = %ld, " + "dp_pixels = %ld, encoded_pixels = %ld\n", + tp_lines, tp_exceptions, tp_pixels, dp_pixels, encoded_pixels); +#endif + + return; +} + + +/* + * Create the next lower resolution version of an image + */ +static void resolution_reduction(struct jbg_enc_state *s, int plane, + int higher_layer) +{ + unsigned long hx, hy, lx, ly, hbpl, lbpl; + unsigned char *hp1, *hp2, *hp3, *lp; + unsigned long line_h1, line_h2, line_h3, line_l2; + unsigned long i, j; + int pix, k, l; + + /* number of pixels in highres image */ + hx = jbg_ceil_half(s->xd, s->d - higher_layer); + hy = jbg_ceil_half(s->yd, s->d - higher_layer); + /* number of pixels in lowres image */ + lx = jbg_ceil_half(hx, 1); + ly = jbg_ceil_half(hy, 1); + /* bytes per line in highres and lowres image */ + hbpl = jbg_ceil_half(hx, 3); + lbpl = jbg_ceil_half(lx, 3); + /* pointers to first image bytes */ + hp2 = s->lhp[s->highres[plane]][plane]; + hp1 = hp2 + hbpl; + hp3 = hp2 - hbpl; + lp = s->lhp[1 - s->highres[plane]][plane]; + +#ifdef DEBUG + fprintf(stderr, "resolution_reduction: plane = %d, higher_layer = %d\n", + plane, higher_layer); +#endif + + /* + * Layout of the variables line_h1, line_h2, line_h3, which contain + * as bits the high resolution neighbour pixels of the currently coded + * lowres pixel /\: + * \/ + * + * 76543210 76543210 76543210 76543210 line_h3 + * 76543210 76543210 765432/\ 76543210 line_h2 + * 76543210 76543210 765432\/ 76543210 line_h1 + * + * Layout of the variable line_l2, which contains the low resolution + * pixels near the currently coded pixel as bits. The lowres pixel + * which is currently coded is marked as X: + * + * 76543210 76543210 76543210 76543210 line_l2 + * X + */ + + for (i = 0; i < ly; i++) { + if (2*i + 1 >= hy) + hp1 = hp2; + pix = 0; + line_h1 = line_h2 = line_h3 = line_l2 = 0; + for (j = 0; j < lbpl * 8; j += 8) { + *lp = 0; + line_l2 |= i ? *(lp-lbpl) : 0; + for (k = 0; k < 8 && j + k < lx; k += 4) { + if (((j + k) >> 2) < hbpl) { + line_h3 |= i ? *hp3 : 0; + ++hp3; + line_h2 |= *(hp2++); + line_h1 |= *(hp1++); + } + for (l = 0; l < 4 && j + k + l < lx; l++) { + line_h3 <<= 2; + line_h2 <<= 2; + line_h1 <<= 2; + line_l2 <<= 1; + pix = s->res_tab[((line_h1 >> 8) & 0x007) | + ((line_h2 >> 5) & 0x038) | + ((line_h3 >> 2) & 0x1c0) | + (pix << 9) | ((line_l2 << 2) & 0xc00)]; + *lp = (*lp << 1) | pix; + } + } + ++lp; + } + *(lp - 1) <<= lbpl * 8 - lx; + hp1 += hbpl; + hp2 += hbpl; + hp3 += hbpl; + } + +#ifdef DEBUG + { + FILE *f; + char fn[50]; + + sprintf(fn, "dbg_d=%02d.pbm", higher_layer - 1); + f = fopen(fn, "wb"); + fprintf(f, "P4\n%lu %lu\n", lx, ly); + fwrite(s->lhp[1 - s->highres[plane]][plane], 1, lbpl * ly, f); + fclose(f); + } +#endif + + return; +} + + +/* + * This function is called inside the three loops of jbg_enc_out() in + * order to write the next SDE. It has first to generate the required + * SDE and all SDEs which have to be encoded before this SDE can be + * created. The problem here is that if we want to output a lower + * resolution layer, we have to allpy the resolution reduction + * algorithm in order to get it. As we try to safe as much memory as + * possible, the resolution reduction will overwrite previous higher + * resolution bitmaps. Consequently, we have to encode and buffer SDEs + * which depend on higher resolution layers before we can start the + * resolution reduction. All this logic about which SDE has to be + * encoded before resolution reduction is allowed is handled here. + * This approach might be a little bit more complex than alternative + * ways to do it, but it allows us to do the encoding with the minimal + * possible amount of temporary memory. + */ +static void output_sde(struct jbg_enc_state *s, + unsigned long stripe, int layer, int plane) +{ + int lfcl; /* lowest fully coded layer */ + long i; + unsigned long u; + + assert(s->sde[stripe][layer][plane] != SDE_DONE); + + if (s->sde[stripe][layer][plane] != SDE_TODO) { +#ifdef DEBUG + fprintf(stderr, "writing SDE: s/d/p = %2lu/%2d/%2d\n", + stripe, layer, plane); +#endif + jbg_buf_output(&s->sde[stripe][layer][plane], s->data_out, s->file); + s->sde[stripe][layer][plane] = SDE_DONE; + return; + } + + /* Determine the smallest resolution layer in this plane for which + * not yet all stripes have been encoded into SDEs. This layer will + * have to be completely coded, before we can apply the next + * resolution reduction step. */ + lfcl = 0; + for (i = s->d; i >= 0; i--) + if (s->sde[s->stripes - 1][i][plane] == SDE_TODO) { + lfcl = i + 1; + break; + } + if (lfcl > s->d && s->d > 0 && stripe == 0) { + /* perform the first resolution reduction */ + resolution_reduction(s, plane, s->d); + } + /* In case HITOLO is not used, we have to encode and store the higher + * resolution layers first, although we do not need them right now. */ + while (lfcl - 1 > layer) { + for (u = 0; u < s->stripes; u++) + encode_sde(s, u, lfcl - 1, plane); + --lfcl; + s->highres[plane] ^= 1; + if (lfcl > 1) + resolution_reduction(s, plane, lfcl - 1); + } + + encode_sde(s, stripe, layer, plane); + +#ifdef DEBUG + fprintf(stderr, "writing SDE: s/d/p = %2lu/%2d/%2d\n", stripe, layer, plane); +#endif + jbg_buf_output(&s->sde[stripe][layer][plane], s->data_out, s->file); + s->sde[stripe][layer][plane] = SDE_DONE; + + if (stripe == s->stripes - 1 && layer > 0 && + s->sde[0][layer-1][plane] == SDE_TODO) { + s->highres[plane] ^= 1; + if (layer > 1) + resolution_reduction(s, plane, layer - 1); + } + + return; +} + + +/* + * Convert the table which controls the deterministic prediction + * process from the internal format into the representation required + * for the 1728 byte long DPTABLE element of a BIH. + * + * The bit order of the DPTABLE format (see also ITU-T T.82 figure 13) is + * + * high res: 4 5 6 low res: 0 1 + * 7 8 9 2 3 + * 10 11 12 + * + * were 4 table entries are packed into one byte, while we here use + * internally an unpacked 6912 byte long table indexed by the following + * bit order: + * + * high res: 7 6 5 high res: 8 7 6 low res: 1 0 + * (phase 0) 4 . . (phase 1) 5 4 . 3 2 + * . . . . . . + * + * high res: 10 9 8 high res: 11 10 9 + * (phase 2) 7 6 5 (phase 3) 8 7 6 + * 4 . . 5 4 . + */ +void jbg_int2dppriv(unsigned char *dptable, const char *internal) +{ + int i, j, k; + int trans0[ 8] = { 1, 0, 3, 2, 7, 6, 5, 4 }; + int trans1[ 9] = { 1, 0, 3, 2, 8, 7, 6, 5, 4 }; + int trans2[11] = { 1, 0, 3, 2, 10, 9, 8, 7, 6, 5, 4 }; + int trans3[12] = { 1, 0, 3, 2, 11, 10, 9, 8, 7, 6, 5, 4 }; + + for (i = 0; i < 1728; dptable[i++] = 0); + +#define FILL_TABLE1(offset, len, trans) \ + for (i = 0; i < len; i++) { \ + k = 0; \ + for (j = 0; j < 8; j++) \ + k |= ((i >> j) & 1) << trans[j]; \ + dptable[(i + offset) >> 2] |= \ + (internal[k + offset] & 3) << ((3 - (i&3)) << 1); \ + } + + FILL_TABLE1( 0, 256, trans0); + FILL_TABLE1( 256, 512, trans1); + FILL_TABLE1( 768, 2048, trans2); + FILL_TABLE1(2816, 4096, trans3); + + return; +} + + +/* + * Convert the table which controls the deterministic prediction + * process from the 1728 byte long DPTABLE format into the 6912 byte long + * internal format. + */ +void jbg_dppriv2int(char *internal, const unsigned char *dptable) +{ + int i, j, k; + int trans0[ 8] = { 1, 0, 3, 2, 7, 6, 5, 4 }; + int trans1[ 9] = { 1, 0, 3, 2, 8, 7, 6, 5, 4 }; + int trans2[11] = { 1, 0, 3, 2, 10, 9, 8, 7, 6, 5, 4 }; + int trans3[12] = { 1, 0, 3, 2, 11, 10, 9, 8, 7, 6, 5, 4 }; + +#define FILL_TABLE2(offset, len, trans) \ + for (i = 0; i < len; i++) { \ + k = 0; \ + for (j = 0; j < 8; j++) \ + k |= ((i >> j) & 1) << trans[j]; \ + internal[k + offset] = \ + (dptable[(i + offset) >> 2] >> ((3 - (i & 3)) << 1)) & 3; \ + } + + FILL_TABLE2( 0, 256, trans0); + FILL_TABLE2( 256, 512, trans1); + FILL_TABLE2( 768, 2048, trans2); + FILL_TABLE2(2816, 4096, trans3); + + return; +} + + +/* + * Encode one full BIE and pass the generated data to the specified + * call-back function + */ +void jbg_enc_out(struct jbg_enc_state *s) +{ + unsigned long bpl; + unsigned char buf[20]; + unsigned long xd, yd, y; + long ii[3], is[3], ie[3]; /* generic variables for the 3 nested loops */ + unsigned long stripe; + int layer, plane; + int order; + unsigned char dpbuf[1728]; + extern char jbg_dptable[]; + + /* some sanity checks */ + s->order &= JBG_HITOLO | JBG_SEQ | JBG_ILEAVE | JBG_SMID; + order = s->order & (JBG_SEQ | JBG_ILEAVE | JBG_SMID); + if (iindex[order][0] < 0) + s->order = order = JBG_SMID | JBG_ILEAVE; + if (s->options & JBG_DPON && s->dppriv != jbg_dptable) + s->options |= JBG_DPPRIV; + if (s->mx > MX_MAX) + s->mx = MX_MAX; + s->my = 0; + if (s->mx && s->mx < ((s->options & JBG_LRLTWO) ? 5U : 3U)) + s->mx = 0; + if (s->d > 255 || s->d < 0 || s->dh > s->d || s->dh < 0 || + s->dl < 0 || s->dl > s->dh || s->planes < 0 || s->planes > 255) + return; + /* prevent uint32 overflow: s->l0 * 2 ^ s->d < 2 ^ 32 */ + if (s->d > 31 || (s->d != 0 && s->l0 >= (1UL << (32 - s->d)))) + return; + if (s->yd1 < s->yd) + s->yd1 = s->yd; + if (s->yd1 > s->yd) + s->options |= JBG_VLENGTH; + + /* ensure correct zero padding of bitmap at the final byte of each line */ + if (s->xd & 7) { + bpl = jbg_ceil_half(s->xd, 3); /* bytes per line */ + for (plane = 0; plane < s->planes; plane++) + for (y = 0; y < s->yd; y++) + s->lhp[0][plane][y * bpl + bpl - 1] &= ~((1 << (8 - (s->xd & 7))) - 1); + } + + /* prepare BIH */ + buf[0] = s->dl; + buf[1] = s->dh; + buf[2] = s->planes; + buf[3] = 0; + xd = jbg_ceil_half(s->xd, s->d - s->dh); + yd = jbg_ceil_half(s->yd1, s->d - s->dh); + buf[4] = (unsigned char)(xd >> 24); + buf[5] = (unsigned char)((xd >> 16) & 0xff); + buf[6] = (unsigned char)((xd >> 8) & 0xff); + buf[7] = (unsigned char)(xd & 0xff); + buf[8] = (unsigned char)(yd >> 24); + buf[9] = (unsigned char)((yd >> 16) & 0xff); + buf[10] = (unsigned char)((yd >> 8) & 0xff); + buf[11] = (unsigned char)(yd & 0xff); + buf[12] = (unsigned char)(s->l0 >> 24); + buf[13] = (unsigned char)((s->l0 >> 16) & 0xff); + buf[14] = (unsigned char)((s->l0 >> 8) & 0xff); + buf[15] = (unsigned char)(s->l0 & 0xff); + buf[16] = (unsigned char)(s->mx); + buf[17] = (unsigned char)(s->my); + buf[18] = (unsigned char)(s->order); + buf[19] = (unsigned char)(s->options & 0x7f); + +#if 0 + /* sanitize L0 (if it was set to 0xffffffff for T.85-style NEWLEN tests) */ + if (s->l0 > (s->yd >> s->d)) + s->l0 = s->yd >> s->d; +#endif + + /* calculate number of stripes that will be required */ + s->stripes = jbg_stripes(s->l0, s->yd, s->d); + + /* allocate buffers for SDE pointers */ + if (s->sde == NULL) { + s->sde = (struct jbg_buf ****) + checked_malloc(s->stripes, sizeof(struct jbg_buf ***)); + for (stripe = 0; stripe < s->stripes; stripe++) { + s->sde[stripe] = (struct jbg_buf ***) + checked_malloc(s->d + 1, sizeof(struct jbg_buf **)); + for (layer = 0; layer < s->d + 1; layer++) { + s->sde[stripe][layer] = (struct jbg_buf **) + checked_malloc(s->planes, sizeof(struct jbg_buf *)); + for (plane = 0; plane < s->planes; plane++) + s->sde[stripe][layer][plane] = SDE_TODO; + } + } + } + + /* output BIH */ + s->data_out(buf, 20, s->file); + if ((s->options & (JBG_DPON | JBG_DPPRIV | JBG_DPLAST)) == + (JBG_DPON | JBG_DPPRIV)) { + /* write private table */ + jbg_int2dppriv(dpbuf, s->dppriv); + s->data_out(dpbuf, 1728, s->file); + } + +#if 0 + /* + * Encode everything first. This is a simple-minded alternative to + * all the tricky on-demand encoding logic in output_sde() for + * debugging purposes. + */ + for (layer = s->dh; layer >= s->dl; layer--) { + for (plane = 0; plane < s->planes; plane++) { + if (layer > 0) + resolution_reduction(s, plane, layer); + for (stripe = 0; stripe < s->stripes; stripe++) + encode_sde(s, stripe, layer, plane); + s->highres[plane] ^= 1; + } + } +#endif + + /* + * Generic loops over all SDEs. Which loop represents layer, plane and + * stripe depends on the option flags. + */ + + /* start and end value vor each loop */ + is[iindex[order][STRIPE]] = 0; + ie[iindex[order][STRIPE]] = s->stripes - 1; + is[iindex[order][LAYER]] = s->dl; + ie[iindex[order][LAYER]] = s->dh; + is[iindex[order][PLANE]] = 0; + ie[iindex[order][PLANE]] = s->planes - 1; + + for (ii[0] = is[0]; ii[0] <= ie[0]; ii[0]++) + for (ii[1] = is[1]; ii[1] <= ie[1]; ii[1]++) + for (ii[2] = is[2]; ii[2] <= ie[2]; ii[2]++) { + + stripe = ii[iindex[order][STRIPE]]; + if (s->order & JBG_HITOLO) + layer = s->dh - (ii[iindex[order][LAYER]] - s->dl); + else + layer = ii[iindex[order][LAYER]]; + plane = ii[iindex[order][PLANE]]; + + output_sde(s, stripe, layer, plane); + + /* + * When we generate a NEWLEN test case (s->yd1 > s->yd), output + * NEWLEN after last stripe if we have only a single + * resolution layer or plane (see ITU-T T.85 profile), otherwise + * output NEWLEN before last stripe. + */ + if (s->yd1 > s->yd && + (stripe == s->stripes - 1 || + (stripe == s->stripes - 2 && + (s->dl != s->dh || s->planes > 1)))) { + s->yd1 = s->yd; + yd = jbg_ceil_half(s->yd, s->d - s->dh); + buf[0] = MARKER_ESC; + buf[1] = MARKER_NEWLEN; + buf[2] = (unsigned char)(yd >> 24); + buf[3] = (unsigned char)((yd >> 16) & 0xff); + buf[4] = (unsigned char)((yd >> 8) & 0xff); + buf[5] = (unsigned char)(yd & 0xff); + s->data_out(buf, 6, s->file); +#ifdef DEBUG + fprintf(stderr, "NEWLEN: yd=%lu\n", yd); +#endif + if (stripe == s->stripes - 1) { + buf[1] = MARKER_SDNORM; + s->data_out(buf, 2, s->file); + } + } + + } + + return; +} + + +void jbg_enc_free(struct jbg_enc_state *s) +{ + unsigned long stripe; + int layer, plane; + +#ifdef DEBUG + fprintf(stderr, "jbg_enc_free(%p)\n", (void *) s); +#endif + + /* clear buffers for SDEs */ + if (s->sde) { + for (stripe = 0; stripe < s->stripes; stripe++) { + for (layer = 0; layer < s->d + 1; layer++) { + for (plane = 0; plane < s->planes; plane++) + if (s->sde[stripe][layer][plane] != SDE_DONE && + s->sde[stripe][layer][plane] != SDE_TODO) + jbg_buf_free(&s->sde[stripe][layer][plane]); + checked_free(s->sde[stripe][layer]); + } + checked_free(s->sde[stripe]); + } + checked_free(s->sde); + } + + /* clear free_list */ + jbg_buf_free(&s->free_list); + + /* clear memory for arithmetic encoder states */ + checked_free(s->s); + + /* clear memory for differential-layer typical prediction buffer */ + checked_free(s->tp); + + /* clear memory for adaptive template pixel offsets */ + checked_free(s->tx); + + /* clear lowres image buffers */ + if (s->lhp[1]) { + for (plane = 0; plane < s->planes; plane++) + checked_free(s->lhp[1][plane]); + checked_free(s->lhp[1]); + } + + /* clear buffer for index of highres image in lhp */ + checked_free(s->highres); + + return; +} + + +/* + * Convert the error codes used by jbg_dec_in() into a string + * written in the selected language and character set. + */ +const char *jbg_strerror(int errnum, int language) +{ + if (errnum < 0 || errnum >= NEMSG) + return "Unknown error code passed to jbg_strerror()"; + if (language < 0 || language >= NEMSG_LANG) + return "Unknown language code passed to jbg_strerror()"; + + return errmsg[language][errnum]; +} + + +/* + * The constructor for a decoder + */ +void jbg_dec_init(struct jbg_dec_state *s) +{ + s->order = 0; + s->d = -1; + s->bie_len = 0; + s->buf_len = 0; + s->dppriv = NULL; + s->xmax = 4294967295UL; + s->ymax = 4294967295UL; + s->dmax = 256; + s->s = NULL; + + return; +} + + +/* + * Specify a maximum image size for the decoder. If the JBIG file has + * the order bit ILEAVE, but not the bit SEQ set, then the decoder + * will abort to decode after the image has reached the maximal + * resolution layer which is still not wider than xmax or higher than + * ymax. + */ +void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax, + unsigned long ymax) +{ + if (xmax > 0) s->xmax = xmax; + if (ymax > 0) s->ymax = ymax; + + return; +} + + +/* + * Decode the new len PSDC bytes to which data points and add them to + * the current stripe. Return the number of bytes which have actually + * been read (this will be less than len if a marker segment was + * part of the data or if the final byte was 0xff were this code + * can not determine, whether we have a marker segment. + */ +static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data, + size_t len) +{ + unsigned long stripe; + unsigned int layer, plane; + unsigned long hl, ll, y, hx, hy, lx, ly, hbpl, lbpl; + unsigned char *hp, *lp1, *lp2, *p1, *q1; + register unsigned long line_h1, line_h2, line_h3; + register unsigned long line_l1, line_l2, line_l3; + struct jbg_ardec_state *se; + unsigned long x; + long o; + unsigned a; + int n; + int pix, cx = 0, slntp, tx; + + /* SDE loop variables */ + stripe = s->ii[iindex[s->order & 7][STRIPE]]; + layer = s->ii[iindex[s->order & 7][LAYER]]; + plane = s->ii[iindex[s->order & 7][PLANE]]; + + /* forward data to arithmetic decoder */ + se = s->s[plane] + layer - s->dl; + se->pscd_ptr = data; + se->pscd_end = data + len; + + /* number of lines per stripe in highres image */ + hl = s->l0 << layer; + /* number of lines per stripe in lowres image */ + ll = hl >> 1; + /* current line number in highres image */ + y = stripe * hl + s->i; + /* number of pixels in highres image */ + hx = jbg_ceil_half(s->xd, s->d - layer); + hy = jbg_ceil_half(s->yd, s->d - layer); + /* number of pixels in lowres image */ + lx = jbg_ceil_half(hx, 1); + ly = jbg_ceil_half(hy, 1); + /* bytes per line in highres and lowres image */ + hbpl = jbg_ceil_half(hx, 3); + lbpl = jbg_ceil_half(lx, 3); + /* pointer to highres and lowres image bytes */ + hp = s->lhp[ layer & 1][plane] + (stripe * hl + s->i) * hbpl + + (s->x >> 3); + lp2 = s->lhp[(layer-1) & 1][plane] + (stripe * ll + (s->i >> 1)) * lbpl + + (s->x >> 4); + lp1 = lp2 + lbpl; + + /* restore a few local variables */ + line_h1 = s->line_h1; + line_h2 = s->line_h2; + line_h3 = s->line_h3; + line_l1 = s->line_l1; + line_l2 = s->line_l2; + line_l3 = s->line_l3; + x = s->x; + + if (s->x == 0 && s->i == 0 && + (stripe == 0 || s->reset[plane][layer - s->dl])) { + s->tx[plane][layer - s->dl] = s->ty[plane][layer - s->dl] = 0; + if (s->pseudo) + s->lntp[plane][layer - s->dl] = 1; + } + +#ifdef DEBUG + if (s->x == 0 && s->i == 0 && s->pseudo) + fprintf(stderr, "decode_pscd(%p, %p, %ld): s/d/p = %2lu/%2u/%2u\n", + (void *) s, (void *) data, (long) len, stripe, layer, plane); +#endif + + if (layer == 0) { + + /* + * Decode lowest resolution layer + */ + + for (; s->i < hl && y < hy; s->i++, y++) { + + /* adaptive template changes */ + if (x == 0) + for (n = 0; n < s->at_moves; n++) + if (s->at_line[n] == s->i) { + s->tx[plane][layer - s->dl] = s->at_tx[n]; + s->ty[plane][layer - s->dl] = s->at_ty[n]; +#ifdef DEBUG + fprintf(stderr, "ATMOVE: line=%lu, tx=%d, ty=%d.\n", s->i, + s->tx[plane][layer - s->dl], s->ty[plane][layer - s->dl]); +#endif + } + tx = s->tx[plane][layer - s->dl]; + assert(tx >= 0); /* i.e., tx can safely be cast to unsigned */ + + /* typical prediction */ + if (s->options & JBG_TPBON && s->pseudo) { + slntp = arith_decode(se, (s->options & JBG_LRLTWO) ? TPB2CX : TPB3CX); + if (se->result == JBG_MORE || se->result == JBG_MARKER) + goto leave; + s->lntp[plane][layer - s->dl] = + !(slntp ^ s->lntp[plane][layer - s->dl]); + if (s->lntp[plane][layer - s->dl]) { + /* this line is 'not typical' and has to be coded completely */ + s->pseudo = 0; + } else { + /* this line is 'typical' (i.e. identical to the previous one) */ + p1 = hp; + if (s->i == 0 && (stripe == 0 || s->reset[plane][layer - s->dl])) + while (p1 < hp + hbpl) *p1++ = 0; + else { + q1 = hp - hbpl; + while (q1 < hp) *p1++ = *q1++; + } + hp += hbpl; + continue; + } + } + + /* + * Layout of the variables line_h1, line_h2, line_h3, which contain + * as bits the neighbour pixels of the currently decoded pixel X: + * + * 76543210 76543210 76543210 76543210 line_h3 + * 76543210 76543210 76543210 76543210 line_h2 + * 76543210 76543210 76543210 76543210 X line_h1 + */ + + if (x == 0) { + line_h1 = line_h2 = line_h3 = 0; + if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) + line_h2 = (long)*(hp - hbpl) << 8; + if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl])) + line_h3 = (long)*(hp - hbpl - hbpl) << 8; + } + + /* + * Another tiny JBIG standard bug: + * + * While implementing the line_h3 handling here, I discovered + * another problem with the ITU-T T.82(1993 E) specification. + * This might be a somewhat pathological case, however. The + * standard is unclear about how a decoder should behave in the + * following situation: + * + * Assume we are in layer 0 and all stripes are single lines + * (L0=1 allowed by table 9). We are now decoding the first (and + * only) line of the third stripe. Assume, the first stripe was + * terminated by SDRST and the second stripe was terminated by + * SDNORM. While decoding the only line of the third stripe with + * the three-line template, we need access to pixels from the + * previous two stripes. We know that the previous stripe + * terminated with SDNROM, so we access the pixel from the + * second stripe. But do we have to replace the pixels from the + * first stripe by background pixels, because this stripe ended + * with SDRST? The standard, especially clause 6.2.5 does never + * mention this case, so the behaviour is undefined here. My + * current implementation remembers only the marker used to + * terminate the previous stripe. In the above example, the + * pixels of the first stripe are accessed despite the fact that + * this stripe ended with SDRST. An alternative (only slightly + * more complicated) implementation would be to remember the end + * marker (SDNORM or SDRST) of the previous two stripes in a + * plane/layer and to act accordingly when accessing the two + * previous lines. What am I supposed to do here? + * + * As the standard is unclear about the correct behaviour in the + * situation of the above example, I strongly suggest to avoid + * the following situation while encoding data with JBIG: + * + * LRLTWO = 0, L0=1 and both SDNORM and SDRST appear in layer 0. + * + * I guess that only a very few if any encoders will switch + * between SDNORM and SDRST, so let us hope that this ambiguity + * in the standard will never cause any interoperability + * problems. + * + * Markus Kuhn -- 1995-04-30 + */ + + /* decode line */ + while (x < hx) { + if ((x & 7) == 0) { + if (x < hbpl * 8 - 8 && + (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl]))) { + line_h2 |= *(hp - hbpl + 1); + if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl])) + line_h3 |= *(hp - hbpl - hbpl + 1); + } + } + if (s->options & JBG_LRLTWO) { + /* two line template */ + do { + if (tx) { + if ((unsigned) tx > x) + a = 0; + else if (tx < 8) + a = ((line_h1 >> (tx - 5)) & 0x010); + else { + o = (x - tx) - (x & ~7L); + a = (hp[o >> 3] >> (7 - (o & 7))) & 1; + a <<= 4; + } + assert(tx > 31 || + a == ((line_h1 >> (tx - 5)) & 0x010)); + pix = arith_decode(se, (((line_h2 >> 9) & 0x3e0) | a | + (line_h1 & 0x00f))); + } else + pix = arith_decode(se, (((line_h2 >> 9) & 0x3f0) | + (line_h1 & 0x00f))); + if (se->result == JBG_MORE || se->result == JBG_MARKER) + goto leave; + line_h1 = (line_h1 << 1) | pix; + line_h2 <<= 1; + } while ((++x & 7) && x < hx); + } else { + /* three line template */ + do { + if (tx) { + if ((unsigned) tx > x) + a = 0; + else if (tx < 8) + a = ((line_h1 >> (tx - 3)) & 0x004); + else { + o = (x - tx) - (x & ~7L); + a = (hp[o >> 3] >> (7 - (o & 7))) & 1; + a <<= 2; + } + assert(tx > 31 || + a == ((line_h1 >> (tx - 3)) & 0x004)); + pix = arith_decode(se, (((line_h3 >> 7) & 0x380) | + ((line_h2 >> 11) & 0x078) | a | + (line_h1 & 0x003))); + } else + pix = arith_decode(se, (((line_h3 >> 7) & 0x380) | + ((line_h2 >> 11) & 0x07c) | + (line_h1 & 0x003))); + if (se->result == JBG_MORE || se->result == JBG_MARKER) + goto leave; + + line_h1 = (line_h1 << 1) | pix; + line_h2 <<= 1; + line_h3 <<= 1; + } while ((++x & 7) && x < hx); + } /* if (s->options & JBG_LRLTWO) */ + *hp++ = (unsigned char)(line_h1); + } /* while */ + *(hp - 1) <<= hbpl * 8 - hx; + x = 0; + s->pseudo = 1; + } /* for (i = ...) */ + + } else { + + /* + * Decode differential layer + */ + + for (; s->i < hl && y < hy; s->i++, y++) { + + /* adaptive template changes */ + if (x == 0) + for (n = 0; n < s->at_moves; n++) + if (s->at_line[n] == s->i) { + s->tx[plane][layer - s->dl] = s->at_tx[n]; + s->ty[plane][layer - s->dl] = s->at_ty[n]; +#ifdef DEBUG + fprintf(stderr, "ATMOVE: line=%lu, tx=%d, ty=%d.\n", s->i, + s->tx[plane][layer - s->dl], s->ty[plane][layer - s->dl]); +#endif + } + tx = s->tx[plane][layer - s->dl]; + + /* handle lower border of low-resolution image */ + if ((s->i >> 1) >= ll - 1 || (y >> 1) >= ly - 1) + lp1 = lp2; + + /* typical prediction */ + if (s->options & JBG_TPDON && s->pseudo) { + s->lntp[plane][layer - s->dl] = arith_decode(se, TPDCX); + if (se->result == JBG_MORE || se->result == JBG_MARKER) + goto leave; + s->pseudo = 0; + } + + + /* + * Layout of the variables line_h1, line_h2, line_h3, which contain + * as bits the high resolution neighbour pixels of the currently + * decoded highres pixel X: + * + * 76543210 76543210 76543210 76543210 line_h3 + * 76543210 76543210 76543210 76543210 line_h2 + * 76543210 76543210 76543210 76543210 X line_h1 + * + * Layout of the variables line_l1, line_l2, line_l3, which contain + * the low resolution pixels near the currently decoded pixel as bits. + * The lowres pixel in which the currently coded highres pixel is + * located is marked as Y: + * + * 76543210 76543210 76543210 76543210 line_l3 + * 76543210 76543210 Y6543210 76543210 line_l2 + * 76543210 76543210 76543210 76543210 line_l1 + */ + + + if (x == 0) { + line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0; + if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) { + line_h2 = (long)*(hp - hbpl) << 8; + if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl])) + line_h3 = (long)*(hp - hbpl - hbpl) << 8; + } + if (s->i > 1 || (y > 1 && !s->reset[plane][layer-s->dl])) + line_l3 = (long)*(lp2 - lbpl) << 8; + line_l2 = (long)*lp2 << 8; + line_l1 = (long)*lp1 << 8; + } + + /* decode line */ + while (x < hx) { + if ((x & 15) == 0) + if ((x >> 1) < lbpl * 8 - 8) { + line_l1 |= *(lp1 + 1); + line_l2 |= *(lp2 + 1); + if (s->i > 1 || + (y > 1 && !s->reset[plane][layer - s->dl])) + line_l3 |= *(lp2 - lbpl + 1); + } + do { + + assert(hp - (s->lhp[ layer &1][plane] + (stripe * hl + s->i) + * hbpl) == (ptrdiff_t) x >> 3); + assert(lp2 - (s->lhp[(layer-1) &1][plane] + (stripe * ll + (s->i>>1)) + * lbpl) == (ptrdiff_t) x >> 4); + + if ((x & 7) == 0) + if (x < hbpl * 8 - 8) { + if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) { + line_h2 |= *(hp + 1 - hbpl); + if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl])) + line_h3 |= *(hp + 1 - hbpl - hbpl); + } + } + do { + if (!s->lntp[plane][layer - s->dl]) + cx = (((line_l3 >> 14) & 0x007) | + ((line_l2 >> 11) & 0x038) | + ((line_l1 >> 8) & 0x1c0)); + if (!s->lntp[plane][layer - s->dl] && + (cx == 0x000 || cx == 0x1ff)) { + /* pixels are typical and have not to be decoded */ + do { + line_h1 = (line_h1 << 1) | (cx & 1); + } while ((++x & 1) && x < hx); + line_h2 <<= 2; line_h3 <<= 2; + } else + do { + + /* deterministic prediction */ + if (s->options & JBG_DPON) + if ((y & 1) == 0) + if ((x & 1) == 0) + /* phase 0 */ + pix = s->dppriv[((line_l3 >> 15) & 0x003) | + ((line_l2 >> 13) & 0x00c) | + ((line_h1 << 4) & 0x010) | + ((line_h2 >> 9) & 0x0e0)]; + else + /* phase 1 */ + pix = s->dppriv[(((line_l3 >> 15) & 0x003) | + ((line_l2 >> 13) & 0x00c) | + ((line_h1 << 4) & 0x030) | + ((line_h2 >> 9) & 0x1c0)) + 256]; + else + if ((x & 1) == 0) + /* phase 2 */ + pix = s->dppriv[(((line_l3 >> 15) & 0x003) | + ((line_l2 >> 13) & 0x00c) | + ((line_h1 << 4) & 0x010) | + ((line_h2 >> 9) & 0x0e0) | + ((line_h3 >> 6) & 0x700)) + 768]; + else + /* phase 3 */ + pix = s->dppriv[(((line_l3 >> 15) & 0x003) | + ((line_l2 >> 13) & 0x00c) | + ((line_h1 << 4) & 0x030) | + ((line_h2 >> 9) & 0x1c0) | + ((line_h3 >> 6) & 0xe00)) + 2816]; + else + pix = 2; + + if (pix & 2) { + if (tx) + cx = ((line_h1 & 0x003) | + (((line_h1 << 2) >> (tx - 3)) & 0x010) | + ((line_h2 >> 12) & 0x00c) | + ((line_h3 >> 10) & 0x020)); + else + cx = ((line_h1 & 0x003) | + ((line_h2 >> 12) & 0x01c) | + ((line_h3 >> 10) & 0x020)); + if (x & 1) + cx |= (((line_l2 >> 8) & 0x0c0) | + ((line_l1 >> 6) & 0x300)) | (1UL << 10); + else + cx |= (((line_l2 >> 9) & 0x0c0) | + ((line_l1 >> 7) & 0x300)); + cx |= (y & 1) << 11; + + pix = arith_decode(se, cx); + if (se->result == JBG_MORE || se->result == JBG_MARKER) + goto leave; + } + + line_h1 = (line_h1 << 1) | pix; + line_h2 <<= 1; + line_h3 <<= 1; + + } while ((++x & 1) && x < hx); + line_l1 <<= 1; line_l2 <<= 1; line_l3 <<= 1; + } while ((x & 7) && x < hx); + *hp++ = (unsigned char)(line_h1); + } while ((x & 15) && x < hx); + ++lp1; + ++lp2; + } /* while */ + x = 0; + + *(hp - 1) <<= hbpl * 8 - hx; + if ((s->i & 1) == 0) { + /* low resolution pixels are used twice */ + lp1 -= lbpl; + lp2 -= lbpl; + } else + s->pseudo = 1; + + } /* for (i = ...) */ + + } + + leave: + + /* save a few local variables */ + s->line_h1 = line_h1; + s->line_h2 = line_h2; + s->line_h3 = line_h3; + s->line_l1 = line_l1; + s->line_l2 = line_l2; + s->line_l3 = line_l3; + s->x = x; + + return se->pscd_ptr - data; +} + + +/* + * Provide a new BIE fragment to the decoder. + * + * If cnt is not NULL, then *cnt will contain after the call the + * number of actually read bytes. If the data was not complete, then + * the return value will be JBG_EAGAIN and *cnt == len. In case this + * function has returned with JBG_EOK, then it has reached the end of + * a BIE but it can be called again with data from the next BIE if + * there exists one in order to get to a higher resolution layer. In + * case the return value was JBG_EOK_INTR then this function can be + * called again with the rest of the BIE, because parsing the BIE has + * been interrupted by a jbg_dec_maxsize() specification. In both + * cases the remaining len - *cnt bytes of the previous block will + * have to passed to this function again (if len > *cnt). In case of + * any other return value than JBG_EOK, JBG_EOK_INTR or JBG_EAGAIN, a + * serious problem has occured and the only function you should call + * is jbg_dec_free() in order to remove the mess (and probably + * jbg_strerror() in order to find out what to tell the user). + */ +int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len, + size_t *cnt) +{ + int i, j, required_length; + unsigned long x, y; + unsigned long is[3], ie[3]; + extern char jbg_dptable[]; + size_t dummy_cnt; + + if (!cnt) cnt = &dummy_cnt; + *cnt = 0; + if (len < 1) return JBG_EAGAIN; + + /* read in 20-byte BIH */ + if (s->bie_len < 20) { + while (s->bie_len < 20 && *cnt < len) + s->buffer[s->bie_len++] = data[(*cnt)++]; + if (s->bie_len < 20) + return JBG_EAGAIN; + if (s->buffer[1] < s->buffer[0]) + return JBG_EINVAL; + /* test whether this looks like a valid JBIG header at all */ + if (s->buffer[3] != 0 || (s->buffer[18] & 0xf0) != 0 || + (s->buffer[19] & 0x80) != 0) + return JBG_EINVAL; + if (s->buffer[0] != s->d + 1) + return JBG_ENOCONT; + s->dl = s->buffer[0]; + s->d = s->buffer[1]; + if (s->dl == 0) + s->planes = s->buffer[2]; + else + if (s->planes != s->buffer[2]) + return JBG_ENOCONT; + x = (((long) s->buffer[ 4] << 24) | ((long) s->buffer[ 5] << 16) | + ((long) s->buffer[ 6] << 8) | (long) s->buffer[ 7]); + y = (((long) s->buffer[ 8] << 24) | ((long) s->buffer[ 9] << 16) | + ((long) s->buffer[10] << 8) | (long) s->buffer[11]); + if (s->dl != 0 && ((s->xd << (s->d - s->dl + 1)) != x && + (s->yd << (s->d - s->dl + 1)) != y)) + return JBG_ENOCONT; + s->xd = x; + s->yd = y; + s->l0 = (((long) s->buffer[12] << 24) | ((long) s->buffer[13] << 16) | + ((long) s->buffer[14] << 8) | (long) s->buffer[15]); + /* ITU-T T.85 trick not directly supported by decoder; for full + * T.85 compatibility with respect to all NEWLEN marker scenarios, + * preprocess BIE with jbg_newlen() before passing it to the decoder. */ + if (s->yd == 0xffffffff) + return JBG_EIMPL; + if (!s->planes || !s->xd || !s->yd || !s->l0) + return JBG_EINVAL; + /* prevent uint32 overflow: s->l0 * 2 ^ s->d < 2 ^ 32 */ + if (s->d > 31 || (s->d != 0 && s->l0 >= (1UL << (32 - s->d)))) + return JBG_EIMPL; + s->mx = s->buffer[16]; + if (s->mx > 127) + return JBG_EINVAL; + s->my = s->buffer[17]; +#if 0 + if (s->my > 0) + return JBG_EIMPL; +#endif + s->order = s->buffer[18]; + if (iindex[s->order & 7][0] < 0) + return JBG_EINVAL; + /* HITOLO and SEQ currently not yet implemented */ + if (s->dl != s->d && (s->order & JBG_HITOLO || s->order & JBG_SEQ)) + return JBG_EIMPL; + s->options = s->buffer[19]; + + /* calculate number of stripes that will be required */ + s->stripes = jbg_stripes(s->l0, s->yd, s->d); + + /* some initialization */ + s->ii[iindex[s->order & 7][STRIPE]] = 0; + s->ii[iindex[s->order & 7][LAYER]] = s->dl; + s->ii[iindex[s->order & 7][PLANE]] = 0; + if (s->dl == 0) { + s->s = (struct jbg_ardec_state **) + checked_malloc(s->planes, sizeof(struct jbg_ardec_state *)); + s->tx = (int **) checked_malloc(s->planes, sizeof(int *)); + s->ty = (int **) checked_malloc(s->planes, sizeof(int *)); + s->reset = (int **) checked_malloc(s->planes, sizeof(int *)); + s->lntp = (int **) checked_malloc(s->planes, sizeof(int *)); + s->lhp[0] = (unsigned char **) + checked_malloc(s->planes, sizeof(unsigned char *)); + s->lhp[1] = (unsigned char **) + checked_malloc(s->planes, sizeof(unsigned char *)); + for (i = 0; i < s->planes; i++) { + s->s[i] = (struct jbg_ardec_state *) + checked_malloc(s->d - s->dl + 1, sizeof(struct jbg_ardec_state)); + s->tx[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int)); + s->ty[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int)); + s->reset[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int)); + s->lntp[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int)); + s->lhp[ s->d & 1][i] = (unsigned char *) + checked_malloc(s->yd, jbg_ceil_half(s->xd, 3)); + s->lhp[(s->d-1) & 1][i] = (unsigned char *) + checked_malloc(jbg_ceil_half(s->yd, 1), jbg_ceil_half(s->xd, 1+3)); + } + } else { + for (i = 0; i < s->planes; i++) { + s->s[i] = (struct jbg_ardec_state *) + checked_realloc(s->s[i], s->d - s->dl + 1, + sizeof(struct jbg_ardec_state)); + s->tx[i] = (int *) checked_realloc(s->tx[i], + s->d - s->dl + 1, sizeof(int)); + s->ty[i] = (int *) checked_realloc(s->ty[i], + s->d - s->dl + 1, sizeof(int)); + s->reset[i] = (int *) checked_realloc(s->reset[i], + s->d - s->dl + 1, sizeof(int)); + s->lntp[i] = (int *) checked_realloc(s->lntp[i], + s->d - s->dl + 1, sizeof(int)); + s->lhp[ s->d & 1][i] = (unsigned char *) + checked_realloc(s->lhp[ s->d & 1][i], + s->yd, jbg_ceil_half(s->xd, 3)); + s->lhp[(s->d-1) & 1][i] = (unsigned char *) + checked_realloc(s->lhp[(s->d-1) & 1][i], + jbg_ceil_half(s->yd, 1), jbg_ceil_half(s->xd, 1+3)); + } + } + for (i = 0; i < s->planes; i++) + for (j = 0; j <= s->d - s->dl; j++) + arith_decode_init(s->s[i] + j, 0); + if (s->dl == 0 || (s->options & JBG_DPON && !(s->options & JBG_DPPRIV))) + s->dppriv = jbg_dptable; + s->comment_skip = 0; + s->buf_len = 0; + s->x = 0; + s->i = 0; + s->pseudo = 1; + s->at_moves = 0; + } + + /* read in DPTABLE */ + if (s->bie_len < 20 + 1728 && + (s->options & (JBG_DPON | JBG_DPPRIV | JBG_DPLAST)) == + (JBG_DPON | JBG_DPPRIV)) { + assert(s->bie_len >= 20); + while (s->bie_len < 20 + 1728 && *cnt < len) + s->buffer[s->bie_len++ - 20] = data[(*cnt)++]; + if (s->bie_len < 20 + 1728) + return JBG_EAGAIN; + if (!s->dppriv || s->dppriv == jbg_dptable) + s->dppriv = (char *) checked_malloc(1728, sizeof(char)); + jbg_dppriv2int(s->dppriv, s->buffer); + } + + /* + * BID processing loop + */ + + while (*cnt < len) { + + /* process floating marker segments */ + + /* skip COMMENT contents */ + if (s->comment_skip) { + if (s->comment_skip <= len - *cnt) { + *cnt += s->comment_skip; + s->comment_skip = 0; + } else { + s->comment_skip -= len - *cnt; + *cnt = len; + } + continue; + } + + /* load complete marker segments into s->buffer for processing */ + if (s->buf_len > 0) { + assert(s->buffer[0] == MARKER_ESC); + while (s->buf_len < 2 && *cnt < len) + s->buffer[s->buf_len++] = data[(*cnt)++]; + if (s->buf_len < 2) continue; + switch (s->buffer[1]) { + case MARKER_COMMENT: required_length = 6; break; + case MARKER_ATMOVE: required_length = 8; break; + case MARKER_NEWLEN: required_length = 6; break; + case MARKER_ABORT: + case MARKER_SDNORM: + case MARKER_SDRST: required_length = 2; break; + case MARKER_STUFF: + /* forward stuffed 0xff to arithmetic decoder */ + s->buf_len = 0; + decode_pscd(s, s->buffer, 2); + continue; + default: + return JBG_EMARKER; + } + while (s->buf_len < required_length && *cnt < len) + s->buffer[s->buf_len++] = data[(*cnt)++]; + if (s->buf_len < required_length) continue; + /* now the buffer is filled with exactly one marker segment */ + switch (s->buffer[1]) { + case MARKER_COMMENT: + s->comment_skip = + (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) | + ((long) s->buffer[4] << 8) | (long) s->buffer[5]); + break; + case MARKER_ATMOVE: + if (s->at_moves < JBG_ATMOVES_MAX) { + s->at_line[s->at_moves] = + (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) | + ((long) s->buffer[4] << 8) | (long) s->buffer[5]); + s->at_tx[s->at_moves] = (signed char) s->buffer[6]; + s->at_ty[s->at_moves] = s->buffer[7]; + if (s->at_tx[s->at_moves] < - (int) s->mx || + s->at_tx[s->at_moves] > (int) s->mx || + s->at_ty[s->at_moves] > (int) s->my || + (s->at_ty[s->at_moves] == 0 && s->at_tx[s->at_moves] < 0)) + return JBG_EINVAL; + if (s->at_ty[s->at_moves] != 0) + return JBG_EIMPL; + s->at_moves++; + } else + return JBG_EIMPL; + break; + case MARKER_NEWLEN: + y = (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) | + ((long) s->buffer[4] << 8) | (long) s->buffer[5]); + if (y > s->yd || !(s->options & JBG_VLENGTH)) + return JBG_EINVAL; + s->yd = y; + /* calculate again number of stripes that will be required */ + s->stripes = jbg_stripes(s->l0, s->yd, s->d); + break; + case MARKER_ABORT: + return JBG_EABORT; + + case MARKER_SDNORM: + case MARKER_SDRST: + /* decode final pixels based on trailing zero bytes */ + decode_pscd(s, s->buffer, 2); + + arith_decode_init(s->s[s->ii[iindex[s->order & 7][PLANE]]] + + s->ii[iindex[s->order & 7][LAYER]] - s->dl, + s->ii[iindex[s->order & 7][STRIPE]] != s->stripes - 1 + && s->buffer[1] != MARKER_SDRST); + + s->reset[s->ii[iindex[s->order & 7][PLANE]]] + [s->ii[iindex[s->order & 7][LAYER]] - s->dl] = + (s->buffer[1] == MARKER_SDRST); + + /* prepare for next SDE */ + s->x = 0; + s->i = 0; + s->pseudo = 1; + s->at_moves = 0; + + /* increment layer/stripe/plane loop variables */ + /* start and end value for each loop: */ + is[iindex[s->order & 7][STRIPE]] = 0; + ie[iindex[s->order & 7][STRIPE]] = s->stripes - 1; + is[iindex[s->order & 7][LAYER]] = s->dl; + ie[iindex[s->order & 7][LAYER]] = s->d; + is[iindex[s->order & 7][PLANE]] = 0; + ie[iindex[s->order & 7][PLANE]] = s->planes - 1; + i = 2; /* index to innermost loop */ + do { + j = 0; /* carry flag */ + if (++s->ii[i] > ie[i]) { + /* handling overflow of loop variable */ + j = 1; + if (i > 0) + s->ii[i] = is[i]; + } + } while (--i >= 0 && j); + + s->buf_len = 0; + + /* check whether this have been all SDEs */ + if (j) { +#ifdef DEBUG + fprintf(stderr, "This was the final SDE in this BIE, " + "%d bytes left.\n", len - *cnt); +#endif + s->bie_len = 0; + return JBG_EOK; + } + + /* check whether we have to abort because of xmax/ymax */ + if (iindex[s->order & 7][LAYER] == 0 && i < 0) { + /* LAYER is the outermost loop and we have just gone to next layer */ + if (jbg_ceil_half(s->xd, s->d - s->ii[0]) > s->xmax || + jbg_ceil_half(s->yd, s->d - s->ii[0]) > s->ymax) { + s->xmax = 4294967295UL; + s->ymax = 4294967295UL; + return JBG_EOK_INTR; + } + if (s->ii[0] > (unsigned long) s->dmax) { + s->dmax = 256; + return JBG_EOK_INTR; + } + } + + break; + } + s->buf_len = 0; + + } else if (data[*cnt] == MARKER_ESC) + s->buffer[s->buf_len++] = data[(*cnt)++]; + + else { + + /* we have found PSCD bytes */ + *cnt += decode_pscd(s, data + *cnt, len - *cnt); + if (*cnt < len && data[*cnt] != 0xff) { +#ifdef DEBUG + fprintf(stderr, "PSCD was longer than expected, unread bytes " + "%02x %02x %02x %02x ...\n", data[*cnt], data[*cnt+1], + data[*cnt+2], data[*cnt+3]); +#endif + return JBG_EINVAL; + } + + } + } /* of BID processing loop 'while (*cnt < len) ...' */ + + return JBG_EAGAIN; +} + + +/* + * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this + * function in order to find out the width of the image. + */ +long jbg_dec_getwidth(const struct jbg_dec_state *s) +{ + if (s->d < 0) + return -1; + if (iindex[s->order & 7][LAYER] == 0) { + if (s->ii[0] < 1) + return -1; + else + return jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1)); + } + + return s->xd; +} + + +/* + * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this + * function in order to find out the height of the image. + */ +long jbg_dec_getheight(const struct jbg_dec_state *s) +{ + if (s->d < 0) + return -1; + if (iindex[s->order & 7][LAYER] == 0) { + if (s->ii[0] < 1) + return -1; + else + return jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1)); + } + + return s->yd; +} + + +/* + * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this + * function in order to get a pointer to the image. + */ +unsigned char *jbg_dec_getimage(const struct jbg_dec_state *s, int plane) +{ + if (s->d < 0) + return NULL; + if (iindex[s->order & 7][LAYER] == 0) { + if (s->ii[0] < 1) + return NULL; + else + return s->lhp[(s->ii[0] - 1) & 1][plane]; + } + + return s->lhp[s->d & 1][plane]; +} + + +/* + * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call + * this function in order to find out the size in bytes of one + * bitplane of the image. + */ +long jbg_dec_getsize(const struct jbg_dec_state *s) +{ + if (s->d < 0) + return -1; + if (iindex[s->order & 7][LAYER] == 0) { + if (s->ii[0] < 1) + return -1; + else + return + jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1) + 3) * + jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1)); + } + + return jbg_ceil_half(s->xd, 3) * s->yd; +} + + +/* + * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call + * this function in order to find out the size of the image that you + * can retrieve with jbg_merge_planes(). + */ +long jbg_dec_getsize_merged(const struct jbg_dec_state *s) +{ + if (s->d < 0) + return -1; + if (iindex[s->order & 7][LAYER] == 0) { + if (s->ii[0] < 1) + return -1; + else + return + jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1)) * + jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1)) * + ((s->planes + 7) / 8); + } + + return s->xd * s->yd * ((s->planes + 7) / 8); +} + + +/* + * The destructor function which releases any resources obtained by the + * other decoder functions. + */ +void jbg_dec_free(struct jbg_dec_state *s) +{ + int i; + extern char jbg_dptable[]; + + if (s->d < 0 || s->s == NULL) + return; + s->d = -2; + + for (i = 0; i < s->planes; i++) { + checked_free(s->s[i]); + checked_free(s->tx[i]); + checked_free(s->ty[i]); + checked_free(s->reset[i]); + checked_free(s->lntp[i]); + checked_free(s->lhp[0][i]); + checked_free(s->lhp[1][i]); + } + + checked_free(s->s); + checked_free(s->tx); + checked_free(s->ty); + checked_free(s->reset); + checked_free(s->lntp); + checked_free(s->lhp[0]); + checked_free(s->lhp[1]); + if (s->dppriv && s->dppriv != jbg_dptable) + checked_free(s->dppriv); + + s->s = NULL; + + return; +} + + +/* + * Split bigendian integer pixel field into separate bit planes. In the + * src array, every pixel is represented by a ((has_planes + 7) / 8) byte + * long word, most significant byte first. While has_planes describes + * the number of used bits per pixel in the source image, encode_plane + * is the number of most significant bits among those that we + * actually transfer to dest. + */ +void jbg_split_planes(unsigned long x, unsigned long y, int has_planes, + int encode_planes, + const unsigned char *src, unsigned char **dest, + int use_graycode) +{ + unsigned long bpl = jbg_ceil_half(x, 3); /* bytes per line in dest plane */ + unsigned long line, i; + unsigned k = 8; + int p; + unsigned prev; /* previous *src byte shifted by 8 bit to the left */ + register int bits, msb = has_planes - 1; + int bitno; + + /* sanity checks */ + if (encode_planes > has_planes) + encode_planes = has_planes; + use_graycode = use_graycode != 0 && encode_planes > 1; + + for (p = 0; p < encode_planes; p++) + memset(dest[p], 0, bpl * y); + + for (line = 0; line < y; line++) { /* lines loop */ + for (i = 0; i * 8 < x; i++) { /* dest bytes loop */ + for (k = 0; k < 8 && i * 8 + k < x; k++) { /* pixel loop */ + prev = 0; + for (p = 0; p < encode_planes; p++) { /* bit planes loop */ + /* calculate which bit in *src do we want */ + bitno = (msb - p) & 7; + /* put this bit with its left neighbor right adjusted into bits */ + bits = (prev | *src) >> bitno; + /* go to next *src byte, but keep old */ + if (bitno == 0) + prev = *src++ << 8; + /* make space for inserting new bit */ + dest[p][bpl * line + i] <<= 1; + /* insert bit, if requested apply Gray encoding */ + dest[p][bpl * line + i] |= (bits ^ (use_graycode & (bits>>1))) & 1; + /* + * Theorem: Let b(n),...,b(1),b(0) be the digits of a + * binary word and let g(n),...,g(1),g(0) be the digits of the + * corresponding Gray code word, then g(i) = b(i) xor b(i+1). + */ + } + /* skip unused *src bytes */ + for (;p < has_planes; p++) + if (((msb - p) & 7) == 0) + src++; + } + } + for (p = 0; p < encode_planes; p++) /* right padding loop */ + dest[p][bpl * (line + 1) - 1] <<= 8 - k; + } + + return; +} + +/* + * Merge the separate bit planes decoded by the JBIG decoder into an + * integer pixel field. This is essentially the counterpart to + * jbg_split_planes(). + */ +void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode, + void (*data_out)(unsigned char *start, size_t len, + void *file), void *file) +{ +#define BUFLEN 4096 + int bpp; + unsigned long bpl, line, i; + unsigned k = 8; + int p; + unsigned char buf[BUFLEN]; + unsigned char *bp = buf; + unsigned char **src; + unsigned long x, y; + unsigned v; + + /* sanity check */ + use_graycode = use_graycode != 0; + + x = jbg_dec_getwidth(s); + y = jbg_dec_getheight(s); + if (x <= 0 || y <= 0) + return; + bpp = (s->planes + 7) / 8; /* bytes per pixel in dest image */ + bpl = jbg_ceil_half(x, 3); /* bytes per line in src plane */ + + if (iindex[s->order & 7][LAYER] == 0) + if (s->ii[0] < 1) + return; + else + src = s->lhp[(s->ii[0] - 1) & 1]; + else + src = s->lhp[s->d & 1]; + + for (line = 0; line < y; line++) { /* lines loop */ + for (i = 0; i * 8 < x; i++) { /* src bytes loop */ + for (k = 0; k < 8 && i * 8 + k < x; k++) { /* pixel loop */ + v = 0; + for (p = 0; p < s->planes;) { /* dest bytes loop */ + do { + v = (v << 1) | + (((src[p][bpl * line + i] >> (7 - k)) & 1) ^ + (use_graycode & v)); + } while ((s->planes - ++p) & 7); + *bp++ = v; + if (bp - buf == BUFLEN) { + data_out(buf, BUFLEN, file); + bp = buf; + } + } + } + } + } + + if (bp - buf > 0) + data_out(buf, bp - buf, file); + + return; +} + + +/* + * Given a pointer p to the first byte of either a marker segment or a + * PSCD, as well as the length len of the remaining data, return + * either the pointer to the first byte of the next marker segment or + * PSCD, or p+len if this was the last one, or NULL if some error was + * encountered. + */ +unsigned char *jbg_next_pscdms(unsigned char *p, size_t len) +{ + unsigned char *pp; + unsigned long l; + + if (len < 2) + return NULL; + + if (p[0] != MARKER_ESC || p[1] == MARKER_STUFF) { + do { + while (p[0] == MARKER_ESC && p[1] == MARKER_STUFF) { + p += 2; + len -= 2; + if (len < 2) return NULL; + } + pp = (unsigned char *) memchr(p, MARKER_ESC, len - 1); + if (!pp) return NULL; + l = pp - p; + assert(l < len); + p += l; + len -= l; + } while (p[1] == MARKER_STUFF); + } else { + switch (p[1]) { + case MARKER_SDNORM: + case MARKER_SDRST: + case MARKER_ABORT: + return p + 2; + case MARKER_NEWLEN: + if (len < 6) return NULL; + return p + 6; + case MARKER_ATMOVE: + if (len < 8) return NULL; + return p + 8; + case MARKER_COMMENT: + if (len < 6) return NULL; + l = (((long) p[2] << 24) | ((long) p[3] << 16) | + ((long) p[4] << 8) | (long) p[5]); + if (len - 6 < l) return NULL; + return p + 6 + l; + default: + return NULL; + } + } + + return p; +} + + +/* + * Scan a complete BIE for a NEWLEN marker segment, then read the new + * YD value found in it and use it to overwrite the one in the BIE + * header. Use this procedure if a BIE initially declares an + * unreasonably high provisional YD value (e.g., 0xffffffff) or + * depends on the fact that section 6.2.6.2 of ITU-T T.82 says that a + * NEWLEN marker segment "could refer to a line in the immediately + * preceding stripe due to an unexpected termination of the image or + * the use of only such stripe". ITU-T.85 explicitely suggests the + * use of this for fax machines that start transmission before having + * encountered the end of the page. None of this is necessary for + * BIEs produced by JBIG-KIT, which normally does not use NEWLEN. + */ +int jbg_newlen(unsigned char *bie, size_t len) +{ + unsigned char *p = bie + 20; + int i; + + if (len < 20) + return JBG_EAGAIN; + if ((bie[19] & (JBG_DPON | JBG_DPPRIV | JBG_DPLAST)) + == (JBG_DPON | JBG_DPPRIV)) + p += 1728; /* skip DPTABLE */ + if (p >= bie + len) + return JBG_EAGAIN; + + while ((p = jbg_next_pscdms(p, len - (p - bie)))) { + if (p == bie + len) + return JBG_EOK; + else if (p[0] == MARKER_ESC) + switch (p[1]) { + case MARKER_NEWLEN: + /* overwrite YD in BIH with YD from NEWLEN */ + for (i = 0; i < 4; i++) { + bie[8+i] = p[2+i]; + } + return JBG_EOK; + case MARKER_ABORT: + return JBG_EABORT; + } + } + return JBG_EINVAL; +} diff --git a/SlnkDWFImpl/CxImage/jbig/jbig.doc b/SlnkDWFImpl/CxImage/jbig/jbig.doc new file mode 100644 index 0000000..81a03ec --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/jbig.doc @@ -0,0 +1,778 @@ + +Using the JBIG-KIT library +-------------------------- + +Markus Kuhn -- 2004-06-10 + + +This text explains how to use the functions provided by the JBIG-KIT +portable image compression library in your application software. + + +1 Introduction to JBIG + +We start with a short introduction to JBIG1. More detailed information +is provided in the "Introduction and overview" section of the JBIG1 +standard. Information on how to obtain a copy of the standard is +available from or . + +Image data encoded with the JBIG algorithm is separated into planes, +layers, and stripes. Each plane contains one bit per pixel. The number +of planes stored in a JBIG data stream is the number of bits per +pixel. Resolution layers are numbered from 0 to D with 0 being the +layer with the lowest resolution and D the one with the highest. Each +next higher resolution layer has twice the number of rows and columns. +Layer 0 is encoded independently of any other data, all other +resolution layers are encoded as only the difference between the next +lower and the current layer. For applications that require very quick +access to parts of an image, it is possible to divide an image into +several horizontal stripes. All stripes of one resolution layer have +equal size, except perhaps the final one. The number of stripes of an +image is equal in all resolution layers and in all bit planes. + +The compressed data stream specified by the JBIG standard is called a +bi-level image entity (BIE). A BIE consists of a 20-byte header, +followed by an optional 1728-byte table (usually not present, except +in special applications) followed by a sequence of stripe data +entities (SDE). Each SDE encodes the content of one single stripe in +one plane of one resolution layer. Between the SDEs, other information +blocks (called floating marker segments) can also be present. They are +used to change certain parameters of the algorithm in the middle of an +image or contain additional application specific information. A BIE +looks like this: + + + +------------------------------------------------+ + | | + | 20-byte header (with image size, #planes, | + | #layers, stripe size, first layer, options, | + | SDE ordering, ...) | + | | + +------------------------------------------------+ + | | + | optional 1728-byte table | + | | + +------------------------------------------------+ + | | + | optional floating marker segments | + | | + +------------------------------------------------+ + | | + | stripe data entity | + | | + +------------------------------------------------+ + | | + | optional floating marker segments | + | | + +------------------------------------------------+ + | | + | stripe data entity | + | | + +------------------------------------------------+ + ... + +------------------------------------------------+ + | | + | stripe data entity | + | | + +------------------------------------------------+ + + +One BIE can contain all resolution layers of an image, but it is also +possible to store various resolution layers in several BIEs. The BIE +header contains the number of the first and the last resolution layer +stored in this BIE, as well as the size of the highest resolution +layer stored in this BIE. Progressive coding is deactivated by simply +storing the image in one single resolution layer. + +Different applications might have different requirements for the order +in which the SDEs for stripes of various planes and layers are stored +in the BIE, so all possible sensible orderings are allowed by the +standard and indicated by four bits in the header. + +It is possible to use the raw BIE data stream as specified by the JBIG +standard directly as the format of a file used for storing images. +This is what the pbmtojbg and jbgtopbm conversion tools do that are +provided in this package as demonstration applications. However, as +the BIE format has been designed for a large number of very different +applications, and to allow efficient direct processing by special JBIG +hardware chip implementations, the BIE header contains only the +minimum amount of information absolutely required by the decompression +algorithm. Many features expected from a good file format are missing +in the BIE data stream: + + - no "magic code" in the first few bytes to allow identification + of the file format on a typeless file system and to allow + automatic distinction from other compression algorithms + + - no standardized way to encode additional information such as a + textual description, information about the meaning of various bit + planes, the physical size and resolution of the document, etc. + + - a checksum to ensure image integrity + + - encryption and signature mechanisms + + - many things more + +Raw BIE data streams alone may therefore not be a suitable format for +document archiving and exchange. A standard format for this purpose +would typically combine a BIE representing the image data with an +additional header providing auxiliary information into one file. +Existing established multi-purpose file formats with a rich set of +auxiliary information attributes like TIFF could be extended easily to +also hold JBIG compressed data. + +On the other hand, in database applications for instance, a BIE might +be stored directly in a variable length field. Auxiliary information +would then be stored in other fields of the same record, to simply +search operations. + + +2 Compressing an image + +2.1 Format of the source image + +To be processed by the JBIG-KIT encoder, the image has to be present +in memory as separate bitmap planes. Each byte of a bitmap contains +eight pixels, where the most significant bit represents the leftmost +of these. Each line of a bitmap has to be stored in an integral number +of bytes. If the image width is not an integral multiple of eight, +then the final byte has to be padded with zero bits. + +For example the 23x5 pixels large single plane image: + + .XXXXX..XXX...X...XXX.. + .....X..X..X..X..X..... + .....X..XXX...X..X.XXX. + .X...X..X..X..X..X...X. + ..XXX...XXX...X...XXX.. + +is represented by the 15 bytes + + 01111100 11100010 00111000 + 00000100 10010010 01000000 + 00000100 11100010 01011100 + 01000100 10010010 01000100 + 00111000 11100010 00111000 + +or in hexadecimal notation + + 7c e2 38 04 92 40 04 e2 5c 44 92 44 38 e2 38 + +This is the format used in binary PBM files and it can also be handled +directly by the Xlib library of the X Window System. + +As JBIG can also handle images with multiple bit planes, the JBIG-KIT +library functions accept and return always arrays of pointers to +bitmaps with one pointer per plane. + +For single-plane images, the standard recommends that a 0 pixel +represents the background and a 1 pixel represents the foreground +color of an image, in other words, 0 is white and 1 is black for +scanned paper documents. For images with several bits per pixel, the +JBIG standard makes no recommendations about how various colors should +be encoded. + +For greyscale images, by using a Gray code instead of a simple binary +weighted representation of the pixel intensity, some increase in +coding efficiency can be reached. + +A Gray code is also a binary representation of integer numbers, but it +has the property that the representations of the integer numbers i and +(i+1) always differ in exactly one bit. For example, the numbers 0 to +7 can be represented in normal binary code and Gray code as in the +following table: + + normal + number binary code Gray code + --------------------------------------- + 0 000 000 + 1 001 001 + 2 010 011 + 3 011 010 + 4 100 110 + 5 101 111 + 6 110 101 + 7 111 100 + +The form of Gray code shown above has the property that the second +half of the code (numbers 4 - 7) is simply the mirrored first half +(numbers 3 - 0) with the first bit set to one. This way, arbitrarily +large Gray codes can be generated quickly by mirroring the above +example and prefixing the first half with zeros and the second half +with ones as often as required. In greyscale images, it is common +practise to use the all-0 code for black and the all-1 code for white. + +No matter whether a Gray code or a binary code is used for encoding a +pixel intensity in several bit planes, it always makes sense to store +the most significant (leftmost) bit in plane 0, which is transmitted +first. This way, a decoder could increase the precision of the +displayed pixel intensities while data is still being received and the +basic structure of the image will become visible as early as possible +during the transmission. + + +2.2 A simple compression application + +In order to use JBIG-KIT in your application, just link libjbig.a to +your executable (on Unix systems just add -ljbig and -L. to the +command line options of your compiler, on other systems you will have +to write a new Makefile anyway), copy the file jbig.h into your source +directory and put the line + + #include "jbig.h" + +into your source code. + +The library interface follows object-oriented programming principles. +You have to declare a variable (object) + + struct jbg_enc_state se; + +which contains the current status of an encoder. Then you initialize +the encoder by calling the constructor function + + void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y, + int pl, unsigned char **p, + void (*data_out)(unsigned char *start, size_t len, + void *file), + void *file); + +The parameters have the following meaning: + + s A pointer to the jbg_enc_state structure which you want + to initialize. + + x The width of your image. + + y The height of your image. + + pl the number of bitmap planes you want to encode. + + p A pointer to an array of pl pointers, where each is again + pointing to the first byte of a bitmap as described in + section 2.1. + + data_out This is a call-back function which will be called during + the compression process by libjbig in order to deliver + the BIE data to the application. The parameters of the + function data_out are a pointer start to the new block + of data to be delivered, as well as the number len of + delivered bytes. The pointer file is transparently + delivered to data_out, as specified in jbg_enc_init(). + Typically, data_out will write the BIE portion to a + file, send it to a network connection, or append it to + some memory buffer. + + file A pointer parameter that is passed on to data_out() + and can be used, for instance, to allow data_out() to + distinguish by which compression task it has been + called in multi-threaded applications. + +In the simplest case, the compression is then started by calling the +function + + void jbg_enc_out(struct jbg_enc_state *s); + +which will deliver the complete BIE to data_out() in several calls. +After jbg_enc_out has returned, a call to the destructor function + + void jbg_enc_free(struct jbg_enc_state *s); + +will release any heap memory allocated by the previous functions. + + +A minimal example application which sends the BIE of the above +bitmap to stdout looks like this: + +--------------------------------------------------------------------------- +/* A sample JBIG encoding application */ + +#include +#include "jbig.h" + +void output_bie(unsigned char *start, size_t len, void *file) +{ + fwrite(start, 1, len, (FILE *) file); + + return; +} + +int main() +{ + unsigned char bitmap[15] = { + /* 23 x 5 pixels, "JBIG" */ + 0x7c, 0xe2, 0x38, 0x04, 0x92, 0x40, 0x04, 0xe2, + 0x5c, 0x44, 0x92, 0x44, 0x38, 0xe2, 0x38 + }; + unsigned char *bitmaps[1] = { bitmap }; + struct jbg_enc_state se; + + jbg_enc_init(&se, 23, 5, 1, bitmaps, + output_bie, stdout); /* initialize encoder */ + jbg_enc_out(&se); /* encode image */ + jbg_enc_free(&se); /* release allocated resources */ + + return 0; +} +--------------------------------------------------------------------------- + +This software produces a 42 byte long BIE. (JBIG is not very good at +compressing extremely small images like in this example, because the +arithmetic encoder requires some startup data in order to generate +reasonable statistics which influence the compression process and +because there is some header overhead.) + + +2.3 More about compression + +If jbg_enc_out() is called directly after jbg_enc_init(), the +following default values are used for various compression parameters: + + - Only one single resolution layer is used, i.e. no progressive + mode. + + - The number of lines per stripe is selected so that approximately + 35 stripes per image are used (as recommended in annex C of the + standard together with the suggested adaptive template change + algorithm). However, not less than 2 and not more than 128 lines + are used in order to stay within the suggested minimum parameter + support range specified in annex A of the standard). + + - All optional parts of the JBIG algorithm are activated (TPBON, + TPDON and DPON). + + - The default resolution reduction table and the default deterministic + prediction table are used + + - The maximal vertical offset of the adaptive template pixel is 0 + and the maximal horizontal offset is 8 (mx = 8, my = 0). + +In order to change any of these default parameters, additional +functions have to be called between jbg_enc_init() and jbg_enc_out(). + +In order to activate progressive encoding, it is possible to specify +with + + void jbg_enc_layers(struct jbg_enc_state *s, int d); + +the number d of differential resolution layers which shall be encoded +in addition to the lowest resolution layer 0. For example, if a +document with 60-micrometer pixels has to be stored, and the lowest +resolution layer shall have 240-micrometer pixels, so that a screen +previewer can directly decompress only the required resolution, then a +call + + jbg_enc_layers(&se, 2); + +will cause three layers with 240, 120 and 60 micrometers resolution to +be generated. + +If the application does not know what typical resolutions are used and +simply wants to ensure that the lowest resolution layer will fit into +a given maximal window size, then as an alternative, a call to + + int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long mwidth, + unsigned long mheight); + +will cause the library to automatically determine the suitable number +of resolutions so that the lowest resolution layer 0 will not be +larger than mwidth x mheight pixels. E.g. if one wants to ensure that +systems with a 640 x 480 pixel large screen can decode the required +resolution directly, then call + + jbg_enc_lrlmax(&se, 640, 480); + +The return value is the number of differential layers selected. + +After the number of resolution layers has been specified by calls to +jbg_enc_layers() or jbg_enc_lrlmax(), by default, all these layers +will be written into the BIE. This can be changed with a call to + + int jbg_enc_lrange(struct jbg_enc_state *s, int dl, int dh); + +Parameter dl specifies the lowest resolution layer and dh the highest +resolution layer that will appear in the BIE. For instance, if layer 0 +shall be written to the first BIE and layer 1 and 2 shall be written +to a second one, then before writing the first BIE, call + + jbg_enc_lrange(&se, 0, 0); + +and before writing the second BIE with jbg_enc_out(), call + + jbg_enc_lrange(&se, 1, 2); + +If any of the parameters is negative, it will be ignored. The return +value is the total number of differential layers that will represent +the input image. This way, jbg_enc_lrange(&se, -1, -1) can be used to +query the layer of the full image resolution. + +A number of other more exotic options of the JBIG algorithm can be +modified by calling + + void jbg_enc_options(struct jbg_enc_state *s, int order, int options, + long l0, int mx, int my); + +before calling jbg_enc_out(). + +The order parameter can be a combination of the bits JBG_HITOLO, +JBG_SEQ, JBG_ILEAVE and JBG_SMID and it determines in which order +the SDEs are stored in the BIE. The bits have the following meaning: + + JBG_HITOLO Usually, the lower resolution layers are stored before + the higher resolution layers, so that a decoder can + already start to display a low resolution version of + the full image once a prefix of the BIE has been + received. When this bit is set, however, the BIE will + contain the higher layers before the lower layers. This + avoids additional buffer memory in the encoder and is + intended for applications where the encoder is connected + to a database which can easily reorder the SDEs before + sending them to a decoder. Warning: JBIG decoders are + not expected to support the HITOLO option (e.g. the + JBIG-KIT decoder currently does not) so you should + normally not use it. + + JBG_SEQ Usually, at first all stripes of one resolution layer + are written to the BIE and then all stripes of the next + layer, and so on. When the SEQ bit is set however, then + all layers of the first stripe will be written, + followed by all layers of the second stripe, etc. This + option also should normally never be required and is + not supported by the current JBIG-KIT decoder. + + JBG_SMID In case there exist several bit planes, then the order of + the stripes is determined by three loops over all stripes, + all planes and all layers. When SMID is set, the loop + over all stripes is the middle loop. + + JBG_ILEAVE If this bit is set, then at first all layers of one + plane are written before the encoder starts with the next + plane. + +The above description may be somewhat confusing, but the following +table (see also Table 11 in ITU-T T.82) clarifies how the three bits +JBG_SEQ, JBIG_ILEAVE and JBG_SMID influence the ordering of the loops +over all stripes, planes and layers: + + + Loops: + JBG_SEQ JBG_ILEAVE JBG_SMID | Outer Middle Inner + ------------------------------------+--------------------------- + 0 0 0 | p d s + 0 1 0 | d p s + 0 1 1 | d s p + 1 0 0 | s p d + 1 0 1 | p s d + 1 1 0 | s d p + + p: plane, s: stripe, d: layer + + +By default, the order combination JBG_ILEAVE | JBG_SMID is used. + +The options value can contain the following bits, which activate +some of the optional algorithms defined by JBIG: + + JBG_LRLTWO Normally, in the lowest resolution layer, pixels + from three lines around the next pixel are used + in order to determine the context in which the next + pixel is encoded. Some people in the JBIG committee + seem to have argued that using only 2 lines will + make software implementations a little bit faster, + however others have argued that using only two lines + will decrease compression efficiency by around 5%. + As you might expect from a committee, now both + alternatives are allowed and if JBG_LRLTWO is set, + the slightly faster but 5% less well compressing two + line alternative is selected. God bless the committees. + Although probably nobody will ever need this option, + it has been implemented in JBIG-KIT and is off by + default. + + JBG_TPDON This activates the "typical prediction" algorithm + for differential layers which avoids that large + areas of equal color have to be encoded at all. + This is on by default and there is no good reason to + switch it off except for debugging or preparing data + for cheap JBIG hardware that might not support this + option. + + JBG_TPBON Like JBG_TPDON this activates the "typical prediction" + algorithm in the lowest resolution layer. Also activated + by default. + + JBG_DPON This bit activates for the differential resolution + layers the "deterministic prediction" algorithm, + which avoids that higher resolution layer pixels are + encoded when their value can already be determined + with the knowledge of the neighbor pixels, the + corresponding lower resolution pixels and the + resolution reduction algorithm. This is also + activated by default and one reason for deactivating + it would be if the default resolution reduction + algorithm were replaced by another one. + + JBG_DELAY_AT Use a slightly less efficient algorithm to determine + when an adaptive template change is necessary. With + this bit set, the encoder output is compatible to the + conformance test examples in cause 7.2 of ITU-T T.82. + Then all adaptive template changes are delayed until + the first line of the next stripe. This option is by + default deactivated and is only required for passing a + special compatibility test suite. + +In addition, parameter l0 in jbg_enc_options() allows you to specify +the number of lines per stripe in resolution layer 0. The parameters +mx and my change the maximal offset allowed for the adaptive template +pixel. JBIG-KIT now supports the full range of possible mx values up +to 127 in the encoder and decoder, but my is at the moment ignored and +always set to 0. As the standard requires of all decoder +implementations only to support maximum values mx = 16 and my = 0, +higher values should normally be avoided in order to guarantee +interoperability. The ITU-T T.85 profile for JBIG in fax machines +requires support for mx = 127 and my = 0. Default is mx = 8 and my = +0. If any of the parameters order, options, mx or my is negative, or +l0 is zero, then the corresponding current value remains unmodified. + +The resolution reduction and deterministic prediction tables can also +be replaced. However as these options are anyway only for experts, +please have a look at the source code of jbg_enc_out() and the struct +members dppriv and res_tab of struct jbg_enc_state for the details of +how to do this, in case you really need it. The functions +jbg_int2dppriv and jbg_dppriv2int are provided in order to convert the +DPTABLE data from the format used in the standard into the more +efficient format used internally by JBIG-KIT. + +If you want to encode a greyscale image, you can use the library +function + + void jbg_split_planes(unsigned long x, unsigned long y, int has_planes, + int encode_planes, + const unsigned char *src, unsigned char **dest, + int use_graycode); + +It separates an image in which each pixel is represented by one or +more bytes into separate bit planes. The dest array of pointers to +these bit planes can then be handed over to jbg_enc_init(). The +variables x and y specify the width and height of the image in pixels, +and has_planes specifies how many bits per pixel are used. As each +pixel is represented by an integral number of consecutive bytes, of +which each contains up to eight bits, the total length of the input +image array src[] will therefore be x * y * ((has_planes + 7) / 8) +bytes. The pixels are stored as usually in English reading order, and +for each pixel the integer value is stored with the most significant +byte coming first (Bigendian). This is exactly the format used in raw +PGM files. In encode_planes, the number of bit planes that shall be +extracted can be specified. This allows for instance to extract only +the most significant 8 bits of a 12-bit image, where each pixel is +represented by two bytes, by specifying has_planes = 12 and +encode_planes = 8. If use_graycode is zero, then the binary code of +the pixel integer values will be used instead of the Gray code. Plane +0 contains always the most significant bit. + + +3 Decompressing an image + +Like with the compression functions, if you want to use the JBIG-KIT +library, you have to put the line + + #include "jbig.h" + +into your source code and link your executable with libjbig.a. + +The state of a JBIG decoder is stored completely in a struct and you +will have to define a variable like + + struct jbg_dec_state sd; + +which is initialized by a call to + + void jbg_dec_init(struct jbg_dec_state *s); + +After this, you can directly start to pass data from the BIE to the decoder +by calling the function + + int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len, + size_t *cnt); + +The pointer data points to the first byte of a data block with length +len, which contains bytes from a BIE. It is not necessary to pass a +whole BIE at once to jbg_dec_in(), it can arrive fragmented in any way +by calling jbg_dec_in() several times. It is also possible to send +several BIEs concatenated to jbg_dec_in(), however these then have to +fit together. If you send several BIEs to the decoder, the lowest +resolution layer in each following BIE has to be the highest +resolution layer in the previous BIE plus one and the image sizes and +number of planes also have to fit together, otherwise jbg_dec_in() +will return the error JBG_ENOCONT after the header of the new BIE has +been received completely. + +If pointer cnt is not NULL, then the number of bytes actually read +from the data block is stored there. In case the data block did not +contain the end of the BIE, then the value JBG_EAGAIN will be returned +and *cnt equals len. + +Once the end of a BIE has been reached, the return value of +jbg_dec_in() will be JBG_EOK. After this has happened, the functions +and macros + + long jbg_dec_getwidth(struct jbg_dec_state *s); + long jbg_dec_getheight(struct jbg_dec_state *s); + int jbg_dec_getplanes(struct jbg_dec_state *s); + unsigned char *jbg_dec_getimage(struct jbg_dec_state *s, int plane); + long jbg_dec_getsize(struct jbg_dec_state *s); + +can be used to query the dimensions of the now completely decoded +image and to get a pointer to all bitmap planes. The bitmaps are +stored as described in section 2.1. The function jbg_dec_getsize() +calculates the number of bytes which one bitmap requires. + +The function + + void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode, + void (*data_out)(unsigned char *start, size_t len, + void *file), void *file); + +allows you to merge the bit planes that can be accessed individually +with jbg_dec_getimage() into an array with one or more bytes per pixel +(i.e., the format provided to jbg_split_planes()). If use_graycode is +zero, then a binary encoding will be used. The output array will be +delivered via the callback function data_out, exactly in the same way +in which the encoder provides the BIE. The function + + long jbg_dec_getsize_merged(const struct jbg_dec_state *s); + +determines how long the data array delivered by jbg_dec_merge_planes() +is going to be. + +Before calling jbg_dec_in() the first time, it is possible to specify with +a call to + + void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax, + unsigned long ymax); + +an abort criterion for progressively encoded images. For instance if an +application will display a whole document on a screen which is 1024 x +768 pixels large, then this application should call + + jbg_dec_maxsize(&sd, 1024, 768); + +before the decoding process starts. If the image has been encoded in +progressive mode (i.e. with several resolution layers), then the +decoder will stop with a return value JBG_EOK_INTR after the largest +resolution layer that is still smaller than 1024 x 768. However this +is no guarantee that the image which can then be read out using +jbg_dec_getimage(), etc. is really not larger than the specified +maximal size. The application will have to check the size of the +image, because the decoder does not automatically apply a resolution +reduction if no suitable resolution layer is available in the BIE. + +If jbg_dec_in() returned JBG_EOK_INTR or JBG_EOK, then it is possible +to continue calling jbg_dec_in() with the remaining data in order to +either decode the remaining resolution layers of the current BIE or in +order to add another BIE with additional resolution layers. In both +cases, after jbg_dec_in() returned JBG_EOK_INTR or JBG_EOK, *cnt is +probably not equal to len and the remainder of the data block which +has not yet been processed by the decoder has to be delivered to +jbg_dec_in() again. + +If any other return value than JBG_EOK, JBG_EOK_INTR or JBG_EAGAIN +has been returned by jbg_dec_in(), then an error has occurred and + + void jbg_dec_free(struct jbg_dec_state *s); + +should be called in order to release any allocated memory. The +destructor jbg_dec_free() should of course also be called, once the +decoded bitmap returned by jbg_dec_getimage() is no longer required +and the memory can be released. + +The function + + const char *jbg_strerror(int errnum, int language); + +returns a pointer to a short single line test message which explains +the return value of jbg_dec_in(). This message can be used in order to +provide the user a brief informative message about what when wrong +while decompressing the JBIG image. The error messages are available +in several languages and in several character sets. Currently +supported are the following values for the language parameter: + + JBG_EN English messages in ASCII + JBG_DE_8859_1 German messages in ISO 8859-1 Latin 1 character set + JBG_DE_UTF_8 German messages in ISO 10646/Unicode UTF-8 encoding + + +The current implementation of the JBIG-KIT decoder has the following +limitations: + + - The maximal vertical offset MY of the adaptive template pixel + must be zero. + + - HITOLO and SEQ bits must not be set in the order value. + + - Not more than JBG_ATMOVES_MAX (currently set to 64) ATMOVE + marker segments can be handled per stripe. + + - the number D of differential layers must be less than 32 + +None of the above limitations can be exceeded by a JBIG data stream +that conforms to the ITU-T T.85 application profile for the use of +JBIG1 in fax machines. + +There are two more limitations of the current implementation of the +JBIG-KIT decoder that might cause problems with processing JBIG data +stream that conform to ITU-T T.85: + + - The JBIG-KIT decoder was designed to operate incrementally. + Each received byte is processed immediately as soon as it arrives. + As a result, it does not look beyond the SDRST/SDNORM at the end + of all stripes for any immediately following NEWLEN marker that + might reduce the number of lines encoded by the current stripe. + However section 6.2.6.2 of ITU-T T.82 says that a NEWLEN marker + segment "could refer to a line in the immediately preceding stripe + due to an unexpected termination of the image or the use of only + such stripe", and ITU-T.85 explicitly suggests the use of this + for fax machines that start transmission before having encountered + the end of the page. + + - The image size initially indicated in the BIE header is used to + allocate memory for a bitmap of this size. This means that BIEs + that set initially Y_D = 0xffffffff (as suggested in ITU-T T.85 + for fax machines that do not know the height of the page at the + start of the transmission) cannot be decoded directly by this + version. + +For both issues, there is a very simple workaround: + +If you encounter a BIE that has in the header the VLENGTH=1 option bit +set, then first wait until you have received the entire BIE and stored +it in memory. Then call the function + + int jbg_newlen(unsigned char *bie, size_t len); + +where bie is a pointer to the first byte of the BIE and len its length +in bytes. This function will scan the entire BIE for the first NEWLEN +marker segment. It will then take the updated image-height value YD +from it and use it to overwrite the YD value in the BIE header. The +jbg_newlen() can return some of the same error codes as jbg_dec_in(), +namely JBG_EOK if everything went fine, JBG_EAGAIN is the data +provided is too short to be a valid BIE, JBG_EINVAL if a format error +was encountered, and JBG_EABORT if an ABORT marker segment was found. +After having patched the image-height value in the BIE using +jbg_newlen(), simply hand over the BIE as usual to jbg_dec_in(). + + +A more detailed description of the JBIG-KIT implementation is + + Markus Kuhn: Effiziente Kompression von bi-level Bilddaten durch + kontextsensitive arithmetische Codierung. Studienarbeit, Lehrstuhl + für Betriebssysteme, IMMD IV, Universität Erlangen-Nürnberg, + Erlangen, July 1995. (German, 62 pages) + + +Please quote the above if you use JBIG-KIT in your research project. + +*** Happy compressing *** + +[end] diff --git a/SlnkDWFImpl/CxImage/jbig/jbig.dsp b/SlnkDWFImpl/CxImage/jbig/jbig.dsp new file mode 100644 index 0000000..57854ba --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/jbig.dsp @@ -0,0 +1,104 @@ +# Microsoft Developer Studio Project File - Name="jbig" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=jbig - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "jbig.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "jbig.mak" CFG="jbig - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "jbig - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "jbig - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "jbig - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D "_AFXDLL" /YX /FD /c +# ADD BASE RSC /l 0x410 /d "NDEBUG" +# ADD RSC /l 0x410 /d "NDEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "jbig - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D "_AFXDLL" /YX /FD /GZ /c +# ADD BASE RSC /l 0x410 /d "_DEBUG" +# ADD RSC /l 0x410 /d "_DEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "jbig - Win32 Release" +# Name "jbig - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\jbig.c +# End Source File +# Begin Source File + +SOURCE=.\jbig_tab.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\jbig.h +# End Source File +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/jbig/jbig.dsw b/SlnkDWFImpl/CxImage/jbig/jbig.dsw new file mode 100644 index 0000000..1b0e7a3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/jbig.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "jbig"=.\jbig.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/jbig/jbig.h b/SlnkDWFImpl/CxImage/jbig/jbig.h new file mode 100644 index 0000000..c441800 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/jbig.h @@ -0,0 +1,272 @@ +/* + * Header file for the portable free JBIG compression library + * + * Markus Kuhn -- http://www.cl.cam.ac.uk/~mgk25/ + * + * $Id: jbig.h,v 1.17 2004-06-11 15:18:21+01 mgk25 Exp $ + */ + +#ifndef JBG_H +#define JBG_H + +#include + +/* + * JBIG-KIT version number + */ + +#define JBG_VERSION "1.6" + +/* + * Buffer block for SDEs which are temporarily stored by encoder + */ + +#define JBG_BUFSIZE 4000 + +struct jbg_buf { + unsigned char d[JBG_BUFSIZE]; /* one block of a buffer list */ + int len; /* length of the data in this block */ + struct jbg_buf *next; /* pointer to next block */ + struct jbg_buf *previous; /* pointer to previous block * + * (unused in freelist) */ + struct jbg_buf *last; /* only used in list head: final block of list */ + struct jbg_buf **free_list; /* pointer to pointer to head of free list */ +}; + +/* + * Maximum number of ATMOVEs per stripe that decoder can handle + */ + +#define JBG_ATMOVES_MAX 64 + +/* + * Option and order flags + */ + +#define JBG_HITOLO 0x08 +#define JBG_SEQ 0x04 +#define JBG_ILEAVE 0x02 +#define JBG_SMID 0x01 + +#define JBG_LRLTWO 0x40 +#define JBG_VLENGTH 0x20 +#define JBG_TPDON 0x10 +#define JBG_TPBON 0x08 +#define JBG_DPON 0x04 +#define JBG_DPPRIV 0x02 +#define JBG_DPLAST 0x01 + +#define JBG_DELAY_AT 0x100 /* delay ATMOVE until the first line of the next + * stripe. Option available for compatibility + * with conformance test example in clause 7.2.*/ + + +/* + * Possible error code return values + */ + +#define JBG_EOK 0 +#define JBG_EOK_INTR 1 +#define JBG_EAGAIN 2 +#define JBG_ENOMEM 3 +#define JBG_EABORT 4 +#define JBG_EMARKER 5 +#define JBG_ENOCONT 6 +#define JBG_EINVAL 7 +#define JBG_EIMPL 8 + +/* + * Language code for error message strings (based on ISO 639 2-letter + * standard language name abbreviations). + */ + +#define JBG_EN 0 /* English */ +#define JBG_DE_8859_1 1 /* German in ISO Latin 1 character set */ +#define JBG_DE_UTF_8 2 /* German in Unicode UTF-8 encoding */ + +/* + * Status description of an arithmetic encoder + */ + +struct jbg_arenc_state { + unsigned char st[4096]; /* probability status for contexts, MSB = MPS */ + unsigned long c; /* C register, base of coding intervall, * + * layout as in Table 23 */ + unsigned long a; /* A register, normalized size of coding intervall */ + long sc; /* counter for buffered 0xff values which might overflow */ + int ct; /* bit shift counter, determines when next byte will be written */ + int buffer; /* buffer for most recent output byte != 0xff */ + void (*byte_out)(int, void *); /* function which receives all PSCD bytes */ + void *file; /* parameter passed to byte_out */ +}; + + +/* + * Status description of an arithmetic decoder + */ + +enum jbg_ardec_result { + JBG_OK, /* symbol has been successfully decoded */ + JBG_READY, /* no more bytes of this PSCD required, marker * + * encountered, probably more symbols available */ + JBG_MORE, /* more PSCD data bytes required to decode a symbol */ + JBG_MARKER /* more PSCD data bytes required, ignored final 0xff byte */ +}; + +struct jbg_ardec_state { + unsigned char st[4096]; /* probability status for contexts, MSB = MPS */ + unsigned long c; /* C register, base of coding intervall, * + * layout as in Table 25 */ + unsigned long a; /* A register, normalized size of coding intervall */ + int ct; /* bit shift counter, determines when next byte will be read */ + unsigned char *pscd_ptr; /* pointer to next PSCD data byte */ + unsigned char *pscd_end; /* pointer to byte after PSCD */ + enum jbg_ardec_result result; /* result of previous decode call */ + int startup; /* controls initial fill of s->c */ +}; + +#ifdef TEST_CODEC +void arith_encode_init(struct jbg_arenc_state *s, int reuse_st); +void arith_encode_flush(struct jbg_arenc_state *s); +void arith_encode(struct jbg_arenc_state *s, int cx, int pix); +void arith_decode_init(struct jbg_ardec_state *s, int reuse_st); +int arith_decode(struct jbg_ardec_state *s, int cx); +#endif + + +/* + * Status of a JBIG encoder + */ + +struct jbg_enc_state { + int d; /* resolution layer of the input image */ + unsigned long xd, yd; /* size of the input image (resolution layer d) */ + unsigned long yd1; /* BIH announced height of image, use yd1 != yd to + emulate T.85-style NEWLEN height updates for tests */ + int planes; /* number of different bitmap planes */ + int dl; /* lowest resolution layer in the next BIE */ + int dh; /* highest resolution layer in the next BIE */ + unsigned long l0; /* number of lines per stripe at lowest * + * resolution layer 0 */ + unsigned long stripes; /* number of stripes required (determ. by l0) */ + unsigned char **lhp[2]; /* pointers to lower/higher resolution images */ + int *highres; /* index [plane] of highres image in lhp[] */ + int order; /* SDE ordering parameters */ + int options; /* encoding parameters */ + unsigned mx, my; /* maximum ATMOVE window size */ + int *tx; /* array [plane] with x-offset of adaptive template pixel */ + char *dppriv; /* optional private deterministic prediction table */ + char *res_tab; /* table for the resolution reduction algorithm */ + struct jbg_buf ****sde; /* array [stripe][layer][plane] pointers to * + * buffers for stored SDEs */ + struct jbg_arenc_state *s; /* array [planes] for arithm. encoder status */ + struct jbg_buf *free_list; /* list of currently unused SDE block buffers */ + void (*data_out)(unsigned char *start, size_t len, void *file); + /* data write callback */ + void *file; /* parameter passed to data_out() */ + char *tp; /* buffer for temp. values used by diff. typical prediction */ +}; + + +/* + * Status of a JBIG decoder + */ + +struct jbg_dec_state { + /* data from BIH */ + int d; /* resolution layer of the full image */ + int dl; /* first resolution layer in this BIE */ + unsigned long xd, yd; /* size of the full image (resolution layer d) */ + int planes; /* number of different bitmap planes */ + unsigned long l0; /* number of lines per stripe at lowest * + * resolution layer 0 */ + unsigned long stripes; /* number of stripes required (determ. by l0) */ + int order; /* SDE ordering parameters */ + int options; /* encoding parameters */ + int mx, my; /* maximum ATMOVE window size */ + char *dppriv; /* optional private deterministic prediction table */ + + /* loop variables */ + unsigned long ii[3]; /* current stripe, layer, plane (outer loop first) */ + + /* + * Pointers to array [planes] of lower/higher resolution images. + * lhp[d & 1] contains image of layer d. + */ + unsigned char **lhp[2]; + + /* status information */ + int **tx, **ty; /* array [plane][layer-dl] with x,y-offset of AT pixel */ + struct jbg_ardec_state **s; /* array [plane][layer-dl] for arithmetic * + * decoder status */ + int **reset; /* array [plane][layer-dl] remembers if previous stripe * + * in that plane/resolution ended with SDRST. */ + unsigned long bie_len; /* number of bytes read so far */ + unsigned char buffer[20]; /* used to store BIH or marker segments fragm. */ + int buf_len; /* number of bytes in buffer */ + unsigned long comment_skip; /* remaining bytes of a COMMENT segment */ + unsigned long x; /* x position of next pixel in current SDE */ + unsigned long i; /* line in current SDE (first line of each stripe is 0) */ + int at_moves; /* number of AT moves in the current stripe */ + unsigned long at_line[JBG_ATMOVES_MAX]; /* lines at which an * + * AT move will happen */ + int at_tx[JBG_ATMOVES_MAX], at_ty[JBG_ATMOVES_MAX]; /* ATMOVE offsets in * + * current stripe */ + unsigned long line_h1, line_h2, line_h3; /* variables of decode_pscd */ + unsigned long line_l1, line_l2, line_l3; + int pseudo; /* flag for TPBON/TPDON: next pixel is pseudo pixel */ + int **lntp; /* flag [plane][layer-dl] for TP: line is not typical */ + + unsigned long xmax, ymax; /* if possible abort before image gets * + * larger than this size */ + int dmax; /* abort after this layer */ +}; + + +/* some macros (too trivial for a function) */ + +#define jbg_dec_getplanes(s) ((s)->planes) + + +/* function prototypes */ + +void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y, + int planes, unsigned char **p, + void (*data_out)(unsigned char *start, size_t len, + void *file), + void *file); +int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long mwidth, + unsigned long mheight); +void jbg_enc_layers(struct jbg_enc_state *s, int d); +int jbg_enc_lrange(struct jbg_enc_state *s, int dl, int dh); +void jbg_enc_options(struct jbg_enc_state *s, int order, int options, + unsigned long l0, int mx, int my); +void jbg_enc_out(struct jbg_enc_state *s); +void jbg_enc_free(struct jbg_enc_state *s); + +void jbg_dec_init(struct jbg_dec_state *s); +void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax, + unsigned long ymax); +int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len, + size_t *cnt); +long jbg_dec_getwidth(const struct jbg_dec_state *s); +long jbg_dec_getheight(const struct jbg_dec_state *s); +unsigned char *jbg_dec_getimage(const struct jbg_dec_state *s, int plane); +long jbg_dec_getsize(const struct jbg_dec_state *s); +void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode, + void (*data_out)(unsigned char *start, size_t len, + void *file), void *file); +long jbg_dec_getsize_merged(const struct jbg_dec_state *s); +void jbg_dec_free(struct jbg_dec_state *s); + +const char *jbg_strerror(int errnum, int language); +void jbg_int2dppriv(unsigned char *dptable, const char *internal); +void jbg_dppriv2int(char *internal, const unsigned char *dptable); +unsigned long jbg_ceil_half(unsigned long x, int n); +void jbg_split_planes(unsigned long x, unsigned long y, int has_planes, + int encode_planes, + const unsigned char *src, unsigned char **dest, + int use_graycode); +int jbg_newlen(unsigned char *bie, size_t len); + +#endif /* JBG_H */ diff --git a/SlnkDWFImpl/CxImage/jbig/jbig.vcproj b/SlnkDWFImpl/CxImage/jbig/jbig.vcproj new file mode 100644 index 0000000..5400483 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/jbig.vcproj @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/jbig/jbig.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/jbig/jbig.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..2bdefdc --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/jbig.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/jbig/jbig_tab.c b/SlnkDWFImpl/CxImage/jbig/jbig_tab.c new file mode 100644 index 0000000..eb73430 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/jbig_tab.c @@ -0,0 +1,428 @@ +/* + * Probability estimation tables for the arithmetic encoder/decoder + * given by ITU T.82 Table 24. + * + * $Id: jbig_tab.c,v 1.6 1998-04-05 18:36:19+01 mgk25 Rel $ + */ + +short jbg_lsz[113] = { + 0x5a1d, 0x2586, 0x1114, 0x080b, 0x03d8, 0x01da, 0x00e5, 0x006f, + 0x0036, 0x001a, 0x000d, 0x0006, 0x0003, 0x0001, 0x5a7f, 0x3f25, + 0x2cf2, 0x207c, 0x17b9, 0x1182, 0x0cef, 0x09a1, 0x072f, 0x055c, + 0x0406, 0x0303, 0x0240, 0x01b1, 0x0144, 0x00f5, 0x00b7, 0x008a, + 0x0068, 0x004e, 0x003b, 0x002c, 0x5ae1, 0x484c, 0x3a0d, 0x2ef1, + 0x261f, 0x1f33, 0x19a8, 0x1518, 0x1177, 0x0e74, 0x0bfb, 0x09f8, + 0x0861, 0x0706, 0x05cd, 0x04de, 0x040f, 0x0363, 0x02d4, 0x025c, + 0x01f8, 0x01a4, 0x0160, 0x0125, 0x00f6, 0x00cb, 0x00ab, 0x008f, + 0x5b12, 0x4d04, 0x412c, 0x37d8, 0x2fe8, 0x293c, 0x2379, 0x1edf, + 0x1aa9, 0x174e, 0x1424, 0x119c, 0x0f6b, 0x0d51, 0x0bb6, 0x0a40, + 0x5832, 0x4d1c, 0x438e, 0x3bdd, 0x34ee, 0x2eae, 0x299a, 0x2516, + 0x5570, 0x4ca9, 0x44d9, 0x3e22, 0x3824, 0x32b4, 0x2e17, 0x56a8, + 0x4f46, 0x47e5, 0x41cf, 0x3c3d, 0x375e, 0x5231, 0x4c0f, 0x4639, + 0x415e, 0x5627, 0x50e7, 0x4b85, 0x5597, 0x504f, 0x5a10, 0x5522, + 0x59eb +}; + +unsigned char jbg_nmps[113] = { + 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 13, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, + 33, 34, 35, 9, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 52, 53, 54, 55, 56, + 57, 58, 59, 60, 61, 62, 63, 32, + 65, 66, 67, 68, 69, 70, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 48, + 81, 82, 83, 84, 85, 86, 87, 71, + 89, 90, 91, 92, 93, 94, 86, 96, + 97, 98, 99, 100, 93, 102, 103, 104, + 99, 106, 107, 103, 109, 107, 111, 109, + 111 +}; + +/* + * least significant 7 bits (mask 0x7f) of jbg_nlps[] contain NLPS value, + * most significant bit (mask 0x80) contains SWTCH bit + */ +unsigned char jbg_nlps[113] = { + 129, 14, 16, 18, 20, 23, 25, 28, + 30, 33, 35, 9, 10, 12, 143, 36, + 38, 39, 40, 42, 43, 45, 46, 48, + 49, 51, 52, 54, 56, 57, 59, 60, + 62, 63, 32, 33, 165, 64, 65, 67, + 68, 69, 70, 72, 73, 74, 75, 77, + 78, 79, 48, 50, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 61, 61, + 193, 80, 81, 82, 83, 84, 86, 87, + 87, 72, 72, 74, 74, 75, 77, 77, + 208, 88, 89, 90, 91, 92, 93, 86, + 216, 95, 96, 97, 99, 99, 93, 223, + 101, 102, 103, 104, 99, 105, 106, 107, + 103, 233, 108, 109, 110, 111, 238, 112, + 240 +}; + +/* + * Resolution reduction table given by ITU-T T.82 Table 17 + */ + +char jbg_resred[4096] = { + 0,0,0,1,0,0,0,1,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, + 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1, + 0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, + 1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1,0,0,1,1,1,0,1,1, + 0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,1,0,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1, + 1,0,0,1,0,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,0,0,0,1,0,0,0,1,0,0,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,1,1,1,1,1,0,1,1,1,0, + 0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1, + 0,0,0,1,0,0,0,1,0,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1, + 1,1,1,0,1,0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1, + 1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,1, + 0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1, + 1,0,0,1,0,0,1,0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0, + 0,0,1,0,1,1,1,1,0,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0, + 0,0,0,0,1,0,0,1,0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,1,0,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1, + 0,0,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,1, + 0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,1,1, + 0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,1,1,1,0,1,1,1, + 0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,1,0,1,0,1,1,0,0,0,1,0,0,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,1,1,1,0,0,1,1, + 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1, + 0,0,1,0,0,1,1,1,0,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,1,0, + 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,1,1,0,1,1,1, + 0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,1,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,0,0,1,1, + 0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,0,0,1,1,0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,1,0,0,0,1,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, + 0,0,0,1,0,0,1,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, + 0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1, + 0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, + 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,1,1,0,1,1, + 0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,1,0,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1,0,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,1,0,0,1,0,0,1,1,0,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1, + 1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,0,1,1,0,1,1,1, + 0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,1,0,1,1,1,1, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,1,0,1,0,1,0,1,1,0,1,0,1,0,0,0,1,1,1,1,1,1,1,1,1, + 1,1,1,0,1,0,0,0,1,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1, + 1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,1,1,0,1,1, + 0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,1,0,1,0,0,0,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1, + 1,0,0,0,1,0,0,0,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,1,1,0,1,1,0, + 0,0,1,1,1,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,1,0,0,0,0,0,0,1,0,0,1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, + 0,0,1,0,1,0,1,1,0,0,1,0,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1, + 0,0,1,0,1,0,1,1,0,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,1, + 0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1, + 0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1, + 0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,1, + 0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1, + 1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,1,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,0, + 0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1, + 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1, + 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1, + 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,1,0,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,1, + 0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,0,0,0,1,1,0,0,0,1,0,1,1,1,0,1,1,1 +}; + +/* + * Deterministic prediction tables given by ITU-T T.82 tables + * 19 to 22. The table below is organized differently, the + * index bits are permutated for higher efficiency. + */ + +char jbg_dptable[256 + 512 + 2048 + 4096] = { + /* phase 0: offset=0 */ + 0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,2,2,2,2,2,0,2,2,2,2,2,2,2, + 0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,2,2,2,2,2,0,2,0,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + /* phase 1: offset=256 */ + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,2,2,2,2,0,2,0,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,2,2,2,2,1,2,1,2,2,2,2,1,1,1,1,2,0,2,0,2,2,2,2,0,2,0,2,2,2,2,2, + 0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,2,2,2,2,0,2,2,2,2,2,2,2, + 0,2,0,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,0,0,2,2,2,2,2,0,0,2,2,2,2,2, + 0,2,2,2,2,1,2,1,2,2,2,2,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1, + 1,2,1,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,1,1,2,2,2,2,2,0,2,2,2,2,2,2, + 2,2,2,2,2,0,2,0,2,2,2,2,0,0,0,0,0,2,0,2,2,2,2,2,0,2,2,2,2,2,2,2, + 0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,2,0,2,0,2,2,2,2,2, + 2,2,2,2,2,1,1,1,2,2,2,2,1,1,1,1,1,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,0,1,2,0,2,0,2,2,2,2,2,0,2,0,2,2,2,2,1, + 0,2,0,2,2,1,2,1,2,2,2,2,1,1,1,1,0,0,0,0,2,2,2,2,0,2,0,2,2,2,2,1, + 2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,0,0,0,2,2,2,2,2, + 2,2,2,2,2,1,2,1,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,1,2,1,2,2,2,2,1, + 2,2,2,2,2,2,2,2,0,2,0,2,2,1,2,2,2,2,2,2,2,2,2,2,0,0,0,2,2,2,2,2, + /* phase 2: offset=768 */ + 2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2,2,2,2,1,1,1,1, + 0,2,2,2,2,1,2,1,2,2,2,2,1,2,1,2,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1, + 2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,1,2,1,2,2,2,2,2,1,1,1, + 2,0,2,2,2,1,2,1,0,2,2,2,1,2,1,2,2,2,2,0,2,2,2,2,0,2,0,2,2,2,2,2, + 0,2,0,0,1,1,1,1,2,2,2,2,1,1,1,1,0,2,0,2,1,1,1,1,2,2,2,2,1,1,1,1, + 2,2,0,2,2,2,1,2,2,2,2,2,1,2,1,2,2,2,0,2,2,1,2,1,0,2,0,2,1,1,1,1, + 2,0,0,2,2,2,2,2,0,2,0,2,2,0,2,0,2,0,2,0,2,2,2,1,2,2,0,2,1,1,2,1, + 2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2,2,2,2,1,1,1,1, + 0,0,0,0,2,2,2,2,0,0,0,0,2,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,0,2,2,2,2,1,0,2,2,2,1,1,1,1,2,0,2,2,2,2,2,2,0,2,0,2,2,1,2,1, + 2,0,2,0,2,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2, + 0,2,2,2,1,2,1,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2, + 2,2,0,2,2,2,2,2,2,2,2,2,2,2,0,2,2,0,0,2,2,1,2,1,0,2,2,2,1,1,1,1, + 2,2,2,0,2,2,2,2,2,2,0,2,2,0,2,0,2,1,2,2,2,2,2,2,1,2,1,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,1, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,1,1,1,2,2,2,2,1,1,1,1, + 2,2,2,1,2,2,2,2,2,2,1,2,0,0,0,0,2,2,0,2,2,1,2,2,2,2,2,2,1,1,1,1, + 2,0,0,0,2,2,2,2,0,2,2,2,2,2,2,0,2,2,2,0,2,2,2,2,2,0,0,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,0,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,1, + 0,2,0,2,2,1,1,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2, + 2,0,2,0,2,1,2,1,0,2,0,2,2,2,1,2,2,0,2,0,2,2,2,2,0,2,0,2,2,2,1,2, + 2,2,2,0,2,2,2,2,2,2,0,2,2,2,2,2,2,2,1,2,2,2,2,2,2,0,1,2,2,2,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 0,2,2,2,1,2,1,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2, + 2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,2,1,2,1,0,2,2,2,1,1,1,1, + 2,0,2,0,2,1,2,2,0,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,1,2,2, + 2,0,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,0,2,0,2,2,2,2,0,0,0,0,2,1,2,1, + 2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,0,2,2,2,2,2,1,2,0,0,2,2,2,1,2,2,2, + 0,0,2,0,2,2,2,2,0,2,0,2,2,0,2,0,1,1,1,2,2,2,2,2,2,2,2,2,2,1,1,1, + 2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,1, + 2,2,0,0,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2,2,2,2,1,1,1,1, + 0,2,2,2,1,2,1,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2, + 2,0,0,2,2,2,2,2,0,2,0,2,2,2,2,2,1,0,1,2,2,2,2,1,0,2,2,2,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,0,2,2,0,2,0,2,1,2,2,2,2,2,2,2,2,0,2,2,1,2,2, + 0,2,0,0,1,1,1,1,0,2,2,2,1,1,1,1,2,2,2,2,2,2,2,2,2,0,2,2,1,2,1,1, + 2,2,0,2,2,1,2,2,2,2,2,2,1,2,2,2,2,0,2,2,2,2,2,2,0,2,0,2,1,2,1,1, + 2,0,2,0,2,2,2,2,0,2,0,2,2,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,1, + 2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,2,2,2,2,0,2,0,2,2,2,2,0,0,0,0,2,2,2,2,2,1,1,2,2,2,2,2,1,2,2,2, + 2,0,2,2,2,1,2,1,0,2,2,2,2,2,1,2,2,0,2,0,2,2,2,2,0,2,0,2,2,1,2,2, + 0,2,0,0,2,2,2,2,1,2,2,2,2,2,2,0,2,1,2,2,2,2,2,2,1,2,2,2,2,2,2,2, + 0,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,1,0,2,2, + 0,0,0,2,2,1,1,1,2,2,2,2,1,2,2,2,2,0,2,0,2,2,2,1,2,2,2,2,1,2,1,2, + 0,0,0,0,2,2,2,2,2,2,0,2,2,1,2,2,2,1,2,1,2,2,2,2,1,2,1,2,0,2,2,2, + 2,0,2,0,2,2,2,2,2,0,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 0,2,2,2,1,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,1,2,2,2,2,2,0,2,2,1,2,2,0,0,0,2,2,2,2,2,1,2,2,0,2,2,2,1,2,1,2, + 2,0,2,0,2,2,2,2,0,2,0,2,2,1,2,2,0,2,0,0,2,2,2,2,2,2,2,2,2,1,2,2, + 2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,1, + 1,2,0,2,2,1,2,1,2,2,2,2,1,2,2,2,2,0,2,0,2,2,2,2,2,0,2,2,1,1,1,1, + 0,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,1,2,1, + 2,2,0,0,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1, + 2,2,2,0,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,1,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2, + 2,0,2,0,2,2,2,2,2,1,1,2,2,2,2,2,2,2,2,2,2,2,2,1,0,2,0,2,2,2,1,2, + 2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2, + 2,0,2,0,2,2,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,2,2,2,0,0,0,0,2,1,2,1, + 2,2,2,2,2,1,2,1,0,2,0,2,2,2,2,2,2,0,2,0,2,2,2,2,0,2,0,2,2,2,2,1, + 2,0,2,0,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,0, + 2,0,2,0,2,2,2,1,2,2,2,0,2,2,2,1,2,0,2,0,2,2,2,2,0,0,0,2,2,2,2,1, + 2,0,2,0,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2, + /* phase 3: offset=2816 */ + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1,2,1,2,0,2,0,1,2,1,2,0,2,0,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,0,2,2,2,1,2,0,2,2,2,1,2,2,2,2,0,2,0,2,1,2,1,0,0,0,0,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,0,2,2,2,1,2, + 2,2,2,1,2,2,2,0,1,1,1,1,0,0,0,0,2,2,2,2,2,2,2,2,2,0,2,0,2,1,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,0,0,0,0,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,1,2,1,0,0,0,0,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,1,2,0,2,0,2, + 2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,0,2,0,2,1,2,1,2,0,2,0,2,1,2,1, + 2,0,0,0,2,1,1,1,0,0,0,0,1,1,1,1,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2, + 2,0,2,2,2,1,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,0,0,2,0,1,1,2,1, + 2,2,2,0,2,2,2,1,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1, + 0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,2,0,2,0,2,1,2,1,0,0,0,0,1,1,1,1, + 2,0,0,2,2,1,1,2,2,2,2,2,2,2,2,2,2,1,2,1,2,0,2,0,2,1,1,1,2,0,0,0, + 2,1,2,1,2,0,2,0,1,2,1,2,0,2,0,2,2,2,2,0,2,2,2,1,2,0,2,0,2,1,2,1, + 2,0,2,0,2,1,2,1,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,2,0,2,0,2,1,2,1, + 2,2,2,2,2,2,2,2,2,0,0,0,2,1,1,1,2,2,2,2,2,2,2,2,2,0,2,0,2,1,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2, + 2,0,0,0,2,1,1,1,0,0,0,0,1,1,1,1,2,0,2,0,2,1,2,1,0,0,2,0,1,1,2,1, + 2,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,0,0,0,2,1,1,1, + 2,2,2,1,2,2,2,0,2,1,1,1,2,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,1,2,1,2,0,2,0,1,2,1,2,0,2,0,2, + 2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,2,1,1,1,0,0,0,0,1,1,1,1, + 2,0,2,2,2,1,2,2,0,0,2,0,1,1,2,1,2,1,2,1,2,0,2,0,2,2,2,2,2,2,2,2, + 2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,0,0,0,0,1,1,1,1, + 2,0,0,0,2,1,1,1,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,2,1,0,2,2,0,1,2, + 2,2,2,1,2,2,2,0,2,1,1,1,2,0,0,0,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2,2, + 2,1,2,1,2,0,2,0,1,2,1,1,0,2,0,0,0,0,2,1,1,1,2,0,0,0,0,0,1,1,1,1, + 2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,0,2,1,2,1,2,0,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,0,2,2,2,1,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,0,2,2,2,1,2,2,2,0,0,2,2,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2, + 2,0,2,0,2,1,2,1,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,0,0,0,0,1,1,1,1, + 2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,0,0,0,2,1,1,1, + 2,2,2,0,2,2,2,1,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2, + 2,0,2,2,2,1,2,2,2,0,2,0,2,1,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,1,2,1,2,0,2,0,1,2,1,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,1,2,1,2,0,2,0,1,2,1,1,0,2,0,0,2,0,2,2,2,1,2,2,0,2,1,2,1,2,0,2, + 2,2,2,1,2,2,2,0,2,2,1,2,2,2,0,2,2,1,2,2,2,0,2,2,2,2,0,2,2,2,1,2, + 0,0,2,0,1,1,2,1,0,0,1,0,1,1,0,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,0,2,2,2,1,1,2,2,2,0,2,2,2,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1, + 2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,0,0,2,2,1,1,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2, + 2,0,0,0,2,1,1,1,0,0,0,0,1,1,1,1,2,2,2,1,2,2,2,0,2,1,2,1,2,0,2,0, + 2,1,2,2,2,0,2,2,2,2,2,2,2,2,2,2,0,2,0,0,1,2,1,1,2,0,0,0,2,1,1,1, + 2,2,2,2,2,2,2,2,2,1,1,1,2,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,0,2,2,2,1,2,2,0,2,2,2,1,2,2,1,2,1,2,0,2,0,2,0,2,2,2,1,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,1,1,1,2,0,0,0, + 2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,0,2,0,0,1,2,1,1, + 2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,0,2,2,2,1,2,2,2, + 2,1,2,1,2,0,2,0,2,1,2,2,2,0,2,2,2,2,2,0,2,2,2,1,2,0,2,0,2,1,2,1, + 2,0,2,0,2,1,2,1,0,2,0,2,1,2,1,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2, + 2,2,2,2,2,2,2,2,0,2,0,2,1,2,1,2,2,2,2,2,2,2,2,2,0,1,0,0,1,0,1,1, + 2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,2,2,1,2,2,2,0,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,1,2,2,1,0,2,0,2,2,2,1,2,2,2, + 2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,2,2,0,2,2,2,1,2,2,0,2,2,2,1,2, + 2,0,2,0,2,1,2,1,0,2,0,2,1,2,1,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2, + 0,2,0,0,1,2,1,1,2,0,0,0,2,1,1,1,2,2,2,2,2,2,2,2,1,0,1,2,0,1,0,2, + 2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,1,2,2,2,0,2,2,1,1,2,2,0,0,2,2, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,1,2,1,2,0,2,0,2,1,2,2,2,0,2,2,2,0,2,2,2,1,2,2,0,2,2,2,1,2,2,2, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,1,2,2,2,0,2,2,2, + 2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,1,2,1,2, + 0,0,0,0,1,1,1,1,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,1,2,0,2,0,2,2,0,2,2,2,1,2, + 2,0,2,0,2,1,2,1,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2, + 0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,1,2,2,2,0,1,1,2,1,0,0,2,0,2,0,2,2,2,1,2,2,0,2,2,2,1,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2,2,2,0,2,2,2,1,2, + 2,0,2,0,2,1,2,1,0,2,0,2,1,2,1,2,2,2,2,2,2,2,2,2,2,1,2,2,2,0,2,2, + 0,2,0,0,1,2,1,1,0,2,0,2,1,2,1,2,2,2,2,2,2,2,2,2,0,0,0,2,1,1,1,2, + 2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,0,0,2,1,1,1,2,0,0,2,2,2,1,2,2,2, + 2,1,2,1,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,0,1,2,1,1, + 0,0,2,2,1,1,2,2,0,2,1,2,1,2,0,2,2,1,2,1,2,0,2,0,1,2,1,2,0,2,0,2, + 2,2,2,2,2,2,2,2,1,2,1,2,0,2,0,2,2,2,2,2,2,2,2,2,2,0,2,0,2,1,2,1, + 2,2,0,0,2,2,1,1,2,2,0,0,2,2,1,1,2,2,2,2,2,2,2,2,2,2,0,0,2,2,1,1, + 2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,0,0,1,2,1,1, + 2,2,2,0,2,2,2,1,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,1,1,1,2,0,0,0,2, + 2,2,2,2,2,2,2,2,1,1,1,2,0,0,0,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2, + 2,0,2,0,2,1,2,1,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,0,0,0,2,1,1,1, + 2,0,2,2,2,1,2,2,0,2,2,2,1,2,2,2,2,0,2,0,2,1,2,1,2,2,2,2,2,2,2,2, + 2,0,2,0,2,1,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,0,2,0,2,1,2,1,2,1,2,0,2,0,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,0,2,0,2,1,2,1,1,2,1,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,1,2,1,2,0,2,0,2,2,1,2,1,2,0,2,0,2,2,2,2,2,2,2,2, + 2,0,2,1,2,1,2,0,0,2,1,2,1,2,0,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,0,2,0,2,1,2,1,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,0,2,0,2,1,2,1, + 2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,1,2,1,2,0,2,0,1,1,1,2,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1, + 2,0,2,0,2,1,2,1,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, +}; diff --git a/SlnkDWFImpl/CxImage/jbig/patents.htm b/SlnkDWFImpl/CxImage/jbig/patents.htm new file mode 100644 index 0000000..291b755 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/patents.htm @@ -0,0 +1,195 @@ + + + +JBIG1 patent information + + + + + + + +

JBIG1 patent information

+ +

by Markus Kuhn + +

For many years, the doubts about the patent situation have +prevented the JBIG1 standard from becoming widely used on the +Internet (e.g., not a single web browser has support for it +integrated). As the author of a freely available JBIG1 +implementation, I'm investigating the current patent license +requirements for the JBIG1 standard, and this page summarizes what I +have found out so far. + +

Patent list

+ +

Annex E of the JBIG1 standard (ITU-T Recommendation T.82(1993) and International Standard +ISO/IEC 1154 4:1993), lists the following patents and says that a +license for these might be required to implement the standard:

+ + +
OwnerTitleNumberpublication datenotes +
IBMA method and means for pipeline decoding of the high to low order pairwise combined digits of a decodable set of relatively shifted finite number of stringsUS 42951251981-10-13 +
IBMA method and means for carry-over control in a high order to low order combining of digits of a decodable set of relatively shifted finite number stringsUS 44633421984-07-31 +
IBMHigh-speed arithmetic compression using concurrent value updatingUS 44673171984-08-21 +
IBMMethod and means for arithmetic coding using a reduced number of operationsUS 42862561981-08-25 +
IBMA multiplication-free multi-alphabet arithmetic codeUS 46528561986-02-04 +
IBMSymmetrical adaptive data compression/decompression systemUS 46334901986-12-30 +
IBMArithmetic coding data compression/de-compression by selectively employed, diverse arithmetic encoders and decodersUS 48916431990-01-02 +
IBMSystem for compression bi-level dataUS 49013631990-02-13 +
IBMArithmetic coding encoder and decoder systemUS 49052971990-02-27 +
IBMProbability adaptation for arithmetic codersUS 49358821990-06-19 +
IBMProbability adaptation for arithmetic codersUS 50994401992-03-24 +
IBMMethod and apparatus for processing pel signals of an imageUS 49822921991-01-01 +
AT&TProgressive transmission of high resolution two-tone facsimile imagesUS 48704971989-09-26 +
AT&TEdge decomposition for the transmission of high resolution facsimile imagesUS 48735771989-10-10 +
AT&TAdaptive probability estimator for entropy encoder/decoderUS 50252581991-06-18 +
AT&TEfficient encoding/decoding in the decomposition and recomposition of a high resolution image utilizing its low resolution replicaUS 49790491990-12-18 +
AT&TEfficient encoding/decoding in the decomposition and recomposition of a high resolution image utilizing pixel clustersUS 50310531991-07-09 +
AT&TEntropy encoder/decoder including a context extractorUS 50236111991-06-11 +
AT&TMethod and apparatus for carry-over control in arithmetic entropy codingUS 49739611990-11-27 +
KDDMethods for reduced-sized imagesJP Appl. 63-212 4321990-03-02JP 02-062164 +
KDDImage reduction systemJP Appl. 1-167 033pendingjoint with Canon +
MitsubishiFacsimile encoding communication systemJP 12514031984-07-06wrong number? +
MitsubishiEncoding methodpending +
CanonImage reduction systemJP Appl. 1-167 033pendingjoint with KDD +
+ +

The owners of the above patents have filed with the ISO and ITU a +statement of willingness to grant a license under these rights on +reasonable and non-discriminatory terms and conditions to applications +desiring to obtain such a license. These statements are recorded in +the ITU Patents +Database. + +

JBIG-KIT comes without any patent licence. I do not know for sure, +which patents still affect which use of JBIG in which country (most of +the ones listed have already expired anyway). The most important +patents are the ones owned by IBM on the QM coder. Some of the other +patents can be avoided by disabling progressive coding. In some +countries, non-commercial and research use of patented ideas does not +require a license anyway. + +

Contacts

+ +

Annex E of JBIG1 also provides contact addresses for patent information: + +

+Director, Telecommunication Standardization Bureau (formerly CCITT)
+International Telecommunication Union
+Place des Nations
+CH-1211 Genève 20
+Switzerland
+Tel: +41 (22) 730 5111
+Fax: +41 (22) 730 5853
+
+ITTF
+International Organization for Standardization
+1, rue de Varembé
+CH-1211 Genève 20
+Switzerland
+Tel: +41 (22) 734 0150
+Fax: +41 (22) 733 3843
+
+Program Manager
+Licensing Intellectual Property and Licensing Services
+IBM Corporation
+208 Harbor Drive
+P.O. Box 10501
+Stamford, Connecticut 08904-2501
+Tel: +1 (203) 973 7935
+Fax: +1 (203) 973 7981
+  or +1 (203) 973 7982
+
+Mitsubishi Electric Corp.
+Intellectual Property License Department
+1-2-3 Morunouchi, Chiyoda-ku
+Tokyo 100
+Japan
+Tel: +81 (3) 3218 3465
+Fax: +81 (3) 3215 3842
+
+International Affairs Department
+Kokusai Denshin Denwa Co. Ltd.
+3-2 Nishishinjuku 2-chome Shinjuku-ku Tokyo 163
+Japan
+Tel: +81 (3) 3347 6457
+Tel: +81 (3) 3347 6470 
+
+AT&T Intellectual Property Division Manager
+Room 3A21
+10 Independence Blvd. Warren, NJ 07059
+USA
+Tel: +1 (908) 580 5392
+Fax: +1 (908) 580 6355
+
+Senior General Manager
+Corporate Intellectual Property and Legal Headquarters
+Canon Inc.
+30-2 Shimomaruko 3-chome
+Ohta-ku, Tokyo 146
+Japan
+Tel: +81 (3) 3758 2111
+Fax: +81 (3) 3756 0947
+
+ +

Information received from these so far: + +

    + +
  • 2000-08-01: All the JBIG1 related AT&T patents are now owned +by Lucent Technologies and can be licensed for a lump sum of 15000 +USD. For more information and a patent license agreement, contact +Larry Greenberg (greenberg at lucent.com), Jim Finnegan, or Peter +Crefeld (pcrefeld at lucent.com) at Lucent. They told me that they +have made a general commitment to Standards Bodies that they will be +non-discriminatory in this licensing, therefore they can't offer a +free license for non-commercial implementations or applications. + +
+ +

JBIG2 license waiver

+ +

I recently read with great interest in Annex I of the final draft +for JBIG2 (ISO/IEC FCD +14492, ITU-T +T.88) that IBM has agreed to license the arithmetic encoding +patents free of charge to JBIG2 implementors. Apparently, the IBM IPR +statement provided for JPEG2000 (ISO/IEC 15444 and ITU-T T.800) and +JBIG2 allowed no-royalty use of the patents on a certain list for "any +WG1 standard", which refers to the ISO/IEC working group that +comprises both JBIG and JPEG. It's possible that this means that IBM +will allow royalty-free use of the patents on that list for JBIG1 as +well, but I don't know yet whether that has been the intention or +effect. + +

I hope that this waiver therefore can also be applied to JBIG1 +implementations, as I would love to be able to add to the +documentation of my package a statement saying that its use will not +require a patent license (or at least not for the non-progressive +modes). I am still struggling to find a competent source to confirm +that this is indeed the case. + +

Thanks to Sebestyen Istvan and William Rucklidge from the JPEG/JBIG +committee (ISO/IEC JTC 1/SC 29/WG 1 and ITU-T SG8) for helpful +information. + +

Markus Kuhn +
created 2002-07-29 -- last modified 2002-07-29 -- +http://www.cl.cam.ac.uk/~mgk25/jbigkit/patents.html + + + diff --git a/SlnkDWFImpl/CxImage/jbig/tstcodec.c b/SlnkDWFImpl/CxImage/jbig/tstcodec.c new file mode 100644 index 0000000..084e4a8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jbig/tstcodec.c @@ -0,0 +1,522 @@ +/* + * A sequence of test procedures for this JBIG implementation + * + * Run this test sequence after each modification on the JBIG library. + * + * Markus Kuhn -- http://www.cl.cam.ac.uk/~mgk25/ + * + * $Id: tstcodec.c,v 1.14 2004-06-11 15:17:06+01 mgk25 Exp $ + */ + +#include +#include +#include +#include + +#include "jbig.h" + +#define TESTBUF_SIZE 400000L +#define TESTPIC_SIZE 477995L + +#define FAILED "F\bFA\bAI\bIL\bLE\bED\bD" +#define PASSED "PASSED" + +unsigned char *testbuf; +unsigned char *testpic; + +long testbuf_len; + + +static void *checkedmalloc(size_t n) +{ + void *p; + + if ((p = malloc(n)) == NULL) { + fprintf(stderr, "Sorry, not enough memory available!\n"); + exit(1); + } + + return p; +} + +static void testbuf_write(int v, void *dummy) +{ + if (testbuf_len < TESTBUF_SIZE) + testbuf[testbuf_len++] = v; + (void) dummy; + return; +} + + +static void testbuf_writel(unsigned char *start, size_t len, void *dummy) +{ + if (testbuf_len < TESTBUF_SIZE) { + if (testbuf_len + len < TESTBUF_SIZE) + memcpy(testbuf + testbuf_len, start, len); + else + memcpy(testbuf + testbuf_len, start, TESTBUF_SIZE - testbuf_len); + } + testbuf_len += len; + +#ifdef DEBUG + { + unsigned char *p; + unsigned sum = 0; + + for (p = start; p - start < (ptrdiff_t) len; sum = (sum ^ *p++) << 1); + printf(" testbuf_writel: %4d bytes, checksum %04x\n", + len, sum & 0xffff); + } +#endif + + (void) dummy; + return; +} + + +/* + * Store the artificial test image defined in T.82, clause 7.2.1 at + * pic. The image requires 477995 bytes of memory, is 1960 x 1951 pixels + * large and has one plane. + */ +static void testimage(unsigned char *pic) +{ + unsigned long i, j, sum; + unsigned int prsg, repeat[8]; + unsigned char *p; + + memset(pic, 0, TESTPIC_SIZE); + p = pic; + prsg = 1; + for (j = 0; j < 1951; j++) + for (i = 0; i < 1960; i++) { + if (j >= 192) { + if (j < 1023 || ((i >> 3) & 3) == 0) { + sum = (prsg & 1) + ((prsg >> 2) & 1) + ((prsg >> 11) & 1) + + ((prsg >> 15) & 1); + prsg = (prsg << 1) + (sum & 1); + if ((prsg & 3) == 0) { + *p |= 1 << (7 - (i & 7)); + repeat[i & 7] = 1; + } else { + repeat[i & 7] = 0; + } + } else { + if (repeat[i & 7]) + *p |= 1 << (7 - (i & 7)); + } + } + if ((i & 7) == 7) ++p; + } + + /* verify test image */ + sum = 0; + for (i = 0; i < TESTPIC_SIZE; i++) + for (j = 0; j < 8; j++) + sum += (pic[i] >> j) & 1; + if (sum != 861965L) + printf("WARNING: Artificial test image has %lu (not 861965) " + "foreground pixels!\n", sum); + + return; +} + + +/* + * Perform a full test cycle with one set of parameters. Encode an image + * and compare the length of the result with correct_length. Then decode + * the image again both in one single chunk or byte by byte and compare + * the results with the original input image. + */ +static int test_cycle(unsigned char **orig_image, int width, int height, + int options, int order, int layers, int planes, + unsigned long l0, int mx, long correct_length, + const char *test_id) +{ + struct jbg_enc_state sje; + struct jbg_dec_state sjd; + int trouble = 0; + long l; + size_t plane_size; + int i, result; + unsigned char **image; + + plane_size = ((width + 7) / 8) * height; + image = (unsigned char **) checkedmalloc(planes * sizeof(unsigned char *)); + for (i = 0; i < planes; i++) { + image[i] = (unsigned char *) checkedmalloc(plane_size); + memcpy(image[i], orig_image[i], plane_size); + } + + printf("\nTest %s.1: Encoding ...\n", test_id); + testbuf_len = 0; + jbg_enc_init(&sje, width, height, planes, image, testbuf_writel, NULL); + jbg_enc_layers(&sje, layers); + jbg_enc_options(&sje, order, options, l0, mx, 0); + jbg_enc_out(&sje); + jbg_enc_free(&sje); + for (i = 0; i < planes; i++) + free(image[i]); + free(image); + printf("Encoded BIE has %6ld bytes: ", testbuf_len); + if (correct_length >= 0) + if (testbuf_len == correct_length) + puts(PASSED); + else { + trouble++; + printf(FAILED ", correct would have been %ld\n", correct_length); + } + else + puts(""); + + printf("Test %s.2: Decoding whole chunk ...\n", test_id); + jbg_dec_init(&sjd); + result = jbg_dec_in(&sjd, testbuf, testbuf_len, NULL); + if (result != JBG_EOK) { + printf("Decoder complained with return value %d: " FAILED "\n" + "Cause: '%s'\n", result, jbg_strerror(result, JBG_EN)); + trouble++; + } else { + printf("Image comparison: "); + result = 1; + for (i = 0; i < planes; i++) { + if (memcmp(orig_image[i], sjd.lhp[layers & 1][i], + ((width + 7) / 8) * height)) { + result = 0; + trouble++; + printf(FAILED " for plane %d\n", i); + } + } + if (result) + puts(PASSED); + } + jbg_dec_free(&sjd); + + printf("Test %s.3: Decoding with single-byte feed ...\n", test_id); + jbg_dec_init(&sjd); + result = JBG_EAGAIN; + for (l = 0; l < testbuf_len; l++) { + result = jbg_dec_in(&sjd, testbuf + l, 1, NULL); + if (l < testbuf_len - 1 && result != JBG_EAGAIN) { + printf("Decoder complained with return value %d at byte %ld: " FAILED + "\nCause: '%s'\n", result, l, jbg_strerror(result, JBG_EN)); + trouble++; + break; + } + } + if (l == testbuf_len) { + if (result != JBG_EOK) { + printf("Decoder complained with return value %d at final byte: " FAILED + "\nCause: '%s'\n", result, jbg_strerror(result, JBG_EN)); + trouble++; + } else { + printf("Image comparison: "); + result = 1; + for (i = 0; i < planes; i++) { + if (memcmp(orig_image[i], sjd.lhp[layers & 1][i], + ((width + 7) / 8) * height)) { + result = 0; + trouble++; + printf(FAILED " for plane %d\n", i); + } + } + if (result) + puts(PASSED); + } + } + + jbg_dec_free(&sjd); + puts(""); + + return trouble != 0; +} + + +int main(int argc, char **argv) +{ + int trouble, problems = 0; + struct jbg_arenc_state *se; + struct jbg_ardec_state *sd; + long i; + int pix, order, layers; + char test[10]; + size_t st; + unsigned char *pp; + unsigned char *ppp[4]; + + int t82pix[16] = { + 0x05e0, 0x0000, 0x8b00, 0x01c4, 0x1700, 0x0034, 0x7fff, 0x1a3f, + 0x951b, 0x05d8, 0x1d17, 0xe770, 0x0000, 0x0000, 0x0656, 0x0e6a + }; + int t82cx[16] = { + 0x0fe0, 0x0000, 0x0f00, 0x00f0, 0xff00, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 + }; + unsigned char t82sde[32] = { + 0x69, 0x89, 0x99, 0x5c, 0x32, 0xea, 0xfa, 0xa0, + 0xd5, 0xff, 0x00, 0x52, 0x7f, 0xff, 0x00, 0xff, + 0x00, 0xff, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x3f, + 0xff, 0x00, 0x2d, 0x20, 0x82, 0x91, 0xff, 0x02 + }; + + /* three 23x5 pixel test images with the letters JBIG */ + unsigned char jbig_normal[15*4] = { + 0x7c, 0xe2, 0x38, 0x04, 0x92, 0x40, 0x04, 0xe2, 0x5c, 0x44, + 0x92, 0x44, 0x38, 0xe2, 0x38, + 0x7c, 0xe2, 0x38, 0x04, 0x92, 0x40, 0x04, 0xe2, 0x5c, 0x44, + 0x92, 0x44, 0x38, 0xe2, 0x38, + 0x7c, 0xe2, 0x38, 0x04, 0x92, 0x40, 0x04, 0xe2, 0x5c, 0x44, + 0x92, 0x44, 0x38, 0xe2, 0x38, + 0x7c, 0xe2, 0x38, 0x04, 0x92, 0x40, 0x04, 0xe2, 0x5c, 0x44, + 0x92, 0x44, 0x38, 0xe2, 0x38 + }; + unsigned char jbig_upsidedown[15*4] = { + 0x38, 0xe2, 0x38, 0x44, 0x92, 0x44, 0x04, 0xe2, 0x5c, 0x04, + 0x92, 0x40, 0x7c, 0xe2, 0x38, + 0x38, 0xe2, 0x38, 0x44, 0x92, 0x44, 0x04, 0xe2, 0x5c, 0x04, + 0x92, 0x40, 0x7c, 0xe2, 0x38, + 0x38, 0xe2, 0x38, 0x44, 0x92, 0x44, 0x04, 0xe2, 0x5c, 0x04, + 0x92, 0x40, 0x7c, 0xe2, 0x38, + 0x38, 0xe2, 0x38, 0x44, 0x92, 0x44, 0x04, 0xe2, 0x5c, 0x04, + 0x92, 0x40, 0x7c, 0xe2, 0x38 + }; + unsigned char jbig_inverse[15*4] = { + 0xff^0x7c, 0xff^0xe2, 0xfe^0x38, 0xff^0x04, 0xff^0x92, + 0xfe^0x40, 0xff^0x04, 0xff^0xe2, 0xfe^0x5c, 0xff^0x44, + 0xff^0x92, 0xfe^0x44, 0xff^0x38, 0xff^0xe2, 0xfe^0x38, + 0xff^0x7c, 0xff^0xe2, 0xfe^0x38, 0xff^0x04, 0xff^0x92, + 0xfe^0x40, 0xff^0x04, 0xff^0xe2, 0xfe^0x5c, 0xff^0x44, + 0xff^0x92, 0xfe^0x44, 0xff^0x38, 0xff^0xe2, 0xfe^0x38, + 0xff^0x7c, 0xff^0xe2, 0xfe^0x38, 0xff^0x04, 0xff^0x92, + 0xfe^0x40, 0xff^0x04, 0xff^0xe2, 0xfe^0x5c, 0xff^0x44, + 0xff^0x92, 0xfe^0x44, 0xff^0x38, 0xff^0xe2, 0xfe^0x38, + 0xff^0x7c, 0xff^0xe2, 0xfe^0x38, 0xff^0x04, 0xff^0x92, + 0xfe^0x40, 0xff^0x04, 0xff^0xe2, 0xfe^0x5c, 0xff^0x44, + 0xff^0x92, 0xfe^0x44, 0xff^0x38, 0xff^0xe2, 0xfe^0x38 + }; + int orders[] = { + 0, + JBG_ILEAVE, + JBG_ILEAVE | JBG_SMID, +#if 0 + JBG_SEQ, + JBG_SEQ | JBG_SMID, + JBG_SEQ | JBG_ILEAVE, + JBG_HITOLO, + JBG_HITOLO | JBG_ILEAVE, + JBG_HITOLO | JBG_ILEAVE | JBG_SMID, + JBG_HITOLO | JBG_SEQ, + JBG_HITOLO | JBG_SEQ | JBG_SMID, + JBG_HITOLO | JBG_SEQ | JBG_ILEAVE +#endif + }; + + printf("\nAutomatic JBIG Compatibility Test Suite\n" + "---------------------------------------\n\n" + "JBIG-KIT Version " JBG_VERSION + " -- This test will take a few minutes.\n\n\n"); + + /* allocate test buffer memory */ + testbuf = (unsigned char *) checkedmalloc(TESTBUF_SIZE); + testpic = (unsigned char *) checkedmalloc(TESTPIC_SIZE); + se = (struct jbg_arenc_state *) checkedmalloc(sizeof(struct jbg_arenc_state)); + sd = (struct jbg_ardec_state *) checkedmalloc(sizeof(struct jbg_ardec_state)); + + /* test a few properties of the machine architecture */ + testbuf[0] = 42; + testbuf[0x10000L] = 0x42; + st = 1 << 16; + testbuf[st]++; + pp = testbuf + 0x4000; + pp += 0x4000; + pp += 0x4000; + pp += 0x4000; + if (testbuf[0] != 42 || *pp != 0x43) { + printf("Porting error detected:\n\n" + "Pointer arithmetic with this compiler has not at least 32 bits!\n" + "Are you sure, you have not compiled this program on an 8-bit\n" + "or 16-bit architecture? This compiler mode can obviously not\n" + "handle arrays with a size of more than 65536 bytes. With this\n" + "memory model, JBIG-KIT can only handle very small images and\n" + "not even this compatibility test suite will run. :-(\n\n"); + exit(1); + } + + /* only supported command line option: + * output file name for exporting test image */ + if (argc > 1) { + FILE *f; + + puts("Generating test image ..."); + testimage(testpic); + printf("Storing in '%s' ...\n", argv[1]); + + /* write out test image as PBM file */ + f = fopen(argv[1], "wb"); + if (!f) abort(); + fprintf(f, "P4\n"); +#if 0 + fprintf(f, "# Test image as defined in ITU-T T.82, clause 7.2.1\n"); +#endif + fprintf(f, "1960 1951\n"); + fwrite(testpic, 1, TESTPIC_SIZE, f); + fclose(f); + exit(0); + } + +#if 1 + puts("1) Arithmetic encoder test sequence from ITU-T T.82, clause 7.1\n" + "---------------------------------------------------------------\n"); + arith_encode_init(se, 0); + testbuf_len = 0; + se->byte_out = testbuf_write; + for (i = 0; i < 16 * 16; i++) + arith_encode(se, (t82cx[i >> 4] >> ((15 - i) & 15)) & 1, + (t82pix[i >> 4] >> ((15 - i) & 15)) & 1); + arith_encode_flush(se); + printf("result of encoder:\n "); + for (i = 0; i < testbuf_len && i < TESTBUF_SIZE; i++) + printf("%02x", testbuf[i]); + printf("\nexpected result:\n "); + for (i = 0; i < 30; i++) + printf("%02x", t82sde[i]); + printf("\n\nTest 1: "); + if (testbuf_len != 30 || memcmp(testbuf, t82sde, 30)) { + problems++; + printf(FAILED); + } else + printf(PASSED); + printf("\n\n"); + + + puts("2) Arithmetic decoder test sequence from ITU-T T.82, clause 7.1\n" + "---------------------------------------------------------------\n"); + printf("Test 2.1: Decoding whole chunk ...\n"); + arith_decode_init(sd, 0); + sd->pscd_ptr = t82sde; + sd->pscd_end = t82sde + 32; + trouble = 0; + for (i = 0; i < 16 * 16 && !trouble; i++) { + pix = arith_decode(sd, (t82cx[i >> 4] >> ((15 - i) & 15)) & 1); + if (pix < 0) { + printf("Problem at Pixel %ld, result code %d.\n\n", i+1, sd->result); + trouble++; + break; + } + if (pix != ((t82pix[i >> 4] >> ((15 - i) & 15)) & 1)) { + printf("Wrong PIX answer at Pixel %ld.\n\n", i+1); + trouble++; + break; + } + } + if (!trouble && sd->result != JBG_READY) { + printf("Result is %d instead of JBG_READY.\n\n", sd->result); + trouble++; + } + printf("Test result: "); + if (trouble) { + problems++; + puts(FAILED); + } else + puts(PASSED); + printf("\n"); + + printf("Test 2.2: Decoding with single byte feed ...\n"); + arith_decode_init(sd, 0); + pp = t82sde; + sd->pscd_ptr = pp; + sd->pscd_end = pp + 1; + trouble = 0; + for (i = 0; i < 16 * 16 && !trouble; i++) { + pix = arith_decode(sd, (t82cx[i >> 4] >> ((15 - i) & 15)) & 1); + while ((sd->result == JBG_MORE || sd->result == JBG_MARKER) && + sd->pscd_end < t82sde + 32) { + pp++; + sd->pscd_end = pp + 1; + if (sd->result == JBG_MARKER) + sd->pscd_ptr = pp - 1; + else + sd->pscd_ptr = pp; + pix = arith_decode(sd, (t82cx[i >> 4] >> ((15 - i) & 15)) & 1); + } + if (pix < 0) { + printf("Problem at Pixel %ld, result code %d.\n\n", i+1, sd->result); + trouble++; + break; + } + if (pix != ((t82pix[i >> 4] >> ((15 - i) & 15)) & 1)) { + printf("Wrong PIX answer at Pixel %ld.\n\n", i+1); + trouble++; + break; + } + } + if (!trouble && sd->result != JBG_READY) { + printf("Result is %d instead of JBG_READY.\n\n", sd->result); + trouble++; + } + printf("Test result: "); + if (trouble) { + problems++; + puts(FAILED); + } else + puts(PASSED); + printf("\n"); + + puts("3) Parametric algorithm test sequence from ITU-T T.82, clause 7.2\n" + "-----------------------------------------------------------------\n"); + puts("Generating test image ..."); + testimage(testpic); + putchar('\n'); + pp = testpic; + + puts("Test 3.1: TPBON=0, Mx=0, LRLTWO=0, L0=1951"); + problems += test_cycle(&pp, 1960, 1951, JBG_DELAY_AT, + 0, 0, 1, 1951, 0, 317384L, "3.1"); + puts("Test 3.2: TPBON=0, Mx=0, LRLTWO=1, L0=1951"); + problems += test_cycle(&pp, 1960, 1951, JBG_DELAY_AT | JBG_LRLTWO, + 0, 0, 1, 1951, 0, 317132L, "3.2"); + puts("Test 3.3: TPBON=1, DPON=1, TPDON=1, Mx=8, LRLTWO=0, L0=128"); + problems += test_cycle(&pp, 1960, 1951, JBG_DELAY_AT | JBG_TPBON, + 0, 0, 1, 128, 8, 253653L, "3.3"); + puts("Test 3.4: TPBON=1, DPON=1, TPDON=1, Mx=8, LRLTWO=0, L0=2, 6 layers"); + problems += test_cycle(&pp, 1960, 1951, + JBG_DELAY_AT | JBG_TPBON | JBG_TPDON | JBG_DPON, + 0, 6, 1, 2, 8, 279314L, "3.4"); +#if 0 + puts("Test 3.5: as TEST 4 but with order bit SEQ set"); + problems += test_cycle(&pp, 1960, 1951, + JBG_DELAY_AT | JBG_TPBON | JBG_TPDON | JBG_DPON, + JBG_SEQ, 6, 1, 2, 8, 279314L, "3.5"); +#endif +#endif + + puts("4) Additional regression tests\n" + "------------------------------\n"); + ppp[0] = jbig_normal; + ppp[1] = jbig_upsidedown; + ppp[2] = jbig_inverse; + ppp[3] = jbig_inverse; + + i = 0; + for (layers = 0; layers <= 3; layers++) + for (order = 0; order < (int) (sizeof(orders)/sizeof(int)); order++) { + sprintf(test, "4.%ld", ++i); + printf("Test %s: order=%d, %d layers, 4 planes", test, orders[order], + layers); + problems += test_cycle(ppp, 23, 5*4, JBG_TPBON | JBG_TPDON | JBG_DPON, + orders[order], layers, 4, 2, 8, -1, test); + } + + + printf("\nTest result summary: the library has %s the test suite.\n\n", + problems ? FAILED : PASSED); + if (problems) + puts("This is bad. If you cannot identify the problem yourself, please " + "send\nthis output plus a detailed description of your " + "compile environment\n(OS, compiler, version, options, etc.) to " + "Markus Kuhn ."); + else + puts("Congratulations, everything is fine.\n"); + + return problems != 0; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/Jpeg.dsp b/SlnkDWFImpl/CxImage/jpeg/Jpeg.dsp new file mode 100644 index 0000000..2c7a7da --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/Jpeg.dsp @@ -0,0 +1,314 @@ +# Microsoft Developer Studio Project File - Name="jpeg" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=Jpeg - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Jpeg.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Jpeg.mak" CFG="Jpeg - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "jpeg - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "jpeg - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "jpeg - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x410 +# ADD RSC /l 0x410 /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "jpeg - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c +# ADD CPP /nologo /MDd /W3 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x410 +# ADD RSC /l 0x410 /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "jpeg - Win32 Release" +# Name "jpeg - Win32 Debug" +# Begin Source File + +SOURCE=.\Jcapimin.c +# End Source File +# Begin Source File + +SOURCE=.\Jcapistd.c +# End Source File +# Begin Source File + +SOURCE=.\Jccoefct.c +# End Source File +# Begin Source File + +SOURCE=.\Jccolor.c +# End Source File +# Begin Source File + +SOURCE=.\Jcdctmgr.c +# End Source File +# Begin Source File + +SOURCE=.\Jchuff.c +# End Source File +# Begin Source File + +SOURCE=.\Jchuff.h +# End Source File +# Begin Source File + +SOURCE=.\Jcinit.c +# End Source File +# Begin Source File + +SOURCE=.\Jcmainct.c +# End Source File +# Begin Source File + +SOURCE=.\Jcmarker.c +# End Source File +# Begin Source File + +SOURCE=.\Jcmaster.c +# End Source File +# Begin Source File + +SOURCE=.\Jcomapi.c +# End Source File +# Begin Source File + +SOURCE=.\Jconfig.h +# End Source File +# Begin Source File + +SOURCE=.\Jcparam.c +# End Source File +# Begin Source File + +SOURCE=.\Jcphuff.c +# End Source File +# Begin Source File + +SOURCE=.\Jcprepct.c +# End Source File +# Begin Source File + +SOURCE=.\Jcsample.c +# End Source File +# Begin Source File + +SOURCE=.\Jctrans.c +# End Source File +# Begin Source File + +SOURCE=.\Jdapimin.c +# End Source File +# Begin Source File + +SOURCE=.\Jdapistd.c +# End Source File +# Begin Source File + +SOURCE=.\Jdatadst.c +# End Source File +# Begin Source File + +SOURCE=.\Jdatasrc.c +# End Source File +# Begin Source File + +SOURCE=.\Jdcoefct.c +# End Source File +# Begin Source File + +SOURCE=.\Jdcolor.c +# End Source File +# Begin Source File + +SOURCE=.\Jdct.h +# End Source File +# Begin Source File + +SOURCE=.\Jddctmgr.c +# End Source File +# Begin Source File + +SOURCE=.\Jdhuff.c +# End Source File +# Begin Source File + +SOURCE=.\Jdhuff.h +# End Source File +# Begin Source File + +SOURCE=.\Jdinput.c +# End Source File +# Begin Source File + +SOURCE=.\Jdmainct.c +# End Source File +# Begin Source File + +SOURCE=.\Jdmarker.c +# End Source File +# Begin Source File + +SOURCE=.\Jdmaster.c +# End Source File +# Begin Source File + +SOURCE=.\Jdmerge.c +# End Source File +# Begin Source File + +SOURCE=.\Jdphuff.c +# End Source File +# Begin Source File + +SOURCE=.\Jdpostct.c +# End Source File +# Begin Source File + +SOURCE=.\Jdsample.c +# End Source File +# Begin Source File + +SOURCE=.\Jdtrans.c +# End Source File +# Begin Source File + +SOURCE=.\Jerror.c +# End Source File +# Begin Source File + +SOURCE=.\Jerror.h +# End Source File +# Begin Source File + +SOURCE=.\Jfdctflt.c +# End Source File +# Begin Source File + +SOURCE=.\Jfdctfst.c +# End Source File +# Begin Source File + +SOURCE=.\Jfdctint.c +# End Source File +# Begin Source File + +SOURCE=.\Jidctflt.c +# End Source File +# Begin Source File + +SOURCE=.\Jidctfst.c +# End Source File +# Begin Source File + +SOURCE=.\Jidctint.c +# End Source File +# Begin Source File + +SOURCE=.\Jidctred.c +# End Source File +# Begin Source File + +SOURCE=.\Jinclude.h +# End Source File +# Begin Source File + +SOURCE=.\Jmemmgr.c +# End Source File +# Begin Source File + +SOURCE=.\Jmemnobs.c +# End Source File +# Begin Source File + +SOURCE=.\Jmemsys.h +# End Source File +# Begin Source File + +SOURCE=.\Jmorecfg.h +# End Source File +# Begin Source File + +SOURCE=.\Jpegint.h +# End Source File +# Begin Source File + +SOURCE=.\Jpeglib.h +# End Source File +# Begin Source File + +SOURCE=.\Jquant1.c +# End Source File +# Begin Source File + +SOURCE=.\Jquant2.c +# End Source File +# Begin Source File + +SOURCE=.\Jutils.c +# End Source File +# Begin Source File + +SOURCE=.\Jversion.h +# End Source File +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/jpeg/Jpeg.dsw b/SlnkDWFImpl/CxImage/jpeg/Jpeg.dsw new file mode 100644 index 0000000..64050a7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/Jpeg.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 5.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "jpeg"=.\jpeg.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/jpeg/Jpeg.sln b/SlnkDWFImpl/CxImage/jpeg/Jpeg.sln new file mode 100644 index 0000000..87888ab --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/Jpeg.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 7.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jpeg", "Jpeg.vcproj", "{C51D2DBC-FCB8-4C79-B38F-6BDA19557640}" +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + ConfigName.0 = Debug + ConfigName.1 = Release + EndGlobalSection + GlobalSection(ProjectDependencies) = postSolution + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {C51D2DBC-FCB8-4C79-B38F-6BDA19557640}.Debug.ActiveCfg = Debug|Win32 + {C51D2DBC-FCB8-4C79-B38F-6BDA19557640}.Debug.Build.0 = Debug|Win32 + {C51D2DBC-FCB8-4C79-B38F-6BDA19557640}.Release.ActiveCfg = Release|Win32 + {C51D2DBC-FCB8-4C79-B38F-6BDA19557640}.Release.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj b/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj new file mode 100644 index 0000000..3256b94 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj @@ -0,0 +1,1130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj.7.00.old b/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj.7.00.old new file mode 100644 index 0000000..6f95cea --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj.7.00.old @@ -0,0 +1,270 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..f57b253 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/Jpeg.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/jpeg/Readme.txt b/SlnkDWFImpl/CxImage/jpeg/Readme.txt new file mode 100644 index 0000000..911d0e8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/Readme.txt @@ -0,0 +1,385 @@ +The Independent JPEG Group's JPEG software +========================================== + +README for release 6b of 27-Mar-1998 +==================================== + +This distribution contains the sixth public release of the Independent JPEG +Group's free JPEG software. You are welcome to redistribute this software and +to use it for any purpose, subject to the conditions under LEGAL ISSUES, below. + +Serious users of this software (particularly those incorporating it into +larger programs) should contact IJG at jpeg-info@uunet.uu.net to be added to +our electronic mailing list. Mailing list members are notified of updates +and have a chance to participate in technical discussions, etc. + +This software is the work of Tom Lane, Philip Gladstone, Jim Boucher, +Lee Crocker, Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, +Guido Vollbeding, Ge' Weijers, and other members of the Independent JPEG +Group. + +IJG is not affiliated with the official ISO JPEG standards committee. + + +DOCUMENTATION ROADMAP +===================== + +This file contains the following sections: + +OVERVIEW General description of JPEG and the IJG software. +LEGAL ISSUES Copyright, lack of warranty, terms of distribution. +REFERENCES Where to learn more about JPEG. +ARCHIVE LOCATIONS Where to find newer versions of this software. +RELATED SOFTWARE Other stuff you should get. +FILE FORMAT WARS Software *not* to get. +TO DO Plans for future IJG releases. + +Other documentation files in the distribution are: + +User documentation: + install.doc How to configure and install the IJG software. + usage.doc Usage instructions for cjpeg, djpeg, jpegtran, + rdjpgcom, and wrjpgcom. + *.1 Unix-style man pages for programs (same info as usage.doc). + wizard.doc Advanced usage instructions for JPEG wizards only. + change.log Version-to-version change highlights. +Programmer and internal documentation: + libjpeg.doc How to use the JPEG library in your own programs. + example.c Sample code for calling the JPEG library. + structure.doc Overview of the JPEG library's internal structure. + filelist.doc Road map of IJG files. + coderules.doc Coding style rules --- please read if you contribute code. + +Please read at least the files install.doc and usage.doc. Useful information +can also be found in the JPEG FAQ (Frequently Asked Questions) article. See +ARCHIVE LOCATIONS below to find out where to obtain the FAQ article. + +If you want to understand how the JPEG code works, we suggest reading one or +more of the REFERENCES, then looking at the documentation files (in roughly +the order listed) before diving into the code. + + +OVERVIEW +======== + +This package contains C software to implement JPEG image compression and +decompression. JPEG (pronounced "jay-peg") is a standardized compression +method for full-color and gray-scale images. JPEG is intended for compressing +"real-world" scenes; line drawings, cartoons and other non-realistic images +are not its strong suit. JPEG is lossy, meaning that the output image is not +exactly identical to the input image. Hence you must not use JPEG if you +have to have identical output bits. However, on typical photographic images, +very good compression levels can be obtained with no visible change, and +remarkably high compression levels are possible if you can tolerate a +low-quality image. For more details, see the references, or just experiment +with various compression settings. + +This software implements JPEG baseline, extended-sequential, and progressive +compression processes. Provision is made for supporting all variants of these +processes, although some uncommon parameter settings aren't implemented yet. +For legal reasons, we are not distributing code for the arithmetic-coding +variants of JPEG; see LEGAL ISSUES. We have made no provision for supporting +the hierarchical or lossless processes defined in the standard. + +We provide a set of library routines for reading and writing JPEG image files, +plus two sample applications "cjpeg" and "djpeg", which use the library to +perform conversion between JPEG and some other popular image file formats. +The library is intended to be reused in other applications. + +In order to support file conversion and viewing software, we have included +considerable functionality beyond the bare JPEG coding/decoding capability; +for example, the color quantization modules are not strictly part of JPEG +decoding, but they are essential for output to colormapped file formats or +colormapped displays. These extra functions can be compiled out of the +library if not required for a particular application. We have also included +"jpegtran", a utility for lossless transcoding between different JPEG +processes, and "rdjpgcom" and "wrjpgcom", two simple applications for +inserting and extracting textual comments in JFIF files. + +The emphasis in designing this software has been on achieving portability and +flexibility, while also making it fast enough to be useful. In particular, +the software is not intended to be read as a tutorial on JPEG. (See the +REFERENCES section for introductory material.) Rather, it is intended to +be reliable, portable, industrial-strength code. We do not claim to have +achieved that goal in every aspect of the software, but we strive for it. + +We welcome the use of this software as a component of commercial products. +No royalty is required, but we do ask for an acknowledgement in product +documentation, as described under LEGAL ISSUES. + + +LEGAL ISSUES +============ + +In plain English: + +1. We don't promise that this software works. (But if you find any bugs, + please let us know!) +2. You can use this software for whatever you want. You don't have to pay us. +3. You may not pretend that you wrote this software. If you use it in a + program, you must acknowledge somewhere in your documentation that + you've used the IJG code. + +In legalese: + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-1998, Thomas G. Lane. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +ansi2knr.c is included in this distribution by permission of L. Peter Deutsch, +sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA. +ansi2knr.c is NOT covered by the above copyright and conditions, but instead +by the usual distribution terms of the Free Software Foundation; principally, +that you must include source code if you redistribute it. (See the file +ansi2knr.c for full details.) However, since ansi2knr.c is not needed as part +of any program generated from the IJG code, this does not limit you more than +the foregoing paragraphs do. + +The Unix configuration script "configure" was produced with GNU Autoconf. +It is copyright by the Free Software Foundation but is freely distributable. +The same holds for its supporting scripts (config.guess, config.sub, +ltconfig, ltmain.sh). Another support script, install-sh, is copyright +by M.I.T. but is also freely distributable. + +It appears that the arithmetic coding option of the JPEG spec is covered by +patents owned by IBM, AT&T, and Mitsubishi. Hence arithmetic coding cannot +legally be used without obtaining one or more licenses. For this reason, +support for arithmetic coding has been removed from the free JPEG software. +(Since arithmetic coding provides only a marginal gain over the unpatented +Huffman mode, it is unlikely that very many implementations will support it.) +So far as we are aware, there are no patent restrictions on the remaining +code. + +The IJG distribution formerly included code to read and write GIF files. +To avoid entanglement with the Unisys LZW patent, GIF reading support has +been removed altogether, and the GIF writer has been simplified to produce +"uncompressed GIFs". This technique does not use the LZW algorithm; the +resulting GIF files are larger than usual, but are readable by all standard +GIF decoders. + +We are required to state that + "The Graphics Interchange Format(c) is the Copyright property of + CompuServe Incorporated. GIF(sm) is a Service Mark property of + CompuServe Incorporated." + + +REFERENCES +========== + +We highly recommend reading one or more of these references before trying to +understand the innards of the JPEG software. + +The best short technical introduction to the JPEG compression algorithm is + Wallace, Gregory K. "The JPEG Still Picture Compression Standard", + Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44. +(Adjacent articles in that issue discuss MPEG motion picture compression, +applications of JPEG, and related topics.) If you don't have the CACM issue +handy, a PostScript file containing a revised version of Wallace's article is +available at ftp://ftp.uu.net/graphics/jpeg/wallace.ps.gz. The file (actually +a preprint for an article that appeared in IEEE Trans. Consumer Electronics) +omits the sample images that appeared in CACM, but it includes corrections +and some added material. Note: the Wallace article is copyright ACM and IEEE, +and it may not be used for commercial purposes. + +A somewhat less technical, more leisurely introduction to JPEG can be found in +"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by +M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides +good explanations and example C code for a multitude of compression methods +including JPEG. It is an excellent source if you are comfortable reading C +code but don't know much about data compression in general. The book's JPEG +sample code is far from industrial-strength, but when you are ready to look +at a full implementation, you've got one here... + +The best full description of JPEG is the textbook "JPEG Still Image Data +Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published +by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. Price US$59.95, 638 pp. +The book includes the complete text of the ISO JPEG standards (DIS 10918-1 +and draft DIS 10918-2). This is by far the most complete exposition of JPEG +in existence, and we highly recommend it. + +The JPEG standard itself is not available electronically; you must order a +paper copy through ISO or ITU. (Unless you feel a need to own a certified +official copy, we recommend buying the Pennebaker and Mitchell book instead; +it's much cheaper and includes a great deal of useful explanatory material.) +In the USA, copies of the standard may be ordered from ANSI Sales at (212) +642-4900, or from Global Engineering Documents at (800) 854-7179. (ANSI +doesn't take credit card orders, but Global does.) It's not cheap: as of +1992, ANSI was charging $95 for Part 1 and $47 for Part 2, plus 7% +shipping/handling. The standard is divided into two parts, Part 1 being the +actual specification, while Part 2 covers compliance testing methods. Part 1 +is titled "Digital Compression and Coding of Continuous-tone Still Images, +Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS +10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of +Continuous-tone Still Images, Part 2: Compliance testing" and has document +numbers ISO/IEC IS 10918-2, ITU-T T.83. + +Some extensions to the original JPEG standard are defined in JPEG Part 3, +a newer ISO standard numbered ISO/IEC IS 10918-3 and ITU-T T.84. IJG +currently does not support any Part 3 extensions. + +The JPEG standard does not specify all details of an interchangeable file +format. For the omitted details we follow the "JFIF" conventions, revision +1.02. A copy of the JFIF spec is available from: + Literature Department + C-Cube Microsystems, Inc. + 1778 McCarthy Blvd. + Milpitas, CA 95035 + phone (408) 944-6300, fax (408) 944-6314 +A PostScript version of this document is available by FTP at +ftp://ftp.uu.net/graphics/jpeg/jfif.ps.gz. There is also a plain text +version at ftp://ftp.uu.net/graphics/jpeg/jfif.txt.gz, but it is missing +the figures. + +The TIFF 6.0 file format specification can be obtained by FTP from +ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation scheme +found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems. +IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6). +Instead, we recommend the JPEG design proposed by TIFF Technical Note #2 +(Compression tag 7). Copies of this Note can be obtained from ftp.sgi.com or +from ftp://ftp.uu.net/graphics/jpeg/. It is expected that the next revision +of the TIFF spec will replace the 6.0 JPEG design with the Note's design. +Although IJG's own code does not support TIFF/JPEG, the free libtiff library +uses our library to implement TIFF/JPEG per the Note. libtiff is available +from ftp://ftp.sgi.com/graphics/tiff/. + + +ARCHIVE LOCATIONS +================= + +The "official" archive site for this software is ftp.uu.net (Internet +address 192.48.96.9). The most recent released version can always be found +there in directory graphics/jpeg. This particular version will be archived +as ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz. If you don't have +direct Internet access, UUNET's archives are also available via UUCP; contact +help@uunet.uu.net for information on retrieving files that way. + +Numerous Internet sites maintain copies of the UUNET files. However, only +ftp.uu.net is guaranteed to have the latest official version. + +You can also obtain this software in DOS-compatible "zip" archive format from +the SimTel archives (ftp://ftp.simtel.net/pub/simtelnet/msdos/graphics/), or +on CompuServe in the Graphics Support forum (GO CIS:GRAPHSUP), library 12 +"JPEG Tools". Again, these versions may sometimes lag behind the ftp.uu.net +release. + +The JPEG FAQ (Frequently Asked Questions) article is a useful source of +general information about JPEG. It is updated constantly and therefore is +not included in this distribution. The FAQ is posted every two weeks to +Usenet newsgroups comp.graphics.misc, news.answers, and other groups. +It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/ +and other news.answers archive sites, including the official news.answers +archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/. +If you don't have Web or FTP access, send e-mail to mail-server@rtfm.mit.edu +with body + send usenet/news.answers/jpeg-faq/part1 + send usenet/news.answers/jpeg-faq/part2 + + +RELATED SOFTWARE +================ + +Numerous viewing and image manipulation programs now support JPEG. (Quite a +few of them use this library to do so.) The JPEG FAQ described above lists +some of the more popular free and shareware viewers, and tells where to +obtain them on Internet. + +If you are on a Unix machine, we highly recommend Jef Poskanzer's free +PBMPLUS software, which provides many useful operations on PPM-format image +files. In particular, it can convert PPM images to and from a wide range of +other formats, thus making cjpeg/djpeg considerably more useful. The latest +version is distributed by the NetPBM group, and is available from numerous +sites, notably ftp://wuarchive.wustl.edu/graphics/graphics/packages/NetPBM/. +Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software is; +you are likely to have difficulty making it work on any non-Unix machine. + +A different free JPEG implementation, written by the PVRG group at Stanford, +is available from ftp://havefun.stanford.edu/pub/jpeg/. This program +is designed for research and experimentation rather than production use; +it is slower, harder to use, and less portable than the IJG code, but it +is easier to read and modify. Also, the PVRG code supports lossless JPEG, +which we do not. (On the other hand, it doesn't do progressive JPEG.) + + +FILE FORMAT WARS +================ + +Some JPEG programs produce files that are not compatible with our library. +The root of the problem is that the ISO JPEG committee failed to specify a +concrete file format. Some vendors "filled in the blanks" on their own, +creating proprietary formats that no one else could read. (For example, none +of the early commercial JPEG implementations for the Macintosh were able to +exchange compressed files.) + +The file format we have adopted is called JFIF (see REFERENCES). This format +has been agreed to by a number of major commercial JPEG vendors, and it has +become the de facto standard. JFIF is a minimal or "low end" representation. +We recommend the use of TIFF/JPEG (TIFF revision 6.0 as modified by TIFF +Technical Note #2) for "high end" applications that need to record a lot of +additional data about an image. TIFF/JPEG is fairly new and not yet widely +supported, unfortunately. + +The upcoming JPEG Part 3 standard defines a file format called SPIFF. +SPIFF is interoperable with JFIF, in the sense that most JFIF decoders should +be able to read the most common variant of SPIFF. SPIFF has some technical +advantages over JFIF, but its major claim to fame is simply that it is an +official standard rather than an informal one. At this point it is unclear +whether SPIFF will supersede JFIF or whether JFIF will remain the de-facto +standard. IJG intends to support SPIFF once the standard is frozen, but we +have not decided whether it should become our default output format or not. +(In any case, our decoder will remain capable of reading JFIF indefinitely.) + +Various proprietary file formats incorporating JPEG compression also exist. +We have little or no sympathy for the existence of these formats. Indeed, +one of the original reasons for developing this free software was to help +force convergence on common, open format standards for JPEG files. Don't +use a proprietary file format! + + +TO DO +===== + +The major thrust for v7 will probably be improvement of visual quality. +The current method for scaling the quantization tables is known not to be +very good at low Q values. We also intend to investigate block boundary +smoothing, "poor man's variable quantization", and other means of improving +quality-vs-file-size performance without sacrificing compatibility. + +In future versions, we are considering supporting some of the upcoming JPEG +Part 3 extensions --- principally, variable quantization and the SPIFF file +format. + +As always, speeding things up is of great interest. + +Please send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net. diff --git a/SlnkDWFImpl/CxImage/jpeg/change.log b/SlnkDWFImpl/CxImage/jpeg/change.log new file mode 100644 index 0000000..953680c --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/change.log @@ -0,0 +1,217 @@ +CHANGE LOG for Independent JPEG Group's JPEG software + + +Version 6b 27-Mar-1998 +----------------------- + +jpegtran has new features for lossless image transformations (rotation +and flipping) as well as "lossless" reduction to grayscale. + +jpegtran now copies comments by default; it has a -copy switch to enable +copying all APPn blocks as well, or to suppress comments. (Formerly it +always suppressed comments and APPn blocks.) jpegtran now also preserves +JFIF version and resolution information. + +New decompressor library feature: COM and APPn markers found in the input +file can be saved in memory for later use by the application. (Before, +you had to code this up yourself with a custom marker processor.) + +There is an unused field "void * client_data" now in compress and decompress +parameter structs; this may be useful in some applications. + +JFIF version number information is now saved by the decoder and accepted by +the encoder. jpegtran uses this to copy the source file's version number, +to ensure "jpegtran -copy all" won't create bogus files that contain JFXX +extensions but claim to be version 1.01. Applications that generate their +own JFXX extension markers also (finally) have a supported way to cause the +encoder to emit JFIF version number 1.02. + +djpeg's trace mode reports JFIF 1.02 thumbnail images as such, rather +than as unknown APP0 markers. + +In -verbose mode, djpeg and rdjpgcom will try to print the contents of +APP12 markers as text. Some digital cameras store useful text information +in APP12 markers. + +Handling of truncated data streams is more robust: blocks beyond the one in +which the error occurs will be output as uniform gray, or left unchanged +if decoding a progressive JPEG. The appearance no longer depends on the +Huffman tables being used. + +Huffman tables are checked for validity much more carefully than before. + +To avoid the Unisys LZW patent, djpeg's GIF output capability has been +changed to produce "uncompressed GIFs", and cjpeg's GIF input capability +has been removed altogether. We're not happy about it either, but there +seems to be no good alternative. + +The configure script now supports building libjpeg as a shared library +on many flavors of Unix (all the ones that GNU libtool knows how to +build shared libraries for). Use "./configure --enable-shared" to +try this out. + +New jconfig file and makefiles for Microsoft Visual C++ and Developer Studio. +Also, a jconfig file and a build script for Metrowerks CodeWarrior +on Apple Macintosh. makefile.dj has been updated for DJGPP v2, and there +are miscellaneous other minor improvements in the makefiles. + +jmemmac.c now knows how to create temporary files following Mac System 7 +conventions. + +djpeg's -map switch is now able to read raw-format PPM files reliably. + +cjpeg -progressive -restart no longer generates any unnecessary DRI markers. + +Multiple calls to jpeg_simple_progression for a single JPEG object +no longer leak memory. + + +Version 6a 7-Feb-96 +-------------------- + +Library initialization sequence modified to detect version mismatches +and struct field packing mismatches between library and calling application. +This change requires applications to be recompiled, but does not require +any application source code change. + +All routine declarations changed to the style "GLOBAL(type) name ...", +that is, GLOBAL, LOCAL, METHODDEF, EXTERN are now macros taking the +routine's return type as an argument. This makes it possible to add +Microsoft-style linkage keywords to all the routines by changing just +these macros. Note that any application code that was using these macros +will have to be changed. + +DCT coefficient quantization tables are now stored in normal array order +rather than zigzag order. Application code that calls jpeg_add_quant_table, +or otherwise manipulates quantization tables directly, will need to be +changed. If you need to make such code work with either older or newer +versions of the library, a test like "#if JPEG_LIB_VERSION >= 61" is +recommended. + +djpeg's trace capability now dumps DQT tables in natural order, not zigzag +order. This allows the trace output to be made into a "-qtables" file +more easily. + +New system-dependent memory manager module for use on Apple Macintosh. + +Fix bug in cjpeg's -smooth option: last one or two scanlines would be +duplicates of the prior line unless the image height mod 16 was 1 or 2. + +Repair minor problems in VMS, BCC, MC6 makefiles. + +New configure script based on latest GNU Autoconf. + +Correct the list of include files needed by MetroWerks C for ccommand(). + +Numerous small documentation updates. + + +Version 6 2-Aug-95 +------------------- + +Progressive JPEG support: library can read and write full progressive JPEG +files. A "buffered image" mode supports incremental decoding for on-the-fly +display of progressive images. Simply recompiling an existing IJG-v5-based +decoder with v6 should allow it to read progressive files, though of course +without any special progressive display. + +New "jpegtran" application performs lossless transcoding between different +JPEG formats; primarily, it can be used to convert baseline to progressive +JPEG and vice versa. In support of jpegtran, the library now allows lossless +reading and writing of JPEG files as DCT coefficient arrays. This ability +may be of use in other applications. + +Notes for programmers: +* We changed jpeg_start_decompress() to be able to suspend; this makes all +decoding modes available to suspending-input applications. However, +existing applications that use suspending input will need to be changed +to check the return value from jpeg_start_decompress(). You don't need to +do anything if you don't use a suspending data source. +* We changed the interface to the virtual array routines: access_virt_array +routines now take a count of the number of rows to access this time. The +last parameter to request_virt_array routines is now interpreted as the +maximum number of rows that may be accessed at once, but not necessarily +the height of every access. + + +Version 5b 15-Mar-95 +--------------------- + +Correct bugs with grayscale images having v_samp_factor > 1. + +jpeg_write_raw_data() now supports output suspension. + +Correct bugs in "configure" script for case of compiling in +a directory other than the one containing the source files. + +Repair bug in jquant1.c: sometimes didn't use as many colors as it could. + +Borland C makefile and jconfig file work under either MS-DOS or OS/2. + +Miscellaneous improvements to documentation. + + +Version 5a 7-Dec-94 +-------------------- + +Changed color conversion roundoff behavior so that grayscale values are +represented exactly. (This causes test image files to change.) + +Make ordered dither use 16x16 instead of 4x4 pattern for a small quality +improvement. + +New configure script based on latest GNU Autoconf. +Fix configure script to handle CFLAGS correctly. +Rename *.auto files to *.cfg, so that configure script still works if +file names have been truncated for DOS. + +Fix bug in rdbmp.c: didn't allow for extra data between header and image. + +Modify rdppm.c/wrppm.c to handle 2-byte raw PPM/PGM formats for 12-bit data. + +Fix several bugs in rdrle.c. + +NEED_SHORT_EXTERNAL_NAMES option was broken. + +Revise jerror.h/jerror.c for more flexibility in message table. + +Repair oversight in jmemname.c NO_MKTEMP case: file could be there +but unreadable. + + +Version 5 24-Sep-94 +-------------------- + +Version 5 represents a nearly complete redesign and rewrite of the IJG +software. Major user-visible changes include: + * Automatic configuration simplifies installation for most Unix systems. + * A range of speed vs. image quality tradeoffs are supported. + This includes resizing of an image during decompression: scaling down + by a factor of 1/2, 1/4, or 1/8 is handled very efficiently. + * New programs rdjpgcom and wrjpgcom allow insertion and extraction + of text comments in a JPEG file. + +The application programmer's interface to the library has changed completely. +Notable improvements include: + * We have eliminated the use of callback routines for handling the + uncompressed image data. The application now sees the library as a + set of routines that it calls to read or write image data on a + scanline-by-scanline basis. + * The application image data is represented in a conventional interleaved- + pixel format, rather than as a separate array for each color channel. + This can save a copying step in many programs. + * The handling of compressed data has been cleaned up: the application can + supply routines to source or sink the compressed data. It is possible to + suspend processing on source/sink buffer overrun, although this is not + supported in all operating modes. + * All static state has been eliminated from the library, so that multiple + instances of compression or decompression can be active concurrently. + * JPEG abbreviated datastream formats are supported, ie, quantization and + Huffman tables can be stored separately from the image data. + * And not only that, but the documentation of the library has improved + considerably! + + +The last widely used release before the version 5 rewrite was version 4A of +18-Feb-93. Change logs before that point have been discarded, since they +are not of much interest after the rewrite. diff --git a/SlnkDWFImpl/CxImage/jpeg/filelist.txt b/SlnkDWFImpl/CxImage/jpeg/filelist.txt new file mode 100644 index 0000000..ad6a82d --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/filelist.txt @@ -0,0 +1,210 @@ +IJG JPEG LIBRARY: FILE LIST + +Copyright (C) 1994-1998, Thomas G. Lane. +This file is part of the Independent JPEG Group's software. +For conditions of distribution and use, see the accompanying README file. + + +Here is a road map to the files in the IJG JPEG distribution. The +distribution includes the JPEG library proper, plus two application +programs ("cjpeg" and "djpeg") which use the library to convert JPEG +files to and from some other popular image formats. A third application +"jpegtran" uses the library to do lossless conversion between different +variants of JPEG. There are also two stand-alone applications, +"rdjpgcom" and "wrjpgcom". + + +THE JPEG LIBRARY +================ + +Include files: + +jpeglib.h JPEG library's exported data and function declarations. +jconfig.h Configuration declarations. Note: this file is not present + in the distribution; it is generated during installation. +jmorecfg.h Additional configuration declarations; need not be changed + for a standard installation. +jerror.h Declares JPEG library's error and trace message codes. +jinclude.h Central include file used by all IJG .c files to reference + system include files. +jpegint.h JPEG library's internal data structures. +jchuff.h Private declarations for Huffman encoder modules. +jdhuff.h Private declarations for Huffman decoder modules. +jdct.h Private declarations for forward & reverse DCT subsystems. +jmemsys.h Private declarations for memory management subsystem. +jversion.h Version information. + +Applications using the library should include jpeglib.h (which in turn +includes jconfig.h and jmorecfg.h). Optionally, jerror.h may be included +if the application needs to reference individual JPEG error codes. The +other include files are intended for internal use and would not normally +be included by an application program. (cjpeg/djpeg/etc do use jinclude.h, +since its function is to improve portability of the whole IJG distribution. +Most other applications will directly include the system include files they +want, and hence won't need jinclude.h.) + + +C source code files: + +These files contain most of the functions intended to be called directly by +an application program: + +jcapimin.c Application program interface: core routines for compression. +jcapistd.c Application program interface: standard compression. +jdapimin.c Application program interface: core routines for decompression. +jdapistd.c Application program interface: standard decompression. +jcomapi.c Application program interface routines common to compression + and decompression. +jcparam.c Compression parameter setting helper routines. +jctrans.c API and library routines for transcoding compression. +jdtrans.c API and library routines for transcoding decompression. + +Compression side of the library: + +jcinit.c Initialization: determines which other modules to use. +jcmaster.c Master control: setup and inter-pass sequencing logic. +jcmainct.c Main buffer controller (preprocessor => JPEG compressor). +jcprepct.c Preprocessor buffer controller. +jccoefct.c Buffer controller for DCT coefficient buffer. +jccolor.c Color space conversion. +jcsample.c Downsampling. +jcdctmgr.c DCT manager (DCT implementation selection & control). +jfdctint.c Forward DCT using slow-but-accurate integer method. +jfdctfst.c Forward DCT using faster, less accurate integer method. +jfdctflt.c Forward DCT using floating-point arithmetic. +jchuff.c Huffman entropy coding for sequential JPEG. +jcphuff.c Huffman entropy coding for progressive JPEG. +jcmarker.c JPEG marker writing. +jdatadst.c Data destination manager for stdio output. + +Decompression side of the library: + +jdmaster.c Master control: determines which other modules to use. +jdinput.c Input controller: controls input processing modules. +jdmainct.c Main buffer controller (JPEG decompressor => postprocessor). +jdcoefct.c Buffer controller for DCT coefficient buffer. +jdpostct.c Postprocessor buffer controller. +jdmarker.c JPEG marker reading. +jdhuff.c Huffman entropy decoding for sequential JPEG. +jdphuff.c Huffman entropy decoding for progressive JPEG. +jddctmgr.c IDCT manager (IDCT implementation selection & control). +jidctint.c Inverse DCT using slow-but-accurate integer method. +jidctfst.c Inverse DCT using faster, less accurate integer method. +jidctflt.c Inverse DCT using floating-point arithmetic. +jidctred.c Inverse DCTs with reduced-size outputs. +jdsample.c Upsampling. +jdcolor.c Color space conversion. +jdmerge.c Merged upsampling/color conversion (faster, lower quality). +jquant1.c One-pass color quantization using a fixed-spacing colormap. +jquant2.c Two-pass color quantization using a custom-generated colormap. + Also handles one-pass quantization to an externally given map. +jdatasrc.c Data source manager for stdio input. + +Support files for both compression and decompression: + +jerror.c Standard error handling routines (application replaceable). +jmemmgr.c System-independent (more or less) memory management code. +jutils.c Miscellaneous utility routines. + +jmemmgr.c relies on a system-dependent memory management module. The IJG +distribution includes the following implementations of the system-dependent +module: + +jmemnobs.c "No backing store": assumes adequate virtual memory exists. +jmemansi.c Makes temporary files with ANSI-standard routine tmpfile(). +jmemname.c Makes temporary files with program-generated file names. +jmemdos.c Custom implementation for MS-DOS (16-bit environment only): + can use extended and expanded memory as well as temp files. +jmemmac.c Custom implementation for Apple Macintosh. + +Exactly one of the system-dependent modules should be configured into an +installed JPEG library (see install.doc for hints about which one to use). +On unusual systems you may find it worthwhile to make a special +system-dependent memory manager. + + +Non-C source code files: + +jmemdosa.asm 80x86 assembly code support for jmemdos.c; used only in + MS-DOS-specific configurations of the JPEG library. + + +CJPEG/DJPEG/JPEGTRAN +==================== + +Include files: + +cdjpeg.h Declarations shared by cjpeg/djpeg/jpegtran modules. +cderror.h Additional error and trace message codes for cjpeg et al. +transupp.h Declarations for jpegtran support routines in transupp.c. + +C source code files: + +cjpeg.c Main program for cjpeg. +djpeg.c Main program for djpeg. +jpegtran.c Main program for jpegtran. +cdjpeg.c Utility routines used by all three programs. +rdcolmap.c Code to read a colormap file for djpeg's "-map" switch. +rdswitch.c Code to process some of cjpeg's more complex switches. + Also used by jpegtran. +transupp.c Support code for jpegtran: lossless image manipulations. + +Image file reader modules for cjpeg: + +rdbmp.c BMP file input. +rdgif.c GIF file input (now just a stub). +rdppm.c PPM/PGM file input. +rdrle.c Utah RLE file input. +rdtarga.c Targa file input. + +Image file writer modules for djpeg: + +wrbmp.c BMP file output. +wrgif.c GIF file output (a mere shadow of its former self). +wrppm.c PPM/PGM file output. +wrrle.c Utah RLE file output. +wrtarga.c Targa file output. + + +RDJPGCOM/WRJPGCOM +================= + +C source code files: + +rdjpgcom.c Stand-alone rdjpgcom application. +wrjpgcom.c Stand-alone wrjpgcom application. + +These programs do not depend on the IJG library. They do use +jconfig.h and jinclude.h, only to improve portability. + + +ADDITIONAL FILES +================ + +Documentation (see README for a guide to the documentation files): + +README Master documentation file. +*.doc Other documentation files. +*.1 Documentation in Unix man page format. +change.log Version-to-version change highlights. +example.c Sample code for calling JPEG library. + +Configuration/installation files and programs (see install.doc for more info): + +configure Unix shell script to perform automatic configuration. +ltconfig Support scripts for configure (from GNU libtool). +ltmain.sh +config.guess +config.sub +install-sh Install shell script for those Unix systems lacking one. +ckconfig.c Program to generate jconfig.h on non-Unix systems. +jconfig.doc Template for making jconfig.h by hand. +makefile.* Sample makefiles for particular systems. +jconfig.* Sample jconfig.h for particular systems. +ansi2knr.c De-ANSIfier for pre-ANSI C compilers (courtesy of + L. Peter Deutsch and Aladdin Enterprises). + +Test files (see install.doc for test procedure): + +test*.* Source and comparison files for confidence test. + These are binary image files, NOT text files. diff --git a/SlnkDWFImpl/CxImage/jpeg/jcapimin.c b/SlnkDWFImpl/CxImage/jpeg/jcapimin.c new file mode 100644 index 0000000..502e62e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcapimin.c @@ -0,0 +1,280 @@ +/* + * jcapimin.c + * + * Copyright (C) 1994-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains application interface code for the compression half + * of the JPEG library. These are the "minimum" API routines that may be + * needed in either the normal full-compression case or the transcoding-only + * case. + * + * Most of the routines intended to be called directly by an application + * are in this file or in jcapistd.c. But also see jcparam.c for + * parameter-setup helper routines, jcomapi.c for routines shared by + * compression and decompression, and jctrans.c for the transcoding case. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* + * Initialization of a JPEG compression object. + * The error manager must already be set up (in case memory manager fails). + */ + +GLOBAL(void) +jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize) +{ + int i; + + /* Guard against version mismatches between library and caller. */ + cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */ + if ((int) version != JPEG_LIB_VERSION) + ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version); + if (structsize != SIZEOF(struct jpeg_compress_struct)) + ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, + (int) SIZEOF(struct jpeg_compress_struct), (int) structsize); + + /* For debugging purposes, we zero the whole master structure. + * But the application has already set the err pointer, and may have set + * client_data, so we have to save and restore those fields. + * Note: if application hasn't set client_data, tools like Purify may + * complain here. + */ + { + struct jpeg_error_mgr * err = cinfo->err; + void * client_data = cinfo->client_data; /* ignore Purify complaint here */ + MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct)); + cinfo->err = err; + cinfo->client_data = client_data; + } + cinfo->is_decompressor = FALSE; + + /* Initialize a memory manager instance for this object */ + jinit_memory_mgr((j_common_ptr) cinfo); + + /* Zero out pointers to permanent structures. */ + cinfo->progress = NULL; + cinfo->dest = NULL; + + cinfo->comp_info = NULL; + + for (i = 0; i < NUM_QUANT_TBLS; i++) + cinfo->quant_tbl_ptrs[i] = NULL; + + for (i = 0; i < NUM_HUFF_TBLS; i++) { + cinfo->dc_huff_tbl_ptrs[i] = NULL; + cinfo->ac_huff_tbl_ptrs[i] = NULL; + } + + cinfo->script_space = NULL; + + cinfo->input_gamma = 1.0; /* in case application forgets */ + + /* OK, I'm ready */ + cinfo->global_state = CSTATE_START; +} + + +/* + * Destruction of a JPEG compression object + */ + +GLOBAL(void) +jpeg_destroy_compress (j_compress_ptr cinfo) +{ + jpeg_destroy((j_common_ptr) cinfo); /* use common routine */ +} + + +/* + * Abort processing of a JPEG compression operation, + * but don't destroy the object itself. + */ + +GLOBAL(void) +jpeg_abort_compress (j_compress_ptr cinfo) +{ + jpeg_abort((j_common_ptr) cinfo); /* use common routine */ +} + + +/* + * Forcibly suppress or un-suppress all quantization and Huffman tables. + * Marks all currently defined tables as already written (if suppress) + * or not written (if !suppress). This will control whether they get emitted + * by a subsequent jpeg_start_compress call. + * + * This routine is exported for use by applications that want to produce + * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but + * since it is called by jpeg_start_compress, we put it here --- otherwise + * jcparam.o would be linked whether the application used it or not. + */ + +GLOBAL(void) +jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress) +{ + int i; + JQUANT_TBL * qtbl; + JHUFF_TBL * htbl; + + for (i = 0; i < NUM_QUANT_TBLS; i++) { + if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL) + qtbl->sent_table = suppress; + } + + for (i = 0; i < NUM_HUFF_TBLS; i++) { + if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL) + htbl->sent_table = suppress; + if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL) + htbl->sent_table = suppress; + } +} + + +/* + * Finish JPEG compression. + * + * If a multipass operating mode was selected, this may do a great deal of + * work including most of the actual output. + */ + +GLOBAL(void) +jpeg_finish_compress (j_compress_ptr cinfo) +{ + JDIMENSION iMCU_row; + + if (cinfo->global_state == CSTATE_SCANNING || + cinfo->global_state == CSTATE_RAW_OK) { + /* Terminate first pass */ + if (cinfo->next_scanline < cinfo->image_height) + ERREXIT(cinfo, JERR_TOO_LITTLE_DATA); + (*cinfo->master->finish_pass) (cinfo); + } else if (cinfo->global_state != CSTATE_WRCOEFS) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + /* Perform any remaining passes */ + while (! cinfo->master->is_last_pass) { + (*cinfo->master->prepare_for_pass) (cinfo); + for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) { + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long) iMCU_row; + cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows; + (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); + } + /* We bypass the main controller and invoke coef controller directly; + * all work is being done from the coefficient buffer. + */ + if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL)) + ERREXIT(cinfo, JERR_CANT_SUSPEND); + } + (*cinfo->master->finish_pass) (cinfo); + } + /* Write EOI, do final cleanup */ + (*cinfo->marker->write_file_trailer) (cinfo); + (*cinfo->dest->term_destination) (cinfo); + /* We can use jpeg_abort to release memory and reset global_state */ + jpeg_abort((j_common_ptr) cinfo); +} + + +/* + * Write a special marker. + * This is only recommended for writing COM or APPn markers. + * Must be called after jpeg_start_compress() and before + * first call to jpeg_write_scanlines() or jpeg_write_raw_data(). + */ + +GLOBAL(void) +jpeg_write_marker (j_compress_ptr cinfo, int marker, + const JOCTET *dataptr, unsigned int datalen) +{ + JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val)); + + if (cinfo->next_scanline != 0 || + (cinfo->global_state != CSTATE_SCANNING && + cinfo->global_state != CSTATE_RAW_OK && + cinfo->global_state != CSTATE_WRCOEFS)) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + (*cinfo->marker->write_marker_header) (cinfo, marker, datalen); + write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */ + while (datalen--) { + (*write_marker_byte) (cinfo, *dataptr); + dataptr++; + } +} + +/* Same, but piecemeal. */ + +GLOBAL(void) +jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen) +{ + if (cinfo->next_scanline != 0 || + (cinfo->global_state != CSTATE_SCANNING && + cinfo->global_state != CSTATE_RAW_OK && + cinfo->global_state != CSTATE_WRCOEFS)) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + (*cinfo->marker->write_marker_header) (cinfo, marker, datalen); +} + +GLOBAL(void) +jpeg_write_m_byte (j_compress_ptr cinfo, int val) +{ + (*cinfo->marker->write_marker_byte) (cinfo, val); +} + + +/* + * Alternate compression function: just write an abbreviated table file. + * Before calling this, all parameters and a data destination must be set up. + * + * To produce a pair of files containing abbreviated tables and abbreviated + * image data, one would proceed as follows: + * + * initialize JPEG object + * set JPEG parameters + * set destination to table file + * jpeg_write_tables(cinfo); + * set destination to image file + * jpeg_start_compress(cinfo, FALSE); + * write data... + * jpeg_finish_compress(cinfo); + * + * jpeg_write_tables has the side effect of marking all tables written + * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress + * will not re-emit the tables unless it is passed write_all_tables=TRUE. + */ + +GLOBAL(void) +jpeg_write_tables (j_compress_ptr cinfo) +{ + if (cinfo->global_state != CSTATE_START) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + /* (Re)initialize error mgr and destination modules */ + (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo); + (*cinfo->dest->init_destination) (cinfo); + /* Initialize the marker writer ... bit of a crock to do it here. */ + jinit_marker_writer(cinfo); + /* Write them tables! */ + (*cinfo->marker->write_tables_only) (cinfo); + /* And clean up. */ + (*cinfo->dest->term_destination) (cinfo); + /* + * In library releases up through v6a, we called jpeg_abort() here to free + * any working memory allocated by the destination manager and marker + * writer. Some applications had a problem with that: they allocated space + * of their own from the library memory manager, and didn't want it to go + * away during write_tables. So now we do nothing. This will cause a + * memory leak if an app calls write_tables repeatedly without doing a full + * compression cycle or otherwise resetting the JPEG object. However, that + * seems less bad than unexpectedly freeing memory in the normal case. + * An app that prefers the old behavior can call jpeg_abort for itself after + * each call to jpeg_write_tables(). + */ +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jcapistd.c b/SlnkDWFImpl/CxImage/jpeg/jcapistd.c new file mode 100644 index 0000000..fed66ca --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcapistd.c @@ -0,0 +1,161 @@ +/* + * jcapistd.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains application interface code for the compression half + * of the JPEG library. These are the "standard" API routines that are + * used in the normal full-compression case. They are not used by a + * transcoding-only application. Note that if an application links in + * jpeg_start_compress, it will end up linking in the entire compressor. + * We thus must separate this file from jcapimin.c to avoid linking the + * whole compression library into a transcoder. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* + * Compression initialization. + * Before calling this, all parameters and a data destination must be set up. + * + * We require a write_all_tables parameter as a failsafe check when writing + * multiple datastreams from the same compression object. Since prior runs + * will have left all the tables marked sent_table=TRUE, a subsequent run + * would emit an abbreviated stream (no tables) by default. This may be what + * is wanted, but for safety's sake it should not be the default behavior: + * programmers should have to make a deliberate choice to emit abbreviated + * images. Therefore the documentation and examples should encourage people + * to pass write_all_tables=TRUE; then it will take active thought to do the + * wrong thing. + */ + +GLOBAL(void) +jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables) +{ + if (cinfo->global_state != CSTATE_START) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + if (write_all_tables) + jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */ + + /* (Re)initialize error mgr and destination modules */ + (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo); + (*cinfo->dest->init_destination) (cinfo); + /* Perform master selection of active modules */ + jinit_compress_master(cinfo); + /* Set up for the first pass */ + (*cinfo->master->prepare_for_pass) (cinfo); + /* Ready for application to drive first pass through jpeg_write_scanlines + * or jpeg_write_raw_data. + */ + cinfo->next_scanline = 0; + cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING); +} + + +/* + * Write some scanlines of data to the JPEG compressor. + * + * The return value will be the number of lines actually written. + * This should be less than the supplied num_lines only in case that + * the data destination module has requested suspension of the compressor, + * or if more than image_height scanlines are passed in. + * + * Note: we warn about excess calls to jpeg_write_scanlines() since + * this likely signals an application programmer error. However, + * excess scanlines passed in the last valid call are *silently* ignored, + * so that the application need not adjust num_lines for end-of-image + * when using a multiple-scanline buffer. + */ + +GLOBAL(JDIMENSION) +jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines, + JDIMENSION num_lines) +{ + JDIMENSION row_ctr, rows_left; + + if (cinfo->global_state != CSTATE_SCANNING) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + if (cinfo->next_scanline >= cinfo->image_height) + WARNMS(cinfo, JWRN_TOO_MUCH_DATA); + + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long) cinfo->next_scanline; + cinfo->progress->pass_limit = (long) cinfo->image_height; + (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); + } + + /* Give master control module another chance if this is first call to + * jpeg_write_scanlines. This lets output of the frame/scan headers be + * delayed so that application can write COM, etc, markers between + * jpeg_start_compress and jpeg_write_scanlines. + */ + if (cinfo->master->call_pass_startup) + (*cinfo->master->pass_startup) (cinfo); + + /* Ignore any extra scanlines at bottom of image. */ + rows_left = cinfo->image_height - cinfo->next_scanline; + if (num_lines > rows_left) + num_lines = rows_left; + + row_ctr = 0; + (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines); + cinfo->next_scanline += row_ctr; + return row_ctr; +} + + +/* + * Alternate entry point to write raw data. + * Processes exactly one iMCU row per call, unless suspended. + */ + +GLOBAL(JDIMENSION) +jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data, + JDIMENSION num_lines) +{ + JDIMENSION lines_per_iMCU_row; + + if (cinfo->global_state != CSTATE_RAW_OK) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + if (cinfo->next_scanline >= cinfo->image_height) { + WARNMS(cinfo, JWRN_TOO_MUCH_DATA); + return 0; + } + + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long) cinfo->next_scanline; + cinfo->progress->pass_limit = (long) cinfo->image_height; + (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); + } + + /* Give master control module another chance if this is first call to + * jpeg_write_raw_data. This lets output of the frame/scan headers be + * delayed so that application can write COM, etc, markers between + * jpeg_start_compress and jpeg_write_raw_data. + */ + if (cinfo->master->call_pass_startup) + (*cinfo->master->pass_startup) (cinfo); + + /* Verify that at least one iMCU row has been passed. */ + lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE; + if (num_lines < lines_per_iMCU_row) + ERREXIT(cinfo, JERR_BUFFER_SIZE); + + /* Directly compress the row. */ + if (! (*cinfo->coef->compress_data) (cinfo, data)) { + /* If compressor did not consume the whole row, suspend processing. */ + return 0; + } + + /* OK, we processed one iMCU row. */ + cinfo->next_scanline += lines_per_iMCU_row; + return lines_per_iMCU_row; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jccoefct.c b/SlnkDWFImpl/CxImage/jpeg/jccoefct.c new file mode 100644 index 0000000..c713b85 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jccoefct.c @@ -0,0 +1,449 @@ +/* + * jccoefct.c + * + * Copyright (C) 1994-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the coefficient buffer controller for compression. + * This controller is the top level of the JPEG compressor proper. + * The coefficient buffer lies between forward-DCT and entropy encoding steps. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* We use a full-image coefficient buffer when doing Huffman optimization, + * and also for writing multiple-scan JPEG files. In all cases, the DCT + * step is run during the first pass, and subsequent passes need only read + * the buffered coefficients. + */ +#ifdef ENTROPY_OPT_SUPPORTED +#define FULL_COEF_BUFFER_SUPPORTED +#else +#ifdef C_MULTISCAN_FILES_SUPPORTED +#define FULL_COEF_BUFFER_SUPPORTED +#endif +#endif + + +/* Private buffer controller object */ + +typedef struct { + struct jpeg_c_coef_controller pub; /* public fields */ + + JDIMENSION iMCU_row_num; /* iMCU row # within image */ + JDIMENSION mcu_ctr; /* counts MCUs processed in current row */ + int MCU_vert_offset; /* counts MCU rows within iMCU row */ + int MCU_rows_per_iMCU_row; /* number of such rows needed */ + + /* For single-pass compression, it's sufficient to buffer just one MCU + * (although this may prove a bit slow in practice). We allocate a + * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each + * MCU constructed and sent. (On 80x86, the workspace is FAR even though + * it's not really very big; this is to keep the module interfaces unchanged + * when a large coefficient buffer is necessary.) + * In multi-pass modes, this array points to the current MCU's blocks + * within the virtual arrays. + */ + JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU]; + + /* In multi-pass modes, we need a virtual block array for each component. */ + jvirt_barray_ptr whole_image[MAX_COMPONENTS]; +} my_coef_controller; + +typedef my_coef_controller * my_coef_ptr; + + +/* Forward declarations */ +METHODDEF(boolean) compress_data + JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); +#ifdef FULL_COEF_BUFFER_SUPPORTED +METHODDEF(boolean) compress_first_pass + JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); +METHODDEF(boolean) compress_output + JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); +#endif + + +LOCAL(void) +start_iMCU_row (j_compress_ptr cinfo) +/* Reset within-iMCU-row counters for a new row */ +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + + /* In an interleaved scan, an MCU row is the same as an iMCU row. + * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. + * But at the bottom of the image, process only what's left. + */ + if (cinfo->comps_in_scan > 1) { + coef->MCU_rows_per_iMCU_row = 1; + } else { + if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1)) + coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; + else + coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; + } + + coef->mcu_ctr = 0; + coef->MCU_vert_offset = 0; +} + + +/* + * Initialize for a processing pass. + */ + +METHODDEF(void) +start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + + coef->iMCU_row_num = 0; + start_iMCU_row(cinfo); + + switch (pass_mode) { + case JBUF_PASS_THRU: + if (coef->whole_image[0] != NULL) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + coef->pub.compress_data = compress_data; + break; +#ifdef FULL_COEF_BUFFER_SUPPORTED + case JBUF_SAVE_AND_PASS: + if (coef->whole_image[0] == NULL) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + coef->pub.compress_data = compress_first_pass; + break; + case JBUF_CRANK_DEST: + if (coef->whole_image[0] == NULL) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + coef->pub.compress_data = compress_output; + break; +#endif + default: + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + break; + } +} + + +/* + * Process some data in the single-pass case. + * We process the equivalent of one fully interleaved MCU row ("iMCU" row) + * per call, ie, v_samp_factor block rows for each component in the image. + * Returns TRUE if the iMCU row is completed, FALSE if suspended. + * + * NB: input_buf contains a plane for each component in image, + * which we index according to the component's SOF position. + */ + +METHODDEF(boolean) +compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + JDIMENSION MCU_col_num; /* index of current MCU within row */ + JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; + JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; + int blkn, bi, ci, yindex, yoffset, blockcnt; + JDIMENSION ypos, xpos; + jpeg_component_info *compptr; + + /* Loop to write as much as one whole iMCU row */ + for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; + yoffset++) { + for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col; + MCU_col_num++) { + /* Determine where data comes from in input_buf and do the DCT thing. + * Each call on forward_DCT processes a horizontal row of DCT blocks + * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks + * sequentially. Dummy blocks at the right or bottom edge are filled in + * specially. The data in them does not matter for image reconstruction, + * so we fill them with values that will encode to the smallest amount of + * data, viz: all zeroes in the AC entries, DC entries equal to previous + * block's DC value. (Thanks to Thomas Kinsman for this idea.) + */ + blkn = 0; + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width + : compptr->last_col_width; + xpos = MCU_col_num * compptr->MCU_sample_width; + ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */ + for (yindex = 0; yindex < compptr->MCU_height; yindex++) { + if (coef->iMCU_row_num < last_iMCU_row || + yoffset+yindex < compptr->last_row_height) { + (*cinfo->fdct->forward_DCT) (cinfo, compptr, + input_buf[compptr->component_index], + coef->MCU_buffer[blkn], + ypos, xpos, (JDIMENSION) blockcnt); + if (blockcnt < compptr->MCU_width) { + /* Create some dummy blocks at the right edge of the image. */ + jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt], + (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK)); + for (bi = blockcnt; bi < compptr->MCU_width; bi++) { + coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0]; + } + } + } else { + /* Create a row of dummy blocks at the bottom of the image. */ + jzero_far((void FAR *) coef->MCU_buffer[blkn], + compptr->MCU_width * SIZEOF(JBLOCK)); + for (bi = 0; bi < compptr->MCU_width; bi++) { + coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0]; + } + } + blkn += compptr->MCU_width; + ypos += DCTSIZE; + } + } + /* Try to write the MCU. In event of a suspension failure, we will + * re-DCT the MCU on restart (a bit inefficient, could be fixed...) + */ + if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) { + /* Suspension forced; update state counters and exit */ + coef->MCU_vert_offset = yoffset; + coef->mcu_ctr = MCU_col_num; + return FALSE; + } + } + /* Completed an MCU row, but perhaps not an iMCU row */ + coef->mcu_ctr = 0; + } + /* Completed the iMCU row, advance counters for next one */ + coef->iMCU_row_num++; + start_iMCU_row(cinfo); + return TRUE; +} + + +#ifdef FULL_COEF_BUFFER_SUPPORTED + +/* + * Process some data in the first pass of a multi-pass case. + * We process the equivalent of one fully interleaved MCU row ("iMCU" row) + * per call, ie, v_samp_factor block rows for each component in the image. + * This amount of data is read from the source buffer, DCT'd and quantized, + * and saved into the virtual arrays. We also generate suitable dummy blocks + * as needed at the right and lower edges. (The dummy blocks are constructed + * in the virtual arrays, which have been padded appropriately.) This makes + * it possible for subsequent passes not to worry about real vs. dummy blocks. + * + * We must also emit the data to the entropy encoder. This is conveniently + * done by calling compress_output() after we've loaded the current strip + * of the virtual arrays. + * + * NB: input_buf contains a plane for each component in image. All + * components are DCT'd and loaded into the virtual arrays in this pass. + * However, it may be that only a subset of the components are emitted to + * the entropy encoder during this first pass; be careful about looking + * at the scan-dependent variables (MCU dimensions, etc). + */ + +METHODDEF(boolean) +compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; + JDIMENSION blocks_across, MCUs_across, MCUindex; + int bi, ci, h_samp_factor, block_row, block_rows, ndummy; + JCOEF lastDC; + jpeg_component_info *compptr; + JBLOCKARRAY buffer; + JBLOCKROW thisblockrow, lastblockrow; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Align the virtual buffer for this component. */ + buffer = (*cinfo->mem->access_virt_barray) + ((j_common_ptr) cinfo, coef->whole_image[ci], + coef->iMCU_row_num * compptr->v_samp_factor, + (JDIMENSION) compptr->v_samp_factor, TRUE); + /* Count non-dummy DCT block rows in this iMCU row. */ + if (coef->iMCU_row_num < last_iMCU_row) + block_rows = compptr->v_samp_factor; + else { + /* NB: can't use last_row_height here, since may not be set! */ + block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); + if (block_rows == 0) block_rows = compptr->v_samp_factor; + } + blocks_across = compptr->width_in_blocks; + h_samp_factor = compptr->h_samp_factor; + /* Count number of dummy blocks to be added at the right margin. */ + ndummy = (int) (blocks_across % h_samp_factor); + if (ndummy > 0) + ndummy = h_samp_factor - ndummy; + /* Perform DCT for all non-dummy blocks in this iMCU row. Each call + * on forward_DCT processes a complete horizontal row of DCT blocks. + */ + for (block_row = 0; block_row < block_rows; block_row++) { + thisblockrow = buffer[block_row]; + (*cinfo->fdct->forward_DCT) (cinfo, compptr, + input_buf[ci], thisblockrow, + (JDIMENSION) (block_row * DCTSIZE), + (JDIMENSION) 0, blocks_across); + if (ndummy > 0) { + /* Create dummy blocks at the right edge of the image. */ + thisblockrow += blocks_across; /* => first dummy block */ + jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK)); + lastDC = thisblockrow[-1][0]; + for (bi = 0; bi < ndummy; bi++) { + thisblockrow[bi][0] = lastDC; + } + } + } + /* If at end of image, create dummy block rows as needed. + * The tricky part here is that within each MCU, we want the DC values + * of the dummy blocks to match the last real block's DC value. + * This squeezes a few more bytes out of the resulting file... + */ + if (coef->iMCU_row_num == last_iMCU_row) { + blocks_across += ndummy; /* include lower right corner */ + MCUs_across = blocks_across / h_samp_factor; + for (block_row = block_rows; block_row < compptr->v_samp_factor; + block_row++) { + thisblockrow = buffer[block_row]; + lastblockrow = buffer[block_row-1]; + jzero_far((void FAR *) thisblockrow, + (size_t) (blocks_across * SIZEOF(JBLOCK))); + for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) { + lastDC = lastblockrow[h_samp_factor-1][0]; + for (bi = 0; bi < h_samp_factor; bi++) { + thisblockrow[bi][0] = lastDC; + } + thisblockrow += h_samp_factor; /* advance to next MCU in row */ + lastblockrow += h_samp_factor; + } + } + } + } + /* NB: compress_output will increment iMCU_row_num if successful. + * A suspension return will result in redoing all the work above next time. + */ + + /* Emit data to the entropy encoder, sharing code with subsequent passes */ + return compress_output(cinfo, input_buf); +} + + +/* + * Process some data in subsequent passes of a multi-pass case. + * We process the equivalent of one fully interleaved MCU row ("iMCU" row) + * per call, ie, v_samp_factor block rows for each component in the scan. + * The data is obtained from the virtual arrays and fed to the entropy coder. + * Returns TRUE if the iMCU row is completed, FALSE if suspended. + * + * NB: input_buf is ignored; it is likely to be a NULL pointer. + */ + +METHODDEF(boolean) +compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + JDIMENSION MCU_col_num; /* index of current MCU within row */ + int blkn, ci, xindex, yindex, yoffset; + JDIMENSION start_col; + JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; + JBLOCKROW buffer_ptr; + jpeg_component_info *compptr; + + /* Align the virtual buffers for the components used in this scan. + * NB: during first pass, this is safe only because the buffers will + * already be aligned properly, so jmemmgr.c won't need to do any I/O. + */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + buffer[ci] = (*cinfo->mem->access_virt_barray) + ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index], + coef->iMCU_row_num * compptr->v_samp_factor, + (JDIMENSION) compptr->v_samp_factor, FALSE); + } + + /* Loop to process one whole iMCU row */ + for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; + yoffset++) { + for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row; + MCU_col_num++) { + /* Construct list of pointers to DCT blocks belonging to this MCU */ + blkn = 0; /* index of current DCT block within MCU */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + start_col = MCU_col_num * compptr->MCU_width; + for (yindex = 0; yindex < compptr->MCU_height; yindex++) { + buffer_ptr = buffer[ci][yindex+yoffset] + start_col; + for (xindex = 0; xindex < compptr->MCU_width; xindex++) { + coef->MCU_buffer[blkn++] = buffer_ptr++; + } + } + } + /* Try to write the MCU. */ + if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) { + /* Suspension forced; update state counters and exit */ + coef->MCU_vert_offset = yoffset; + coef->mcu_ctr = MCU_col_num; + return FALSE; + } + } + /* Completed an MCU row, but perhaps not an iMCU row */ + coef->mcu_ctr = 0; + } + /* Completed the iMCU row, advance counters for next one */ + coef->iMCU_row_num++; + start_iMCU_row(cinfo); + return TRUE; +} + +#endif /* FULL_COEF_BUFFER_SUPPORTED */ + + +/* + * Initialize coefficient buffer controller. + */ + +GLOBAL(void) +jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer) +{ + my_coef_ptr coef; + + coef = (my_coef_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_coef_controller)); + cinfo->coef = (struct jpeg_c_coef_controller *) coef; + coef->pub.start_pass = start_pass_coef; + + /* Create the coefficient buffer. */ + if (need_full_buffer) { +#ifdef FULL_COEF_BUFFER_SUPPORTED + /* Allocate a full-image virtual array for each component, */ + /* padded to a multiple of samp_factor DCT blocks in each direction. */ + int ci; + jpeg_component_info *compptr; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + coef->whole_image[ci] = (*cinfo->mem->request_virt_barray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, + (JDIMENSION) jround_up((long) compptr->width_in_blocks, + (long) compptr->h_samp_factor), + (JDIMENSION) jround_up((long) compptr->height_in_blocks, + (long) compptr->v_samp_factor), + (JDIMENSION) compptr->v_samp_factor); + } +#else + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); +#endif + } else { + /* We only need a single-MCU buffer. */ + JBLOCKROW buffer; + int i; + + buffer = (JBLOCKROW) + (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, + C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); + for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) { + coef->MCU_buffer[i] = buffer + i; + } + coef->whole_image[0] = NULL; /* flag for no virtual arrays */ + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jccolor.c b/SlnkDWFImpl/CxImage/jpeg/jccolor.c new file mode 100644 index 0000000..73c90f2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jccolor.c @@ -0,0 +1,458 @@ +/* + * jccolor.c + * + * Copyright (C) 1991-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains input colorspace conversion routines. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + +/* Private subobject */ + +typedef struct { + struct jpeg_color_converter pub; /* public fields */ + + /* Private state for RGB->YCC conversion */ + INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */ +} my_color_converter; + +typedef my_color_converter * my_cconvert_ptr; + + +/**************** RGB -> YCbCr conversion: most common case **************/ + +/* + * YCbCr is defined per CCIR 601-1, except that Cb and Cr are + * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5. + * The conversion equations to be implemented are therefore + * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B + * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE + * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE + * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.) + * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2, + * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and + * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0) + * were not represented exactly. Now we sacrifice exact representation of + * maximum red and maximum blue in order to get exact grayscales. + * + * To avoid floating-point arithmetic, we represent the fractional constants + * as integers scaled up by 2^16 (about 4 digits precision); we have to divide + * the products by 2^16, with appropriate rounding, to get the correct answer. + * + * For even more speed, we avoid doing any multiplications in the inner loop + * by precalculating the constants times R,G,B for all possible values. + * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table); + * for 12-bit samples it is still acceptable. It's not very reasonable for + * 16-bit samples, but if you want lossless storage you shouldn't be changing + * colorspace anyway. + * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included + * in the tables to save adding them separately in the inner loop. + */ + +#define SCALEBITS 16 /* speediest right-shift on some machines */ +#define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS) +#define ONE_HALF ((INT32) 1 << (SCALEBITS-1)) +#define FIX(x) ((INT32) ((x) * (1L< Y section */ +#define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */ +#define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */ +#define R_CB_OFF (3*(MAXJSAMPLE+1)) +#define G_CB_OFF (4*(MAXJSAMPLE+1)) +#define B_CB_OFF (5*(MAXJSAMPLE+1)) +#define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */ +#define G_CR_OFF (6*(MAXJSAMPLE+1)) +#define B_CR_OFF (7*(MAXJSAMPLE+1)) +#define TABLE_SIZE (8*(MAXJSAMPLE+1)) + + +/* + * Initialize for RGB->YCC colorspace conversion. + */ + +METHODDEF(void) +rgb_ycc_start (j_compress_ptr cinfo) +{ + my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; + INT32 * rgb_ycc_tab; + INT32 i; + + /* Allocate and fill in the conversion tables. */ + cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (TABLE_SIZE * SIZEOF(INT32))); + + for (i = 0; i <= MAXJSAMPLE; i++) { + rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i; + rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i; + rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF; + rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i; + rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i; + /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr. + * This ensures that the maximum output will round to MAXJSAMPLE + * not MAXJSAMPLE+1, and thus that we don't have to range-limit. + */ + rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1; +/* B=>Cb and R=>Cr tables are the same + rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1; +*/ + rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i; + rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i; + } +} + + +/* + * Convert some rows of samples to the JPEG colorspace. + * + * Note that we change from the application's interleaved-pixel format + * to our internal noninterleaved, one-plane-per-component format. + * The input buffer is therefore three times as wide as the output buffer. + * + * A starting row offset is provided only for the output buffer. The caller + * can easily adjust the passed input_buf value to accommodate any row + * offset required on that side. + */ + +METHODDEF(void) +rgb_ycc_convert (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPIMAGE output_buf, + JDIMENSION output_row, int num_rows) +{ + my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; + register int r, g, b; + register INT32 * ctab = cconvert->rgb_ycc_tab; + register JSAMPROW inptr; + register JSAMPROW outptr0, outptr1, outptr2; + register JDIMENSION col; + JDIMENSION num_cols = cinfo->image_width; + + while (--num_rows >= 0) { + inptr = *input_buf++; + outptr0 = output_buf[0][output_row]; + outptr1 = output_buf[1][output_row]; + outptr2 = output_buf[2][output_row]; + output_row++; + for (col = 0; col < num_cols; col++) { + r = GETJSAMPLE(inptr[RGB_RED]); + g = GETJSAMPLE(inptr[RGB_GREEN]); + b = GETJSAMPLE(inptr[RGB_BLUE]); + inptr += RGB_PIXELSIZE; + /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations + * must be too; we do not need an explicit range-limiting operation. + * Hence the value being shifted is never negative, and we don't + * need the general RIGHT_SHIFT macro. + */ + /* Y */ + outptr0[col] = (JSAMPLE) + ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) + >> SCALEBITS); + /* Cb */ + outptr1[col] = (JSAMPLE) + ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF]) + >> SCALEBITS); + /* Cr */ + outptr2[col] = (JSAMPLE) + ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF]) + >> SCALEBITS); + } + } +} + + +/**************** Cases other than RGB -> YCbCr **************/ + + +/* + * Convert some rows of samples to the JPEG colorspace. + * This version handles RGB->grayscale conversion, which is the same + * as the RGB->Y portion of RGB->YCbCr. + * We assume rgb_ycc_start has been called (we only use the Y tables). + */ + +METHODDEF(void) +rgb_gray_convert (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPIMAGE output_buf, + JDIMENSION output_row, int num_rows) +{ + my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; + register int r, g, b; + register INT32 * ctab = cconvert->rgb_ycc_tab; + register JSAMPROW inptr; + register JSAMPROW outptr; + register JDIMENSION col; + JDIMENSION num_cols = cinfo->image_width; + + while (--num_rows >= 0) { + inptr = *input_buf++; + outptr = output_buf[0][output_row]; + output_row++; + for (col = 0; col < num_cols; col++) { + r = GETJSAMPLE(inptr[RGB_RED]); + g = GETJSAMPLE(inptr[RGB_GREEN]); + b = GETJSAMPLE(inptr[RGB_BLUE]); + inptr += RGB_PIXELSIZE; + /* Y */ + outptr[col] = (JSAMPLE) + ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) + >> SCALEBITS); + } + } +} + + +/* + * Convert some rows of samples to the JPEG colorspace. + * This version handles Adobe-style CMYK->YCCK conversion, + * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same + * conversion as above, while passing K (black) unchanged. + * We assume rgb_ycc_start has been called. + */ + +METHODDEF(void) +cmyk_ycck_convert (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPIMAGE output_buf, + JDIMENSION output_row, int num_rows) +{ + my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; + register int r, g, b; + register INT32 * ctab = cconvert->rgb_ycc_tab; + register JSAMPROW inptr; + register JSAMPROW outptr0, outptr1, outptr2, outptr3; + register JDIMENSION col; + JDIMENSION num_cols = cinfo->image_width; + + while (--num_rows >= 0) { + inptr = *input_buf++; + outptr0 = output_buf[0][output_row]; + outptr1 = output_buf[1][output_row]; + outptr2 = output_buf[2][output_row]; + outptr3 = output_buf[3][output_row]; + output_row++; + for (col = 0; col < num_cols; col++) { + r = MAXJSAMPLE - GETJSAMPLE(inptr[0]); + g = MAXJSAMPLE - GETJSAMPLE(inptr[1]); + b = MAXJSAMPLE - GETJSAMPLE(inptr[2]); + /* K passes through as-is */ + outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */ + inptr += 4; + /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations + * must be too; we do not need an explicit range-limiting operation. + * Hence the value being shifted is never negative, and we don't + * need the general RIGHT_SHIFT macro. + */ + /* Y */ + outptr0[col] = (JSAMPLE) + ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) + >> SCALEBITS); + /* Cb */ + outptr1[col] = (JSAMPLE) + ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF]) + >> SCALEBITS); + /* Cr */ + outptr2[col] = (JSAMPLE) + ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF]) + >> SCALEBITS); + } + } +} + + +/* + * Convert some rows of samples to the JPEG colorspace. + * This version handles grayscale output with no conversion. + * The source can be either plain grayscale or YCbCr (since Y == gray). + */ + +METHODDEF(void) +grayscale_convert (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPIMAGE output_buf, + JDIMENSION output_row, int num_rows) +{ + register JSAMPROW inptr; + register JSAMPROW outptr; + register JDIMENSION col; + JDIMENSION num_cols = cinfo->image_width; + int instride = cinfo->input_components; + + while (--num_rows >= 0) { + inptr = *input_buf++; + outptr = output_buf[0][output_row]; + output_row++; + for (col = 0; col < num_cols; col++) { + outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */ + inptr += instride; + } + } +} + + +/* + * Convert some rows of samples to the JPEG colorspace. + * This version handles multi-component colorspaces without conversion. + * We assume input_components == num_components. + */ + +METHODDEF(void) +null_convert (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPIMAGE output_buf, + JDIMENSION output_row, int num_rows) +{ + register JSAMPROW inptr; + register JSAMPROW outptr; + register JDIMENSION col; + register int ci; + int nc = cinfo->num_components; + JDIMENSION num_cols = cinfo->image_width; + + while (--num_rows >= 0) { + /* It seems fastest to make a separate pass for each component. */ + for (ci = 0; ci < nc; ci++) { + inptr = *input_buf; + outptr = output_buf[ci][output_row]; + for (col = 0; col < num_cols; col++) { + outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */ + inptr += nc; + } + } + input_buf++; + output_row++; + } +} + + +/* + * Empty method for start_pass. + */ + +METHODDEF(void) +null_method (j_compress_ptr cinfo) +{ + /* no work needed */ +} + + +/* + * Module initialization routine for input colorspace conversion. + */ + +GLOBAL(void) +jinit_color_converter (j_compress_ptr cinfo) +{ + my_cconvert_ptr cconvert; + + cconvert = (my_cconvert_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_color_converter)); + cinfo->cconvert = (struct jpeg_color_converter *) cconvert; + /* set start_pass to null method until we find out differently */ + cconvert->pub.start_pass = null_method; + + /* Make sure input_components agrees with in_color_space */ + switch (cinfo->in_color_space) { + case JCS_GRAYSCALE: + if (cinfo->input_components != 1) + ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); + break; + + case JCS_RGB: +#if RGB_PIXELSIZE != 3 + if (cinfo->input_components != RGB_PIXELSIZE) + ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); + break; +#endif /* else share code with YCbCr */ + + case JCS_YCbCr: + if (cinfo->input_components != 3) + ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); + break; + + case JCS_CMYK: + case JCS_YCCK: + if (cinfo->input_components != 4) + ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); + break; + + default: /* JCS_UNKNOWN can be anything */ + if (cinfo->input_components < 1) + ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); + break; + } + + /* Check num_components, set conversion method based on requested space */ + switch (cinfo->jpeg_color_space) { + case JCS_GRAYSCALE: + if (cinfo->num_components != 1) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + if (cinfo->in_color_space == JCS_GRAYSCALE) + cconvert->pub.color_convert = grayscale_convert; + else if (cinfo->in_color_space == JCS_RGB) { + cconvert->pub.start_pass = rgb_ycc_start; + cconvert->pub.color_convert = rgb_gray_convert; + } else if (cinfo->in_color_space == JCS_YCbCr) + cconvert->pub.color_convert = grayscale_convert; + else + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + + case JCS_RGB: + if (cinfo->num_components != 3) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3) + cconvert->pub.color_convert = null_convert; + else + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + + case JCS_YCbCr: + if (cinfo->num_components != 3) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + if (cinfo->in_color_space == JCS_RGB) { + cconvert->pub.start_pass = rgb_ycc_start; + cconvert->pub.color_convert = rgb_ycc_convert; + } else if (cinfo->in_color_space == JCS_YCbCr) + cconvert->pub.color_convert = null_convert; + else + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + + case JCS_CMYK: + if (cinfo->num_components != 4) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + if (cinfo->in_color_space == JCS_CMYK) + cconvert->pub.color_convert = null_convert; + else + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + + case JCS_YCCK: + if (cinfo->num_components != 4) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + if (cinfo->in_color_space == JCS_CMYK) { + cconvert->pub.start_pass = rgb_ycc_start; + cconvert->pub.color_convert = cmyk_ycck_convert; + } else if (cinfo->in_color_space == JCS_YCCK) + cconvert->pub.color_convert = null_convert; + else + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + + default: /* allow null conversion of JCS_UNKNOWN */ + if (cinfo->jpeg_color_space != cinfo->in_color_space || + cinfo->num_components != cinfo->input_components) + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + cconvert->pub.color_convert = null_convert; + break; + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jcdctmgr.c b/SlnkDWFImpl/CxImage/jpeg/jcdctmgr.c new file mode 100644 index 0000000..e3f90dc --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcdctmgr.c @@ -0,0 +1,387 @@ +/* + * jcdctmgr.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the forward-DCT management logic. + * This code selects a particular DCT implementation to be used, + * and it performs related housekeeping chores including coefficient + * quantization. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + + +/* Private subobject for this module */ + +typedef struct { + struct jpeg_forward_dct pub; /* public fields */ + + /* Pointer to the DCT routine actually in use */ + forward_DCT_method_ptr do_dct; + + /* The actual post-DCT divisors --- not identical to the quant table + * entries, because of scaling (especially for an unnormalized DCT). + * Each table is given in normal array order. + */ + DCTELEM * divisors[NUM_QUANT_TBLS]; + +#ifdef DCT_FLOAT_SUPPORTED + /* Same as above for the floating-point case. */ + float_DCT_method_ptr do_float_dct; + FAST_FLOAT * float_divisors[NUM_QUANT_TBLS]; +#endif +} my_fdct_controller; + +typedef my_fdct_controller * my_fdct_ptr; + + +/* + * Initialize for a processing pass. + * Verify that all referenced Q-tables are present, and set up + * the divisor table for each one. + * In the current implementation, DCT of all components is done during + * the first pass, even if only some components will be output in the + * first scan. Hence all components should be examined here. + */ + +METHODDEF(void) +start_pass_fdctmgr (j_compress_ptr cinfo) +{ + my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; + int ci, qtblno, i; + jpeg_component_info *compptr; + JQUANT_TBL * qtbl; + DCTELEM * dtbl; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + qtblno = compptr->quant_tbl_no; + /* Make sure specified quantization table is present */ + if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || + cinfo->quant_tbl_ptrs[qtblno] == NULL) + ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno); + qtbl = cinfo->quant_tbl_ptrs[qtblno]; + /* Compute divisors for this quant table */ + /* We may do this more than once for same table, but it's not a big deal */ + switch (cinfo->dct_method) { +#ifdef DCT_ISLOW_SUPPORTED + case JDCT_ISLOW: + /* For LL&M IDCT method, divisors are equal to raw quantization + * coefficients multiplied by 8 (to counteract scaling). + */ + if (fdct->divisors[qtblno] == NULL) { + fdct->divisors[qtblno] = (DCTELEM *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + DCTSIZE2 * SIZEOF(DCTELEM)); + } + dtbl = fdct->divisors[qtblno]; + for (i = 0; i < DCTSIZE2; i++) { + dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3; + } + break; +#endif +#ifdef DCT_IFAST_SUPPORTED + case JDCT_IFAST: + { + /* For AA&N IDCT method, divisors are equal to quantization + * coefficients scaled by scalefactor[row]*scalefactor[col], where + * scalefactor[0] = 1 + * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 + * We apply a further scale factor of 8. + */ +#define CONST_BITS 14 + static const INT16 aanscales[DCTSIZE2] = { + /* precomputed values scaled up by 14 bits */ + 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, + 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270, + 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, + 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315, + 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, + 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552, + 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, + 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247 + }; + SHIFT_TEMPS + + if (fdct->divisors[qtblno] == NULL) { + fdct->divisors[qtblno] = (DCTELEM *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + DCTSIZE2 * SIZEOF(DCTELEM)); + } + dtbl = fdct->divisors[qtblno]; + for (i = 0; i < DCTSIZE2; i++) { + dtbl[i] = (DCTELEM) + DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i], + (INT32) aanscales[i]), + CONST_BITS-3); + } + } + break; +#endif +#ifdef DCT_FLOAT_SUPPORTED + case JDCT_FLOAT: + { + /* For float AA&N IDCT method, divisors are equal to quantization + * coefficients scaled by scalefactor[row]*scalefactor[col], where + * scalefactor[0] = 1 + * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 + * We apply a further scale factor of 8. + * What's actually stored is 1/divisor so that the inner loop can + * use a multiplication rather than a division. + */ + FAST_FLOAT * fdtbl; + int row, col; + static const double aanscalefactor[DCTSIZE] = { + 1.0, 1.387039845, 1.306562965, 1.175875602, + 1.0, 0.785694958, 0.541196100, 0.275899379 + }; + + if (fdct->float_divisors[qtblno] == NULL) { + fdct->float_divisors[qtblno] = (FAST_FLOAT *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + DCTSIZE2 * SIZEOF(FAST_FLOAT)); + } + fdtbl = fdct->float_divisors[qtblno]; + i = 0; + for (row = 0; row < DCTSIZE; row++) { + for (col = 0; col < DCTSIZE; col++) { + fdtbl[i] = (FAST_FLOAT) + (1.0 / (((double) qtbl->quantval[i] * + aanscalefactor[row] * aanscalefactor[col] * 8.0))); + i++; + } + } + } + break; +#endif + default: + ERREXIT(cinfo, JERR_NOT_COMPILED); + break; + } + } +} + + +/* + * Perform forward DCT on one or more blocks of a component. + * + * The input samples are taken from the sample_data[] array starting at + * position start_row/start_col, and moving to the right for any additional + * blocks. The quantized coefficients are returned in coef_blocks[]. + */ + +METHODDEF(void) +forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY sample_data, JBLOCKROW coef_blocks, + JDIMENSION start_row, JDIMENSION start_col, + JDIMENSION num_blocks) +/* This version is used for integer DCT implementations. */ +{ + /* This routine is heavily used, so it's worth coding it tightly. */ + my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; + forward_DCT_method_ptr do_dct = fdct->do_dct; + DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no]; + DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */ + JDIMENSION bi; + + sample_data += start_row; /* fold in the vertical offset once */ + + for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) { + /* Load data into workspace, applying unsigned->signed conversion */ + { register DCTELEM *workspaceptr; + register JSAMPROW elemptr; + register int elemr; + + workspaceptr = workspace; + for (elemr = 0; elemr < DCTSIZE; elemr++) { + elemptr = sample_data[elemr] + start_col; +#if DCTSIZE == 8 /* unroll the inner loop */ + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; +#else + { register int elemc; + for (elemc = DCTSIZE; elemc > 0; elemc--) { + *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; + } + } +#endif + } + } + + /* Perform the DCT */ + (*do_dct) (workspace); + + /* Quantize/descale the coefficients, and store into coef_blocks[] */ + { register DCTELEM temp, qval; + register int i; + register JCOEFPTR output_ptr = coef_blocks[bi]; + + for (i = 0; i < DCTSIZE2; i++) { + qval = divisors[i]; + temp = workspace[i]; + /* Divide the coefficient value by qval, ensuring proper rounding. + * Since C does not specify the direction of rounding for negative + * quotients, we have to force the dividend positive for portability. + * + * In most files, at least half of the output values will be zero + * (at default quantization settings, more like three-quarters...) + * so we should ensure that this case is fast. On many machines, + * a comparison is enough cheaper than a divide to make a special test + * a win. Since both inputs will be nonnegative, we need only test + * for a < b to discover whether a/b is 0. + * If your machine's division is fast enough, define FAST_DIVIDE. + */ +#ifdef FAST_DIVIDE +#define DIVIDE_BY(a,b) a /= b +#else +#define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0 +#endif + if (temp < 0) { + temp = -temp; + temp += qval>>1; /* for rounding */ + DIVIDE_BY(temp, qval); + temp = -temp; + } else { + temp += qval>>1; /* for rounding */ + DIVIDE_BY(temp, qval); + } + output_ptr[i] = (JCOEF) temp; + } + } + } +} + + +#ifdef DCT_FLOAT_SUPPORTED + +METHODDEF(void) +forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY sample_data, JBLOCKROW coef_blocks, + JDIMENSION start_row, JDIMENSION start_col, + JDIMENSION num_blocks) +/* This version is used for floating-point DCT implementations. */ +{ + /* This routine is heavily used, so it's worth coding it tightly. */ + my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; + float_DCT_method_ptr do_dct = fdct->do_float_dct; + FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no]; + FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */ + JDIMENSION bi; + + sample_data += start_row; /* fold in the vertical offset once */ + + for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) { + /* Load data into workspace, applying unsigned->signed conversion */ + { register FAST_FLOAT *workspaceptr; + register JSAMPROW elemptr; + register int elemr; + + workspaceptr = workspace; + for (elemr = 0; elemr < DCTSIZE; elemr++) { + elemptr = sample_data[elemr] + start_col; +#if DCTSIZE == 8 /* unroll the inner loop */ + *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); + *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); + *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); + *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); + *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); + *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); + *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); + *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); +#else + { register int elemc; + for (elemc = DCTSIZE; elemc > 0; elemc--) { + *workspaceptr++ = (FAST_FLOAT) + (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); + } + } +#endif + } + } + + /* Perform the DCT */ + (*do_dct) (workspace); + + /* Quantize/descale the coefficients, and store into coef_blocks[] */ + { register FAST_FLOAT temp; + register int i; + register JCOEFPTR output_ptr = coef_blocks[bi]; + + for (i = 0; i < DCTSIZE2; i++) { + /* Apply the quantization and scaling factor */ + temp = workspace[i] * divisors[i]; + /* Round to nearest integer. + * Since C does not specify the direction of rounding for negative + * quotients, we have to force the dividend positive for portability. + * The maximum coefficient size is +-16K (for 12-bit data), so this + * code should work for either 16-bit or 32-bit ints. + */ + output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384); + } + } + } +} + +#endif /* DCT_FLOAT_SUPPORTED */ + + +/* + * Initialize FDCT manager. + */ + +GLOBAL(void) +jinit_forward_dct (j_compress_ptr cinfo) +{ + my_fdct_ptr fdct; + int i; + + fdct = (my_fdct_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_fdct_controller)); + cinfo->fdct = (struct jpeg_forward_dct *) fdct; + fdct->pub.start_pass = start_pass_fdctmgr; + + switch (cinfo->dct_method) { +#ifdef DCT_ISLOW_SUPPORTED + case JDCT_ISLOW: + fdct->pub.forward_DCT = forward_DCT; + fdct->do_dct = jpeg_fdct_islow; + break; +#endif +#ifdef DCT_IFAST_SUPPORTED + case JDCT_IFAST: + fdct->pub.forward_DCT = forward_DCT; + fdct->do_dct = jpeg_fdct_ifast; + break; +#endif +#ifdef DCT_FLOAT_SUPPORTED + case JDCT_FLOAT: + fdct->pub.forward_DCT = forward_DCT_float; + fdct->do_float_dct = jpeg_fdct_float; + break; +#endif + default: + ERREXIT(cinfo, JERR_NOT_COMPILED); + break; + } + + /* Mark divisor tables unallocated */ + for (i = 0; i < NUM_QUANT_TBLS; i++) { + fdct->divisors[i] = NULL; +#ifdef DCT_FLOAT_SUPPORTED + fdct->float_divisors[i] = NULL; +#endif + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jchuff.c b/SlnkDWFImpl/CxImage/jpeg/jchuff.c new file mode 100644 index 0000000..16d9366 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jchuff.c @@ -0,0 +1,909 @@ +/* + * jchuff.c + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains Huffman entropy encoding routines. + * + * Much of the complexity here has to do with supporting output suspension. + * If the data destination module demands suspension, we want to be able to + * back up to the start of the current MCU. To do this, we copy state + * variables into local working storage, and update them back to the + * permanent JPEG objects only upon successful completion of an MCU. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jchuff.h" /* Declarations shared with jcphuff.c */ + + +/* Expanded entropy encoder object for Huffman encoding. + * + * The savable_state subrecord contains fields that change within an MCU, + * but must not be updated permanently until we complete the MCU. + */ + +typedef struct { + INT32 put_buffer; /* current bit-accumulation buffer */ + int put_bits; /* # of bits now in it */ + int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ +} savable_state; + +/* This macro is to work around compilers with missing or broken + * structure assignment. You'll need to fix this code if you have + * such a compiler and you change MAX_COMPS_IN_SCAN. + */ + +#ifndef NO_STRUCT_ASSIGN +#define ASSIGN_STATE(dest,src) ((dest) = (src)) +#else +#if MAX_COMPS_IN_SCAN == 4 +#define ASSIGN_STATE(dest,src) \ + ((dest).put_buffer = (src).put_buffer, \ + (dest).put_bits = (src).put_bits, \ + (dest).last_dc_val[0] = (src).last_dc_val[0], \ + (dest).last_dc_val[1] = (src).last_dc_val[1], \ + (dest).last_dc_val[2] = (src).last_dc_val[2], \ + (dest).last_dc_val[3] = (src).last_dc_val[3]) +#endif +#endif + + +typedef struct { + struct jpeg_entropy_encoder pub; /* public fields */ + + savable_state saved; /* Bit buffer & DC state at start of MCU */ + + /* These fields are NOT loaded into local working state. */ + unsigned int restarts_to_go; /* MCUs left in this restart interval */ + int next_restart_num; /* next restart number to write (0-7) */ + + /* Pointers to derived tables (these workspaces have image lifespan) */ + c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS]; + c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS]; + +#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */ + long * dc_count_ptrs[NUM_HUFF_TBLS]; + long * ac_count_ptrs[NUM_HUFF_TBLS]; +#endif +} huff_entropy_encoder; + +typedef huff_entropy_encoder * huff_entropy_ptr; + +/* Working state while writing an MCU. + * This struct contains all the fields that are needed by subroutines. + */ + +typedef struct { + JOCTET * next_output_byte; /* => next byte to write in buffer */ + size_t free_in_buffer; /* # of byte spaces remaining in buffer */ + savable_state cur; /* Current bit buffer & DC state */ + j_compress_ptr cinfo; /* dump_buffer needs access to this */ +} working_state; + + +/* Forward declarations */ +METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo)); +#ifdef ENTROPY_OPT_SUPPORTED +METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo)); +#endif + + +/* + * Initialize for a Huffman-compressed scan. + * If gather_statistics is TRUE, we do not output anything during the scan, + * just count the Huffman symbols used and generate Huffman code tables. + */ + +METHODDEF(void) +start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics) +{ + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; + int ci, dctbl, actbl; + jpeg_component_info * compptr; + + if (gather_statistics) { +#ifdef ENTROPY_OPT_SUPPORTED + entropy->pub.encode_mcu = encode_mcu_gather; + entropy->pub.finish_pass = finish_pass_gather; +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else { + entropy->pub.encode_mcu = encode_mcu_huff; + entropy->pub.finish_pass = finish_pass_huff; + } + + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + dctbl = compptr->dc_tbl_no; + actbl = compptr->ac_tbl_no; + if (gather_statistics) { +#ifdef ENTROPY_OPT_SUPPORTED + /* Check for invalid table indexes */ + /* (make_c_derived_tbl does this in the other path) */ + if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS) + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl); + if (actbl < 0 || actbl >= NUM_HUFF_TBLS) + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl); + /* Allocate and zero the statistics tables */ + /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */ + if (entropy->dc_count_ptrs[dctbl] == NULL) + entropy->dc_count_ptrs[dctbl] = (long *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + 257 * SIZEOF(long)); + MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long)); + if (entropy->ac_count_ptrs[actbl] == NULL) + entropy->ac_count_ptrs[actbl] = (long *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + 257 * SIZEOF(long)); + MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long)); +#endif + } else { + /* Compute derived values for Huffman tables */ + /* We may do this more than once for a table, but it's not expensive */ + jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl, + & entropy->dc_derived_tbls[dctbl]); + jpeg_make_c_derived_tbl(cinfo, FALSE, actbl, + & entropy->ac_derived_tbls[actbl]); + } + /* Initialize DC predictions to 0 */ + entropy->saved.last_dc_val[ci] = 0; + } + + /* Initialize bit buffer to empty */ + entropy->saved.put_buffer = 0; + entropy->saved.put_bits = 0; + + /* Initialize restart stuff */ + entropy->restarts_to_go = cinfo->restart_interval; + entropy->next_restart_num = 0; +} + + +/* + * Compute the derived values for a Huffman table. + * This routine also performs some validation checks on the table. + * + * Note this is also used by jcphuff.c. + */ + +GLOBAL(void) +jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno, + c_derived_tbl ** pdtbl) +{ + JHUFF_TBL *htbl; + c_derived_tbl *dtbl; + int p, i, l, lastp, si, maxsymbol; + char huffsize[257]; + unsigned int huffcode[257]; + unsigned int code; + + /* Note that huffsize[] and huffcode[] are filled in code-length order, + * paralleling the order of the symbols themselves in htbl->huffval[]. + */ + + /* Find the input Huffman table */ + if (tblno < 0 || tblno >= NUM_HUFF_TBLS) + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); + htbl = + isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno]; + if (htbl == NULL) + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); + + /* Allocate a workspace if we haven't already done so. */ + if (*pdtbl == NULL) + *pdtbl = (c_derived_tbl *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(c_derived_tbl)); + dtbl = *pdtbl; + + /* Figure C.1: make table of Huffman code length for each symbol */ + + p = 0; + for (l = 1; l <= 16; l++) { + i = (int) htbl->bits[l]; + if (i < 0 || p + i > 256) /* protect against table overrun */ + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + while (i--) + huffsize[p++] = (char) l; + } + huffsize[p] = 0; + lastp = p; + + /* Figure C.2: generate the codes themselves */ + /* We also validate that the counts represent a legal Huffman code tree. */ + + code = 0; + si = huffsize[0]; + p = 0; + while (huffsize[p]) { + while (((int) huffsize[p]) == si) { + huffcode[p++] = code; + code++; + } + /* code is now 1 more than the last code used for codelength si; but + * it must still fit in si bits, since no code is allowed to be all ones. + */ + if (((INT32) code) >= (((INT32) 1) << si)) + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + code <<= 1; + si++; + } + + /* Figure C.3: generate encoding tables */ + /* These are code and size indexed by symbol value */ + + /* Set all codeless symbols to have code length 0; + * this lets us detect duplicate VAL entries here, and later + * allows emit_bits to detect any attempt to emit such symbols. + */ + MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi)); + + /* This is also a convenient place to check for out-of-range + * and duplicated VAL entries. We allow 0..255 for AC symbols + * but only 0..15 for DC. (We could constrain them further + * based on data depth and mode, but this seems enough.) + */ + maxsymbol = isDC ? 15 : 255; + + for (p = 0; p < lastp; p++) { + i = htbl->huffval[p]; + if (i < 0 || i > maxsymbol || dtbl->ehufsi[i]) + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + dtbl->ehufco[i] = huffcode[p]; + dtbl->ehufsi[i] = huffsize[p]; + } +} + + +/* Outputting bytes to the file */ + +/* Emit a byte, taking 'action' if must suspend. */ +#define emit_byte(state,val,action) \ + { *(state)->next_output_byte++ = (JOCTET) (val); \ + if (--(state)->free_in_buffer == 0) \ + if (! dump_buffer(state)) \ + { action; } } + + +LOCAL(boolean) +dump_buffer (working_state * state) +/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */ +{ + struct jpeg_destination_mgr * dest = state->cinfo->dest; + + if (! (*dest->empty_output_buffer) (state->cinfo)) + return FALSE; + /* After a successful buffer dump, must reset buffer pointers */ + state->next_output_byte = dest->next_output_byte; + state->free_in_buffer = dest->free_in_buffer; + return TRUE; +} + + +/* Outputting bits to the file */ + +/* Only the right 24 bits of put_buffer are used; the valid bits are + * left-justified in this part. At most 16 bits can be passed to emit_bits + * in one call, and we never retain more than 7 bits in put_buffer + * between calls, so 24 bits are sufficient. + */ + +INLINE +LOCAL(boolean) +emit_bits (working_state * state, unsigned int code, int size) +/* Emit some bits; return TRUE if successful, FALSE if must suspend */ +{ + /* This routine is heavily used, so it's worth coding tightly. */ + register INT32 put_buffer = (INT32) code; + register int put_bits = state->cur.put_bits; + + /* if size is 0, caller used an invalid Huffman table entry */ + if (size == 0) + ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE); + + put_buffer &= (((INT32) 1)<cur.put_buffer; /* and merge with old buffer contents */ + + while (put_bits >= 8) { + int c = (int) ((put_buffer >> 16) & 0xFF); + + emit_byte(state, c, return FALSE); + if (c == 0xFF) { /* need to stuff a zero byte? */ + emit_byte(state, 0, return FALSE); + } + put_buffer <<= 8; + put_bits -= 8; + } + + state->cur.put_buffer = put_buffer; /* update state variables */ + state->cur.put_bits = put_bits; + + return TRUE; +} + + +LOCAL(boolean) +flush_bits (working_state * state) +{ + if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */ + return FALSE; + state->cur.put_buffer = 0; /* and reset bit-buffer to empty */ + state->cur.put_bits = 0; + return TRUE; +} + + +/* Encode a single block's worth of coefficients */ + +LOCAL(boolean) +encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val, + c_derived_tbl *dctbl, c_derived_tbl *actbl) +{ + register int temp, temp2; + register int nbits; + register int k, r, i; + + /* Encode the DC coefficient difference per section F.1.2.1 */ + + temp = temp2 = block[0] - last_dc_val; + + if (temp < 0) { + temp = -temp; /* temp is abs value of input */ + /* For a negative input, want temp2 = bitwise complement of abs(input) */ + /* This code assumes we are on a two's complement machine */ + temp2--; + } + + /* Find the number of bits needed for the magnitude of the coefficient */ + nbits = 0; + while (temp) { + nbits++; + temp >>= 1; + } + /* Check for out-of-range coefficient values. + * Since we're encoding a difference, the range limit is twice as much. + */ + if (nbits > MAX_COEF_BITS+1) + ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); + + /* Emit the Huffman-coded symbol for the number of bits */ + if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits])) + return FALSE; + + /* Emit that number of bits of the value, if positive, */ + /* or the complement of its magnitude, if negative. */ + if (nbits) /* emit_bits rejects calls with size 0 */ + if (! emit_bits(state, (unsigned int) temp2, nbits)) + return FALSE; + + /* Encode the AC coefficients per section F.1.2.2 */ + + r = 0; /* r = run length of zeros */ + + for (k = 1; k < DCTSIZE2; k++) { + if ((temp = block[jpeg_natural_order[k]]) == 0) { + r++; + } else { + /* if run length > 15, must emit special run-length-16 codes (0xF0) */ + while (r > 15) { + if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0])) + return FALSE; + r -= 16; + } + + temp2 = temp; + if (temp < 0) { + temp = -temp; /* temp is abs value of input */ + /* This code assumes we are on a two's complement machine */ + temp2--; + } + + /* Find the number of bits needed for the magnitude of the coefficient */ + nbits = 1; /* there must be at least one 1 bit */ + while ((temp >>= 1)) + nbits++; + /* Check for out-of-range coefficient values */ + if (nbits > MAX_COEF_BITS) + ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); + + /* Emit Huffman symbol for run length / number of bits */ + i = (r << 4) + nbits; + if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i])) + return FALSE; + + /* Emit that number of bits of the value, if positive, */ + /* or the complement of its magnitude, if negative. */ + if (! emit_bits(state, (unsigned int) temp2, nbits)) + return FALSE; + + r = 0; + } + } + + /* If the last coef(s) were zero, emit an end-of-block code */ + if (r > 0) + if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0])) + return FALSE; + + return TRUE; +} + + +/* + * Emit a restart marker & resynchronize predictions. + */ + +LOCAL(boolean) +emit_restart (working_state * state, int restart_num) +{ + int ci; + + if (! flush_bits(state)) + return FALSE; + + emit_byte(state, 0xFF, return FALSE); + emit_byte(state, JPEG_RST0 + restart_num, return FALSE); + + /* Re-initialize DC predictions to 0 */ + for (ci = 0; ci < state->cinfo->comps_in_scan; ci++) + state->cur.last_dc_val[ci] = 0; + + /* The restart counter is not updated until we successfully write the MCU. */ + + return TRUE; +} + + +/* + * Encode and output one MCU's worth of Huffman-compressed coefficients. + */ + +METHODDEF(boolean) +encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data) +{ + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; + working_state state; + int blkn, ci; + jpeg_component_info * compptr; + + /* Load up working state */ + state.next_output_byte = cinfo->dest->next_output_byte; + state.free_in_buffer = cinfo->dest->free_in_buffer; + ASSIGN_STATE(state.cur, entropy->saved); + state.cinfo = cinfo; + + /* Emit restart marker if needed */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) + if (! emit_restart(&state, entropy->next_restart_num)) + return FALSE; + } + + /* Encode the MCU data blocks */ + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { + ci = cinfo->MCU_membership[blkn]; + compptr = cinfo->cur_comp_info[ci]; + if (! encode_one_block(&state, + MCU_data[blkn][0], state.cur.last_dc_val[ci], + entropy->dc_derived_tbls[compptr->dc_tbl_no], + entropy->ac_derived_tbls[compptr->ac_tbl_no])) + return FALSE; + /* Update last_dc_val */ + state.cur.last_dc_val[ci] = MCU_data[blkn][0][0]; + } + + /* Completed MCU, so update state */ + cinfo->dest->next_output_byte = state.next_output_byte; + cinfo->dest->free_in_buffer = state.free_in_buffer; + ASSIGN_STATE(entropy->saved, state.cur); + + /* Update restart-interval state too */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) { + entropy->restarts_to_go = cinfo->restart_interval; + entropy->next_restart_num++; + entropy->next_restart_num &= 7; + } + entropy->restarts_to_go--; + } + + return TRUE; +} + + +/* + * Finish up at the end of a Huffman-compressed scan. + */ + +METHODDEF(void) +finish_pass_huff (j_compress_ptr cinfo) +{ + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; + working_state state; + + /* Load up working state ... flush_bits needs it */ + state.next_output_byte = cinfo->dest->next_output_byte; + state.free_in_buffer = cinfo->dest->free_in_buffer; + ASSIGN_STATE(state.cur, entropy->saved); + state.cinfo = cinfo; + + /* Flush out the last data */ + if (! flush_bits(&state)) + ERREXIT(cinfo, JERR_CANT_SUSPEND); + + /* Update state */ + cinfo->dest->next_output_byte = state.next_output_byte; + cinfo->dest->free_in_buffer = state.free_in_buffer; + ASSIGN_STATE(entropy->saved, state.cur); +} + + +/* + * Huffman coding optimization. + * + * We first scan the supplied data and count the number of uses of each symbol + * that is to be Huffman-coded. (This process MUST agree with the code above.) + * Then we build a Huffman coding tree for the observed counts. + * Symbols which are not needed at all for the particular image are not + * assigned any code, which saves space in the DHT marker as well as in + * the compressed data. + */ + +#ifdef ENTROPY_OPT_SUPPORTED + + +/* Process a single block's worth of coefficients */ + +LOCAL(void) +htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val, + long dc_counts[], long ac_counts[]) +{ + register int temp; + register int nbits; + register int k, r; + + /* Encode the DC coefficient difference per section F.1.2.1 */ + + temp = block[0] - last_dc_val; + if (temp < 0) + temp = -temp; + + /* Find the number of bits needed for the magnitude of the coefficient */ + nbits = 0; + while (temp) { + nbits++; + temp >>= 1; + } + /* Check for out-of-range coefficient values. + * Since we're encoding a difference, the range limit is twice as much. + */ + if (nbits > MAX_COEF_BITS+1) + ERREXIT(cinfo, JERR_BAD_DCT_COEF); + + /* Count the Huffman symbol for the number of bits */ + dc_counts[nbits]++; + + /* Encode the AC coefficients per section F.1.2.2 */ + + r = 0; /* r = run length of zeros */ + + for (k = 1; k < DCTSIZE2; k++) { + if ((temp = block[jpeg_natural_order[k]]) == 0) { + r++; + } else { + /* if run length > 15, must emit special run-length-16 codes (0xF0) */ + while (r > 15) { + ac_counts[0xF0]++; + r -= 16; + } + + /* Find the number of bits needed for the magnitude of the coefficient */ + if (temp < 0) + temp = -temp; + + /* Find the number of bits needed for the magnitude of the coefficient */ + nbits = 1; /* there must be at least one 1 bit */ + while ((temp >>= 1)) + nbits++; + /* Check for out-of-range coefficient values */ + if (nbits > MAX_COEF_BITS) + ERREXIT(cinfo, JERR_BAD_DCT_COEF); + + /* Count Huffman symbol for run length / number of bits */ + ac_counts[(r << 4) + nbits]++; + + r = 0; + } + } + + /* If the last coef(s) were zero, emit an end-of-block code */ + if (r > 0) + ac_counts[0]++; +} + + +/* + * Trial-encode one MCU's worth of Huffman-compressed coefficients. + * No data is actually output, so no suspension return is possible. + */ + +METHODDEF(boolean) +encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data) +{ + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; + int blkn, ci; + jpeg_component_info * compptr; + + /* Take care of restart intervals if needed */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) { + /* Re-initialize DC predictions to 0 */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) + entropy->saved.last_dc_val[ci] = 0; + /* Update restart state */ + entropy->restarts_to_go = cinfo->restart_interval; + } + entropy->restarts_to_go--; + } + + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { + ci = cinfo->MCU_membership[blkn]; + compptr = cinfo->cur_comp_info[ci]; + htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci], + entropy->dc_count_ptrs[compptr->dc_tbl_no], + entropy->ac_count_ptrs[compptr->ac_tbl_no]); + entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0]; + } + + return TRUE; +} + + +/* + * Generate the best Huffman code table for the given counts, fill htbl. + * Note this is also used by jcphuff.c. + * + * The JPEG standard requires that no symbol be assigned a codeword of all + * one bits (so that padding bits added at the end of a compressed segment + * can't look like a valid code). Because of the canonical ordering of + * codewords, this just means that there must be an unused slot in the + * longest codeword length category. Section K.2 of the JPEG spec suggests + * reserving such a slot by pretending that symbol 256 is a valid symbol + * with count 1. In theory that's not optimal; giving it count zero but + * including it in the symbol set anyway should give a better Huffman code. + * But the theoretically better code actually seems to come out worse in + * practice, because it produces more all-ones bytes (which incur stuffed + * zero bytes in the final file). In any case the difference is tiny. + * + * The JPEG standard requires Huffman codes to be no more than 16 bits long. + * If some symbols have a very small but nonzero probability, the Huffman tree + * must be adjusted to meet the code length restriction. We currently use + * the adjustment method suggested in JPEG section K.2. This method is *not* + * optimal; it may not choose the best possible limited-length code. But + * typically only very-low-frequency symbols will be given less-than-optimal + * lengths, so the code is almost optimal. Experimental comparisons against + * an optimal limited-length-code algorithm indicate that the difference is + * microscopic --- usually less than a hundredth of a percent of total size. + * So the extra complexity of an optimal algorithm doesn't seem worthwhile. + */ + +GLOBAL(void) +jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]) +{ +#define MAX_CLEN 32 /* assumed maximum initial code length */ + UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */ + int codesize[257]; /* codesize[k] = code length of symbol k */ + int others[257]; /* next symbol in current branch of tree */ + int c1, c2; + int p, i, j; + long v; + + /* This algorithm is explained in section K.2 of the JPEG standard */ + + MEMZERO(bits, SIZEOF(bits)); + MEMZERO(codesize, SIZEOF(codesize)); + for (i = 0; i < 257; i++) + others[i] = -1; /* init links to empty */ + + freq[256] = 1; /* make sure 256 has a nonzero count */ + /* Including the pseudo-symbol 256 in the Huffman procedure guarantees + * that no real symbol is given code-value of all ones, because 256 + * will be placed last in the largest codeword category. + */ + + /* Huffman's basic algorithm to assign optimal code lengths to symbols */ + + for (;;) { + /* Find the smallest nonzero frequency, set c1 = its symbol */ + /* In case of ties, take the larger symbol number */ + c1 = -1; + v = 1000000000L; + for (i = 0; i <= 256; i++) { + if (freq[i] && freq[i] <= v) { + v = freq[i]; + c1 = i; + } + } + + /* Find the next smallest nonzero frequency, set c2 = its symbol */ + /* In case of ties, take the larger symbol number */ + c2 = -1; + v = 1000000000L; + for (i = 0; i <= 256; i++) { + if (freq[i] && freq[i] <= v && i != c1) { + v = freq[i]; + c2 = i; + } + } + + /* Done if we've merged everything into one frequency */ + if (c2 < 0) + break; + + /* Else merge the two counts/trees */ + freq[c1] += freq[c2]; + freq[c2] = 0; + + /* Increment the codesize of everything in c1's tree branch */ + codesize[c1]++; + while (others[c1] >= 0) { + c1 = others[c1]; + codesize[c1]++; + } + + others[c1] = c2; /* chain c2 onto c1's tree branch */ + + /* Increment the codesize of everything in c2's tree branch */ + codesize[c2]++; + while (others[c2] >= 0) { + c2 = others[c2]; + codesize[c2]++; + } + } + + /* Now count the number of symbols of each code length */ + for (i = 0; i <= 256; i++) { + if (codesize[i]) { + /* The JPEG standard seems to think that this can't happen, */ + /* but I'm paranoid... */ + if (codesize[i] > MAX_CLEN) + ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW); + + bits[codesize[i]]++; + } + } + + /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure + * Huffman procedure assigned any such lengths, we must adjust the coding. + * Here is what the JPEG spec says about how this next bit works: + * Since symbols are paired for the longest Huffman code, the symbols are + * removed from this length category two at a time. The prefix for the pair + * (which is one bit shorter) is allocated to one of the pair; then, + * skipping the BITS entry for that prefix length, a code word from the next + * shortest nonzero BITS entry is converted into a prefix for two code words + * one bit longer. + */ + + for (i = MAX_CLEN; i > 16; i--) { + while (bits[i] > 0) { + j = i - 2; /* find length of new prefix to be used */ + while (bits[j] == 0) + j--; + + bits[i] -= 2; /* remove two symbols */ + bits[i-1]++; /* one goes in this length */ + bits[j+1] += 2; /* two new symbols in this length */ + bits[j]--; /* symbol of this length is now a prefix */ + } + } + + /* Remove the count for the pseudo-symbol 256 from the largest codelength */ + while (bits[i] == 0) /* find largest codelength still in use */ + i--; + bits[i]--; + + /* Return final symbol counts (only for lengths 0..16) */ + MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits)); + + /* Return a list of the symbols sorted by code length */ + /* It's not real clear to me why we don't need to consider the codelength + * changes made above, but the JPEG spec seems to think this works. + */ + p = 0; + for (i = 1; i <= MAX_CLEN; i++) { + for (j = 0; j <= 255; j++) { + if (codesize[j] == i) { + htbl->huffval[p] = (UINT8) j; + p++; + } + } + } + + /* Set sent_table FALSE so updated table will be written to JPEG file. */ + htbl->sent_table = FALSE; +} + + +/* + * Finish up a statistics-gathering pass and create the new Huffman tables. + */ + +METHODDEF(void) +finish_pass_gather (j_compress_ptr cinfo) +{ + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; + int ci, dctbl, actbl; + jpeg_component_info * compptr; + JHUFF_TBL **htblptr; + boolean did_dc[NUM_HUFF_TBLS]; + boolean did_ac[NUM_HUFF_TBLS]; + + /* It's important not to apply jpeg_gen_optimal_table more than once + * per table, because it clobbers the input frequency counts! + */ + MEMZERO(did_dc, SIZEOF(did_dc)); + MEMZERO(did_ac, SIZEOF(did_ac)); + + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + dctbl = compptr->dc_tbl_no; + actbl = compptr->ac_tbl_no; + if (! did_dc[dctbl]) { + htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl]; + if (*htblptr == NULL) + *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); + jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]); + did_dc[dctbl] = TRUE; + } + if (! did_ac[actbl]) { + htblptr = & cinfo->ac_huff_tbl_ptrs[actbl]; + if (*htblptr == NULL) + *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); + jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]); + did_ac[actbl] = TRUE; + } + } +} + + +#endif /* ENTROPY_OPT_SUPPORTED */ + + +/* + * Module initialization routine for Huffman entropy encoding. + */ + +GLOBAL(void) +jinit_huff_encoder (j_compress_ptr cinfo) +{ + huff_entropy_ptr entropy; + int i; + + entropy = (huff_entropy_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(huff_entropy_encoder)); + cinfo->entropy = (struct jpeg_entropy_encoder *) entropy; + entropy->pub.start_pass = start_pass_huff; + + /* Mark tables unallocated */ + for (i = 0; i < NUM_HUFF_TBLS; i++) { + entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL; +#ifdef ENTROPY_OPT_SUPPORTED + entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL; +#endif + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jchuff.h b/SlnkDWFImpl/CxImage/jpeg/jchuff.h new file mode 100644 index 0000000..8c02c09 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jchuff.h @@ -0,0 +1,47 @@ +/* + * jchuff.h + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains declarations for Huffman entropy encoding routines + * that are shared between the sequential encoder (jchuff.c) and the + * progressive encoder (jcphuff.c). No other modules need to see these. + */ + +/* The legal range of a DCT coefficient is + * -1024 .. +1023 for 8-bit data; + * -16384 .. +16383 for 12-bit data. + * Hence the magnitude should always fit in 10 or 14 bits respectively. + */ + +#if BITS_IN_JSAMPLE == 8 +#define MAX_COEF_BITS 10 +#else +#define MAX_COEF_BITS 14 +#endif + +/* Derived data constructed for each Huffman table */ + +typedef struct { + unsigned int ehufco[256]; /* code for each symbol */ + char ehufsi[256]; /* length of code for each symbol */ + /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */ +} c_derived_tbl; + +/* Short forms of external names for systems with brain-damaged linkers. */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jpeg_make_c_derived_tbl jMkCDerived +#define jpeg_gen_optimal_table jGenOptTbl +#endif /* NEED_SHORT_EXTERNAL_NAMES */ + +/* Expand a Huffman table definition into the derived format */ +EXTERN(void) jpeg_make_c_derived_tbl + JPP((j_compress_ptr cinfo, boolean isDC, int tblno, + c_derived_tbl ** pdtbl)); + +/* Generate an optimal table definition given the specified counts */ +EXTERN(void) jpeg_gen_optimal_table + JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])); diff --git a/SlnkDWFImpl/CxImage/jpeg/jcinit.c b/SlnkDWFImpl/CxImage/jpeg/jcinit.c new file mode 100644 index 0000000..19de8d0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcinit.c @@ -0,0 +1,72 @@ +/* + * jcinit.c + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains initialization logic for the JPEG compressor. + * This routine is in charge of selecting the modules to be executed and + * making an initialization call to each one. + * + * Logically, this code belongs in jcmaster.c. It's split out because + * linking this routine implies linking the entire compression library. + * For a transcoding-only application, we want to be able to use jcmaster.c + * without linking in the whole library. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* + * Master selection of compression modules. + * This is done once at the start of processing an image. We determine + * which modules will be used and give them appropriate initialization calls. + */ + +GLOBAL(void) +jinit_compress_master (j_compress_ptr cinfo) +{ + /* Initialize master control (includes parameter checking/processing) */ + jinit_c_master_control(cinfo, FALSE /* full compression */); + + /* Preprocessing */ + if (! cinfo->raw_data_in) { + jinit_color_converter(cinfo); + jinit_downsampler(cinfo); + jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */); + } + /* Forward DCT */ + jinit_forward_dct(cinfo); + /* Entropy encoding: either Huffman or arithmetic coding. */ + if (cinfo->arith_code) { + ERREXIT(cinfo, JERR_ARITH_NOTIMPL); + } else { + if (cinfo->progressive_mode) { +#ifdef C_PROGRESSIVE_SUPPORTED + jinit_phuff_encoder(cinfo); +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else + jinit_huff_encoder(cinfo); + } + + /* Need a full-image coefficient buffer in any multi-pass mode. */ + jinit_c_coef_controller(cinfo, + (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding)); + jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */); + + jinit_marker_writer(cinfo); + + /* We can now tell the memory manager to allocate virtual arrays. */ + (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); + + /* Write the datastream header (SOI) immediately. + * Frame and scan headers are postponed till later. + * This lets application insert special markers after the SOI. + */ + (*cinfo->marker->write_file_header) (cinfo); +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jcmainct.c b/SlnkDWFImpl/CxImage/jpeg/jcmainct.c new file mode 100644 index 0000000..14aa4c7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcmainct.c @@ -0,0 +1,293 @@ +/* + * jcmainct.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the main buffer controller for compression. + * The main buffer lies between the pre-processor and the JPEG + * compressor proper; it holds downsampled data in the JPEG colorspace. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Note: currently, there is no operating mode in which a full-image buffer + * is needed at this step. If there were, that mode could not be used with + * "raw data" input, since this module is bypassed in that case. However, + * we've left the code here for possible use in special applications. + */ +#undef FULL_MAIN_BUFFER_SUPPORTED + + +/* Private buffer controller object */ + +typedef struct { + struct jpeg_c_main_controller pub; /* public fields */ + + JDIMENSION cur_iMCU_row; /* number of current iMCU row */ + JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */ + boolean suspended; /* remember if we suspended output */ + J_BUF_MODE pass_mode; /* current operating mode */ + + /* If using just a strip buffer, this points to the entire set of buffers + * (we allocate one for each component). In the full-image case, this + * points to the currently accessible strips of the virtual arrays. + */ + JSAMPARRAY buffer[MAX_COMPONENTS]; + +#ifdef FULL_MAIN_BUFFER_SUPPORTED + /* If using full-image storage, this array holds pointers to virtual-array + * control blocks for each component. Unused if not full-image storage. + */ + jvirt_sarray_ptr whole_image[MAX_COMPONENTS]; +#endif +} my_main_controller; + +typedef my_main_controller * my_main_ptr; + + +/* Forward declarations */ +METHODDEF(void) process_data_simple_main + JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf, + JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail)); +#ifdef FULL_MAIN_BUFFER_SUPPORTED +METHODDEF(void) process_data_buffer_main + JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf, + JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail)); +#endif + + +/* + * Initialize for a processing pass. + */ + +METHODDEF(void) +start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode) +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + + /* Do nothing in raw-data mode. */ + if (cinfo->raw_data_in) + return; + + main->cur_iMCU_row = 0; /* initialize counters */ + main->rowgroup_ctr = 0; + main->suspended = FALSE; + main->pass_mode = pass_mode; /* save mode for use by process_data */ + + switch (pass_mode) { + case JBUF_PASS_THRU: +#ifdef FULL_MAIN_BUFFER_SUPPORTED + if (main->whole_image[0] != NULL) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); +#endif + main->pub.process_data = process_data_simple_main; + break; +#ifdef FULL_MAIN_BUFFER_SUPPORTED + case JBUF_SAVE_SOURCE: + case JBUF_CRANK_DEST: + case JBUF_SAVE_AND_PASS: + if (main->whole_image[0] == NULL) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + main->pub.process_data = process_data_buffer_main; + break; +#endif + default: + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + break; + } +} + + +/* + * Process some data. + * This routine handles the simple pass-through mode, + * where we have only a strip buffer. + */ + +METHODDEF(void) +process_data_simple_main (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, + JDIMENSION in_rows_avail) +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + + while (main->cur_iMCU_row < cinfo->total_iMCU_rows) { + /* Read input data if we haven't filled the main buffer yet */ + if (main->rowgroup_ctr < DCTSIZE) + (*cinfo->prep->pre_process_data) (cinfo, + input_buf, in_row_ctr, in_rows_avail, + main->buffer, &main->rowgroup_ctr, + (JDIMENSION) DCTSIZE); + + /* If we don't have a full iMCU row buffered, return to application for + * more data. Note that preprocessor will always pad to fill the iMCU row + * at the bottom of the image. + */ + if (main->rowgroup_ctr != DCTSIZE) + return; + + /* Send the completed row to the compressor */ + if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) { + /* If compressor did not consume the whole row, then we must need to + * suspend processing and return to the application. In this situation + * we pretend we didn't yet consume the last input row; otherwise, if + * it happened to be the last row of the image, the application would + * think we were done. + */ + if (! main->suspended) { + (*in_row_ctr)--; + main->suspended = TRUE; + } + return; + } + /* We did finish the row. Undo our little suspension hack if a previous + * call suspended; then mark the main buffer empty. + */ + if (main->suspended) { + (*in_row_ctr)++; + main->suspended = FALSE; + } + main->rowgroup_ctr = 0; + main->cur_iMCU_row++; + } +} + + +#ifdef FULL_MAIN_BUFFER_SUPPORTED + +/* + * Process some data. + * This routine handles all of the modes that use a full-size buffer. + */ + +METHODDEF(void) +process_data_buffer_main (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, + JDIMENSION in_rows_avail) +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + int ci; + jpeg_component_info *compptr; + boolean writing = (main->pass_mode != JBUF_CRANK_DEST); + + while (main->cur_iMCU_row < cinfo->total_iMCU_rows) { + /* Realign the virtual buffers if at the start of an iMCU row. */ + if (main->rowgroup_ctr == 0) { + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + main->buffer[ci] = (*cinfo->mem->access_virt_sarray) + ((j_common_ptr) cinfo, main->whole_image[ci], + main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE), + (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing); + } + /* In a read pass, pretend we just read some source data. */ + if (! writing) { + *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE; + main->rowgroup_ctr = DCTSIZE; + } + } + + /* If a write pass, read input data until the current iMCU row is full. */ + /* Note: preprocessor will pad if necessary to fill the last iMCU row. */ + if (writing) { + (*cinfo->prep->pre_process_data) (cinfo, + input_buf, in_row_ctr, in_rows_avail, + main->buffer, &main->rowgroup_ctr, + (JDIMENSION) DCTSIZE); + /* Return to application if we need more data to fill the iMCU row. */ + if (main->rowgroup_ctr < DCTSIZE) + return; + } + + /* Emit data, unless this is a sink-only pass. */ + if (main->pass_mode != JBUF_SAVE_SOURCE) { + if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) { + /* If compressor did not consume the whole row, then we must need to + * suspend processing and return to the application. In this situation + * we pretend we didn't yet consume the last input row; otherwise, if + * it happened to be the last row of the image, the application would + * think we were done. + */ + if (! main->suspended) { + (*in_row_ctr)--; + main->suspended = TRUE; + } + return; + } + /* We did finish the row. Undo our little suspension hack if a previous + * call suspended; then mark the main buffer empty. + */ + if (main->suspended) { + (*in_row_ctr)++; + main->suspended = FALSE; + } + } + + /* If get here, we are done with this iMCU row. Mark buffer empty. */ + main->rowgroup_ctr = 0; + main->cur_iMCU_row++; + } +} + +#endif /* FULL_MAIN_BUFFER_SUPPORTED */ + + +/* + * Initialize main buffer controller. + */ + +GLOBAL(void) +jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer) +{ + my_main_ptr main; + int ci; + jpeg_component_info *compptr; + + main = (my_main_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_main_controller)); + cinfo->main = (struct jpeg_c_main_controller *) main; + main->pub.start_pass = start_pass_main; + + /* We don't need to create a buffer in raw-data mode. */ + if (cinfo->raw_data_in) + return; + + /* Create the buffer. It holds downsampled data, so each component + * may be of a different size. + */ + if (need_full_buffer) { +#ifdef FULL_MAIN_BUFFER_SUPPORTED + /* Allocate a full-image virtual array for each component */ + /* Note we pad the bottom to a multiple of the iMCU height */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + main->whole_image[ci] = (*cinfo->mem->request_virt_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, + compptr->width_in_blocks * DCTSIZE, + (JDIMENSION) jround_up((long) compptr->height_in_blocks, + (long) compptr->v_samp_factor) * DCTSIZE, + (JDIMENSION) (compptr->v_samp_factor * DCTSIZE)); + } +#else + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); +#endif + } else { +#ifdef FULL_MAIN_BUFFER_SUPPORTED + main->whole_image[0] = NULL; /* flag for no virtual arrays */ +#endif + /* Allocate a strip buffer for each component */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + main->buffer[ci] = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + compptr->width_in_blocks * DCTSIZE, + (JDIMENSION) (compptr->v_samp_factor * DCTSIZE)); + } + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jcmarker.c b/SlnkDWFImpl/CxImage/jpeg/jcmarker.c new file mode 100644 index 0000000..0d3ca5e --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcmarker.c @@ -0,0 +1,664 @@ +/* + * jcmarker.c + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains routines to write JPEG datastream markers. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +typedef enum { /* JPEG marker codes */ + M_SOF0 = 0xc0, + M_SOF1 = 0xc1, + M_SOF2 = 0xc2, + M_SOF3 = 0xc3, + + M_SOF5 = 0xc5, + M_SOF6 = 0xc6, + M_SOF7 = 0xc7, + + M_JPG = 0xc8, + M_SOF9 = 0xc9, + M_SOF10 = 0xca, + M_SOF11 = 0xcb, + + M_SOF13 = 0xcd, + M_SOF14 = 0xce, + M_SOF15 = 0xcf, + + M_DHT = 0xc4, + + M_DAC = 0xcc, + + M_RST0 = 0xd0, + M_RST1 = 0xd1, + M_RST2 = 0xd2, + M_RST3 = 0xd3, + M_RST4 = 0xd4, + M_RST5 = 0xd5, + M_RST6 = 0xd6, + M_RST7 = 0xd7, + + M_SOI = 0xd8, + M_EOI = 0xd9, + M_SOS = 0xda, + M_DQT = 0xdb, + M_DNL = 0xdc, + M_DRI = 0xdd, + M_DHP = 0xde, + M_EXP = 0xdf, + + M_APP0 = 0xe0, + M_APP1 = 0xe1, + M_APP2 = 0xe2, + M_APP3 = 0xe3, + M_APP4 = 0xe4, + M_APP5 = 0xe5, + M_APP6 = 0xe6, + M_APP7 = 0xe7, + M_APP8 = 0xe8, + M_APP9 = 0xe9, + M_APP10 = 0xea, + M_APP11 = 0xeb, + M_APP12 = 0xec, + M_APP13 = 0xed, + M_APP14 = 0xee, + M_APP15 = 0xef, + + M_JPG0 = 0xf0, + M_JPG13 = 0xfd, + M_COM = 0xfe, + + M_TEM = 0x01, + + M_ERROR = 0x100 +} JPEG_MARKER; + + +/* Private state */ + +typedef struct { + struct jpeg_marker_writer pub; /* public fields */ + + unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */ +} my_marker_writer; + +typedef my_marker_writer * my_marker_ptr; + + +/* + * Basic output routines. + * + * Note that we do not support suspension while writing a marker. + * Therefore, an application using suspension must ensure that there is + * enough buffer space for the initial markers (typ. 600-700 bytes) before + * calling jpeg_start_compress, and enough space to write the trailing EOI + * (a few bytes) before calling jpeg_finish_compress. Multipass compression + * modes are not supported at all with suspension, so those two are the only + * points where markers will be written. + */ + +LOCAL(void) +emit_byte (j_compress_ptr cinfo, int val) +/* Emit a byte */ +{ + struct jpeg_destination_mgr * dest = cinfo->dest; + + *(dest->next_output_byte)++ = (JOCTET) val; + if (--dest->free_in_buffer == 0) { + if (! (*dest->empty_output_buffer) (cinfo)) + ERREXIT(cinfo, JERR_CANT_SUSPEND); + } +} + + +LOCAL(void) +emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark) +/* Emit a marker code */ +{ + emit_byte(cinfo, 0xFF); + emit_byte(cinfo, (int) mark); +} + + +LOCAL(void) +emit_2bytes (j_compress_ptr cinfo, int value) +/* Emit a 2-byte integer; these are always MSB first in JPEG files */ +{ + emit_byte(cinfo, (value >> 8) & 0xFF); + emit_byte(cinfo, value & 0xFF); +} + + +/* + * Routines to write specific marker types. + */ + +LOCAL(int) +emit_dqt (j_compress_ptr cinfo, int index) +/* Emit a DQT marker */ +/* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */ +{ + JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index]; + int prec; + int i; + + if (qtbl == NULL) + ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index); + + prec = 0; + for (i = 0; i < DCTSIZE2; i++) { + if (qtbl->quantval[i] > 255) + prec = 1; + } + + if (! qtbl->sent_table) { + emit_marker(cinfo, M_DQT); + + emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2); + + emit_byte(cinfo, index + (prec<<4)); + + for (i = 0; i < DCTSIZE2; i++) { + /* The table entries must be emitted in zigzag order. */ + unsigned int qval = qtbl->quantval[jpeg_natural_order[i]]; + if (prec) + emit_byte(cinfo, (int) (qval >> 8)); + emit_byte(cinfo, (int) (qval & 0xFF)); + } + + qtbl->sent_table = TRUE; + } + + return prec; +} + + +LOCAL(void) +emit_dht (j_compress_ptr cinfo, int index, boolean is_ac) +/* Emit a DHT marker */ +{ + JHUFF_TBL * htbl; + int length, i; + + if (is_ac) { + htbl = cinfo->ac_huff_tbl_ptrs[index]; + index += 0x10; /* output index has AC bit set */ + } else { + htbl = cinfo->dc_huff_tbl_ptrs[index]; + } + + if (htbl == NULL) + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index); + + if (! htbl->sent_table) { + emit_marker(cinfo, M_DHT); + + length = 0; + for (i = 1; i <= 16; i++) + length += htbl->bits[i]; + + emit_2bytes(cinfo, length + 2 + 1 + 16); + emit_byte(cinfo, index); + + for (i = 1; i <= 16; i++) + emit_byte(cinfo, htbl->bits[i]); + + for (i = 0; i < length; i++) + emit_byte(cinfo, htbl->huffval[i]); + + htbl->sent_table = TRUE; + } +} + + +LOCAL(void) +emit_dac (j_compress_ptr cinfo) +/* Emit a DAC marker */ +/* Since the useful info is so small, we want to emit all the tables in */ +/* one DAC marker. Therefore this routine does its own scan of the table. */ +{ +#ifdef C_ARITH_CODING_SUPPORTED + char dc_in_use[NUM_ARITH_TBLS]; + char ac_in_use[NUM_ARITH_TBLS]; + int length, i; + jpeg_component_info *compptr; + + for (i = 0; i < NUM_ARITH_TBLS; i++) + dc_in_use[i] = ac_in_use[i] = 0; + + for (i = 0; i < cinfo->comps_in_scan; i++) { + compptr = cinfo->cur_comp_info[i]; + dc_in_use[compptr->dc_tbl_no] = 1; + ac_in_use[compptr->ac_tbl_no] = 1; + } + + length = 0; + for (i = 0; i < NUM_ARITH_TBLS; i++) + length += dc_in_use[i] + ac_in_use[i]; + + emit_marker(cinfo, M_DAC); + + emit_2bytes(cinfo, length*2 + 2); + + for (i = 0; i < NUM_ARITH_TBLS; i++) { + if (dc_in_use[i]) { + emit_byte(cinfo, i); + emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4)); + } + if (ac_in_use[i]) { + emit_byte(cinfo, i + 0x10); + emit_byte(cinfo, cinfo->arith_ac_K[i]); + } + } +#endif /* C_ARITH_CODING_SUPPORTED */ +} + + +LOCAL(void) +emit_dri (j_compress_ptr cinfo) +/* Emit a DRI marker */ +{ + emit_marker(cinfo, M_DRI); + + emit_2bytes(cinfo, 4); /* fixed length */ + + emit_2bytes(cinfo, (int) cinfo->restart_interval); +} + + +LOCAL(void) +emit_sof (j_compress_ptr cinfo, JPEG_MARKER code) +/* Emit a SOF marker */ +{ + int ci; + jpeg_component_info *compptr; + + emit_marker(cinfo, code); + + emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */ + + /* Make sure image isn't bigger than SOF field can handle */ + if ((long) cinfo->image_height > 65535L || + (long) cinfo->image_width > 65535L) + ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535); + + emit_byte(cinfo, cinfo->data_precision); + emit_2bytes(cinfo, (int) cinfo->image_height); + emit_2bytes(cinfo, (int) cinfo->image_width); + + emit_byte(cinfo, cinfo->num_components); + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + emit_byte(cinfo, compptr->component_id); + emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor); + emit_byte(cinfo, compptr->quant_tbl_no); + } +} + + +LOCAL(void) +emit_sos (j_compress_ptr cinfo) +/* Emit a SOS marker */ +{ + int i, td, ta; + jpeg_component_info *compptr; + + emit_marker(cinfo, M_SOS); + + emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */ + + emit_byte(cinfo, cinfo->comps_in_scan); + + for (i = 0; i < cinfo->comps_in_scan; i++) { + compptr = cinfo->cur_comp_info[i]; + emit_byte(cinfo, compptr->component_id); + td = compptr->dc_tbl_no; + ta = compptr->ac_tbl_no; + if (cinfo->progressive_mode) { + /* Progressive mode: only DC or only AC tables are used in one scan; + * furthermore, Huffman coding of DC refinement uses no table at all. + * We emit 0 for unused field(s); this is recommended by the P&M text + * but does not seem to be specified in the standard. + */ + if (cinfo->Ss == 0) { + ta = 0; /* DC scan */ + if (cinfo->Ah != 0 && !cinfo->arith_code) + td = 0; /* no DC table either */ + } else { + td = 0; /* AC scan */ + } + } + emit_byte(cinfo, (td << 4) + ta); + } + + emit_byte(cinfo, cinfo->Ss); + emit_byte(cinfo, cinfo->Se); + emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al); +} + + +LOCAL(void) +emit_jfif_app0 (j_compress_ptr cinfo) +/* Emit a JFIF-compliant APP0 marker */ +{ + /* + * Length of APP0 block (2 bytes) + * Block ID (4 bytes - ASCII "JFIF") + * Zero byte (1 byte to terminate the ID string) + * Version Major, Minor (2 bytes - major first) + * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm) + * Xdpu (2 bytes - dots per unit horizontal) + * Ydpu (2 bytes - dots per unit vertical) + * Thumbnail X size (1 byte) + * Thumbnail Y size (1 byte) + */ + + emit_marker(cinfo, M_APP0); + + emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */ + + emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */ + emit_byte(cinfo, 0x46); + emit_byte(cinfo, 0x49); + emit_byte(cinfo, 0x46); + emit_byte(cinfo, 0); + emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */ + emit_byte(cinfo, cinfo->JFIF_minor_version); + emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */ + emit_2bytes(cinfo, (int) cinfo->X_density); + emit_2bytes(cinfo, (int) cinfo->Y_density); + emit_byte(cinfo, 0); /* No thumbnail image */ + emit_byte(cinfo, 0); +} + + +LOCAL(void) +emit_adobe_app14 (j_compress_ptr cinfo) +/* Emit an Adobe APP14 marker */ +{ + /* + * Length of APP14 block (2 bytes) + * Block ID (5 bytes - ASCII "Adobe") + * Version Number (2 bytes - currently 100) + * Flags0 (2 bytes - currently 0) + * Flags1 (2 bytes - currently 0) + * Color transform (1 byte) + * + * Although Adobe TN 5116 mentions Version = 101, all the Adobe files + * now in circulation seem to use Version = 100, so that's what we write. + * + * We write the color transform byte as 1 if the JPEG color space is + * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with + * whether the encoder performed a transformation, which is pretty useless. + */ + + emit_marker(cinfo, M_APP14); + + emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */ + + emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */ + emit_byte(cinfo, 0x64); + emit_byte(cinfo, 0x6F); + emit_byte(cinfo, 0x62); + emit_byte(cinfo, 0x65); + emit_2bytes(cinfo, 100); /* Version */ + emit_2bytes(cinfo, 0); /* Flags0 */ + emit_2bytes(cinfo, 0); /* Flags1 */ + switch (cinfo->jpeg_color_space) { + case JCS_YCbCr: + emit_byte(cinfo, 1); /* Color transform = 1 */ + break; + case JCS_YCCK: + emit_byte(cinfo, 2); /* Color transform = 2 */ + break; + default: + emit_byte(cinfo, 0); /* Color transform = 0 */ + break; + } +} + + +/* + * These routines allow writing an arbitrary marker with parameters. + * The only intended use is to emit COM or APPn markers after calling + * write_file_header and before calling write_frame_header. + * Other uses are not guaranteed to produce desirable results. + * Counting the parameter bytes properly is the caller's responsibility. + */ + +METHODDEF(void) +write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen) +/* Emit an arbitrary marker header */ +{ + if (datalen > (unsigned int) 65533) /* safety check */ + ERREXIT(cinfo, JERR_BAD_LENGTH); + + emit_marker(cinfo, (JPEG_MARKER) marker); + + emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */ +} + +METHODDEF(void) +write_marker_byte (j_compress_ptr cinfo, int val) +/* Emit one byte of marker parameters following write_marker_header */ +{ + emit_byte(cinfo, val); +} + + +/* + * Write datastream header. + * This consists of an SOI and optional APPn markers. + * We recommend use of the JFIF marker, but not the Adobe marker, + * when using YCbCr or grayscale data. The JFIF marker should NOT + * be used for any other JPEG colorspace. The Adobe marker is helpful + * to distinguish RGB, CMYK, and YCCK colorspaces. + * Note that an application can write additional header markers after + * jpeg_start_compress returns. + */ + +METHODDEF(void) +write_file_header (j_compress_ptr cinfo) +{ + my_marker_ptr marker = (my_marker_ptr) cinfo->marker; + + emit_marker(cinfo, M_SOI); /* first the SOI */ + + /* SOI is defined to reset restart interval to 0 */ + marker->last_restart_interval = 0; + + if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */ + emit_jfif_app0(cinfo); + if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */ + emit_adobe_app14(cinfo); +} + + +/* + * Write frame header. + * This consists of DQT and SOFn markers. + * Note that we do not emit the SOF until we have emitted the DQT(s). + * This avoids compatibility problems with incorrect implementations that + * try to error-check the quant table numbers as soon as they see the SOF. + */ + +METHODDEF(void) +write_frame_header (j_compress_ptr cinfo) +{ + int ci, prec; + boolean is_baseline; + jpeg_component_info *compptr; + + /* Emit DQT for each quantization table. + * Note that emit_dqt() suppresses any duplicate tables. + */ + prec = 0; + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + prec += emit_dqt(cinfo, compptr->quant_tbl_no); + } + /* now prec is nonzero iff there are any 16-bit quant tables. */ + + /* Check for a non-baseline specification. + * Note we assume that Huffman table numbers won't be changed later. + */ + if (cinfo->arith_code || cinfo->progressive_mode || + cinfo->data_precision != 8) { + is_baseline = FALSE; + } else { + is_baseline = TRUE; + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1) + is_baseline = FALSE; + } + if (prec && is_baseline) { + is_baseline = FALSE; + /* If it's baseline except for quantizer size, warn the user */ + TRACEMS(cinfo, 0, JTRC_16BIT_TABLES); + } + } + + /* Emit the proper SOF marker */ + if (cinfo->arith_code) { + emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */ + } else { + if (cinfo->progressive_mode) + emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */ + else if (is_baseline) + emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */ + else + emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */ + } +} + + +/* + * Write scan header. + * This consists of DHT or DAC markers, optional DRI, and SOS. + * Compressed data will be written following the SOS. + */ + +METHODDEF(void) +write_scan_header (j_compress_ptr cinfo) +{ + my_marker_ptr marker = (my_marker_ptr) cinfo->marker; + int i; + jpeg_component_info *compptr; + + if (cinfo->arith_code) { + /* Emit arith conditioning info. We may have some duplication + * if the file has multiple scans, but it's so small it's hardly + * worth worrying about. + */ + emit_dac(cinfo); + } else { + /* Emit Huffman tables. + * Note that emit_dht() suppresses any duplicate tables. + */ + for (i = 0; i < cinfo->comps_in_scan; i++) { + compptr = cinfo->cur_comp_info[i]; + if (cinfo->progressive_mode) { + /* Progressive mode: only DC or only AC tables are used in one scan */ + if (cinfo->Ss == 0) { + if (cinfo->Ah == 0) /* DC needs no table for refinement scan */ + emit_dht(cinfo, compptr->dc_tbl_no, FALSE); + } else { + emit_dht(cinfo, compptr->ac_tbl_no, TRUE); + } + } else { + /* Sequential mode: need both DC and AC tables */ + emit_dht(cinfo, compptr->dc_tbl_no, FALSE); + emit_dht(cinfo, compptr->ac_tbl_no, TRUE); + } + } + } + + /* Emit DRI if required --- note that DRI value could change for each scan. + * We avoid wasting space with unnecessary DRIs, however. + */ + if (cinfo->restart_interval != marker->last_restart_interval) { + emit_dri(cinfo); + marker->last_restart_interval = cinfo->restart_interval; + } + + emit_sos(cinfo); +} + + +/* + * Write datastream trailer. + */ + +METHODDEF(void) +write_file_trailer (j_compress_ptr cinfo) +{ + emit_marker(cinfo, M_EOI); +} + + +/* + * Write an abbreviated table-specification datastream. + * This consists of SOI, DQT and DHT tables, and EOI. + * Any table that is defined and not marked sent_table = TRUE will be + * emitted. Note that all tables will be marked sent_table = TRUE at exit. + */ + +METHODDEF(void) +write_tables_only (j_compress_ptr cinfo) +{ + int i; + + emit_marker(cinfo, M_SOI); + + for (i = 0; i < NUM_QUANT_TBLS; i++) { + if (cinfo->quant_tbl_ptrs[i] != NULL) + (void) emit_dqt(cinfo, i); + } + + if (! cinfo->arith_code) { + for (i = 0; i < NUM_HUFF_TBLS; i++) { + if (cinfo->dc_huff_tbl_ptrs[i] != NULL) + emit_dht(cinfo, i, FALSE); + if (cinfo->ac_huff_tbl_ptrs[i] != NULL) + emit_dht(cinfo, i, TRUE); + } + } + + emit_marker(cinfo, M_EOI); +} + + +/* + * Initialize the marker writer module. + */ + +GLOBAL(void) +jinit_marker_writer (j_compress_ptr cinfo) +{ + my_marker_ptr marker; + + /* Create the subobject */ + marker = (my_marker_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_marker_writer)); + cinfo->marker = (struct jpeg_marker_writer *) marker; + /* Initialize method pointers */ + marker->pub.write_file_header = write_file_header; + marker->pub.write_frame_header = write_frame_header; + marker->pub.write_scan_header = write_scan_header; + marker->pub.write_file_trailer = write_file_trailer; + marker->pub.write_tables_only = write_tables_only; + marker->pub.write_marker_header = write_marker_header; + marker->pub.write_marker_byte = write_marker_byte; + /* Initialize private state */ + marker->last_restart_interval = 0; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jcmaster.c b/SlnkDWFImpl/CxImage/jpeg/jcmaster.c new file mode 100644 index 0000000..e61138b --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcmaster.c @@ -0,0 +1,590 @@ +/* + * jcmaster.c + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains master control logic for the JPEG compressor. + * These routines are concerned with parameter validation, initial setup, + * and inter-pass control (determining the number of passes and the work + * to be done in each pass). + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Private state */ + +typedef enum { + main_pass, /* input data, also do first output step */ + huff_opt_pass, /* Huffman code optimization pass */ + output_pass /* data output pass */ +} c_pass_type; + +typedef struct { + struct jpeg_comp_master pub; /* public fields */ + + c_pass_type pass_type; /* the type of the current pass */ + + int pass_number; /* # of passes completed */ + int total_passes; /* total # of passes needed */ + + int scan_number; /* current index in scan_info[] */ +} my_comp_master; + +typedef my_comp_master * my_master_ptr; + + +/* + * Support routines that do various essential calculations. + */ + +LOCAL(void) +initial_setup (j_compress_ptr cinfo) +/* Do computations that are needed before master selection phase */ +{ + int ci; + jpeg_component_info *compptr; + long samplesperrow; + JDIMENSION jd_samplesperrow; + + /* Sanity check on image dimensions */ + if (cinfo->image_height <= 0 || cinfo->image_width <= 0 + || cinfo->num_components <= 0 || cinfo->input_components <= 0) + ERREXIT(cinfo, JERR_EMPTY_IMAGE); + + /* Make sure image isn't bigger than I can handle */ + if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION || + (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION) + ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); + + /* Width of an input scanline must be representable as JDIMENSION. */ + samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components; + jd_samplesperrow = (JDIMENSION) samplesperrow; + if ((long) jd_samplesperrow != samplesperrow) + ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); + + /* For now, precision must match compiled-in value... */ + if (cinfo->data_precision != BITS_IN_JSAMPLE) + ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision); + + /* Check that number of components won't exceed internal array sizes */ + if (cinfo->num_components > MAX_COMPONENTS) + ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, + MAX_COMPONENTS); + + /* Compute maximum sampling factors; check factor validity */ + cinfo->max_h_samp_factor = 1; + cinfo->max_v_samp_factor = 1; + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR || + compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR) + ERREXIT(cinfo, JERR_BAD_SAMPLING); + cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor, + compptr->h_samp_factor); + cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor, + compptr->v_samp_factor); + } + + /* Compute dimensions of components */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Fill in the correct component_index value; don't rely on application */ + compptr->component_index = ci; + /* For compression, we never do DCT scaling. */ + compptr->DCT_scaled_size = DCTSIZE; + /* Size in DCT blocks */ + compptr->width_in_blocks = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, + (long) (cinfo->max_h_samp_factor * DCTSIZE)); + compptr->height_in_blocks = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, + (long) (cinfo->max_v_samp_factor * DCTSIZE)); + /* Size in samples */ + compptr->downsampled_width = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, + (long) cinfo->max_h_samp_factor); + compptr->downsampled_height = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, + (long) cinfo->max_v_samp_factor); + /* Mark component needed (this flag isn't actually used for compression) */ + compptr->component_needed = TRUE; + } + + /* Compute number of fully interleaved MCU rows (number of times that + * main controller will call coefficient controller). + */ + cinfo->total_iMCU_rows = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height, + (long) (cinfo->max_v_samp_factor*DCTSIZE)); +} + + +#ifdef C_MULTISCAN_FILES_SUPPORTED + +LOCAL(void) +validate_script (j_compress_ptr cinfo) +/* Verify that the scan script in cinfo->scan_info[] is valid; also + * determine whether it uses progressive JPEG, and set cinfo->progressive_mode. + */ +{ + const jpeg_scan_info * scanptr; + int scanno, ncomps, ci, coefi, thisi; + int Ss, Se, Ah, Al; + boolean component_sent[MAX_COMPONENTS]; +#ifdef C_PROGRESSIVE_SUPPORTED + int * last_bitpos_ptr; + int last_bitpos[MAX_COMPONENTS][DCTSIZE2]; + /* -1 until that coefficient has been seen; then last Al for it */ +#endif + + if (cinfo->num_scans <= 0) + ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0); + + /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1; + * for progressive JPEG, no scan can have this. + */ + scanptr = cinfo->scan_info; + if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) { +#ifdef C_PROGRESSIVE_SUPPORTED + cinfo->progressive_mode = TRUE; + last_bitpos_ptr = & last_bitpos[0][0]; + for (ci = 0; ci < cinfo->num_components; ci++) + for (coefi = 0; coefi < DCTSIZE2; coefi++) + *last_bitpos_ptr++ = -1; +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else { + cinfo->progressive_mode = FALSE; + for (ci = 0; ci < cinfo->num_components; ci++) + component_sent[ci] = FALSE; + } + + for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) { + /* Validate component indexes */ + ncomps = scanptr->comps_in_scan; + if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN) + ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN); + for (ci = 0; ci < ncomps; ci++) { + thisi = scanptr->component_index[ci]; + if (thisi < 0 || thisi >= cinfo->num_components) + ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); + /* Components must appear in SOF order within each scan */ + if (ci > 0 && thisi <= scanptr->component_index[ci-1]) + ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); + } + /* Validate progression parameters */ + Ss = scanptr->Ss; + Se = scanptr->Se; + Ah = scanptr->Ah; + Al = scanptr->Al; + if (cinfo->progressive_mode) { +#ifdef C_PROGRESSIVE_SUPPORTED + /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that + * seems wrong: the upper bound ought to depend on data precision. + * Perhaps they really meant 0..N+1 for N-bit precision. + * Here we allow 0..10 for 8-bit data; Al larger than 10 results in + * out-of-range reconstructed DC values during the first DC scan, + * which might cause problems for some decoders. + */ +#if BITS_IN_JSAMPLE == 8 +#define MAX_AH_AL 10 +#else +#define MAX_AH_AL 13 +#endif + if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 || + Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL) + ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); + if (Ss == 0) { + if (Se != 0) /* DC and AC together not OK */ + ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); + } else { + if (ncomps != 1) /* AC scans must be for only one component */ + ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); + } + for (ci = 0; ci < ncomps; ci++) { + last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0]; + if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */ + ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); + for (coefi = Ss; coefi <= Se; coefi++) { + if (last_bitpos_ptr[coefi] < 0) { + /* first scan of this coefficient */ + if (Ah != 0) + ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); + } else { + /* not first scan */ + if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1) + ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); + } + last_bitpos_ptr[coefi] = Al; + } + } +#endif + } else { + /* For sequential JPEG, all progression parameters must be these: */ + if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0) + ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); + /* Make sure components are not sent twice */ + for (ci = 0; ci < ncomps; ci++) { + thisi = scanptr->component_index[ci]; + if (component_sent[thisi]) + ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); + component_sent[thisi] = TRUE; + } + } + } + + /* Now verify that everything got sent. */ + if (cinfo->progressive_mode) { +#ifdef C_PROGRESSIVE_SUPPORTED + /* For progressive mode, we only check that at least some DC data + * got sent for each component; the spec does not require that all bits + * of all coefficients be transmitted. Would it be wiser to enforce + * transmission of all coefficient bits?? + */ + for (ci = 0; ci < cinfo->num_components; ci++) { + if (last_bitpos[ci][0] < 0) + ERREXIT(cinfo, JERR_MISSING_DATA); + } +#endif + } else { + for (ci = 0; ci < cinfo->num_components; ci++) { + if (! component_sent[ci]) + ERREXIT(cinfo, JERR_MISSING_DATA); + } + } +} + +#endif /* C_MULTISCAN_FILES_SUPPORTED */ + + +LOCAL(void) +select_scan_parameters (j_compress_ptr cinfo) +/* Set up the scan parameters for the current scan */ +{ + int ci; + +#ifdef C_MULTISCAN_FILES_SUPPORTED + if (cinfo->scan_info != NULL) { + /* Prepare for current scan --- the script is already validated */ + my_master_ptr master = (my_master_ptr) cinfo->master; + const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number; + + cinfo->comps_in_scan = scanptr->comps_in_scan; + for (ci = 0; ci < scanptr->comps_in_scan; ci++) { + cinfo->cur_comp_info[ci] = + &cinfo->comp_info[scanptr->component_index[ci]]; + } + cinfo->Ss = scanptr->Ss; + cinfo->Se = scanptr->Se; + cinfo->Ah = scanptr->Ah; + cinfo->Al = scanptr->Al; + } + else +#endif + { + /* Prepare for single sequential-JPEG scan containing all components */ + if (cinfo->num_components > MAX_COMPS_IN_SCAN) + ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, + MAX_COMPS_IN_SCAN); + cinfo->comps_in_scan = cinfo->num_components; + for (ci = 0; ci < cinfo->num_components; ci++) { + cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci]; + } + cinfo->Ss = 0; + cinfo->Se = DCTSIZE2-1; + cinfo->Ah = 0; + cinfo->Al = 0; + } +} + + +LOCAL(void) +per_scan_setup (j_compress_ptr cinfo) +/* Do computations that are needed before processing a JPEG scan */ +/* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */ +{ + int ci, mcublks, tmp; + jpeg_component_info *compptr; + + if (cinfo->comps_in_scan == 1) { + + /* Noninterleaved (single-component) scan */ + compptr = cinfo->cur_comp_info[0]; + + /* Overall image size in MCUs */ + cinfo->MCUs_per_row = compptr->width_in_blocks; + cinfo->MCU_rows_in_scan = compptr->height_in_blocks; + + /* For noninterleaved scan, always one block per MCU */ + compptr->MCU_width = 1; + compptr->MCU_height = 1; + compptr->MCU_blocks = 1; + compptr->MCU_sample_width = DCTSIZE; + compptr->last_col_width = 1; + /* For noninterleaved scans, it is convenient to define last_row_height + * as the number of block rows present in the last iMCU row. + */ + tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor); + if (tmp == 0) tmp = compptr->v_samp_factor; + compptr->last_row_height = tmp; + + /* Prepare array describing MCU composition */ + cinfo->blocks_in_MCU = 1; + cinfo->MCU_membership[0] = 0; + + } else { + + /* Interleaved (multi-component) scan */ + if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN) + ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan, + MAX_COMPS_IN_SCAN); + + /* Overall image size in MCUs */ + cinfo->MCUs_per_row = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width, + (long) (cinfo->max_h_samp_factor*DCTSIZE)); + cinfo->MCU_rows_in_scan = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height, + (long) (cinfo->max_v_samp_factor*DCTSIZE)); + + cinfo->blocks_in_MCU = 0; + + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + /* Sampling factors give # of blocks of component in each MCU */ + compptr->MCU_width = compptr->h_samp_factor; + compptr->MCU_height = compptr->v_samp_factor; + compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height; + compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE; + /* Figure number of non-dummy blocks in last MCU column & row */ + tmp = (int) (compptr->width_in_blocks % compptr->MCU_width); + if (tmp == 0) tmp = compptr->MCU_width; + compptr->last_col_width = tmp; + tmp = (int) (compptr->height_in_blocks % compptr->MCU_height); + if (tmp == 0) tmp = compptr->MCU_height; + compptr->last_row_height = tmp; + /* Prepare array describing MCU composition */ + mcublks = compptr->MCU_blocks; + if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU) + ERREXIT(cinfo, JERR_BAD_MCU_SIZE); + while (mcublks-- > 0) { + cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci; + } + } + + } + + /* Convert restart specified in rows to actual MCU count. */ + /* Note that count must fit in 16 bits, so we provide limiting. */ + if (cinfo->restart_in_rows > 0) { + long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row; + cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L); + } +} + + +/* + * Per-pass setup. + * This is called at the beginning of each pass. We determine which modules + * will be active during this pass and give them appropriate start_pass calls. + * We also set is_last_pass to indicate whether any more passes will be + * required. + */ + +METHODDEF(void) +prepare_for_pass (j_compress_ptr cinfo) +{ + my_master_ptr master = (my_master_ptr) cinfo->master; + + switch (master->pass_type) { + case main_pass: + /* Initial pass: will collect input data, and do either Huffman + * optimization or data output for the first scan. + */ + select_scan_parameters(cinfo); + per_scan_setup(cinfo); + if (! cinfo->raw_data_in) { + (*cinfo->cconvert->start_pass) (cinfo); + (*cinfo->downsample->start_pass) (cinfo); + (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU); + } + (*cinfo->fdct->start_pass) (cinfo); + (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding); + (*cinfo->coef->start_pass) (cinfo, + (master->total_passes > 1 ? + JBUF_SAVE_AND_PASS : JBUF_PASS_THRU)); + (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU); + if (cinfo->optimize_coding) { + /* No immediate data output; postpone writing frame/scan headers */ + master->pub.call_pass_startup = FALSE; + } else { + /* Will write frame/scan headers at first jpeg_write_scanlines call */ + master->pub.call_pass_startup = TRUE; + } + break; +#ifdef ENTROPY_OPT_SUPPORTED + case huff_opt_pass: + /* Do Huffman optimization for a scan after the first one. */ + select_scan_parameters(cinfo); + per_scan_setup(cinfo); + if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) { + (*cinfo->entropy->start_pass) (cinfo, TRUE); + (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST); + master->pub.call_pass_startup = FALSE; + break; + } + /* Special case: Huffman DC refinement scans need no Huffman table + * and therefore we can skip the optimization pass for them. + */ + master->pass_type = output_pass; + master->pass_number++; + /*FALLTHROUGH*/ +#endif + case output_pass: + /* Do a data-output pass. */ + /* We need not repeat per-scan setup if prior optimization pass did it. */ + if (! cinfo->optimize_coding) { + select_scan_parameters(cinfo); + per_scan_setup(cinfo); + } + (*cinfo->entropy->start_pass) (cinfo, FALSE); + (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST); + /* We emit frame/scan headers now */ + if (master->scan_number == 0) + (*cinfo->marker->write_frame_header) (cinfo); + (*cinfo->marker->write_scan_header) (cinfo); + master->pub.call_pass_startup = FALSE; + break; + default: + ERREXIT(cinfo, JERR_NOT_COMPILED); + } + + master->pub.is_last_pass = (master->pass_number == master->total_passes-1); + + /* Set up progress monitor's pass info if present */ + if (cinfo->progress != NULL) { + cinfo->progress->completed_passes = master->pass_number; + cinfo->progress->total_passes = master->total_passes; + } +} + + +/* + * Special start-of-pass hook. + * This is called by jpeg_write_scanlines if call_pass_startup is TRUE. + * In single-pass processing, we need this hook because we don't want to + * write frame/scan headers during jpeg_start_compress; we want to let the + * application write COM markers etc. between jpeg_start_compress and the + * jpeg_write_scanlines loop. + * In multi-pass processing, this routine is not used. + */ + +METHODDEF(void) +pass_startup (j_compress_ptr cinfo) +{ + cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */ + + (*cinfo->marker->write_frame_header) (cinfo); + (*cinfo->marker->write_scan_header) (cinfo); +} + + +/* + * Finish up at end of pass. + */ + +METHODDEF(void) +finish_pass_master (j_compress_ptr cinfo) +{ + my_master_ptr master = (my_master_ptr) cinfo->master; + + /* The entropy coder always needs an end-of-pass call, + * either to analyze statistics or to flush its output buffer. + */ + (*cinfo->entropy->finish_pass) (cinfo); + + /* Update state for next pass */ + switch (master->pass_type) { + case main_pass: + /* next pass is either output of scan 0 (after optimization) + * or output of scan 1 (if no optimization). + */ + master->pass_type = output_pass; + if (! cinfo->optimize_coding) + master->scan_number++; + break; + case huff_opt_pass: + /* next pass is always output of current scan */ + master->pass_type = output_pass; + break; + case output_pass: + /* next pass is either optimization or output of next scan */ + if (cinfo->optimize_coding) + master->pass_type = huff_opt_pass; + master->scan_number++; + break; + } + + master->pass_number++; +} + + +/* + * Initialize master compression control. + */ + +GLOBAL(void) +jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only) +{ + my_master_ptr master; + + master = (my_master_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_comp_master)); + cinfo->master = (struct jpeg_comp_master *) master; + master->pub.prepare_for_pass = prepare_for_pass; + master->pub.pass_startup = pass_startup; + master->pub.finish_pass = finish_pass_master; + master->pub.is_last_pass = FALSE; + + /* Validate parameters, determine derived values */ + initial_setup(cinfo); + + if (cinfo->scan_info != NULL) { +#ifdef C_MULTISCAN_FILES_SUPPORTED + validate_script(cinfo); +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else { + cinfo->progressive_mode = FALSE; + cinfo->num_scans = 1; + } + + if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */ + cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */ + + /* Initialize my private state */ + if (transcode_only) { + /* no main pass in transcoding */ + if (cinfo->optimize_coding) + master->pass_type = huff_opt_pass; + else + master->pass_type = output_pass; + } else { + /* for normal compression, first pass is always this type: */ + master->pass_type = main_pass; + } + master->scan_number = 0; + master->pass_number = 0; + if (cinfo->optimize_coding) + master->total_passes = cinfo->num_scans * 2; + else + master->total_passes = cinfo->num_scans; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jcomapi.c b/SlnkDWFImpl/CxImage/jpeg/jcomapi.c new file mode 100644 index 0000000..1b1a340 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcomapi.c @@ -0,0 +1,106 @@ +/* + * jcomapi.c + * + * Copyright (C) 1994-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains application interface routines that are used for both + * compression and decompression. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* + * Abort processing of a JPEG compression or decompression operation, + * but don't destroy the object itself. + * + * For this, we merely clean up all the nonpermanent memory pools. + * Note that temp files (virtual arrays) are not allowed to belong to + * the permanent pool, so we will be able to close all temp files here. + * Closing a data source or destination, if necessary, is the application's + * responsibility. + */ + +GLOBAL(void) +jpeg_abort (j_common_ptr cinfo) +{ + int pool; + + /* Do nothing if called on a not-initialized or destroyed JPEG object. */ + if (cinfo->mem == NULL) + return; + + /* Releasing pools in reverse order might help avoid fragmentation + * with some (brain-damaged) malloc libraries. + */ + for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) { + (*cinfo->mem->free_pool) (cinfo, pool); + } + + /* Reset overall state for possible reuse of object */ + if (cinfo->is_decompressor) { + cinfo->global_state = DSTATE_START; + /* Try to keep application from accessing now-deleted marker list. + * A bit kludgy to do it here, but this is the most central place. + */ + ((j_decompress_ptr) cinfo)->marker_list = NULL; + } else { + cinfo->global_state = CSTATE_START; + } +} + + +/* + * Destruction of a JPEG object. + * + * Everything gets deallocated except the master jpeg_compress_struct itself + * and the error manager struct. Both of these are supplied by the application + * and must be freed, if necessary, by the application. (Often they are on + * the stack and so don't need to be freed anyway.) + * Closing a data source or destination, if necessary, is the application's + * responsibility. + */ + +GLOBAL(void) +jpeg_destroy (j_common_ptr cinfo) +{ + /* We need only tell the memory manager to release everything. */ + /* NB: mem pointer is NULL if memory mgr failed to initialize. */ + if (cinfo->mem != NULL) + (*cinfo->mem->self_destruct) (cinfo); + cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */ + cinfo->global_state = 0; /* mark it destroyed */ +} + + +/* + * Convenience routines for allocating quantization and Huffman tables. + * (Would jutils.c be a more reasonable place to put these?) + */ + +GLOBAL(JQUANT_TBL *) +jpeg_alloc_quant_table (j_common_ptr cinfo) +{ + JQUANT_TBL *tbl; + + tbl = (JQUANT_TBL *) + (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL)); + tbl->sent_table = FALSE; /* make sure this is false in any new table */ + return tbl; +} + + +GLOBAL(JHUFF_TBL *) +jpeg_alloc_huff_table (j_common_ptr cinfo) +{ + JHUFF_TBL *tbl; + + tbl = (JHUFF_TBL *) + (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL)); + tbl->sent_table = FALSE; /* make sure this is false in any new table */ + return tbl; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jconfig.h b/SlnkDWFImpl/CxImage/jpeg/jconfig.h new file mode 100644 index 0000000..f72861d --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jconfig.h @@ -0,0 +1,54 @@ +/* jconfig.bcc --- jconfig.h for Borland C (Turbo C) on MS-DOS or OS/2. */ +/* see jconfig.doc for explanations */ + +#define HAVE_PROTOTYPES +#define HAVE_UNSIGNED_CHAR +#define HAVE_UNSIGNED_SHORT +/* #define void char */ +/* #define const */ +#undef CHAR_IS_UNSIGNED +#define HAVE_STDDEF_H +#define HAVE_STDLIB_H +#undef NEED_BSD_STRINGS +#undef NEED_SYS_TYPES_H +#ifdef __MSDOS__ +#define NEED_FAR_POINTERS /* for small or medium memory model */ +#endif +#undef NEED_SHORT_EXTERNAL_NAMES +#undef INCOMPLETE_TYPES_BROKEN /* this assumes you have -w-stu in CFLAGS */ + +/* Define "boolean" as unsigned char, not int, per Windows custom */ +#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */ +typedef unsigned char boolean; +#endif +#define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ + +#ifdef JPEG_INTERNALS + +#undef RIGHT_SHIFT_IS_UNSIGNED + +#ifdef __MSDOS__ +#define USE_MSDOS_MEMMGR /* Define this if you use jmemdos.c */ +#define MAX_ALLOC_CHUNK 65520L /* Maximum request to malloc() */ +#define USE_FMEM /* Borland has _fmemcpy() and _fmemset() */ +#endif + +#endif /* JPEG_INTERNALS */ + +#ifdef JPEG_CJPEG_DJPEG + +#define BMP_SUPPORTED /* BMP image file format */ +#define GIF_SUPPORTED /* GIF image file format */ +#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ +#undef RLE_SUPPORTED /* Utah RLE image file format */ +#define TARGA_SUPPORTED /* Targa image file format */ + +#define TWO_FILE_COMMANDLINE +#define USE_SETMODE /* Borland has setmode() */ +#ifdef __MSDOS__ +#define NEED_SIGNAL_CATCHER /* Define this if you use jmemdos.c */ +#endif +#undef DONT_USE_B_MODE +#undef PROGRESS_REPORT /* optional */ + +#endif /* JPEG_CJPEG_DJPEG */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jcparam.c b/SlnkDWFImpl/CxImage/jpeg/jcparam.c new file mode 100644 index 0000000..bbd175c --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcparam.c @@ -0,0 +1,610 @@ +/* + * jcparam.c + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains optional default-setting code for the JPEG compressor. + * Applications do not have to use this file, but those that don't use it + * must know a lot more about the innards of the JPEG code. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* + * Quantization table setup routines + */ + +GLOBAL(void) +jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl, + const unsigned int *basic_table, + int scale_factor, boolean force_baseline) +/* Define a quantization table equal to the basic_table times + * a scale factor (given as a percentage). + * If force_baseline is TRUE, the computed quantization table entries + * are limited to 1..255 for JPEG baseline compatibility. + */ +{ + JQUANT_TBL ** qtblptr; + int i; + long temp; + + /* Safety check to ensure start_compress not called yet. */ + if (cinfo->global_state != CSTATE_START) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS) + ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl); + + qtblptr = & cinfo->quant_tbl_ptrs[which_tbl]; + + if (*qtblptr == NULL) + *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo); + + for (i = 0; i < DCTSIZE2; i++) { + temp = ((long) basic_table[i] * scale_factor + 50L) / 100L; + /* limit the values to the valid range */ + if (temp <= 0L) temp = 1L; + if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */ + if (force_baseline && temp > 255L) + temp = 255L; /* limit to baseline range if requested */ + (*qtblptr)->quantval[i] = (UINT16) temp; + } + + /* Initialize sent_table FALSE so table will be written to JPEG file. */ + (*qtblptr)->sent_table = FALSE; +} + + +GLOBAL(void) +jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor, + boolean force_baseline) +/* Set or change the 'quality' (quantization) setting, using default tables + * and a straight percentage-scaling quality scale. In most cases it's better + * to use jpeg_set_quality (below); this entry point is provided for + * applications that insist on a linear percentage scaling. + */ +{ + /* These are the sample quantization tables given in JPEG spec section K.1. + * The spec says that the values given produce "good" quality, and + * when divided by 2, "very good" quality. + */ + static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = { + 16, 11, 10, 16, 24, 40, 51, 61, + 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, + 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, + 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, + 72, 92, 95, 98, 112, 100, 103, 99 + }; + static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = { + 17, 18, 24, 47, 99, 99, 99, 99, + 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, + 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99 + }; + + /* Set up two quantization tables using the specified scaling */ + jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl, + scale_factor, force_baseline); + jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl, + scale_factor, force_baseline); +} + + +GLOBAL(int) +jpeg_quality_scaling (int quality) +/* Convert a user-specified quality rating to a percentage scaling factor + * for an underlying quantization table, using our recommended scaling curve. + * The input 'quality' factor should be 0 (terrible) to 100 (very good). + */ +{ + /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */ + if (quality <= 0) quality = 1; + if (quality > 100) quality = 100; + + /* The basic table is used as-is (scaling 100) for a quality of 50. + * Qualities 50..100 are converted to scaling percentage 200 - 2*Q; + * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table + * to make all the table entries 1 (hence, minimum quantization loss). + * Qualities 1..50 are converted to scaling percentage 5000/Q. + */ + if (quality < 50) + quality = 5000 / quality; + else + quality = 200 - quality*2; + + return quality; +} + + +GLOBAL(void) +jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline) +/* Set or change the 'quality' (quantization) setting, using default tables. + * This is the standard quality-adjusting entry point for typical user + * interfaces; only those who want detailed control over quantization tables + * would use the preceding three routines directly. + */ +{ + /* Convert user 0-100 rating to percentage scaling */ + quality = jpeg_quality_scaling(quality); + + /* Set up standard quality tables */ + jpeg_set_linear_quality(cinfo, quality, force_baseline); +} + + +/* + * Huffman table setup routines + */ + +LOCAL(void) +add_huff_table (j_compress_ptr cinfo, + JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val) +/* Define a Huffman table */ +{ + int nsymbols, len; + + if (*htblptr == NULL) + *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); + + /* Copy the number-of-symbols-of-each-code-length counts */ + MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits)); + + /* Validate the counts. We do this here mainly so we can copy the right + * number of symbols from the val[] array, without risking marching off + * the end of memory. jchuff.c will do a more thorough test later. + */ + nsymbols = 0; + for (len = 1; len <= 16; len++) + nsymbols += bits[len]; + if (nsymbols < 1 || nsymbols > 256) + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + + MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8)); + + /* Initialize sent_table FALSE so table will be written to JPEG file. */ + (*htblptr)->sent_table = FALSE; +} + + +LOCAL(void) +std_huff_tables (j_compress_ptr cinfo) +/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */ +/* IMPORTANT: these are only valid for 8-bit data precision! */ +{ + static const UINT8 bits_dc_luminance[17] = + { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }; + static const UINT8 val_dc_luminance[] = + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; + + static const UINT8 bits_dc_chrominance[17] = + { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }; + static const UINT8 val_dc_chrominance[] = + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; + + static const UINT8 bits_ac_luminance[17] = + { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }; + static const UINT8 val_ac_luminance[] = + { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, + 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, + 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, + 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, + 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, + 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, + 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, + 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa }; + + static const UINT8 bits_ac_chrominance[17] = + { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }; + static const UINT8 val_ac_chrominance[] = + { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, + 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, + 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, + 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, + 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, + 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, + 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, + 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, + 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, + 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa }; + + add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0], + bits_dc_luminance, val_dc_luminance); + add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0], + bits_ac_luminance, val_ac_luminance); + add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1], + bits_dc_chrominance, val_dc_chrominance); + add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1], + bits_ac_chrominance, val_ac_chrominance); +} + + +/* + * Default parameter setup for compression. + * + * Applications that don't choose to use this routine must do their + * own setup of all these parameters. Alternately, you can call this + * to establish defaults and then alter parameters selectively. This + * is the recommended approach since, if we add any new parameters, + * your code will still work (they'll be set to reasonable defaults). + */ + +GLOBAL(void) +jpeg_set_defaults (j_compress_ptr cinfo) +{ + int i; + + /* Safety check to ensure start_compress not called yet. */ + if (cinfo->global_state != CSTATE_START) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + /* Allocate comp_info array large enough for maximum component count. + * Array is made permanent in case application wants to compress + * multiple images at same param settings. + */ + if (cinfo->comp_info == NULL) + cinfo->comp_info = (jpeg_component_info *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + MAX_COMPONENTS * SIZEOF(jpeg_component_info)); + + /* Initialize everything not dependent on the color space */ + + cinfo->data_precision = BITS_IN_JSAMPLE; + /* Set up two quantization tables using default quality of 75 */ + jpeg_set_quality(cinfo, 75, TRUE); + /* Set up two Huffman tables */ + std_huff_tables(cinfo); + + /* Initialize default arithmetic coding conditioning */ + for (i = 0; i < NUM_ARITH_TBLS; i++) { + cinfo->arith_dc_L[i] = 0; + cinfo->arith_dc_U[i] = 1; + cinfo->arith_ac_K[i] = 5; + } + + /* Default is no multiple-scan output */ + cinfo->scan_info = NULL; + cinfo->num_scans = 0; + + /* Expect normal source image, not raw downsampled data */ + cinfo->raw_data_in = FALSE; + + /* Use Huffman coding, not arithmetic coding, by default */ + cinfo->arith_code = FALSE; + + /* By default, don't do extra passes to optimize entropy coding */ + cinfo->optimize_coding = FALSE; + /* The standard Huffman tables are only valid for 8-bit data precision. + * If the precision is higher, force optimization on so that usable + * tables will be computed. This test can be removed if default tables + * are supplied that are valid for the desired precision. + */ + if (cinfo->data_precision > 8) + cinfo->optimize_coding = TRUE; + + /* By default, use the simpler non-cosited sampling alignment */ + cinfo->CCIR601_sampling = FALSE; + + /* No input smoothing */ + cinfo->smoothing_factor = 0; + + /* DCT algorithm preference */ + cinfo->dct_method = JDCT_DEFAULT; + + /* No restart markers */ + cinfo->restart_interval = 0; + cinfo->restart_in_rows = 0; + + /* Fill in default JFIF marker parameters. Note that whether the marker + * will actually be written is determined by jpeg_set_colorspace. + * + * By default, the library emits JFIF version code 1.01. + * An application that wants to emit JFIF 1.02 extension markers should set + * JFIF_minor_version to 2. We could probably get away with just defaulting + * to 1.02, but there may still be some decoders in use that will complain + * about that; saying 1.01 should minimize compatibility problems. + */ + cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */ + cinfo->JFIF_minor_version = 1; + cinfo->density_unit = 0; /* Pixel size is unknown by default */ + cinfo->X_density = 1; /* Pixel aspect ratio is square by default */ + cinfo->Y_density = 1; + + /* Choose JPEG colorspace based on input space, set defaults accordingly */ + + jpeg_default_colorspace(cinfo); +} + + +/* + * Select an appropriate JPEG colorspace for in_color_space. + */ + +GLOBAL(void) +jpeg_default_colorspace (j_compress_ptr cinfo) +{ + switch (cinfo->in_color_space) { + case JCS_GRAYSCALE: + jpeg_set_colorspace(cinfo, JCS_GRAYSCALE); + break; + case JCS_RGB: + jpeg_set_colorspace(cinfo, JCS_YCbCr); + break; + case JCS_YCbCr: + jpeg_set_colorspace(cinfo, JCS_YCbCr); + break; + case JCS_CMYK: + jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */ + break; + case JCS_YCCK: + jpeg_set_colorspace(cinfo, JCS_YCCK); + break; + case JCS_UNKNOWN: + jpeg_set_colorspace(cinfo, JCS_UNKNOWN); + break; + default: + ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); + } +} + + +/* + * Set the JPEG colorspace, and choose colorspace-dependent default values. + */ + +GLOBAL(void) +jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace) +{ + jpeg_component_info * compptr; + int ci; + +#define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \ + (compptr = &cinfo->comp_info[index], \ + compptr->component_id = (id), \ + compptr->h_samp_factor = (hsamp), \ + compptr->v_samp_factor = (vsamp), \ + compptr->quant_tbl_no = (quant), \ + compptr->dc_tbl_no = (dctbl), \ + compptr->ac_tbl_no = (actbl) ) + + /* Safety check to ensure start_compress not called yet. */ + if (cinfo->global_state != CSTATE_START) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + /* For all colorspaces, we use Q and Huff tables 0 for luminance components, + * tables 1 for chrominance components. + */ + + cinfo->jpeg_color_space = colorspace; + + cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */ + cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */ + + switch (colorspace) { + case JCS_GRAYSCALE: + cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */ + cinfo->num_components = 1; + /* JFIF specifies component ID 1 */ + SET_COMP(0, 1, 1,1, 0, 0,0); + break; + case JCS_RGB: + cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */ + cinfo->num_components = 3; + SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0); + SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0); + SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0); + break; + case JCS_YCbCr: + cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */ + cinfo->num_components = 3; + /* JFIF specifies component IDs 1,2,3 */ + /* We default to 2x2 subsamples of chrominance */ + SET_COMP(0, 1, 2,2, 0, 0,0); + SET_COMP(1, 2, 1,1, 1, 1,1); + SET_COMP(2, 3, 1,1, 1, 1,1); + break; + case JCS_CMYK: + cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */ + cinfo->num_components = 4; + SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0); + SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0); + SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0); + SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0); + break; + case JCS_YCCK: + cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */ + cinfo->num_components = 4; + SET_COMP(0, 1, 2,2, 0, 0,0); + SET_COMP(1, 2, 1,1, 1, 1,1); + SET_COMP(2, 3, 1,1, 1, 1,1); + SET_COMP(3, 4, 2,2, 0, 0,0); + break; + case JCS_UNKNOWN: + cinfo->num_components = cinfo->input_components; + if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS) + ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, + MAX_COMPONENTS); + for (ci = 0; ci < cinfo->num_components; ci++) { + SET_COMP(ci, ci, 1,1, 0, 0,0); + } + break; + default: + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + } +} + + +#ifdef C_PROGRESSIVE_SUPPORTED + +LOCAL(jpeg_scan_info *) +fill_a_scan (jpeg_scan_info * scanptr, int ci, + int Ss, int Se, int Ah, int Al) +/* Support routine: generate one scan for specified component */ +{ + scanptr->comps_in_scan = 1; + scanptr->component_index[0] = ci; + scanptr->Ss = Ss; + scanptr->Se = Se; + scanptr->Ah = Ah; + scanptr->Al = Al; + scanptr++; + return scanptr; +} + +LOCAL(jpeg_scan_info *) +fill_scans (jpeg_scan_info * scanptr, int ncomps, + int Ss, int Se, int Ah, int Al) +/* Support routine: generate one scan for each component */ +{ + int ci; + + for (ci = 0; ci < ncomps; ci++) { + scanptr->comps_in_scan = 1; + scanptr->component_index[0] = ci; + scanptr->Ss = Ss; + scanptr->Se = Se; + scanptr->Ah = Ah; + scanptr->Al = Al; + scanptr++; + } + return scanptr; +} + +LOCAL(jpeg_scan_info *) +fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al) +/* Support routine: generate interleaved DC scan if possible, else N scans */ +{ + int ci; + + if (ncomps <= MAX_COMPS_IN_SCAN) { + /* Single interleaved DC scan */ + scanptr->comps_in_scan = ncomps; + for (ci = 0; ci < ncomps; ci++) + scanptr->component_index[ci] = ci; + scanptr->Ss = scanptr->Se = 0; + scanptr->Ah = Ah; + scanptr->Al = Al; + scanptr++; + } else { + /* Noninterleaved DC scan for each component */ + scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al); + } + return scanptr; +} + + +/* + * Create a recommended progressive-JPEG script. + * cinfo->num_components and cinfo->jpeg_color_space must be correct. + */ + +GLOBAL(void) +jpeg_simple_progression (j_compress_ptr cinfo) +{ + int ncomps = cinfo->num_components; + int nscans; + jpeg_scan_info * scanptr; + + /* Safety check to ensure start_compress not called yet. */ + if (cinfo->global_state != CSTATE_START) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + /* Figure space needed for script. Calculation must match code below! */ + if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) { + /* Custom script for YCbCr color images. */ + nscans = 10; + } else { + /* All-purpose script for other color spaces. */ + if (ncomps > MAX_COMPS_IN_SCAN) + nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */ + else + nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */ + } + + /* Allocate space for script. + * We need to put it in the permanent pool in case the application performs + * multiple compressions without changing the settings. To avoid a memory + * leak if jpeg_simple_progression is called repeatedly for the same JPEG + * object, we try to re-use previously allocated space, and we allocate + * enough space to handle YCbCr even if initially asked for grayscale. + */ + if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) { + cinfo->script_space_size = MAX(nscans, 10); + cinfo->script_space = (jpeg_scan_info *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + cinfo->script_space_size * SIZEOF(jpeg_scan_info)); + } + scanptr = cinfo->script_space; + cinfo->scan_info = scanptr; + cinfo->num_scans = nscans; + + if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) { + /* Custom script for YCbCr color images. */ + /* Initial DC scan */ + scanptr = fill_dc_scans(scanptr, ncomps, 0, 1); + /* Initial AC scan: get some luma data out in a hurry */ + scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2); + /* Chroma data is too small to be worth expending many scans on */ + scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1); + scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1); + /* Complete spectral selection for luma AC */ + scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2); + /* Refine next bit of luma AC */ + scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1); + /* Finish DC successive approximation */ + scanptr = fill_dc_scans(scanptr, ncomps, 1, 0); + /* Finish AC successive approximation */ + scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0); + scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0); + /* Luma bottom bit comes last since it's usually largest scan */ + scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0); + } else { + /* All-purpose script for other color spaces. */ + /* Successive approximation first pass */ + scanptr = fill_dc_scans(scanptr, ncomps, 0, 1); + scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2); + scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2); + /* Successive approximation second pass */ + scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1); + /* Successive approximation final pass */ + scanptr = fill_dc_scans(scanptr, ncomps, 1, 0); + scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0); + } +} + +#endif /* C_PROGRESSIVE_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jcphuff.c b/SlnkDWFImpl/CxImage/jpeg/jcphuff.c new file mode 100644 index 0000000..a4ee850 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcphuff.c @@ -0,0 +1,833 @@ +/* + * jcphuff.c + * + * Copyright (C) 1995-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains Huffman entropy encoding routines for progressive JPEG. + * + * We do not support output suspension in this module, since the library + * currently does not allow multiple-scan files to be written with output + * suspension. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jchuff.h" /* Declarations shared with jchuff.c */ + +#ifdef C_PROGRESSIVE_SUPPORTED + +/* Expanded entropy encoder object for progressive Huffman encoding. */ + +typedef struct { + struct jpeg_entropy_encoder pub; /* public fields */ + + /* Mode flag: TRUE for optimization, FALSE for actual data output */ + boolean gather_statistics; + + /* Bit-level coding status. + * next_output_byte/free_in_buffer are local copies of cinfo->dest fields. + */ + JOCTET * next_output_byte; /* => next byte to write in buffer */ + size_t free_in_buffer; /* # of byte spaces remaining in buffer */ + INT32 put_buffer; /* current bit-accumulation buffer */ + int put_bits; /* # of bits now in it */ + j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */ + + /* Coding status for DC components */ + int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ + + /* Coding status for AC components */ + int ac_tbl_no; /* the table number of the single component */ + unsigned int EOBRUN; /* run length of EOBs */ + unsigned int BE; /* # of buffered correction bits before MCU */ + char * bit_buffer; /* buffer for correction bits (1 per char) */ + /* packing correction bits tightly would save some space but cost time... */ + + unsigned int restarts_to_go; /* MCUs left in this restart interval */ + int next_restart_num; /* next restart number to write (0-7) */ + + /* Pointers to derived tables (these workspaces have image lifespan). + * Since any one scan codes only DC or only AC, we only need one set + * of tables, not one for DC and one for AC. + */ + c_derived_tbl * derived_tbls[NUM_HUFF_TBLS]; + + /* Statistics tables for optimization; again, one set is enough */ + long * count_ptrs[NUM_HUFF_TBLS]; +} phuff_entropy_encoder; + +typedef phuff_entropy_encoder * phuff_entropy_ptr; + +/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit + * buffer can hold. Larger sizes may slightly improve compression, but + * 1000 is already well into the realm of overkill. + * The minimum safe size is 64 bits. + */ + +#define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */ + +/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32. + * We assume that int right shift is unsigned if INT32 right shift is, + * which should be safe. + */ + +#ifdef RIGHT_SHIFT_IS_UNSIGNED +#define ISHIFT_TEMPS int ishift_temp; +#define IRIGHT_SHIFT(x,shft) \ + ((ishift_temp = (x)) < 0 ? \ + (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \ + (ishift_temp >> (shft))) +#else +#define ISHIFT_TEMPS +#define IRIGHT_SHIFT(x,shft) ((x) >> (shft)) +#endif + +/* Forward declarations */ +METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo)); +METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo)); + + +/* + * Initialize for a Huffman-compressed scan using progressive JPEG. + */ + +METHODDEF(void) +start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + boolean is_DC_band; + int ci, tbl; + jpeg_component_info * compptr; + + entropy->cinfo = cinfo; + entropy->gather_statistics = gather_statistics; + + is_DC_band = (cinfo->Ss == 0); + + /* We assume jcmaster.c already validated the scan parameters. */ + + /* Select execution routines */ + if (cinfo->Ah == 0) { + if (is_DC_band) + entropy->pub.encode_mcu = encode_mcu_DC_first; + else + entropy->pub.encode_mcu = encode_mcu_AC_first; + } else { + if (is_DC_band) + entropy->pub.encode_mcu = encode_mcu_DC_refine; + else { + entropy->pub.encode_mcu = encode_mcu_AC_refine; + /* AC refinement needs a correction bit buffer */ + if (entropy->bit_buffer == NULL) + entropy->bit_buffer = (char *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + MAX_CORR_BITS * SIZEOF(char)); + } + } + if (gather_statistics) + entropy->pub.finish_pass = finish_pass_gather_phuff; + else + entropy->pub.finish_pass = finish_pass_phuff; + + /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1 + * for AC coefficients. + */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + /* Initialize DC predictions to 0 */ + entropy->last_dc_val[ci] = 0; + /* Get table index */ + if (is_DC_band) { + if (cinfo->Ah != 0) /* DC refinement needs no table */ + continue; + tbl = compptr->dc_tbl_no; + } else { + entropy->ac_tbl_no = tbl = compptr->ac_tbl_no; + } + if (gather_statistics) { + /* Check for invalid table index */ + /* (make_c_derived_tbl does this in the other path) */ + if (tbl < 0 || tbl >= NUM_HUFF_TBLS) + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl); + /* Allocate and zero the statistics tables */ + /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */ + if (entropy->count_ptrs[tbl] == NULL) + entropy->count_ptrs[tbl] = (long *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + 257 * SIZEOF(long)); + MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long)); + } else { + /* Compute derived values for Huffman table */ + /* We may do this more than once for a table, but it's not expensive */ + jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl, + & entropy->derived_tbls[tbl]); + } + } + + /* Initialize AC stuff */ + entropy->EOBRUN = 0; + entropy->BE = 0; + + /* Initialize bit buffer to empty */ + entropy->put_buffer = 0; + entropy->put_bits = 0; + + /* Initialize restart stuff */ + entropy->restarts_to_go = cinfo->restart_interval; + entropy->next_restart_num = 0; +} + + +/* Outputting bytes to the file. + * NB: these must be called only when actually outputting, + * that is, entropy->gather_statistics == FALSE. + */ + +/* Emit a byte */ +#define emit_byte(entropy,val) \ + { *(entropy)->next_output_byte++ = (JOCTET) (val); \ + if (--(entropy)->free_in_buffer == 0) \ + dump_buffer(entropy); } + + +LOCAL(void) +dump_buffer (phuff_entropy_ptr entropy) +/* Empty the output buffer; we do not support suspension in this module. */ +{ + struct jpeg_destination_mgr * dest = entropy->cinfo->dest; + + if (! (*dest->empty_output_buffer) (entropy->cinfo)) + ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND); + /* After a successful buffer dump, must reset buffer pointers */ + entropy->next_output_byte = dest->next_output_byte; + entropy->free_in_buffer = dest->free_in_buffer; +} + + +/* Outputting bits to the file */ + +/* Only the right 24 bits of put_buffer are used; the valid bits are + * left-justified in this part. At most 16 bits can be passed to emit_bits + * in one call, and we never retain more than 7 bits in put_buffer + * between calls, so 24 bits are sufficient. + */ + +INLINE +LOCAL(void) +emit_bits (phuff_entropy_ptr entropy, unsigned int code, int size) +/* Emit some bits, unless we are in gather mode */ +{ + /* This routine is heavily used, so it's worth coding tightly. */ + register INT32 put_buffer = (INT32) code; + register int put_bits = entropy->put_bits; + + /* if size is 0, caller used an invalid Huffman table entry */ + if (size == 0) + ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE); + + if (entropy->gather_statistics) + return; /* do nothing if we're only getting stats */ + + put_buffer &= (((INT32) 1)<put_buffer; /* and merge with old buffer contents */ + + while (put_bits >= 8) { + int c = (int) ((put_buffer >> 16) & 0xFF); + + emit_byte(entropy, c); + if (c == 0xFF) { /* need to stuff a zero byte? */ + emit_byte(entropy, 0); + } + put_buffer <<= 8; + put_bits -= 8; + } + + entropy->put_buffer = put_buffer; /* update variables */ + entropy->put_bits = put_bits; +} + + +LOCAL(void) +flush_bits (phuff_entropy_ptr entropy) +{ + emit_bits(entropy, 0x7F, 7); /* fill any partial byte with ones */ + entropy->put_buffer = 0; /* and reset bit-buffer to empty */ + entropy->put_bits = 0; +} + + +/* + * Emit (or just count) a Huffman symbol. + */ + +INLINE +LOCAL(void) +emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol) +{ + if (entropy->gather_statistics) + entropy->count_ptrs[tbl_no][symbol]++; + else { + c_derived_tbl * tbl = entropy->derived_tbls[tbl_no]; + emit_bits(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]); + } +} + + +/* + * Emit bits from a correction bit buffer. + */ + +LOCAL(void) +emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart, + unsigned int nbits) +{ + if (entropy->gather_statistics) + return; /* no real work */ + + while (nbits > 0) { + emit_bits(entropy, (unsigned int) (*bufstart), 1); + bufstart++; + nbits--; + } +} + + +/* + * Emit any pending EOBRUN symbol. + */ + +LOCAL(void) +emit_eobrun (phuff_entropy_ptr entropy) +{ + register int temp, nbits; + + if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */ + temp = entropy->EOBRUN; + nbits = 0; + while ((temp >>= 1)) + nbits++; + /* safety check: shouldn't happen given limited correction-bit buffer */ + if (nbits > 14) + ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE); + + emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4); + if (nbits) + emit_bits(entropy, entropy->EOBRUN, nbits); + + entropy->EOBRUN = 0; + + /* Emit any buffered correction bits */ + emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE); + entropy->BE = 0; + } +} + + +/* + * Emit a restart marker & resynchronize predictions. + */ + +LOCAL(void) +emit_restart (phuff_entropy_ptr entropy, int restart_num) +{ + int ci; + + emit_eobrun(entropy); + + if (! entropy->gather_statistics) { + flush_bits(entropy); + emit_byte(entropy, 0xFF); + emit_byte(entropy, JPEG_RST0 + restart_num); + } + + if (entropy->cinfo->Ss == 0) { + /* Re-initialize DC predictions to 0 */ + for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++) + entropy->last_dc_val[ci] = 0; + } else { + /* Re-initialize all AC-related fields to 0 */ + entropy->EOBRUN = 0; + entropy->BE = 0; + } +} + + +/* + * MCU encoding for DC initial scan (either spectral selection, + * or first pass of successive approximation). + */ + +METHODDEF(boolean) +encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + register int temp, temp2; + register int nbits; + int blkn, ci; + int Al = cinfo->Al; + JBLOCKROW block; + jpeg_component_info * compptr; + ISHIFT_TEMPS + + entropy->next_output_byte = cinfo->dest->next_output_byte; + entropy->free_in_buffer = cinfo->dest->free_in_buffer; + + /* Emit restart marker if needed */ + if (cinfo->restart_interval) + if (entropy->restarts_to_go == 0) + emit_restart(entropy, entropy->next_restart_num); + + /* Encode the MCU data blocks */ + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { + block = MCU_data[blkn]; + ci = cinfo->MCU_membership[blkn]; + compptr = cinfo->cur_comp_info[ci]; + + /* Compute the DC value after the required point transform by Al. + * This is simply an arithmetic right shift. + */ + temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al); + + /* DC differences are figured on the point-transformed values. */ + temp = temp2 - entropy->last_dc_val[ci]; + entropy->last_dc_val[ci] = temp2; + + /* Encode the DC coefficient difference per section G.1.2.1 */ + temp2 = temp; + if (temp < 0) { + temp = -temp; /* temp is abs value of input */ + /* For a negative input, want temp2 = bitwise complement of abs(input) */ + /* This code assumes we are on a two's complement machine */ + temp2--; + } + + /* Find the number of bits needed for the magnitude of the coefficient */ + nbits = 0; + while (temp) { + nbits++; + temp >>= 1; + } + /* Check for out-of-range coefficient values. + * Since we're encoding a difference, the range limit is twice as much. + */ + if (nbits > MAX_COEF_BITS+1) + ERREXIT(cinfo, JERR_BAD_DCT_COEF); + + /* Count/emit the Huffman-coded symbol for the number of bits */ + emit_symbol(entropy, compptr->dc_tbl_no, nbits); + + /* Emit that number of bits of the value, if positive, */ + /* or the complement of its magnitude, if negative. */ + if (nbits) /* emit_bits rejects calls with size 0 */ + emit_bits(entropy, (unsigned int) temp2, nbits); + } + + cinfo->dest->next_output_byte = entropy->next_output_byte; + cinfo->dest->free_in_buffer = entropy->free_in_buffer; + + /* Update restart-interval state too */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) { + entropy->restarts_to_go = cinfo->restart_interval; + entropy->next_restart_num++; + entropy->next_restart_num &= 7; + } + entropy->restarts_to_go--; + } + + return TRUE; +} + + +/* + * MCU encoding for AC initial scan (either spectral selection, + * or first pass of successive approximation). + */ + +METHODDEF(boolean) +encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + register int temp, temp2; + register int nbits; + register int r, k; + int Se = cinfo->Se; + int Al = cinfo->Al; + JBLOCKROW block; + + entropy->next_output_byte = cinfo->dest->next_output_byte; + entropy->free_in_buffer = cinfo->dest->free_in_buffer; + + /* Emit restart marker if needed */ + if (cinfo->restart_interval) + if (entropy->restarts_to_go == 0) + emit_restart(entropy, entropy->next_restart_num); + + /* Encode the MCU data block */ + block = MCU_data[0]; + + /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */ + + r = 0; /* r = run length of zeros */ + + for (k = cinfo->Ss; k <= Se; k++) { + if ((temp = (*block)[jpeg_natural_order[k]]) == 0) { + r++; + continue; + } + /* We must apply the point transform by Al. For AC coefficients this + * is an integer division with rounding towards 0. To do this portably + * in C, we shift after obtaining the absolute value; so the code is + * interwoven with finding the abs value (temp) and output bits (temp2). + */ + if (temp < 0) { + temp = -temp; /* temp is abs value of input */ + temp >>= Al; /* apply the point transform */ + /* For a negative coef, want temp2 = bitwise complement of abs(coef) */ + temp2 = ~temp; + } else { + temp >>= Al; /* apply the point transform */ + temp2 = temp; + } + /* Watch out for case that nonzero coef is zero after point transform */ + if (temp == 0) { + r++; + continue; + } + + /* Emit any pending EOBRUN */ + if (entropy->EOBRUN > 0) + emit_eobrun(entropy); + /* if run length > 15, must emit special run-length-16 codes (0xF0) */ + while (r > 15) { + emit_symbol(entropy, entropy->ac_tbl_no, 0xF0); + r -= 16; + } + + /* Find the number of bits needed for the magnitude of the coefficient */ + nbits = 1; /* there must be at least one 1 bit */ + while ((temp >>= 1)) + nbits++; + /* Check for out-of-range coefficient values */ + if (nbits > MAX_COEF_BITS) + ERREXIT(cinfo, JERR_BAD_DCT_COEF); + + /* Count/emit Huffman symbol for run length / number of bits */ + emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits); + + /* Emit that number of bits of the value, if positive, */ + /* or the complement of its magnitude, if negative. */ + emit_bits(entropy, (unsigned int) temp2, nbits); + + r = 0; /* reset zero run length */ + } + + if (r > 0) { /* If there are trailing zeroes, */ + entropy->EOBRUN++; /* count an EOB */ + if (entropy->EOBRUN == 0x7FFF) + emit_eobrun(entropy); /* force it out to avoid overflow */ + } + + cinfo->dest->next_output_byte = entropy->next_output_byte; + cinfo->dest->free_in_buffer = entropy->free_in_buffer; + + /* Update restart-interval state too */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) { + entropy->restarts_to_go = cinfo->restart_interval; + entropy->next_restart_num++; + entropy->next_restart_num &= 7; + } + entropy->restarts_to_go--; + } + + return TRUE; +} + + +/* + * MCU encoding for DC successive approximation refinement scan. + * Note: we assume such scans can be multi-component, although the spec + * is not very clear on the point. + */ + +METHODDEF(boolean) +encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + register int temp; + int blkn; + int Al = cinfo->Al; + JBLOCKROW block; + + entropy->next_output_byte = cinfo->dest->next_output_byte; + entropy->free_in_buffer = cinfo->dest->free_in_buffer; + + /* Emit restart marker if needed */ + if (cinfo->restart_interval) + if (entropy->restarts_to_go == 0) + emit_restart(entropy, entropy->next_restart_num); + + /* Encode the MCU data blocks */ + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { + block = MCU_data[blkn]; + + /* We simply emit the Al'th bit of the DC coefficient value. */ + temp = (*block)[0]; + emit_bits(entropy, (unsigned int) (temp >> Al), 1); + } + + cinfo->dest->next_output_byte = entropy->next_output_byte; + cinfo->dest->free_in_buffer = entropy->free_in_buffer; + + /* Update restart-interval state too */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) { + entropy->restarts_to_go = cinfo->restart_interval; + entropy->next_restart_num++; + entropy->next_restart_num &= 7; + } + entropy->restarts_to_go--; + } + + return TRUE; +} + + +/* + * MCU encoding for AC successive approximation refinement scan. + */ + +METHODDEF(boolean) +encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + register int temp; + register int r, k; + int EOB; + char *BR_buffer; + unsigned int BR; + int Se = cinfo->Se; + int Al = cinfo->Al; + JBLOCKROW block; + int absvalues[DCTSIZE2]; + + entropy->next_output_byte = cinfo->dest->next_output_byte; + entropy->free_in_buffer = cinfo->dest->free_in_buffer; + + /* Emit restart marker if needed */ + if (cinfo->restart_interval) + if (entropy->restarts_to_go == 0) + emit_restart(entropy, entropy->next_restart_num); + + /* Encode the MCU data block */ + block = MCU_data[0]; + + /* It is convenient to make a pre-pass to determine the transformed + * coefficients' absolute values and the EOB position. + */ + EOB = 0; + for (k = cinfo->Ss; k <= Se; k++) { + temp = (*block)[jpeg_natural_order[k]]; + /* We must apply the point transform by Al. For AC coefficients this + * is an integer division with rounding towards 0. To do this portably + * in C, we shift after obtaining the absolute value. + */ + if (temp < 0) + temp = -temp; /* temp is abs value of input */ + temp >>= Al; /* apply the point transform */ + absvalues[k] = temp; /* save abs value for main pass */ + if (temp == 1) + EOB = k; /* EOB = index of last newly-nonzero coef */ + } + + /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */ + + r = 0; /* r = run length of zeros */ + BR = 0; /* BR = count of buffered bits added now */ + BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */ + + for (k = cinfo->Ss; k <= Se; k++) { + if ((temp = absvalues[k]) == 0) { + r++; + continue; + } + + /* Emit any required ZRLs, but not if they can be folded into EOB */ + while (r > 15 && k <= EOB) { + /* emit any pending EOBRUN and the BE correction bits */ + emit_eobrun(entropy); + /* Emit ZRL */ + emit_symbol(entropy, entropy->ac_tbl_no, 0xF0); + r -= 16; + /* Emit buffered correction bits that must be associated with ZRL */ + emit_buffered_bits(entropy, BR_buffer, BR); + BR_buffer = entropy->bit_buffer; /* BE bits are gone now */ + BR = 0; + } + + /* If the coef was previously nonzero, it only needs a correction bit. + * NOTE: a straight translation of the spec's figure G.7 would suggest + * that we also need to test r > 15. But if r > 15, we can only get here + * if k > EOB, which implies that this coefficient is not 1. + */ + if (temp > 1) { + /* The correction bit is the next bit of the absolute value. */ + BR_buffer[BR++] = (char) (temp & 1); + continue; + } + + /* Emit any pending EOBRUN and the BE correction bits */ + emit_eobrun(entropy); + + /* Count/emit Huffman symbol for run length / number of bits */ + emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1); + + /* Emit output bit for newly-nonzero coef */ + temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1; + emit_bits(entropy, (unsigned int) temp, 1); + + /* Emit buffered correction bits that must be associated with this code */ + emit_buffered_bits(entropy, BR_buffer, BR); + BR_buffer = entropy->bit_buffer; /* BE bits are gone now */ + BR = 0; + r = 0; /* reset zero run length */ + } + + if (r > 0 || BR > 0) { /* If there are trailing zeroes, */ + entropy->EOBRUN++; /* count an EOB */ + entropy->BE += BR; /* concat my correction bits to older ones */ + /* We force out the EOB if we risk either: + * 1. overflow of the EOB counter; + * 2. overflow of the correction bit buffer during the next MCU. + */ + if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1)) + emit_eobrun(entropy); + } + + cinfo->dest->next_output_byte = entropy->next_output_byte; + cinfo->dest->free_in_buffer = entropy->free_in_buffer; + + /* Update restart-interval state too */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) { + entropy->restarts_to_go = cinfo->restart_interval; + entropy->next_restart_num++; + entropy->next_restart_num &= 7; + } + entropy->restarts_to_go--; + } + + return TRUE; +} + + +/* + * Finish up at the end of a Huffman-compressed progressive scan. + */ + +METHODDEF(void) +finish_pass_phuff (j_compress_ptr cinfo) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + + entropy->next_output_byte = cinfo->dest->next_output_byte; + entropy->free_in_buffer = cinfo->dest->free_in_buffer; + + /* Flush out any buffered data */ + emit_eobrun(entropy); + flush_bits(entropy); + + cinfo->dest->next_output_byte = entropy->next_output_byte; + cinfo->dest->free_in_buffer = entropy->free_in_buffer; +} + + +/* + * Finish up a statistics-gathering pass and create the new Huffman tables. + */ + +METHODDEF(void) +finish_pass_gather_phuff (j_compress_ptr cinfo) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + boolean is_DC_band; + int ci, tbl; + jpeg_component_info * compptr; + JHUFF_TBL **htblptr; + boolean did[NUM_HUFF_TBLS]; + + /* Flush out buffered data (all we care about is counting the EOB symbol) */ + emit_eobrun(entropy); + + is_DC_band = (cinfo->Ss == 0); + + /* It's important not to apply jpeg_gen_optimal_table more than once + * per table, because it clobbers the input frequency counts! + */ + MEMZERO(did, SIZEOF(did)); + + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + if (is_DC_band) { + if (cinfo->Ah != 0) /* DC refinement needs no table */ + continue; + tbl = compptr->dc_tbl_no; + } else { + tbl = compptr->ac_tbl_no; + } + if (! did[tbl]) { + if (is_DC_band) + htblptr = & cinfo->dc_huff_tbl_ptrs[tbl]; + else + htblptr = & cinfo->ac_huff_tbl_ptrs[tbl]; + if (*htblptr == NULL) + *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); + jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]); + did[tbl] = TRUE; + } + } +} + + +/* + * Module initialization routine for progressive Huffman entropy encoding. + */ + +GLOBAL(void) +jinit_phuff_encoder (j_compress_ptr cinfo) +{ + phuff_entropy_ptr entropy; + int i; + + entropy = (phuff_entropy_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(phuff_entropy_encoder)); + cinfo->entropy = (struct jpeg_entropy_encoder *) entropy; + entropy->pub.start_pass = start_pass_phuff; + + /* Mark tables unallocated */ + for (i = 0; i < NUM_HUFF_TBLS; i++) { + entropy->derived_tbls[i] = NULL; + entropy->count_ptrs[i] = NULL; + } + entropy->bit_buffer = NULL; /* needed only in AC refinement scan */ +} + +#endif /* C_PROGRESSIVE_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jcprepct.c b/SlnkDWFImpl/CxImage/jpeg/jcprepct.c new file mode 100644 index 0000000..fdc4bc2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcprepct.c @@ -0,0 +1,354 @@ +/* + * jcprepct.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the compression preprocessing controller. + * This controller manages the color conversion, downsampling, + * and edge expansion steps. + * + * Most of the complexity here is associated with buffering input rows + * as required by the downsampler. See the comments at the head of + * jcsample.c for the downsampler's needs. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* At present, jcsample.c can request context rows only for smoothing. + * In the future, we might also need context rows for CCIR601 sampling + * or other more-complex downsampling procedures. The code to support + * context rows should be compiled only if needed. + */ +#ifdef INPUT_SMOOTHING_SUPPORTED +#define CONTEXT_ROWS_SUPPORTED +#endif + + +/* + * For the simple (no-context-row) case, we just need to buffer one + * row group's worth of pixels for the downsampling step. At the bottom of + * the image, we pad to a full row group by replicating the last pixel row. + * The downsampler's last output row is then replicated if needed to pad + * out to a full iMCU row. + * + * When providing context rows, we must buffer three row groups' worth of + * pixels. Three row groups are physically allocated, but the row pointer + * arrays are made five row groups high, with the extra pointers above and + * below "wrapping around" to point to the last and first real row groups. + * This allows the downsampler to access the proper context rows. + * At the top and bottom of the image, we create dummy context rows by + * copying the first or last real pixel row. This copying could be avoided + * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the + * trouble on the compression side. + */ + + +/* Private buffer controller object */ + +typedef struct { + struct jpeg_c_prep_controller pub; /* public fields */ + + /* Downsampling input buffer. This buffer holds color-converted data + * until we have enough to do a downsample step. + */ + JSAMPARRAY color_buf[MAX_COMPONENTS]; + + JDIMENSION rows_to_go; /* counts rows remaining in source image */ + int next_buf_row; /* index of next row to store in color_buf */ + +#ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */ + int this_row_group; /* starting row index of group to process */ + int next_buf_stop; /* downsample when we reach this index */ +#endif +} my_prep_controller; + +typedef my_prep_controller * my_prep_ptr; + + +/* + * Initialize for a processing pass. + */ + +METHODDEF(void) +start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode) +{ + my_prep_ptr prep = (my_prep_ptr) cinfo->prep; + + if (pass_mode != JBUF_PASS_THRU) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + + /* Initialize total-height counter for detecting bottom of image */ + prep->rows_to_go = cinfo->image_height; + /* Mark the conversion buffer empty */ + prep->next_buf_row = 0; +#ifdef CONTEXT_ROWS_SUPPORTED + /* Preset additional state variables for context mode. + * These aren't used in non-context mode, so we needn't test which mode. + */ + prep->this_row_group = 0; + /* Set next_buf_stop to stop after two row groups have been read in. */ + prep->next_buf_stop = 2 * cinfo->max_v_samp_factor; +#endif +} + + +/* + * Expand an image vertically from height input_rows to height output_rows, + * by duplicating the bottom row. + */ + +LOCAL(void) +expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols, + int input_rows, int output_rows) +{ + register int row; + + for (row = input_rows; row < output_rows; row++) { + jcopy_sample_rows(image_data, input_rows-1, image_data, row, + 1, num_cols); + } +} + + +/* + * Process some data in the simple no-context case. + * + * Preprocessor output data is counted in "row groups". A row group + * is defined to be v_samp_factor sample rows of each component. + * Downsampling will produce this much data from each max_v_samp_factor + * input rows. + */ + +METHODDEF(void) +pre_process_data (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, + JDIMENSION in_rows_avail, + JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr, + JDIMENSION out_row_groups_avail) +{ + my_prep_ptr prep = (my_prep_ptr) cinfo->prep; + int numrows, ci; + JDIMENSION inrows; + jpeg_component_info * compptr; + + while (*in_row_ctr < in_rows_avail && + *out_row_group_ctr < out_row_groups_avail) { + /* Do color conversion to fill the conversion buffer. */ + inrows = in_rows_avail - *in_row_ctr; + numrows = cinfo->max_v_samp_factor - prep->next_buf_row; + numrows = (int) MIN((JDIMENSION) numrows, inrows); + (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr, + prep->color_buf, + (JDIMENSION) prep->next_buf_row, + numrows); + *in_row_ctr += numrows; + prep->next_buf_row += numrows; + prep->rows_to_go -= numrows; + /* If at bottom of image, pad to fill the conversion buffer. */ + if (prep->rows_to_go == 0 && + prep->next_buf_row < cinfo->max_v_samp_factor) { + for (ci = 0; ci < cinfo->num_components; ci++) { + expand_bottom_edge(prep->color_buf[ci], cinfo->image_width, + prep->next_buf_row, cinfo->max_v_samp_factor); + } + prep->next_buf_row = cinfo->max_v_samp_factor; + } + /* If we've filled the conversion buffer, empty it. */ + if (prep->next_buf_row == cinfo->max_v_samp_factor) { + (*cinfo->downsample->downsample) (cinfo, + prep->color_buf, (JDIMENSION) 0, + output_buf, *out_row_group_ctr); + prep->next_buf_row = 0; + (*out_row_group_ctr)++; + } + /* If at bottom of image, pad the output to a full iMCU height. + * Note we assume the caller is providing a one-iMCU-height output buffer! + */ + if (prep->rows_to_go == 0 && + *out_row_group_ctr < out_row_groups_avail) { + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + expand_bottom_edge(output_buf[ci], + compptr->width_in_blocks * DCTSIZE, + (int) (*out_row_group_ctr * compptr->v_samp_factor), + (int) (out_row_groups_avail * compptr->v_samp_factor)); + } + *out_row_group_ctr = out_row_groups_avail; + break; /* can exit outer loop without test */ + } + } +} + + +#ifdef CONTEXT_ROWS_SUPPORTED + +/* + * Process some data in the context case. + */ + +METHODDEF(void) +pre_process_context (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, + JDIMENSION in_rows_avail, + JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr, + JDIMENSION out_row_groups_avail) +{ + my_prep_ptr prep = (my_prep_ptr) cinfo->prep; + int numrows, ci; + int buf_height = cinfo->max_v_samp_factor * 3; + JDIMENSION inrows; + + while (*out_row_group_ctr < out_row_groups_avail) { + if (*in_row_ctr < in_rows_avail) { + /* Do color conversion to fill the conversion buffer. */ + inrows = in_rows_avail - *in_row_ctr; + numrows = prep->next_buf_stop - prep->next_buf_row; + numrows = (int) MIN((JDIMENSION) numrows, inrows); + (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr, + prep->color_buf, + (JDIMENSION) prep->next_buf_row, + numrows); + /* Pad at top of image, if first time through */ + if (prep->rows_to_go == cinfo->image_height) { + for (ci = 0; ci < cinfo->num_components; ci++) { + int row; + for (row = 1; row <= cinfo->max_v_samp_factor; row++) { + jcopy_sample_rows(prep->color_buf[ci], 0, + prep->color_buf[ci], -row, + 1, cinfo->image_width); + } + } + } + *in_row_ctr += numrows; + prep->next_buf_row += numrows; + prep->rows_to_go -= numrows; + } else { + /* Return for more data, unless we are at the bottom of the image. */ + if (prep->rows_to_go != 0) + break; + /* When at bottom of image, pad to fill the conversion buffer. */ + if (prep->next_buf_row < prep->next_buf_stop) { + for (ci = 0; ci < cinfo->num_components; ci++) { + expand_bottom_edge(prep->color_buf[ci], cinfo->image_width, + prep->next_buf_row, prep->next_buf_stop); + } + prep->next_buf_row = prep->next_buf_stop; + } + } + /* If we've gotten enough data, downsample a row group. */ + if (prep->next_buf_row == prep->next_buf_stop) { + (*cinfo->downsample->downsample) (cinfo, + prep->color_buf, + (JDIMENSION) prep->this_row_group, + output_buf, *out_row_group_ctr); + (*out_row_group_ctr)++; + /* Advance pointers with wraparound as necessary. */ + prep->this_row_group += cinfo->max_v_samp_factor; + if (prep->this_row_group >= buf_height) + prep->this_row_group = 0; + if (prep->next_buf_row >= buf_height) + prep->next_buf_row = 0; + prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor; + } + } +} + + +/* + * Create the wrapped-around downsampling input buffer needed for context mode. + */ + +LOCAL(void) +create_context_buffer (j_compress_ptr cinfo) +{ + my_prep_ptr prep = (my_prep_ptr) cinfo->prep; + int rgroup_height = cinfo->max_v_samp_factor; + int ci, i; + jpeg_component_info * compptr; + JSAMPARRAY true_buffer, fake_buffer; + + /* Grab enough space for fake row pointers for all the components; + * we need five row groups' worth of pointers for each component. + */ + fake_buffer = (JSAMPARRAY) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (cinfo->num_components * 5 * rgroup_height) * + SIZEOF(JSAMPROW)); + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Allocate the actual buffer space (3 row groups) for this component. + * We make the buffer wide enough to allow the downsampler to edge-expand + * horizontally within the buffer, if it so chooses. + */ + true_buffer = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE * + cinfo->max_h_samp_factor) / compptr->h_samp_factor), + (JDIMENSION) (3 * rgroup_height)); + /* Copy true buffer row pointers into the middle of the fake row array */ + MEMCOPY(fake_buffer + rgroup_height, true_buffer, + 3 * rgroup_height * SIZEOF(JSAMPROW)); + /* Fill in the above and below wraparound pointers */ + for (i = 0; i < rgroup_height; i++) { + fake_buffer[i] = true_buffer[2 * rgroup_height + i]; + fake_buffer[4 * rgroup_height + i] = true_buffer[i]; + } + prep->color_buf[ci] = fake_buffer + rgroup_height; + fake_buffer += 5 * rgroup_height; /* point to space for next component */ + } +} + +#endif /* CONTEXT_ROWS_SUPPORTED */ + + +/* + * Initialize preprocessing controller. + */ + +GLOBAL(void) +jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer) +{ + my_prep_ptr prep; + int ci; + jpeg_component_info * compptr; + + if (need_full_buffer) /* safety check */ + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + + prep = (my_prep_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_prep_controller)); + cinfo->prep = (struct jpeg_c_prep_controller *) prep; + prep->pub.start_pass = start_pass_prep; + + /* Allocate the color conversion buffer. + * We make the buffer wide enough to allow the downsampler to edge-expand + * horizontally within the buffer, if it so chooses. + */ + if (cinfo->downsample->need_context_rows) { + /* Set up to provide context rows */ +#ifdef CONTEXT_ROWS_SUPPORTED + prep->pub.pre_process_data = pre_process_context; + create_context_buffer(cinfo); +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else { + /* No context, just make it tall enough for one row group */ + prep->pub.pre_process_data = pre_process_data; + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + prep->color_buf[ci] = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE * + cinfo->max_h_samp_factor) / compptr->h_samp_factor), + (JDIMENSION) cinfo->max_v_samp_factor); + } + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jcsample.c b/SlnkDWFImpl/CxImage/jpeg/jcsample.c new file mode 100644 index 0000000..fe29fca --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jcsample.c @@ -0,0 +1,519 @@ +/* + * jcsample.c + * + * Copyright (C) 1991-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains downsampling routines. + * + * Downsampling input data is counted in "row groups". A row group + * is defined to be max_v_samp_factor pixel rows of each component, + * from which the downsampler produces v_samp_factor sample rows. + * A single row group is processed in each call to the downsampler module. + * + * The downsampler is responsible for edge-expansion of its output data + * to fill an integral number of DCT blocks horizontally. The source buffer + * may be modified if it is helpful for this purpose (the source buffer is + * allocated wide enough to correspond to the desired output width). + * The caller (the prep controller) is responsible for vertical padding. + * + * The downsampler may request "context rows" by setting need_context_rows + * during startup. In this case, the input arrays will contain at least + * one row group's worth of pixels above and below the passed-in data; + * the caller will create dummy rows at image top and bottom by replicating + * the first or last real pixel row. + * + * An excellent reference for image resampling is + * Digital Image Warping, George Wolberg, 1990. + * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7. + * + * The downsampling algorithm used here is a simple average of the source + * pixels covered by the output pixel. The hi-falutin sampling literature + * refers to this as a "box filter". In general the characteristics of a box + * filter are not very good, but for the specific cases we normally use (1:1 + * and 2:1 ratios) the box is equivalent to a "triangle filter" which is not + * nearly so bad. If you intend to use other sampling ratios, you'd be well + * advised to improve this code. + * + * A simple input-smoothing capability is provided. This is mainly intended + * for cleaning up color-dithered GIF input files (if you find it inadequate, + * we suggest using an external filtering program such as pnmconvol). When + * enabled, each input pixel P is replaced by a weighted sum of itself and its + * eight neighbors. P's weight is 1-8*SF and each neighbor's weight is SF, + * where SF = (smoothing_factor / 1024). + * Currently, smoothing is only supported for 2h2v sampling factors. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Pointer to routine to downsample a single component */ +typedef JMETHOD(void, downsample1_ptr, + (j_compress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY output_data)); + +/* Private subobject */ + +typedef struct { + struct jpeg_downsampler pub; /* public fields */ + + /* Downsampling method pointers, one per component */ + downsample1_ptr methods[MAX_COMPONENTS]; +} my_downsampler; + +typedef my_downsampler * my_downsample_ptr; + + +/* + * Initialize for a downsampling pass. + */ + +METHODDEF(void) +start_pass_downsample (j_compress_ptr cinfo) +{ + /* no work for now */ +} + + +/* + * Expand a component horizontally from width input_cols to width output_cols, + * by duplicating the rightmost samples. + */ + +LOCAL(void) +expand_right_edge (JSAMPARRAY image_data, int num_rows, + JDIMENSION input_cols, JDIMENSION output_cols) +{ + register JSAMPROW ptr; + register JSAMPLE pixval; + register int count; + int row; + int numcols = (int) (output_cols - input_cols); + + if (numcols > 0) { + for (row = 0; row < num_rows; row++) { + ptr = image_data[row] + input_cols; + pixval = ptr[-1]; /* don't need GETJSAMPLE() here */ + for (count = numcols; count > 0; count--) + *ptr++ = pixval; + } + } +} + + +/* + * Do downsampling for a whole row group (all components). + * + * In this version we simply downsample each component independently. + */ + +METHODDEF(void) +sep_downsample (j_compress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION in_row_index, + JSAMPIMAGE output_buf, JDIMENSION out_row_group_index) +{ + my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample; + int ci; + jpeg_component_info * compptr; + JSAMPARRAY in_ptr, out_ptr; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + in_ptr = input_buf[ci] + in_row_index; + out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor); + (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr); + } +} + + +/* + * Downsample pixel values of a single component. + * One row group is processed per call. + * This version handles arbitrary integral sampling ratios, without smoothing. + * Note that this version is not actually used for customary sampling ratios. + */ + +METHODDEF(void) +int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY output_data) +{ + int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v; + JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */ + JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; + JSAMPROW inptr, outptr; + INT32 outvalue; + + h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor; + v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor; + numpix = h_expand * v_expand; + numpix2 = numpix/2; + + /* Expand input data enough to let all the output samples be generated + * by the standard loop. Special-casing padded output would be more + * efficient. + */ + expand_right_edge(input_data, cinfo->max_v_samp_factor, + cinfo->image_width, output_cols * h_expand); + + inrow = 0; + for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { + outptr = output_data[outrow]; + for (outcol = 0, outcol_h = 0; outcol < output_cols; + outcol++, outcol_h += h_expand) { + outvalue = 0; + for (v = 0; v < v_expand; v++) { + inptr = input_data[inrow+v] + outcol_h; + for (h = 0; h < h_expand; h++) { + outvalue += (INT32) GETJSAMPLE(*inptr++); + } + } + *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix); + } + inrow += v_expand; + } +} + + +/* + * Downsample pixel values of a single component. + * This version handles the special case of a full-size component, + * without smoothing. + */ + +METHODDEF(void) +fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY output_data) +{ + /* Copy the data */ + jcopy_sample_rows(input_data, 0, output_data, 0, + cinfo->max_v_samp_factor, cinfo->image_width); + /* Edge-expand */ + expand_right_edge(output_data, cinfo->max_v_samp_factor, + cinfo->image_width, compptr->width_in_blocks * DCTSIZE); +} + + +/* + * Downsample pixel values of a single component. + * This version handles the common case of 2:1 horizontal and 1:1 vertical, + * without smoothing. + * + * A note about the "bias" calculations: when rounding fractional values to + * integer, we do not want to always round 0.5 up to the next integer. + * If we did that, we'd introduce a noticeable bias towards larger values. + * Instead, this code is arranged so that 0.5 will be rounded up or down at + * alternate pixel locations (a simple ordered dither pattern). + */ + +METHODDEF(void) +h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY output_data) +{ + int outrow; + JDIMENSION outcol; + JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; + register JSAMPROW inptr, outptr; + register int bias; + + /* Expand input data enough to let all the output samples be generated + * by the standard loop. Special-casing padded output would be more + * efficient. + */ + expand_right_edge(input_data, cinfo->max_v_samp_factor, + cinfo->image_width, output_cols * 2); + + for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { + outptr = output_data[outrow]; + inptr = input_data[outrow]; + bias = 0; /* bias = 0,1,0,1,... for successive samples */ + for (outcol = 0; outcol < output_cols; outcol++) { + *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1]) + + bias) >> 1); + bias ^= 1; /* 0=>1, 1=>0 */ + inptr += 2; + } + } +} + + +/* + * Downsample pixel values of a single component. + * This version handles the standard case of 2:1 horizontal and 2:1 vertical, + * without smoothing. + */ + +METHODDEF(void) +h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY output_data) +{ + int inrow, outrow; + JDIMENSION outcol; + JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; + register JSAMPROW inptr0, inptr1, outptr; + register int bias; + + /* Expand input data enough to let all the output samples be generated + * by the standard loop. Special-casing padded output would be more + * efficient. + */ + expand_right_edge(input_data, cinfo->max_v_samp_factor, + cinfo->image_width, output_cols * 2); + + inrow = 0; + for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { + outptr = output_data[outrow]; + inptr0 = input_data[inrow]; + inptr1 = input_data[inrow+1]; + bias = 1; /* bias = 1,2,1,2,... for successive samples */ + for (outcol = 0; outcol < output_cols; outcol++) { + *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]) + + bias) >> 2); + bias ^= 3; /* 1=>2, 2=>1 */ + inptr0 += 2; inptr1 += 2; + } + inrow += 2; + } +} + + +#ifdef INPUT_SMOOTHING_SUPPORTED + +/* + * Downsample pixel values of a single component. + * This version handles the standard case of 2:1 horizontal and 2:1 vertical, + * with smoothing. One row of context is required. + */ + +METHODDEF(void) +h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY output_data) +{ + int inrow, outrow; + JDIMENSION colctr; + JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; + register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr; + INT32 membersum, neighsum, memberscale, neighscale; + + /* Expand input data enough to let all the output samples be generated + * by the standard loop. Special-casing padded output would be more + * efficient. + */ + expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2, + cinfo->image_width, output_cols * 2); + + /* We don't bother to form the individual "smoothed" input pixel values; + * we can directly compute the output which is the average of the four + * smoothed values. Each of the four member pixels contributes a fraction + * (1-8*SF) to its own smoothed image and a fraction SF to each of the three + * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final + * output. The four corner-adjacent neighbor pixels contribute a fraction + * SF to just one smoothed pixel, or SF/4 to the final output; while the + * eight edge-adjacent neighbors contribute SF to each of two smoothed + * pixels, or SF/2 overall. In order to use integer arithmetic, these + * factors are scaled by 2^16 = 65536. + * Also recall that SF = smoothing_factor / 1024. + */ + + memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */ + neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */ + + inrow = 0; + for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { + outptr = output_data[outrow]; + inptr0 = input_data[inrow]; + inptr1 = input_data[inrow+1]; + above_ptr = input_data[inrow-1]; + below_ptr = input_data[inrow+2]; + + /* Special case for first column: pretend column -1 is same as column 0 */ + membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); + neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + + GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) + + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]); + neighsum += neighsum; + neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) + + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]); + membersum = membersum * memberscale + neighsum * neighscale; + *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); + inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2; + + for (colctr = output_cols - 2; colctr > 0; colctr--) { + /* sum of pixels directly mapped to this output element */ + membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); + /* sum of edge-neighbor pixels */ + neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + + GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) + + GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]); + /* The edge-neighbors count twice as much as corner-neighbors */ + neighsum += neighsum; + /* Add in the corner-neighbors */ + neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) + + GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]); + /* form final output scaled up by 2^16 */ + membersum = membersum * memberscale + neighsum * neighscale; + /* round, descale and output it */ + *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); + inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2; + } + + /* Special case for last column */ + membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); + neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + + GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) + + GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]); + neighsum += neighsum; + neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) + + GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]); + membersum = membersum * memberscale + neighsum * neighscale; + *outptr = (JSAMPLE) ((membersum + 32768) >> 16); + + inrow += 2; + } +} + + +/* + * Downsample pixel values of a single component. + * This version handles the special case of a full-size component, + * with smoothing. One row of context is required. + */ + +METHODDEF(void) +fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr, + JSAMPARRAY input_data, JSAMPARRAY output_data) +{ + int outrow; + JDIMENSION colctr; + JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; + register JSAMPROW inptr, above_ptr, below_ptr, outptr; + INT32 membersum, neighsum, memberscale, neighscale; + int colsum, lastcolsum, nextcolsum; + + /* Expand input data enough to let all the output samples be generated + * by the standard loop. Special-casing padded output would be more + * efficient. + */ + expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2, + cinfo->image_width, output_cols); + + /* Each of the eight neighbor pixels contributes a fraction SF to the + * smoothed pixel, while the main pixel contributes (1-8*SF). In order + * to use integer arithmetic, these factors are multiplied by 2^16 = 65536. + * Also recall that SF = smoothing_factor / 1024. + */ + + memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */ + neighscale = cinfo->smoothing_factor * 64; /* scaled SF */ + + for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { + outptr = output_data[outrow]; + inptr = input_data[outrow]; + above_ptr = input_data[outrow-1]; + below_ptr = input_data[outrow+1]; + + /* Special case for first column */ + colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) + + GETJSAMPLE(*inptr); + membersum = GETJSAMPLE(*inptr++); + nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) + + GETJSAMPLE(*inptr); + neighsum = colsum + (colsum - membersum) + nextcolsum; + membersum = membersum * memberscale + neighsum * neighscale; + *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); + lastcolsum = colsum; colsum = nextcolsum; + + for (colctr = output_cols - 2; colctr > 0; colctr--) { + membersum = GETJSAMPLE(*inptr++); + above_ptr++; below_ptr++; + nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) + + GETJSAMPLE(*inptr); + neighsum = lastcolsum + (colsum - membersum) + nextcolsum; + membersum = membersum * memberscale + neighsum * neighscale; + *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); + lastcolsum = colsum; colsum = nextcolsum; + } + + /* Special case for last column */ + membersum = GETJSAMPLE(*inptr); + neighsum = lastcolsum + (colsum - membersum) + colsum; + membersum = membersum * memberscale + neighsum * neighscale; + *outptr = (JSAMPLE) ((membersum + 32768) >> 16); + + } +} + +#endif /* INPUT_SMOOTHING_SUPPORTED */ + + +/* + * Module initialization routine for downsampling. + * Note that we must select a routine for each component. + */ + +GLOBAL(void) +jinit_downsampler (j_compress_ptr cinfo) +{ + my_downsample_ptr downsample; + int ci; + jpeg_component_info * compptr; + boolean smoothok = TRUE; + + downsample = (my_downsample_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_downsampler)); + cinfo->downsample = (struct jpeg_downsampler *) downsample; + downsample->pub.start_pass = start_pass_downsample; + downsample->pub.downsample = sep_downsample; + downsample->pub.need_context_rows = FALSE; + + if (cinfo->CCIR601_sampling) + ERREXIT(cinfo, JERR_CCIR601_NOTIMPL); + + /* Verify we can handle the sampling factors, and set up method pointers */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + if (compptr->h_samp_factor == cinfo->max_h_samp_factor && + compptr->v_samp_factor == cinfo->max_v_samp_factor) { +#ifdef INPUT_SMOOTHING_SUPPORTED + if (cinfo->smoothing_factor) { + downsample->methods[ci] = fullsize_smooth_downsample; + downsample->pub.need_context_rows = TRUE; + } else +#endif + downsample->methods[ci] = fullsize_downsample; + } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor && + compptr->v_samp_factor == cinfo->max_v_samp_factor) { + smoothok = FALSE; + downsample->methods[ci] = h2v1_downsample; + } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor && + compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) { +#ifdef INPUT_SMOOTHING_SUPPORTED + if (cinfo->smoothing_factor) { + downsample->methods[ci] = h2v2_smooth_downsample; + downsample->pub.need_context_rows = TRUE; + } else +#endif + downsample->methods[ci] = h2v2_downsample; + } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 && + (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) { + smoothok = FALSE; + downsample->methods[ci] = int_downsample; + } else + ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL); + } + +#ifdef INPUT_SMOOTHING_SUPPORTED + if (cinfo->smoothing_factor && !smoothok) + TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL); +#endif +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jctrans.c b/SlnkDWFImpl/CxImage/jpeg/jctrans.c new file mode 100644 index 0000000..8b36e36 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jctrans.c @@ -0,0 +1,388 @@ +/* + * jctrans.c + * + * Copyright (C) 1995-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains library routines for transcoding compression, + * that is, writing raw DCT coefficient arrays to an output JPEG file. + * The routines in jcapimin.c will also be needed by a transcoder. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Forward declarations */ +LOCAL(void) transencode_master_selection + JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)); +LOCAL(void) transencode_coef_controller + JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)); + + +/* + * Compression initialization for writing raw-coefficient data. + * Before calling this, all parameters and a data destination must be set up. + * Call jpeg_finish_compress() to actually write the data. + * + * The number of passed virtual arrays must match cinfo->num_components. + * Note that the virtual arrays need not be filled or even realized at + * the time write_coefficients is called; indeed, if the virtual arrays + * were requested from this compression object's memory manager, they + * typically will be realized during this routine and filled afterwards. + */ + +GLOBAL(void) +jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays) +{ + if (cinfo->global_state != CSTATE_START) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + /* Mark all tables to be written */ + jpeg_suppress_tables(cinfo, FALSE); + /* (Re)initialize error mgr and destination modules */ + (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo); + (*cinfo->dest->init_destination) (cinfo); + /* Perform master selection of active modules */ + transencode_master_selection(cinfo, coef_arrays); + /* Wait for jpeg_finish_compress() call */ + cinfo->next_scanline = 0; /* so jpeg_write_marker works */ + cinfo->global_state = CSTATE_WRCOEFS; +} + + +/* + * Initialize the compression object with default parameters, + * then copy from the source object all parameters needed for lossless + * transcoding. Parameters that can be varied without loss (such as + * scan script and Huffman optimization) are left in their default states. + */ + +GLOBAL(void) +jpeg_copy_critical_parameters (j_decompress_ptr srcinfo, + j_compress_ptr dstinfo) +{ + JQUANT_TBL ** qtblptr; + jpeg_component_info *incomp, *outcomp; + JQUANT_TBL *c_quant, *slot_quant; + int tblno, ci, coefi; + + /* Safety check to ensure start_compress not called yet. */ + if (dstinfo->global_state != CSTATE_START) + ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state); + /* Copy fundamental image dimensions */ + dstinfo->image_width = srcinfo->image_width; + dstinfo->image_height = srcinfo->image_height; + dstinfo->input_components = srcinfo->num_components; + dstinfo->in_color_space = srcinfo->jpeg_color_space; + /* Initialize all parameters to default values */ + jpeg_set_defaults(dstinfo); + /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB. + * Fix it to get the right header markers for the image colorspace. + */ + jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space); + dstinfo->data_precision = srcinfo->data_precision; + dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling; + /* Copy the source's quantization tables. */ + for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) { + if (srcinfo->quant_tbl_ptrs[tblno] != NULL) { + qtblptr = & dstinfo->quant_tbl_ptrs[tblno]; + if (*qtblptr == NULL) + *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo); + MEMCOPY((*qtblptr)->quantval, + srcinfo->quant_tbl_ptrs[tblno]->quantval, + SIZEOF((*qtblptr)->quantval)); + (*qtblptr)->sent_table = FALSE; + } + } + /* Copy the source's per-component info. + * Note we assume jpeg_set_defaults has allocated the dest comp_info array. + */ + dstinfo->num_components = srcinfo->num_components; + if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS) + ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components, + MAX_COMPONENTS); + for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info; + ci < dstinfo->num_components; ci++, incomp++, outcomp++) { + outcomp->component_id = incomp->component_id; + outcomp->h_samp_factor = incomp->h_samp_factor; + outcomp->v_samp_factor = incomp->v_samp_factor; + outcomp->quant_tbl_no = incomp->quant_tbl_no; + /* Make sure saved quantization table for component matches the qtable + * slot. If not, the input file re-used this qtable slot. + * IJG encoder currently cannot duplicate this. + */ + tblno = outcomp->quant_tbl_no; + if (tblno < 0 || tblno >= NUM_QUANT_TBLS || + srcinfo->quant_tbl_ptrs[tblno] == NULL) + ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno); + slot_quant = srcinfo->quant_tbl_ptrs[tblno]; + c_quant = incomp->quant_table; + if (c_quant != NULL) { + for (coefi = 0; coefi < DCTSIZE2; coefi++) { + if (c_quant->quantval[coefi] != slot_quant->quantval[coefi]) + ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno); + } + } + /* Note: we do not copy the source's Huffman table assignments; + * instead we rely on jpeg_set_colorspace to have made a suitable choice. + */ + } + /* Also copy JFIF version and resolution information, if available. + * Strictly speaking this isn't "critical" info, but it's nearly + * always appropriate to copy it if available. In particular, + * if the application chooses to copy JFIF 1.02 extension markers from + * the source file, we need to copy the version to make sure we don't + * emit a file that has 1.02 extensions but a claimed version of 1.01. + * We will *not*, however, copy version info from mislabeled "2.01" files. + */ + if (srcinfo->saw_JFIF_marker) { + if (srcinfo->JFIF_major_version == 1) { + dstinfo->JFIF_major_version = srcinfo->JFIF_major_version; + dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version; + } + dstinfo->density_unit = srcinfo->density_unit; + dstinfo->X_density = srcinfo->X_density; + dstinfo->Y_density = srcinfo->Y_density; + } +} + + +/* + * Master selection of compression modules for transcoding. + * This substitutes for jcinit.c's initialization of the full compressor. + */ + +LOCAL(void) +transencode_master_selection (j_compress_ptr cinfo, + jvirt_barray_ptr * coef_arrays) +{ + /* Although we don't actually use input_components for transcoding, + * jcmaster.c's initial_setup will complain if input_components is 0. + */ + cinfo->input_components = 1; + /* Initialize master control (includes parameter checking/processing) */ + jinit_c_master_control(cinfo, TRUE /* transcode only */); + + /* Entropy encoding: either Huffman or arithmetic coding. */ + if (cinfo->arith_code) { + ERREXIT(cinfo, JERR_ARITH_NOTIMPL); + } else { + if (cinfo->progressive_mode) { +#ifdef C_PROGRESSIVE_SUPPORTED + jinit_phuff_encoder(cinfo); +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else + jinit_huff_encoder(cinfo); + } + + /* We need a special coefficient buffer controller. */ + transencode_coef_controller(cinfo, coef_arrays); + + jinit_marker_writer(cinfo); + + /* We can now tell the memory manager to allocate virtual arrays. */ + (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); + + /* Write the datastream header (SOI, JFIF) immediately. + * Frame and scan headers are postponed till later. + * This lets application insert special markers after the SOI. + */ + (*cinfo->marker->write_file_header) (cinfo); +} + + +/* + * The rest of this file is a special implementation of the coefficient + * buffer controller. This is similar to jccoefct.c, but it handles only + * output from presupplied virtual arrays. Furthermore, we generate any + * dummy padding blocks on-the-fly rather than expecting them to be present + * in the arrays. + */ + +/* Private buffer controller object */ + +typedef struct { + struct jpeg_c_coef_controller pub; /* public fields */ + + JDIMENSION iMCU_row_num; /* iMCU row # within image */ + JDIMENSION mcu_ctr; /* counts MCUs processed in current row */ + int MCU_vert_offset; /* counts MCU rows within iMCU row */ + int MCU_rows_per_iMCU_row; /* number of such rows needed */ + + /* Virtual block array for each component. */ + jvirt_barray_ptr * whole_image; + + /* Workspace for constructing dummy blocks at right/bottom edges. */ + JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU]; +} my_coef_controller; + +typedef my_coef_controller * my_coef_ptr; + + +LOCAL(void) +start_iMCU_row (j_compress_ptr cinfo) +/* Reset within-iMCU-row counters for a new row */ +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + + /* In an interleaved scan, an MCU row is the same as an iMCU row. + * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. + * But at the bottom of the image, process only what's left. + */ + if (cinfo->comps_in_scan > 1) { + coef->MCU_rows_per_iMCU_row = 1; + } else { + if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1)) + coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; + else + coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; + } + + coef->mcu_ctr = 0; + coef->MCU_vert_offset = 0; +} + + +/* + * Initialize for a processing pass. + */ + +METHODDEF(void) +start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + + if (pass_mode != JBUF_CRANK_DEST) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + + coef->iMCU_row_num = 0; + start_iMCU_row(cinfo); +} + + +/* + * Process some data. + * We process the equivalent of one fully interleaved MCU row ("iMCU" row) + * per call, ie, v_samp_factor block rows for each component in the scan. + * The data is obtained from the virtual arrays and fed to the entropy coder. + * Returns TRUE if the iMCU row is completed, FALSE if suspended. + * + * NB: input_buf is ignored; it is likely to be a NULL pointer. + */ + +METHODDEF(boolean) +compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + JDIMENSION MCU_col_num; /* index of current MCU within row */ + JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; + JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; + int blkn, ci, xindex, yindex, yoffset, blockcnt; + JDIMENSION start_col; + JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; + JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU]; + JBLOCKROW buffer_ptr; + jpeg_component_info *compptr; + + /* Align the virtual buffers for the components used in this scan. */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + buffer[ci] = (*cinfo->mem->access_virt_barray) + ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index], + coef->iMCU_row_num * compptr->v_samp_factor, + (JDIMENSION) compptr->v_samp_factor, FALSE); + } + + /* Loop to process one whole iMCU row */ + for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; + yoffset++) { + for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row; + MCU_col_num++) { + /* Construct list of pointers to DCT blocks belonging to this MCU */ + blkn = 0; /* index of current DCT block within MCU */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + start_col = MCU_col_num * compptr->MCU_width; + blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width + : compptr->last_col_width; + for (yindex = 0; yindex < compptr->MCU_height; yindex++) { + if (coef->iMCU_row_num < last_iMCU_row || + yindex+yoffset < compptr->last_row_height) { + /* Fill in pointers to real blocks in this row */ + buffer_ptr = buffer[ci][yindex+yoffset] + start_col; + for (xindex = 0; xindex < blockcnt; xindex++) + MCU_buffer[blkn++] = buffer_ptr++; + } else { + /* At bottom of image, need a whole row of dummy blocks */ + xindex = 0; + } + /* Fill in any dummy blocks needed in this row. + * Dummy blocks are filled in the same way as in jccoefct.c: + * all zeroes in the AC entries, DC entries equal to previous + * block's DC value. The init routine has already zeroed the + * AC entries, so we need only set the DC entries correctly. + */ + for (; xindex < compptr->MCU_width; xindex++) { + MCU_buffer[blkn] = coef->dummy_buffer[blkn]; + MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0]; + blkn++; + } + } + } + /* Try to write the MCU. */ + if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) { + /* Suspension forced; update state counters and exit */ + coef->MCU_vert_offset = yoffset; + coef->mcu_ctr = MCU_col_num; + return FALSE; + } + } + /* Completed an MCU row, but perhaps not an iMCU row */ + coef->mcu_ctr = 0; + } + /* Completed the iMCU row, advance counters for next one */ + coef->iMCU_row_num++; + start_iMCU_row(cinfo); + return TRUE; +} + + +/* + * Initialize coefficient buffer controller. + * + * Each passed coefficient array must be the right size for that + * coefficient: width_in_blocks wide and height_in_blocks high, + * with unitheight at least v_samp_factor. + */ + +LOCAL(void) +transencode_coef_controller (j_compress_ptr cinfo, + jvirt_barray_ptr * coef_arrays) +{ + my_coef_ptr coef; + JBLOCKROW buffer; + int i; + + coef = (my_coef_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_coef_controller)); + cinfo->coef = (struct jpeg_c_coef_controller *) coef; + coef->pub.start_pass = start_pass_coef; + coef->pub.compress_data = compress_output; + + /* Save pointer to virtual arrays */ + coef->whole_image = coef_arrays; + + /* Allocate and pre-zero space for dummy DCT blocks. */ + buffer = (JBLOCKROW) + (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, + C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); + jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); + for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) { + coef->dummy_buffer[i] = buffer + i; + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdapimin.c b/SlnkDWFImpl/CxImage/jpeg/jdapimin.c new file mode 100644 index 0000000..6a72ad1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdapimin.c @@ -0,0 +1,395 @@ +/* + * jdapimin.c + * + * Copyright (C) 1994-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains application interface code for the decompression half + * of the JPEG library. These are the "minimum" API routines that may be + * needed in either the normal full-decompression case or the + * transcoding-only case. + * + * Most of the routines intended to be called directly by an application + * are in this file or in jdapistd.c. But also see jcomapi.c for routines + * shared by compression and decompression, and jdtrans.c for the transcoding + * case. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* + * Initialization of a JPEG decompression object. + * The error manager must already be set up (in case memory manager fails). + */ + +GLOBAL(void) +jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize) +{ + int i; + + /* Guard against version mismatches between library and caller. */ + cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */ + if ((int) version != JPEG_LIB_VERSION) + ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version); + if (structsize != SIZEOF(struct jpeg_decompress_struct)) + ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, + (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize); + + /* For debugging purposes, we zero the whole master structure. + * But the application has already set the err pointer, and may have set + * client_data, so we have to save and restore those fields. + * Note: if application hasn't set client_data, tools like Purify may + * complain here. + */ + { + struct jpeg_error_mgr * err = cinfo->err; + void * client_data = cinfo->client_data; /* ignore Purify complaint here */ + MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct)); + cinfo->err = err; + cinfo->client_data = client_data; + } + cinfo->is_decompressor = TRUE; + + /* Initialize a memory manager instance for this object */ + jinit_memory_mgr((j_common_ptr) cinfo); + + /* Zero out pointers to permanent structures. */ + cinfo->progress = NULL; + cinfo->src = NULL; + + for (i = 0; i < NUM_QUANT_TBLS; i++) + cinfo->quant_tbl_ptrs[i] = NULL; + + for (i = 0; i < NUM_HUFF_TBLS; i++) { + cinfo->dc_huff_tbl_ptrs[i] = NULL; + cinfo->ac_huff_tbl_ptrs[i] = NULL; + } + + /* Initialize marker processor so application can override methods + * for COM, APPn markers before calling jpeg_read_header. + */ + cinfo->marker_list = NULL; + jinit_marker_reader(cinfo); + + /* And initialize the overall input controller. */ + jinit_input_controller(cinfo); + + /* OK, I'm ready */ + cinfo->global_state = DSTATE_START; +} + + +/* + * Destruction of a JPEG decompression object + */ + +GLOBAL(void) +jpeg_destroy_decompress (j_decompress_ptr cinfo) +{ + jpeg_destroy((j_common_ptr) cinfo); /* use common routine */ +} + + +/* + * Abort processing of a JPEG decompression operation, + * but don't destroy the object itself. + */ + +GLOBAL(void) +jpeg_abort_decompress (j_decompress_ptr cinfo) +{ + jpeg_abort((j_common_ptr) cinfo); /* use common routine */ +} + + +/* + * Set default decompression parameters. + */ + +LOCAL(void) +default_decompress_parms (j_decompress_ptr cinfo) +{ + /* Guess the input colorspace, and set output colorspace accordingly. */ + /* (Wish JPEG committee had provided a real way to specify this...) */ + /* Note application may override our guesses. */ + switch (cinfo->num_components) { + case 1: + cinfo->jpeg_color_space = JCS_GRAYSCALE; + cinfo->out_color_space = JCS_GRAYSCALE; + break; + + case 3: + if (cinfo->saw_JFIF_marker) { + cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */ + } else if (cinfo->saw_Adobe_marker) { + switch (cinfo->Adobe_transform) { + case 0: + cinfo->jpeg_color_space = JCS_RGB; + break; + case 1: + cinfo->jpeg_color_space = JCS_YCbCr; + break; + default: + WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform); + cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ + break; + } + } else { + /* Saw no special markers, try to guess from the component IDs */ + int cid0 = cinfo->comp_info[0].component_id; + int cid1 = cinfo->comp_info[1].component_id; + int cid2 = cinfo->comp_info[2].component_id; + + if (cid0 == 1 && cid1 == 2 && cid2 == 3) + cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */ + else if (cid0 == 82 && cid1 == 71 && cid2 == 66) + cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */ + else { + TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2); + cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ + } + } + /* Always guess RGB is proper output colorspace. */ + cinfo->out_color_space = JCS_RGB; + break; + + case 4: + if (cinfo->saw_Adobe_marker) { + switch (cinfo->Adobe_transform) { + case 0: + cinfo->jpeg_color_space = JCS_CMYK; + break; + case 2: + cinfo->jpeg_color_space = JCS_YCCK; + break; + default: + WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform); + cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */ + break; + } + } else { + /* No special markers, assume straight CMYK. */ + cinfo->jpeg_color_space = JCS_CMYK; + } + cinfo->out_color_space = JCS_CMYK; + break; + + default: + cinfo->jpeg_color_space = JCS_UNKNOWN; + cinfo->out_color_space = JCS_UNKNOWN; + break; + } + + /* Set defaults for other decompression parameters. */ + cinfo->scale_num = 1; /* 1:1 scaling */ + cinfo->scale_denom = 1; + cinfo->output_gamma = 1.0; + cinfo->buffered_image = FALSE; + cinfo->raw_data_out = FALSE; + cinfo->dct_method = JDCT_DEFAULT; + cinfo->do_fancy_upsampling = TRUE; + cinfo->do_block_smoothing = TRUE; + cinfo->quantize_colors = FALSE; + /* We set these in case application only sets quantize_colors. */ + cinfo->dither_mode = JDITHER_FS; +#ifdef QUANT_2PASS_SUPPORTED + cinfo->two_pass_quantize = TRUE; +#else + cinfo->two_pass_quantize = FALSE; +#endif + cinfo->desired_number_of_colors = 256; + cinfo->colormap = NULL; + /* Initialize for no mode change in buffered-image mode. */ + cinfo->enable_1pass_quant = FALSE; + cinfo->enable_external_quant = FALSE; + cinfo->enable_2pass_quant = FALSE; +} + + +/* + * Decompression startup: read start of JPEG datastream to see what's there. + * Need only initialize JPEG object and supply a data source before calling. + * + * This routine will read as far as the first SOS marker (ie, actual start of + * compressed data), and will save all tables and parameters in the JPEG + * object. It will also initialize the decompression parameters to default + * values, and finally return JPEG_HEADER_OK. On return, the application may + * adjust the decompression parameters and then call jpeg_start_decompress. + * (Or, if the application only wanted to determine the image parameters, + * the data need not be decompressed. In that case, call jpeg_abort or + * jpeg_destroy to release any temporary space.) + * If an abbreviated (tables only) datastream is presented, the routine will + * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then + * re-use the JPEG object to read the abbreviated image datastream(s). + * It is unnecessary (but OK) to call jpeg_abort in this case. + * The JPEG_SUSPENDED return code only occurs if the data source module + * requests suspension of the decompressor. In this case the application + * should load more source data and then re-call jpeg_read_header to resume + * processing. + * If a non-suspending data source is used and require_image is TRUE, then the + * return code need not be inspected since only JPEG_HEADER_OK is possible. + * + * This routine is now just a front end to jpeg_consume_input, with some + * extra error checking. + */ + +GLOBAL(int) +jpeg_read_header (j_decompress_ptr cinfo, boolean require_image) +{ + int retcode; + + if (cinfo->global_state != DSTATE_START && + cinfo->global_state != DSTATE_INHEADER) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + retcode = jpeg_consume_input(cinfo); + + switch (retcode) { + case JPEG_REACHED_SOS: + retcode = JPEG_HEADER_OK; + break; + case JPEG_REACHED_EOI: + if (require_image) /* Complain if application wanted an image */ + ERREXIT(cinfo, JERR_NO_IMAGE); + /* Reset to start state; it would be safer to require the application to + * call jpeg_abort, but we can't change it now for compatibility reasons. + * A side effect is to free any temporary memory (there shouldn't be any). + */ + jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */ + retcode = JPEG_HEADER_TABLES_ONLY; + break; + case JPEG_SUSPENDED: + /* no work */ + break; + } + + return retcode; +} + + +/* + * Consume data in advance of what the decompressor requires. + * This can be called at any time once the decompressor object has + * been created and a data source has been set up. + * + * This routine is essentially a state machine that handles a couple + * of critical state-transition actions, namely initial setup and + * transition from header scanning to ready-for-start_decompress. + * All the actual input is done via the input controller's consume_input + * method. + */ + +GLOBAL(int) +jpeg_consume_input (j_decompress_ptr cinfo) +{ + int retcode = JPEG_SUSPENDED; + + /* NB: every possible DSTATE value should be listed in this switch */ + switch (cinfo->global_state) { + case DSTATE_START: + /* Start-of-datastream actions: reset appropriate modules */ + (*cinfo->inputctl->reset_input_controller) (cinfo); + /* Initialize application's data source module */ + (*cinfo->src->init_source) (cinfo); + cinfo->global_state = DSTATE_INHEADER; + /*FALLTHROUGH*/ + case DSTATE_INHEADER: + retcode = (*cinfo->inputctl->consume_input) (cinfo); + if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */ + /* Set up default parameters based on header data */ + default_decompress_parms(cinfo); + /* Set global state: ready for start_decompress */ + cinfo->global_state = DSTATE_READY; + } + break; + case DSTATE_READY: + /* Can't advance past first SOS until start_decompress is called */ + retcode = JPEG_REACHED_SOS; + break; + case DSTATE_PRELOAD: + case DSTATE_PRESCAN: + case DSTATE_SCANNING: + case DSTATE_RAW_OK: + case DSTATE_BUFIMAGE: + case DSTATE_BUFPOST: + case DSTATE_STOPPING: + retcode = (*cinfo->inputctl->consume_input) (cinfo); + break; + default: + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + } + return retcode; +} + + +/* + * Have we finished reading the input file? + */ + +GLOBAL(boolean) +jpeg_input_complete (j_decompress_ptr cinfo) +{ + /* Check for valid jpeg object */ + if (cinfo->global_state < DSTATE_START || + cinfo->global_state > DSTATE_STOPPING) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + return cinfo->inputctl->eoi_reached; +} + + +/* + * Is there more than one scan? + */ + +GLOBAL(boolean) +jpeg_has_multiple_scans (j_decompress_ptr cinfo) +{ + /* Only valid after jpeg_read_header completes */ + if (cinfo->global_state < DSTATE_READY || + cinfo->global_state > DSTATE_STOPPING) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + return cinfo->inputctl->has_multiple_scans; +} + + +/* + * Finish JPEG decompression. + * + * This will normally just verify the file trailer and release temp storage. + * + * Returns FALSE if suspended. The return value need be inspected only if + * a suspending data source is used. + */ + +GLOBAL(boolean) +jpeg_finish_decompress (j_decompress_ptr cinfo) +{ + if ((cinfo->global_state == DSTATE_SCANNING || + cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) { + /* Terminate final pass of non-buffered mode */ + if (cinfo->output_scanline < cinfo->output_height) + ERREXIT(cinfo, JERR_TOO_LITTLE_DATA); + (*cinfo->master->finish_output_pass) (cinfo); + cinfo->global_state = DSTATE_STOPPING; + } else if (cinfo->global_state == DSTATE_BUFIMAGE) { + /* Finishing after a buffered-image operation */ + cinfo->global_state = DSTATE_STOPPING; + } else if (cinfo->global_state != DSTATE_STOPPING) { + /* STOPPING = repeat call after a suspension, anything else is error */ + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + } + /* Read until EOI */ + while (! cinfo->inputctl->eoi_reached) { + if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED) + return FALSE; /* Suspend, come back later */ + } + /* Do final cleanup */ + (*cinfo->src->term_source) (cinfo); + /* We can use jpeg_abort to release memory and reset global_state */ + jpeg_abort((j_common_ptr) cinfo); + return TRUE; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdapistd.c b/SlnkDWFImpl/CxImage/jpeg/jdapistd.c new file mode 100644 index 0000000..f6c7fff --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdapistd.c @@ -0,0 +1,275 @@ +/* + * jdapistd.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains application interface code for the decompression half + * of the JPEG library. These are the "standard" API routines that are + * used in the normal full-decompression case. They are not used by a + * transcoding-only application. Note that if an application links in + * jpeg_start_decompress, it will end up linking in the entire decompressor. + * We thus must separate this file from jdapimin.c to avoid linking the + * whole decompression library into a transcoder. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Forward declarations */ +LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo)); + + +/* + * Decompression initialization. + * jpeg_read_header must be completed before calling this. + * + * If a multipass operating mode was selected, this will do all but the + * last pass, and thus may take a great deal of time. + * + * Returns FALSE if suspended. The return value need be inspected only if + * a suspending data source is used. + */ + +GLOBAL(boolean) +jpeg_start_decompress (j_decompress_ptr cinfo) +{ + if (cinfo->global_state == DSTATE_READY) { + /* First call: initialize master control, select active modules */ + jinit_master_decompress(cinfo); + if (cinfo->buffered_image) { + /* No more work here; expecting jpeg_start_output next */ + cinfo->global_state = DSTATE_BUFIMAGE; + return TRUE; + } + cinfo->global_state = DSTATE_PRELOAD; + } + if (cinfo->global_state == DSTATE_PRELOAD) { + /* If file has multiple scans, absorb them all into the coef buffer */ + if (cinfo->inputctl->has_multiple_scans) { +#ifdef D_MULTISCAN_FILES_SUPPORTED + for (;;) { + int retcode; + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) + (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); + /* Absorb some more input */ + retcode = (*cinfo->inputctl->consume_input) (cinfo); + if (retcode == JPEG_SUSPENDED) + return FALSE; + if (retcode == JPEG_REACHED_EOI) + break; + /* Advance progress counter if appropriate */ + if (cinfo->progress != NULL && + (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) { + if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) { + /* jdmaster underestimated number of scans; ratchet up one scan */ + cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows; + } + } + } +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif /* D_MULTISCAN_FILES_SUPPORTED */ + } + cinfo->output_scan_number = cinfo->input_scan_number; + } else if (cinfo->global_state != DSTATE_PRESCAN) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + /* Perform any dummy output passes, and set up for the final pass */ + return output_pass_setup(cinfo); +} + + +/* + * Set up for an output pass, and perform any dummy pass(es) needed. + * Common subroutine for jpeg_start_decompress and jpeg_start_output. + * Entry: global_state = DSTATE_PRESCAN only if previously suspended. + * Exit: If done, returns TRUE and sets global_state for proper output mode. + * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN. + */ + +LOCAL(boolean) +output_pass_setup (j_decompress_ptr cinfo) +{ + if (cinfo->global_state != DSTATE_PRESCAN) { + /* First call: do pass setup */ + (*cinfo->master->prepare_for_output_pass) (cinfo); + cinfo->output_scanline = 0; + cinfo->global_state = DSTATE_PRESCAN; + } + /* Loop over any required dummy passes */ + while (cinfo->master->is_dummy_pass) { +#ifdef QUANT_2PASS_SUPPORTED + /* Crank through the dummy pass */ + while (cinfo->output_scanline < cinfo->output_height) { + JDIMENSION last_scanline; + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long) cinfo->output_scanline; + cinfo->progress->pass_limit = (long) cinfo->output_height; + (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); + } + /* Process some data */ + last_scanline = cinfo->output_scanline; + (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL, + &cinfo->output_scanline, (JDIMENSION) 0); + if (cinfo->output_scanline == last_scanline) + return FALSE; /* No progress made, must suspend */ + } + /* Finish up dummy pass, and set up for another one */ + (*cinfo->master->finish_output_pass) (cinfo); + (*cinfo->master->prepare_for_output_pass) (cinfo); + cinfo->output_scanline = 0; +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif /* QUANT_2PASS_SUPPORTED */ + } + /* Ready for application to drive output pass through + * jpeg_read_scanlines or jpeg_read_raw_data. + */ + cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING; + return TRUE; +} + + +/* + * Read some scanlines of data from the JPEG decompressor. + * + * The return value will be the number of lines actually read. + * This may be less than the number requested in several cases, + * including bottom of image, data source suspension, and operating + * modes that emit multiple scanlines at a time. + * + * Note: we warn about excess calls to jpeg_read_scanlines() since + * this likely signals an application programmer error. However, + * an oversize buffer (max_lines > scanlines remaining) is not an error. + */ + +GLOBAL(JDIMENSION) +jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines, + JDIMENSION max_lines) +{ + JDIMENSION row_ctr; + + if (cinfo->global_state != DSTATE_SCANNING) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + if (cinfo->output_scanline >= cinfo->output_height) { + WARNMS(cinfo, JWRN_TOO_MUCH_DATA); + return 0; + } + + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long) cinfo->output_scanline; + cinfo->progress->pass_limit = (long) cinfo->output_height; + (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); + } + + /* Process some data */ + row_ctr = 0; + (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines); + cinfo->output_scanline += row_ctr; + return row_ctr; +} + + +/* + * Alternate entry point to read raw data. + * Processes exactly one iMCU row per call, unless suspended. + */ + +GLOBAL(JDIMENSION) +jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data, + JDIMENSION max_lines) +{ + JDIMENSION lines_per_iMCU_row; + + if (cinfo->global_state != DSTATE_RAW_OK) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + if (cinfo->output_scanline >= cinfo->output_height) { + WARNMS(cinfo, JWRN_TOO_MUCH_DATA); + return 0; + } + + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long) cinfo->output_scanline; + cinfo->progress->pass_limit = (long) cinfo->output_height; + (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); + } + + /* Verify that at least one iMCU row can be returned. */ + lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size; + if (max_lines < lines_per_iMCU_row) + ERREXIT(cinfo, JERR_BUFFER_SIZE); + + /* Decompress directly into user's buffer. */ + if (! (*cinfo->coef->decompress_data) (cinfo, data)) + return 0; /* suspension forced, can do nothing more */ + + /* OK, we processed one iMCU row. */ + cinfo->output_scanline += lines_per_iMCU_row; + return lines_per_iMCU_row; +} + + +/* Additional entry points for buffered-image mode. */ + +#ifdef D_MULTISCAN_FILES_SUPPORTED + +/* + * Initialize for an output pass in buffered-image mode. + */ + +GLOBAL(boolean) +jpeg_start_output (j_decompress_ptr cinfo, int scan_number) +{ + if (cinfo->global_state != DSTATE_BUFIMAGE && + cinfo->global_state != DSTATE_PRESCAN) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + /* Limit scan number to valid range */ + if (scan_number <= 0) + scan_number = 1; + if (cinfo->inputctl->eoi_reached && + scan_number > cinfo->input_scan_number) + scan_number = cinfo->input_scan_number; + cinfo->output_scan_number = scan_number; + /* Perform any dummy output passes, and set up for the real pass */ + return output_pass_setup(cinfo); +} + + +/* + * Finish up after an output pass in buffered-image mode. + * + * Returns FALSE if suspended. The return value need be inspected only if + * a suspending data source is used. + */ + +GLOBAL(boolean) +jpeg_finish_output (j_decompress_ptr cinfo) +{ + if ((cinfo->global_state == DSTATE_SCANNING || + cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) { + /* Terminate this pass. */ + /* We do not require the whole pass to have been completed. */ + (*cinfo->master->finish_output_pass) (cinfo); + cinfo->global_state = DSTATE_BUFPOST; + } else if (cinfo->global_state != DSTATE_BUFPOST) { + /* BUFPOST = repeat call after a suspension, anything else is error */ + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + } + /* Read markers looking for SOS or EOI */ + while (cinfo->input_scan_number <= cinfo->output_scan_number && + ! cinfo->inputctl->eoi_reached) { + if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED) + return FALSE; /* Suspend, come back later */ + } + cinfo->global_state = DSTATE_BUFIMAGE; + return TRUE; +} + +#endif /* D_MULTISCAN_FILES_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jdatadst.c b/SlnkDWFImpl/CxImage/jpeg/jdatadst.c new file mode 100644 index 0000000..2ece4e9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdatadst.c @@ -0,0 +1,151 @@ +/* + * jdatadst.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains compression data destination routines for the case of + * emitting JPEG data to a file (or any stdio stream). While these routines + * are sufficient for most applications, some will want to use a different + * destination manager. + * IMPORTANT: we assume that fwrite() will correctly transcribe an array of + * JOCTETs into 8-bit-wide elements on external storage. If char is wider + * than 8 bits on your machine, you may need to do some tweaking. + */ + +/* this is not a core library module, so it doesn't define JPEG_INTERNALS */ +#include "jinclude.h" +#include "jpeglib.h" +#include "jerror.h" + + +/* Expanded data destination object for stdio output */ + +typedef struct { + struct jpeg_destination_mgr pub; /* public fields */ + + FILE * outfile; /* target stream */ + JOCTET * buffer; /* start of buffer */ +} my_destination_mgr; + +typedef my_destination_mgr * my_dest_ptr; + +#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */ + + +/* + * Initialize destination --- called by jpeg_start_compress + * before any data is actually written. + */ + +METHODDEF(void) +init_destination (j_compress_ptr cinfo) +{ + my_dest_ptr dest = (my_dest_ptr) cinfo->dest; + + /* Allocate the output buffer --- it will be released when done with image */ + dest->buffer = (JOCTET *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + OUTPUT_BUF_SIZE * SIZEOF(JOCTET)); + + dest->pub.next_output_byte = dest->buffer; + dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; +} + + +/* + * Empty the output buffer --- called whenever buffer fills up. + * + * In typical applications, this should write the entire output buffer + * (ignoring the current state of next_output_byte & free_in_buffer), + * reset the pointer & count to the start of the buffer, and return TRUE + * indicating that the buffer has been dumped. + * + * In applications that need to be able to suspend compression due to output + * overrun, a FALSE return indicates that the buffer cannot be emptied now. + * In this situation, the compressor will return to its caller (possibly with + * an indication that it has not accepted all the supplied scanlines). The + * application should resume compression after it has made more room in the + * output buffer. Note that there are substantial restrictions on the use of + * suspension --- see the documentation. + * + * When suspending, the compressor will back up to a convenient restart point + * (typically the start of the current MCU). next_output_byte & free_in_buffer + * indicate where the restart point will be if the current call returns FALSE. + * Data beyond this point will be regenerated after resumption, so do not + * write it out when emptying the buffer externally. + */ + +METHODDEF(boolean) +empty_output_buffer (j_compress_ptr cinfo) +{ + my_dest_ptr dest = (my_dest_ptr) cinfo->dest; + + if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) != + (size_t) OUTPUT_BUF_SIZE) + ERREXIT(cinfo, JERR_FILE_WRITE); + + dest->pub.next_output_byte = dest->buffer; + dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; + + return TRUE; +} + + +/* + * Terminate destination --- called by jpeg_finish_compress + * after all data has been written. Usually needs to flush buffer. + * + * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding + * application must deal with any cleanup that should happen even + * for error exit. + */ + +METHODDEF(void) +term_destination (j_compress_ptr cinfo) +{ + my_dest_ptr dest = (my_dest_ptr) cinfo->dest; + size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; + + /* Write any data remaining in the buffer */ + if (datacount > 0) { + if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount) + ERREXIT(cinfo, JERR_FILE_WRITE); + } + fflush(dest->outfile); + /* Make sure we wrote the output file OK */ + if (ferror(dest->outfile)) + ERREXIT(cinfo, JERR_FILE_WRITE); +} + + +/* + * Prepare for output to a stdio stream. + * The caller must have already opened the stream, and is responsible + * for closing it after finishing compression. + */ + +GLOBAL(void) +jpeg_stdio_dest (j_compress_ptr cinfo, FILE * outfile) +{ + my_dest_ptr dest; + + /* The destination object is made permanent so that multiple JPEG images + * can be written to the same file without re-executing jpeg_stdio_dest. + * This makes it dangerous to use this manager and a different destination + * manager serially with the same JPEG object, because their private object + * sizes may be different. Caveat programmer. + */ + if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + cinfo->dest = (struct jpeg_destination_mgr *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + SIZEOF(my_destination_mgr)); + } + + dest = (my_dest_ptr) cinfo->dest; + dest->pub.init_destination = init_destination; + dest->pub.empty_output_buffer = empty_output_buffer; + dest->pub.term_destination = term_destination; + dest->outfile = outfile; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdatasrc.c b/SlnkDWFImpl/CxImage/jpeg/jdatasrc.c new file mode 100644 index 0000000..29b6983 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdatasrc.c @@ -0,0 +1,212 @@ +/* + * jdatasrc.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains decompression data source routines for the case of + * reading JPEG data from a file (or any stdio stream). While these routines + * are sufficient for most applications, some will want to use a different + * source manager. + * IMPORTANT: we assume that fread() will correctly transcribe an array of + * JOCTETs from 8-bit-wide elements on external storage. If char is wider + * than 8 bits on your machine, you may need to do some tweaking. + */ + +/* this is not a core library module, so it doesn't define JPEG_INTERNALS */ +#include "jinclude.h" +#include "jpeglib.h" +#include "jerror.h" + + +/* Expanded data source object for stdio input */ + +typedef struct { + struct jpeg_source_mgr pub; /* public fields */ + + FILE * infile; /* source stream */ + JOCTET * buffer; /* start of buffer */ + boolean start_of_file; /* have we gotten any data yet? */ +} my_source_mgr; + +typedef my_source_mgr * my_src_ptr; + +#define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */ + + +/* + * Initialize source --- called by jpeg_read_header + * before any data is actually read. + */ + +METHODDEF(void) +init_source (j_decompress_ptr cinfo) +{ + my_src_ptr src = (my_src_ptr) cinfo->src; + + /* We reset the empty-input-file flag for each image, + * but we don't clear the input buffer. + * This is correct behavior for reading a series of images from one source. + */ + src->start_of_file = TRUE; +} + + +/* + * Fill the input buffer --- called whenever buffer is emptied. + * + * In typical applications, this should read fresh data into the buffer + * (ignoring the current state of next_input_byte & bytes_in_buffer), + * reset the pointer & count to the start of the buffer, and return TRUE + * indicating that the buffer has been reloaded. It is not necessary to + * fill the buffer entirely, only to obtain at least one more byte. + * + * There is no such thing as an EOF return. If the end of the file has been + * reached, the routine has a choice of ERREXIT() or inserting fake data into + * the buffer. In most cases, generating a warning message and inserting a + * fake EOI marker is the best course of action --- this will allow the + * decompressor to output however much of the image is there. However, + * the resulting error message is misleading if the real problem is an empty + * input file, so we handle that case specially. + * + * In applications that need to be able to suspend compression due to input + * not being available yet, a FALSE return indicates that no more data can be + * obtained right now, but more may be forthcoming later. In this situation, + * the decompressor will return to its caller (with an indication of the + * number of scanlines it has read, if any). The application should resume + * decompression after it has loaded more data into the input buffer. Note + * that there are substantial restrictions on the use of suspension --- see + * the documentation. + * + * When suspending, the decompressor will back up to a convenient restart point + * (typically the start of the current MCU). next_input_byte & bytes_in_buffer + * indicate where the restart point will be if the current call returns FALSE. + * Data beyond this point must be rescanned after resumption, so move it to + * the front of the buffer rather than discarding it. + */ + +METHODDEF(boolean) +fill_input_buffer (j_decompress_ptr cinfo) +{ + my_src_ptr src = (my_src_ptr) cinfo->src; + size_t nbytes; + + nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE); + + if (nbytes <= 0) { + if (src->start_of_file) /* Treat empty input file as fatal error */ + ERREXIT(cinfo, JERR_INPUT_EMPTY); + WARNMS(cinfo, JWRN_JPEG_EOF); + /* Insert a fake EOI marker */ + src->buffer[0] = (JOCTET) 0xFF; + src->buffer[1] = (JOCTET) JPEG_EOI; + nbytes = 2; + } + + src->pub.next_input_byte = src->buffer; + src->pub.bytes_in_buffer = nbytes; + src->start_of_file = FALSE; + + return TRUE; +} + + +/* + * Skip data --- used to skip over a potentially large amount of + * uninteresting data (such as an APPn marker). + * + * Writers of suspendable-input applications must note that skip_input_data + * is not granted the right to give a suspension return. If the skip extends + * beyond the data currently in the buffer, the buffer can be marked empty so + * that the next read will cause a fill_input_buffer call that can suspend. + * Arranging for additional bytes to be discarded before reloading the input + * buffer is the application writer's problem. + */ + +METHODDEF(void) +skip_input_data (j_decompress_ptr cinfo, long num_bytes) +{ + my_src_ptr src = (my_src_ptr) cinfo->src; + + /* Just a dumb implementation for now. Could use fseek() except + * it doesn't work on pipes. Not clear that being smart is worth + * any trouble anyway --- large skips are infrequent. + */ + if (num_bytes > 0) { + while (num_bytes > (long) src->pub.bytes_in_buffer) { + num_bytes -= (long) src->pub.bytes_in_buffer; + (void) fill_input_buffer(cinfo); + /* note we assume that fill_input_buffer will never return FALSE, + * so suspension need not be handled. + */ + } + src->pub.next_input_byte += (size_t) num_bytes; + src->pub.bytes_in_buffer -= (size_t) num_bytes; + } +} + + +/* + * An additional method that can be provided by data source modules is the + * resync_to_restart method for error recovery in the presence of RST markers. + * For the moment, this source module just uses the default resync method + * provided by the JPEG library. That method assumes that no backtracking + * is possible. + */ + + +/* + * Terminate source --- called by jpeg_finish_decompress + * after all data has been read. Often a no-op. + * + * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding + * application must deal with any cleanup that should happen even + * for error exit. + */ + +METHODDEF(void) +term_source (j_decompress_ptr cinfo) +{ + /* no work necessary here */ +} + + +/* + * Prepare for input from a stdio stream. + * The caller must have already opened the stream, and is responsible + * for closing it after finishing decompression. + */ + +GLOBAL(void) +jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile) +{ + my_src_ptr src; + + /* The source object and input buffer are made permanent so that a series + * of JPEG images can be read from the same file by calling jpeg_stdio_src + * only before the first one. (If we discarded the buffer at the end of + * one image, we'd likely lose the start of the next one.) + * This makes it unsafe to use this manager and a different source + * manager serially with the same JPEG object. Caveat programmer. + */ + if (cinfo->src == NULL) { /* first time for this JPEG object? */ + cinfo->src = (struct jpeg_source_mgr *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + SIZEOF(my_source_mgr)); + src = (my_src_ptr) cinfo->src; + src->buffer = (JOCTET *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + INPUT_BUF_SIZE * SIZEOF(JOCTET)); + } + + src = (my_src_ptr) cinfo->src; + src->pub.init_source = init_source; + src->pub.fill_input_buffer = fill_input_buffer; + src->pub.skip_input_data = skip_input_data; + src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ + src->pub.term_source = term_source; + src->infile = infile; + src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ + src->pub.next_input_byte = NULL; /* until buffer loaded */ +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdcoefct.c b/SlnkDWFImpl/CxImage/jpeg/jdcoefct.c new file mode 100644 index 0000000..992bd10 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdcoefct.c @@ -0,0 +1,736 @@ +/* + * jdcoefct.c + * + * Copyright (C) 1994-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the coefficient buffer controller for decompression. + * This controller is the top level of the JPEG decompressor proper. + * The coefficient buffer lies between entropy decoding and inverse-DCT steps. + * + * In buffered-image mode, this controller is the interface between + * input-oriented processing and output-oriented processing. + * Also, the input side (only) is used when reading a file for transcoding. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + +/* Block smoothing is only applicable for progressive JPEG, so: */ +#ifndef D_PROGRESSIVE_SUPPORTED +#undef BLOCK_SMOOTHING_SUPPORTED +#endif + +/* Private buffer controller object */ + +typedef struct { + struct jpeg_d_coef_controller pub; /* public fields */ + + /* These variables keep track of the current location of the input side. */ + /* cinfo->input_iMCU_row is also used for this. */ + JDIMENSION MCU_ctr; /* counts MCUs processed in current row */ + int MCU_vert_offset; /* counts MCU rows within iMCU row */ + int MCU_rows_per_iMCU_row; /* number of such rows needed */ + + /* The output side's location is represented by cinfo->output_iMCU_row. */ + + /* In single-pass modes, it's sufficient to buffer just one MCU. + * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks, + * and let the entropy decoder write into that workspace each time. + * (On 80x86, the workspace is FAR even though it's not really very big; + * this is to keep the module interfaces unchanged when a large coefficient + * buffer is necessary.) + * In multi-pass modes, this array points to the current MCU's blocks + * within the virtual arrays; it is used only by the input side. + */ + JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU]; + +#ifdef D_MULTISCAN_FILES_SUPPORTED + /* In multi-pass modes, we need a virtual block array for each component. */ + jvirt_barray_ptr whole_image[MAX_COMPONENTS]; +#endif + +#ifdef BLOCK_SMOOTHING_SUPPORTED + /* When doing block smoothing, we latch coefficient Al values here */ + int * coef_bits_latch; +#define SAVED_COEFS 6 /* we save coef_bits[0..5] */ +#endif +} my_coef_controller; + +typedef my_coef_controller * my_coef_ptr; + +/* Forward declarations */ +METHODDEF(int) decompress_onepass + JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); +#ifdef D_MULTISCAN_FILES_SUPPORTED +METHODDEF(int) decompress_data + JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); +#endif +#ifdef BLOCK_SMOOTHING_SUPPORTED +LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo)); +METHODDEF(int) decompress_smooth_data + JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); +#endif + + +LOCAL(void) +start_iMCU_row (j_decompress_ptr cinfo) +/* Reset within-iMCU-row counters for a new row (input side) */ +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + + /* In an interleaved scan, an MCU row is the same as an iMCU row. + * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. + * But at the bottom of the image, process only what's left. + */ + if (cinfo->comps_in_scan > 1) { + coef->MCU_rows_per_iMCU_row = 1; + } else { + if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1)) + coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; + else + coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; + } + + coef->MCU_ctr = 0; + coef->MCU_vert_offset = 0; +} + + +/* + * Initialize for an input processing pass. + */ + +METHODDEF(void) +start_input_pass (j_decompress_ptr cinfo) +{ + cinfo->input_iMCU_row = 0; + start_iMCU_row(cinfo); +} + + +/* + * Initialize for an output processing pass. + */ + +METHODDEF(void) +start_output_pass (j_decompress_ptr cinfo) +{ +#ifdef BLOCK_SMOOTHING_SUPPORTED + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + + /* If multipass, check to see whether to use block smoothing on this pass */ + if (coef->pub.coef_arrays != NULL) { + if (cinfo->do_block_smoothing && smoothing_ok(cinfo)) + coef->pub.decompress_data = decompress_smooth_data; + else + coef->pub.decompress_data = decompress_data; + } +#endif + cinfo->output_iMCU_row = 0; +} + + +/* + * Decompress and return some data in the single-pass case. + * Always attempts to emit one fully interleaved MCU row ("iMCU" row). + * Input and output must run in lockstep since we have only a one-MCU buffer. + * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. + * + * NB: output_buf contains a plane for each component in image, + * which we index according to the component's SOF position. + */ + +METHODDEF(int) +decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + JDIMENSION MCU_col_num; /* index of current MCU within row */ + JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; + JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; + int blkn, ci, xindex, yindex, yoffset, useful_width; + JSAMPARRAY output_ptr; + JDIMENSION start_col, output_col; + jpeg_component_info *compptr; + inverse_DCT_method_ptr inverse_DCT; + + /* Loop to process as much as one whole iMCU row */ + for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; + yoffset++) { + for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col; + MCU_col_num++) { + /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */ + jzero_far((void FAR *) coef->MCU_buffer[0], + (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK))); + if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) { + /* Suspension forced; update state counters and exit */ + coef->MCU_vert_offset = yoffset; + coef->MCU_ctr = MCU_col_num; + return JPEG_SUSPENDED; + } + /* Determine where data should go in output_buf and do the IDCT thing. + * We skip dummy blocks at the right and bottom edges (but blkn gets + * incremented past them!). Note the inner loop relies on having + * allocated the MCU_buffer[] blocks sequentially. + */ + blkn = 0; /* index of current DCT block within MCU */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + /* Don't bother to IDCT an uninteresting component. */ + if (! compptr->component_needed) { + blkn += compptr->MCU_blocks; + continue; + } + inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index]; + useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width + : compptr->last_col_width; + output_ptr = output_buf[compptr->component_index] + + yoffset * compptr->DCT_scaled_size; + start_col = MCU_col_num * compptr->MCU_sample_width; + for (yindex = 0; yindex < compptr->MCU_height; yindex++) { + if (cinfo->input_iMCU_row < last_iMCU_row || + yoffset+yindex < compptr->last_row_height) { + output_col = start_col; + for (xindex = 0; xindex < useful_width; xindex++) { + (*inverse_DCT) (cinfo, compptr, + (JCOEFPTR) coef->MCU_buffer[blkn+xindex], + output_ptr, output_col); + output_col += compptr->DCT_scaled_size; + } + } + blkn += compptr->MCU_width; + output_ptr += compptr->DCT_scaled_size; + } + } + } + /* Completed an MCU row, but perhaps not an iMCU row */ + coef->MCU_ctr = 0; + } + /* Completed the iMCU row, advance counters for next one */ + cinfo->output_iMCU_row++; + if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) { + start_iMCU_row(cinfo); + return JPEG_ROW_COMPLETED; + } + /* Completed the scan */ + (*cinfo->inputctl->finish_input_pass) (cinfo); + return JPEG_SCAN_COMPLETED; +} + + +/* + * Dummy consume-input routine for single-pass operation. + */ + +METHODDEF(int) +dummy_consume_data (j_decompress_ptr cinfo) +{ + return JPEG_SUSPENDED; /* Always indicate nothing was done */ +} + + +#ifdef D_MULTISCAN_FILES_SUPPORTED + +/* + * Consume input data and store it in the full-image coefficient buffer. + * We read as much as one fully interleaved MCU row ("iMCU" row) per call, + * ie, v_samp_factor block rows for each component in the scan. + * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. + */ + +METHODDEF(int) +consume_data (j_decompress_ptr cinfo) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + JDIMENSION MCU_col_num; /* index of current MCU within row */ + int blkn, ci, xindex, yindex, yoffset; + JDIMENSION start_col; + JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; + JBLOCKROW buffer_ptr; + jpeg_component_info *compptr; + + /* Align the virtual buffers for the components used in this scan. */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + buffer[ci] = (*cinfo->mem->access_virt_barray) + ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index], + cinfo->input_iMCU_row * compptr->v_samp_factor, + (JDIMENSION) compptr->v_samp_factor, TRUE); + /* Note: entropy decoder expects buffer to be zeroed, + * but this is handled automatically by the memory manager + * because we requested a pre-zeroed array. + */ + } + + /* Loop to process one whole iMCU row */ + for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; + yoffset++) { + for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row; + MCU_col_num++) { + /* Construct list of pointers to DCT blocks belonging to this MCU */ + blkn = 0; /* index of current DCT block within MCU */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + start_col = MCU_col_num * compptr->MCU_width; + for (yindex = 0; yindex < compptr->MCU_height; yindex++) { + buffer_ptr = buffer[ci][yindex+yoffset] + start_col; + for (xindex = 0; xindex < compptr->MCU_width; xindex++) { + coef->MCU_buffer[blkn++] = buffer_ptr++; + } + } + } + /* Try to fetch the MCU. */ + if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) { + /* Suspension forced; update state counters and exit */ + coef->MCU_vert_offset = yoffset; + coef->MCU_ctr = MCU_col_num; + return JPEG_SUSPENDED; + } + } + /* Completed an MCU row, but perhaps not an iMCU row */ + coef->MCU_ctr = 0; + } + /* Completed the iMCU row, advance counters for next one */ + if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) { + start_iMCU_row(cinfo); + return JPEG_ROW_COMPLETED; + } + /* Completed the scan */ + (*cinfo->inputctl->finish_input_pass) (cinfo); + return JPEG_SCAN_COMPLETED; +} + + +/* + * Decompress and return some data in the multi-pass case. + * Always attempts to emit one fully interleaved MCU row ("iMCU" row). + * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. + * + * NB: output_buf contains a plane for each component in image. + */ + +METHODDEF(int) +decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; + JDIMENSION block_num; + int ci, block_row, block_rows; + JBLOCKARRAY buffer; + JBLOCKROW buffer_ptr; + JSAMPARRAY output_ptr; + JDIMENSION output_col; + jpeg_component_info *compptr; + inverse_DCT_method_ptr inverse_DCT; + + /* Force some input to be done if we are getting ahead of the input. */ + while (cinfo->input_scan_number < cinfo->output_scan_number || + (cinfo->input_scan_number == cinfo->output_scan_number && + cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) { + if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED) + return JPEG_SUSPENDED; + } + + /* OK, output from the virtual arrays. */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Don't bother to IDCT an uninteresting component. */ + if (! compptr->component_needed) + continue; + /* Align the virtual buffer for this component. */ + buffer = (*cinfo->mem->access_virt_barray) + ((j_common_ptr) cinfo, coef->whole_image[ci], + cinfo->output_iMCU_row * compptr->v_samp_factor, + (JDIMENSION) compptr->v_samp_factor, FALSE); + /* Count non-dummy DCT block rows in this iMCU row. */ + if (cinfo->output_iMCU_row < last_iMCU_row) + block_rows = compptr->v_samp_factor; + else { + /* NB: can't use last_row_height here; it is input-side-dependent! */ + block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); + if (block_rows == 0) block_rows = compptr->v_samp_factor; + } + inverse_DCT = cinfo->idct->inverse_DCT[ci]; + output_ptr = output_buf[ci]; + /* Loop over all DCT blocks to be processed. */ + for (block_row = 0; block_row < block_rows; block_row++) { + buffer_ptr = buffer[block_row]; + output_col = 0; + for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) { + (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr, + output_ptr, output_col); + buffer_ptr++; + output_col += compptr->DCT_scaled_size; + } + output_ptr += compptr->DCT_scaled_size; + } + } + + if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows) + return JPEG_ROW_COMPLETED; + return JPEG_SCAN_COMPLETED; +} + +#endif /* D_MULTISCAN_FILES_SUPPORTED */ + + +#ifdef BLOCK_SMOOTHING_SUPPORTED + +/* + * This code applies interblock smoothing as described by section K.8 + * of the JPEG standard: the first 5 AC coefficients are estimated from + * the DC values of a DCT block and its 8 neighboring blocks. + * We apply smoothing only for progressive JPEG decoding, and only if + * the coefficients it can estimate are not yet known to full precision. + */ + +/* Natural-order array positions of the first 5 zigzag-order coefficients */ +#define Q01_POS 1 +#define Q10_POS 8 +#define Q20_POS 16 +#define Q11_POS 9 +#define Q02_POS 2 + +/* + * Determine whether block smoothing is applicable and safe. + * We also latch the current states of the coef_bits[] entries for the + * AC coefficients; otherwise, if the input side of the decompressor + * advances into a new scan, we might think the coefficients are known + * more accurately than they really are. + */ + +LOCAL(boolean) +smoothing_ok (j_decompress_ptr cinfo) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + boolean smoothing_useful = FALSE; + int ci, coefi; + jpeg_component_info *compptr; + JQUANT_TBL * qtable; + int * coef_bits; + int * coef_bits_latch; + + if (! cinfo->progressive_mode || cinfo->coef_bits == NULL) + return FALSE; + + /* Allocate latch area if not already done */ + if (coef->coef_bits_latch == NULL) + coef->coef_bits_latch = (int *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + cinfo->num_components * + (SAVED_COEFS * SIZEOF(int))); + coef_bits_latch = coef->coef_bits_latch; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* All components' quantization values must already be latched. */ + if ((qtable = compptr->quant_table) == NULL) + return FALSE; + /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */ + if (qtable->quantval[0] == 0 || + qtable->quantval[Q01_POS] == 0 || + qtable->quantval[Q10_POS] == 0 || + qtable->quantval[Q20_POS] == 0 || + qtable->quantval[Q11_POS] == 0 || + qtable->quantval[Q02_POS] == 0) + return FALSE; + /* DC values must be at least partly known for all components. */ + coef_bits = cinfo->coef_bits[ci]; + if (coef_bits[0] < 0) + return FALSE; + /* Block smoothing is helpful if some AC coefficients remain inaccurate. */ + for (coefi = 1; coefi <= 5; coefi++) { + coef_bits_latch[coefi] = coef_bits[coefi]; + if (coef_bits[coefi] != 0) + smoothing_useful = TRUE; + } + coef_bits_latch += SAVED_COEFS; + } + + return smoothing_useful; +} + + +/* + * Variant of decompress_data for use when doing block smoothing. + */ + +METHODDEF(int) +decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) +{ + my_coef_ptr coef = (my_coef_ptr) cinfo->coef; + JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; + JDIMENSION block_num, last_block_column; + int ci, block_row, block_rows, access_rows; + JBLOCKARRAY buffer; + JBLOCKROW buffer_ptr, prev_block_row, next_block_row; + JSAMPARRAY output_ptr; + JDIMENSION output_col; + jpeg_component_info *compptr; + inverse_DCT_method_ptr inverse_DCT; + boolean first_row, last_row; + JBLOCK workspace; + int *coef_bits; + JQUANT_TBL *quanttbl; + INT32 Q00,Q01,Q02,Q10,Q11,Q20, num; + int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9; + int Al, pred; + + /* Force some input to be done if we are getting ahead of the input. */ + while (cinfo->input_scan_number <= cinfo->output_scan_number && + ! cinfo->inputctl->eoi_reached) { + if (cinfo->input_scan_number == cinfo->output_scan_number) { + /* If input is working on current scan, we ordinarily want it to + * have completed the current row. But if input scan is DC, + * we want it to keep one row ahead so that next block row's DC + * values are up to date. + */ + JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0; + if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta) + break; + } + if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED) + return JPEG_SUSPENDED; + } + + /* OK, output from the virtual arrays. */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Don't bother to IDCT an uninteresting component. */ + if (! compptr->component_needed) + continue; + /* Count non-dummy DCT block rows in this iMCU row. */ + if (cinfo->output_iMCU_row < last_iMCU_row) { + block_rows = compptr->v_samp_factor; + access_rows = block_rows * 2; /* this and next iMCU row */ + last_row = FALSE; + } else { + /* NB: can't use last_row_height here; it is input-side-dependent! */ + block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); + if (block_rows == 0) block_rows = compptr->v_samp_factor; + access_rows = block_rows; /* this iMCU row only */ + last_row = TRUE; + } + /* Align the virtual buffer for this component. */ + if (cinfo->output_iMCU_row > 0) { + access_rows += compptr->v_samp_factor; /* prior iMCU row too */ + buffer = (*cinfo->mem->access_virt_barray) + ((j_common_ptr) cinfo, coef->whole_image[ci], + (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor, + (JDIMENSION) access_rows, FALSE); + buffer += compptr->v_samp_factor; /* point to current iMCU row */ + first_row = FALSE; + } else { + buffer = (*cinfo->mem->access_virt_barray) + ((j_common_ptr) cinfo, coef->whole_image[ci], + (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE); + first_row = TRUE; + } + /* Fetch component-dependent info */ + coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS); + quanttbl = compptr->quant_table; + Q00 = quanttbl->quantval[0]; + Q01 = quanttbl->quantval[Q01_POS]; + Q10 = quanttbl->quantval[Q10_POS]; + Q20 = quanttbl->quantval[Q20_POS]; + Q11 = quanttbl->quantval[Q11_POS]; + Q02 = quanttbl->quantval[Q02_POS]; + inverse_DCT = cinfo->idct->inverse_DCT[ci]; + output_ptr = output_buf[ci]; + /* Loop over all DCT blocks to be processed. */ + for (block_row = 0; block_row < block_rows; block_row++) { + buffer_ptr = buffer[block_row]; + if (first_row && block_row == 0) + prev_block_row = buffer_ptr; + else + prev_block_row = buffer[block_row-1]; + if (last_row && block_row == block_rows-1) + next_block_row = buffer_ptr; + else + next_block_row = buffer[block_row+1]; + /* We fetch the surrounding DC values using a sliding-register approach. + * Initialize all nine here so as to do the right thing on narrow pics. + */ + DC1 = DC2 = DC3 = (int) prev_block_row[0][0]; + DC4 = DC5 = DC6 = (int) buffer_ptr[0][0]; + DC7 = DC8 = DC9 = (int) next_block_row[0][0]; + output_col = 0; + last_block_column = compptr->width_in_blocks - 1; + for (block_num = 0; block_num <= last_block_column; block_num++) { + /* Fetch current DCT block into workspace so we can modify it. */ + jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1); + /* Update DC values */ + if (block_num < last_block_column) { + DC3 = (int) prev_block_row[1][0]; + DC6 = (int) buffer_ptr[1][0]; + DC9 = (int) next_block_row[1][0]; + } + /* Compute coefficient estimates per K.8. + * An estimate is applied only if coefficient is still zero, + * and is not known to be fully accurate. + */ + /* AC01 */ + if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) { + num = 36 * Q00 * (DC4 - DC6); + if (num >= 0) { + pred = (int) (((Q01<<7) + num) / (Q01<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (int) (((Q10<<7) + num) / (Q10<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (int) (((Q20<<7) + num) / (Q20<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (int) (((Q11<<7) + num) / (Q11<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (int) (((Q02<<7) + num) / (Q02<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<DCT_scaled_size; + } + output_ptr += compptr->DCT_scaled_size; + } + } + + if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows) + return JPEG_ROW_COMPLETED; + return JPEG_SCAN_COMPLETED; +} + +#endif /* BLOCK_SMOOTHING_SUPPORTED */ + + +/* + * Initialize coefficient buffer controller. + */ + +GLOBAL(void) +jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer) +{ + my_coef_ptr coef; + + coef = (my_coef_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_coef_controller)); + cinfo->coef = (struct jpeg_d_coef_controller *) coef; + coef->pub.start_input_pass = start_input_pass; + coef->pub.start_output_pass = start_output_pass; +#ifdef BLOCK_SMOOTHING_SUPPORTED + coef->coef_bits_latch = NULL; +#endif + + /* Create the coefficient buffer. */ + if (need_full_buffer) { +#ifdef D_MULTISCAN_FILES_SUPPORTED + /* Allocate a full-image virtual array for each component, */ + /* padded to a multiple of samp_factor DCT blocks in each direction. */ + /* Note we ask for a pre-zeroed array. */ + int ci, access_rows; + jpeg_component_info *compptr; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + access_rows = compptr->v_samp_factor; +#ifdef BLOCK_SMOOTHING_SUPPORTED + /* If block smoothing could be used, need a bigger window */ + if (cinfo->progressive_mode) + access_rows *= 3; +#endif + coef->whole_image[ci] = (*cinfo->mem->request_virt_barray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE, + (JDIMENSION) jround_up((long) compptr->width_in_blocks, + (long) compptr->h_samp_factor), + (JDIMENSION) jround_up((long) compptr->height_in_blocks, + (long) compptr->v_samp_factor), + (JDIMENSION) access_rows); + } + coef->pub.consume_data = consume_data; + coef->pub.decompress_data = decompress_data; + coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */ +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else { + /* We only need a single-MCU buffer. */ + JBLOCKROW buffer; + int i; + + buffer = (JBLOCKROW) + (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, + D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); + for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) { + coef->MCU_buffer[i] = buffer + i; + } + coef->pub.consume_data = dummy_consume_data; + coef->pub.decompress_data = decompress_onepass; + coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */ + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdcolor.c b/SlnkDWFImpl/CxImage/jpeg/jdcolor.c new file mode 100644 index 0000000..8bf581d --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdcolor.c @@ -0,0 +1,396 @@ +/* + * jdcolor.c + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains output colorspace conversion routines. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Private subobject */ + +typedef struct { + struct jpeg_color_deconverter pub; /* public fields */ + + /* Private state for YCC->RGB conversion */ + int * Cr_r_tab; /* => table for Cr to R conversion */ + int * Cb_b_tab; /* => table for Cb to B conversion */ + INT32 * Cr_g_tab; /* => table for Cr to G conversion */ + INT32 * Cb_g_tab; /* => table for Cb to G conversion */ +} my_color_deconverter; + +typedef my_color_deconverter * my_cconvert_ptr; + + +/**************** YCbCr -> RGB conversion: most common case **************/ + +/* + * YCbCr is defined per CCIR 601-1, except that Cb and Cr are + * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5. + * The conversion equations to be implemented are therefore + * R = Y + 1.40200 * Cr + * G = Y - 0.34414 * Cb - 0.71414 * Cr + * B = Y + 1.77200 * Cb + * where Cb and Cr represent the incoming values less CENTERJSAMPLE. + * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.) + * + * To avoid floating-point arithmetic, we represent the fractional constants + * as integers scaled up by 2^16 (about 4 digits precision); we have to divide + * the products by 2^16, with appropriate rounding, to get the correct answer. + * Notice that Y, being an integral input, does not contribute any fraction + * so it need not participate in the rounding. + * + * For even more speed, we avoid doing any multiplications in the inner loop + * by precalculating the constants times Cb and Cr for all possible values. + * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table); + * for 12-bit samples it is still acceptable. It's not very reasonable for + * 16-bit samples, but if you want lossless storage you shouldn't be changing + * colorspace anyway. + * The Cr=>R and Cb=>B values can be rounded to integers in advance; the + * values for the G calculation are left scaled up, since we must add them + * together before rounding. + */ + +#define SCALEBITS 16 /* speediest right-shift on some machines */ +#define ONE_HALF ((INT32) 1 << (SCALEBITS-1)) +#define FIX(x) ((INT32) ((x) * (1L<RGB colorspace conversion. + */ + +LOCAL(void) +build_ycc_rgb_table (j_decompress_ptr cinfo) +{ + my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; + int i; + INT32 x; + SHIFT_TEMPS + + cconvert->Cr_r_tab = (int *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (MAXJSAMPLE+1) * SIZEOF(int)); + cconvert->Cb_b_tab = (int *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (MAXJSAMPLE+1) * SIZEOF(int)); + cconvert->Cr_g_tab = (INT32 *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (MAXJSAMPLE+1) * SIZEOF(INT32)); + cconvert->Cb_g_tab = (INT32 *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (MAXJSAMPLE+1) * SIZEOF(INT32)); + + for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) { + /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ + /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ + /* Cr=>R value is nearest int to 1.40200 * x */ + cconvert->Cr_r_tab[i] = (int) + RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS); + /* Cb=>B value is nearest int to 1.77200 * x */ + cconvert->Cb_b_tab[i] = (int) + RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS); + /* Cr=>G value is scaled-up -0.71414 * x */ + cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x; + /* Cb=>G value is scaled-up -0.34414 * x */ + /* We also add in ONE_HALF so that need not do it in inner loop */ + cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF; + } +} + + +/* + * Convert some rows of samples to the output colorspace. + * + * Note that we change from noninterleaved, one-plane-per-component format + * to interleaved-pixel format. The output buffer is therefore three times + * as wide as the input buffer. + * A starting row offset is provided only for the input buffer. The caller + * can easily adjust the passed output_buf value to accommodate any row + * offset required on that side. + */ + +METHODDEF(void) +ycc_rgb_convert (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION input_row, + JSAMPARRAY output_buf, int num_rows) +{ + my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; + register int y, cb, cr; + register JSAMPROW outptr; + register JSAMPROW inptr0, inptr1, inptr2; + register JDIMENSION col; + JDIMENSION num_cols = cinfo->output_width; + /* copy these pointers into registers if possible */ + register JSAMPLE * range_limit = cinfo->sample_range_limit; + register int * Crrtab = cconvert->Cr_r_tab; + register int * Cbbtab = cconvert->Cb_b_tab; + register INT32 * Crgtab = cconvert->Cr_g_tab; + register INT32 * Cbgtab = cconvert->Cb_g_tab; + SHIFT_TEMPS + + while (--num_rows >= 0) { + inptr0 = input_buf[0][input_row]; + inptr1 = input_buf[1][input_row]; + inptr2 = input_buf[2][input_row]; + input_row++; + outptr = *output_buf++; + for (col = 0; col < num_cols; col++) { + y = GETJSAMPLE(inptr0[col]); + cb = GETJSAMPLE(inptr1[col]); + cr = GETJSAMPLE(inptr2[col]); + /* Range-limiting is essential due to noise introduced by DCT losses. */ + outptr[RGB_RED] = range_limit[y + Crrtab[cr]]; + outptr[RGB_GREEN] = range_limit[y + + ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], + SCALEBITS))]; + outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]]; + outptr += RGB_PIXELSIZE; + } + } +} + + +/**************** Cases other than YCbCr -> RGB **************/ + + +/* + * Color conversion for no colorspace change: just copy the data, + * converting from separate-planes to interleaved representation. + */ + +METHODDEF(void) +null_convert (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION input_row, + JSAMPARRAY output_buf, int num_rows) +{ + register JSAMPROW inptr, outptr; + register JDIMENSION count; + register int num_components = cinfo->num_components; + JDIMENSION num_cols = cinfo->output_width; + int ci; + + while (--num_rows >= 0) { + for (ci = 0; ci < num_components; ci++) { + inptr = input_buf[ci][input_row]; + outptr = output_buf[0] + ci; + for (count = num_cols; count > 0; count--) { + *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */ + outptr += num_components; + } + } + input_row++; + output_buf++; + } +} + + +/* + * Color conversion for grayscale: just copy the data. + * This also works for YCbCr -> grayscale conversion, in which + * we just copy the Y (luminance) component and ignore chrominance. + */ + +METHODDEF(void) +grayscale_convert (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION input_row, + JSAMPARRAY output_buf, int num_rows) +{ + jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0, + num_rows, cinfo->output_width); +} + + +/* + * Convert grayscale to RGB: just duplicate the graylevel three times. + * This is provided to support applications that don't want to cope + * with grayscale as a separate case. + */ + +METHODDEF(void) +gray_rgb_convert (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION input_row, + JSAMPARRAY output_buf, int num_rows) +{ + register JSAMPROW inptr, outptr; + register JDIMENSION col; + JDIMENSION num_cols = cinfo->output_width; + + while (--num_rows >= 0) { + inptr = input_buf[0][input_row++]; + outptr = *output_buf++; + for (col = 0; col < num_cols; col++) { + /* We can dispense with GETJSAMPLE() here */ + outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col]; + outptr += RGB_PIXELSIZE; + } + } +} + + +/* + * Adobe-style YCCK->CMYK conversion. + * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same + * conversion as above, while passing K (black) unchanged. + * We assume build_ycc_rgb_table has been called. + */ + +METHODDEF(void) +ycck_cmyk_convert (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION input_row, + JSAMPARRAY output_buf, int num_rows) +{ + my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; + register int y, cb, cr; + register JSAMPROW outptr; + register JSAMPROW inptr0, inptr1, inptr2, inptr3; + register JDIMENSION col; + JDIMENSION num_cols = cinfo->output_width; + /* copy these pointers into registers if possible */ + register JSAMPLE * range_limit = cinfo->sample_range_limit; + register int * Crrtab = cconvert->Cr_r_tab; + register int * Cbbtab = cconvert->Cb_b_tab; + register INT32 * Crgtab = cconvert->Cr_g_tab; + register INT32 * Cbgtab = cconvert->Cb_g_tab; + SHIFT_TEMPS + + while (--num_rows >= 0) { + inptr0 = input_buf[0][input_row]; + inptr1 = input_buf[1][input_row]; + inptr2 = input_buf[2][input_row]; + inptr3 = input_buf[3][input_row]; + input_row++; + outptr = *output_buf++; + for (col = 0; col < num_cols; col++) { + y = GETJSAMPLE(inptr0[col]); + cb = GETJSAMPLE(inptr1[col]); + cr = GETJSAMPLE(inptr2[col]); + /* Range-limiting is essential due to noise introduced by DCT losses. */ + outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */ + outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */ + ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], + SCALEBITS)))]; + outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */ + /* K passes through unchanged */ + outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */ + outptr += 4; + } + } +} + + +/* + * Empty method for start_pass. + */ + +METHODDEF(void) +start_pass_dcolor (j_decompress_ptr cinfo) +{ + /* no work needed */ +} + + +/* + * Module initialization routine for output colorspace conversion. + */ + +GLOBAL(void) +jinit_color_deconverter (j_decompress_ptr cinfo) +{ + my_cconvert_ptr cconvert; + int ci; + + cconvert = (my_cconvert_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_color_deconverter)); + cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert; + cconvert->pub.start_pass = start_pass_dcolor; + + /* Make sure num_components agrees with jpeg_color_space */ + switch (cinfo->jpeg_color_space) { + case JCS_GRAYSCALE: + if (cinfo->num_components != 1) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + break; + + case JCS_RGB: + case JCS_YCbCr: + if (cinfo->num_components != 3) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + break; + + case JCS_CMYK: + case JCS_YCCK: + if (cinfo->num_components != 4) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + break; + + default: /* JCS_UNKNOWN can be anything */ + if (cinfo->num_components < 1) + ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); + break; + } + + /* Set out_color_components and conversion method based on requested space. + * Also clear the component_needed flags for any unused components, + * so that earlier pipeline stages can avoid useless computation. + */ + + switch (cinfo->out_color_space) { + case JCS_GRAYSCALE: + cinfo->out_color_components = 1; + if (cinfo->jpeg_color_space == JCS_GRAYSCALE || + cinfo->jpeg_color_space == JCS_YCbCr) { + cconvert->pub.color_convert = grayscale_convert; + /* For color->grayscale conversion, only the Y (0) component is needed */ + for (ci = 1; ci < cinfo->num_components; ci++) + cinfo->comp_info[ci].component_needed = FALSE; + } else + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + + case JCS_RGB: + cinfo->out_color_components = RGB_PIXELSIZE; + if (cinfo->jpeg_color_space == JCS_YCbCr) { + cconvert->pub.color_convert = ycc_rgb_convert; + build_ycc_rgb_table(cinfo); + } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) { + cconvert->pub.color_convert = gray_rgb_convert; + } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) { + cconvert->pub.color_convert = null_convert; + } else + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + + case JCS_CMYK: + cinfo->out_color_components = 4; + if (cinfo->jpeg_color_space == JCS_YCCK) { + cconvert->pub.color_convert = ycck_cmyk_convert; + build_ycc_rgb_table(cinfo); + } else if (cinfo->jpeg_color_space == JCS_CMYK) { + cconvert->pub.color_convert = null_convert; + } else + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + + default: + /* Permit null conversion to same output space */ + if ((cinfo->out_color_space == cinfo->jpeg_color_space)||(cinfo->out_color_space = cinfo->jpeg_color_space)) { + cinfo->out_color_components = cinfo->num_components; + cconvert->pub.color_convert = null_convert; + } else /* unsupported non-null conversion */ + ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); + break; + } + + if (cinfo->quantize_colors) + cinfo->output_components = 1; /* single colormapped output component */ + else + cinfo->output_components = cinfo->out_color_components; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdct.h b/SlnkDWFImpl/CxImage/jpeg/jdct.h new file mode 100644 index 0000000..b664cab --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdct.h @@ -0,0 +1,176 @@ +/* + * jdct.h + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This include file contains common declarations for the forward and + * inverse DCT modules. These declarations are private to the DCT managers + * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms. + * The individual DCT algorithms are kept in separate files to ease + * machine-dependent tuning (e.g., assembly coding). + */ + + +/* + * A forward DCT routine is given a pointer to a work area of type DCTELEM[]; + * the DCT is to be performed in-place in that buffer. Type DCTELEM is int + * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT + * implementations use an array of type FAST_FLOAT, instead.) + * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE). + * The DCT outputs are returned scaled up by a factor of 8; they therefore + * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This + * convention improves accuracy in integer implementations and saves some + * work in floating-point ones. + * Quantization of the output coefficients is done by jcdctmgr.c. + */ + +#if BITS_IN_JSAMPLE == 8 +typedef int DCTELEM; /* 16 or 32 bits is fine */ +#else +typedef INT32 DCTELEM; /* must have 32 bits */ +#endif + +typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data)); +typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data)); + + +/* + * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer + * to an output sample array. The routine must dequantize the input data as + * well as perform the IDCT; for dequantization, it uses the multiplier table + * pointed to by compptr->dct_table. The output data is to be placed into the + * sample array starting at a specified column. (Any row offset needed will + * be applied to the array pointer before it is passed to the IDCT code.) + * Note that the number of samples emitted by the IDCT routine is + * DCT_scaled_size * DCT_scaled_size. + */ + +/* typedef inverse_DCT_method_ptr is declared in jpegint.h */ + +/* + * Each IDCT routine has its own ideas about the best dct_table element type. + */ + +typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */ +#if BITS_IN_JSAMPLE == 8 +typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */ +#define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */ +#else +typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */ +#define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */ +#endif +typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */ + + +/* + * Each IDCT routine is responsible for range-limiting its results and + * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could + * be quite far out of range if the input data is corrupt, so a bulletproof + * range-limiting step is required. We use a mask-and-table-lookup method + * to do the combined operations quickly. See the comments with + * prepare_range_limit_table (in jdmaster.c) for more info. + */ + +#define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE) + +#define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */ + + +/* Short forms of external names for systems with brain-damaged linkers. */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jpeg_fdct_islow jFDislow +#define jpeg_fdct_ifast jFDifast +#define jpeg_fdct_float jFDfloat +#define jpeg_idct_islow jRDislow +#define jpeg_idct_ifast jRDifast +#define jpeg_idct_float jRDfloat +#define jpeg_idct_4x4 jRD4x4 +#define jpeg_idct_2x2 jRD2x2 +#define jpeg_idct_1x1 jRD1x1 +#endif /* NEED_SHORT_EXTERNAL_NAMES */ + +/* Extern declarations for the forward and inverse DCT routines. */ + +EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data)); +EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data)); +EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data)); + +EXTERN(void) jpeg_idct_islow + JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); +EXTERN(void) jpeg_idct_ifast + JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); +EXTERN(void) jpeg_idct_float + JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); +EXTERN(void) jpeg_idct_4x4 + JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); +EXTERN(void) jpeg_idct_2x2 + JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); +EXTERN(void) jpeg_idct_1x1 + JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); + + +/* + * Macros for handling fixed-point arithmetic; these are used by many + * but not all of the DCT/IDCT modules. + * + * All values are expected to be of type INT32. + * Fractional constants are scaled left by CONST_BITS bits. + * CONST_BITS is defined within each module using these macros, + * and may differ from one module to the next. + */ + +#define ONE ((INT32) 1) +#define CONST_SCALE (ONE << CONST_BITS) + +/* Convert a positive real constant to an integer scaled by CONST_SCALE. + * Caution: some C compilers fail to reduce "FIX(constant)" at compile time, + * thus causing a lot of useless floating-point operations at run time. + */ + +#define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5)) + +/* Descale and correctly round an INT32 value that's scaled by N bits. + * We assume RIGHT_SHIFT rounds towards minus infinity, so adding + * the fudge factor is correct for either sign of X. + */ + +#define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n) + +/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. + * This macro is used only when the two inputs will actually be no more than + * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a + * full 32x32 multiply. This provides a useful speedup on many machines. + * Unfortunately there is no way to specify a 16x16->32 multiply portably + * in C, but some C compilers will do the right thing if you provide the + * correct combination of casts. + */ + +#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */ +#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const))) +#endif +#ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */ +#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const))) +#endif + +#ifndef MULTIPLY16C16 /* default definition */ +#define MULTIPLY16C16(var,const) ((var) * (const)) +#endif + +/* Same except both inputs are variables. */ + +#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */ +#define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2))) +#endif + +#ifndef MULTIPLY16V16 /* default definition */ +#define MULTIPLY16V16(var1,var2) ((var1) * (var2)) +#endif diff --git a/SlnkDWFImpl/CxImage/jpeg/jddctmgr.c b/SlnkDWFImpl/CxImage/jpeg/jddctmgr.c new file mode 100644 index 0000000..0e44eb1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jddctmgr.c @@ -0,0 +1,269 @@ +/* + * jddctmgr.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the inverse-DCT management logic. + * This code selects a particular IDCT implementation to be used, + * and it performs related housekeeping chores. No code in this file + * is executed per IDCT step, only during output pass setup. + * + * Note that the IDCT routines are responsible for performing coefficient + * dequantization as well as the IDCT proper. This module sets up the + * dequantization multiplier table needed by the IDCT routine. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + + +/* + * The decompressor input side (jdinput.c) saves away the appropriate + * quantization table for each component at the start of the first scan + * involving that component. (This is necessary in order to correctly + * decode files that reuse Q-table slots.) + * When we are ready to make an output pass, the saved Q-table is converted + * to a multiplier table that will actually be used by the IDCT routine. + * The multiplier table contents are IDCT-method-dependent. To support + * application changes in IDCT method between scans, we can remake the + * multiplier tables if necessary. + * In buffered-image mode, the first output pass may occur before any data + * has been seen for some components, and thus before their Q-tables have + * been saved away. To handle this case, multiplier tables are preset + * to zeroes; the result of the IDCT will be a neutral gray level. + */ + + +/* Private subobject for this module */ + +typedef struct { + struct jpeg_inverse_dct pub; /* public fields */ + + /* This array contains the IDCT method code that each multiplier table + * is currently set up for, or -1 if it's not yet set up. + * The actual multiplier tables are pointed to by dct_table in the + * per-component comp_info structures. + */ + int cur_method[MAX_COMPONENTS]; +} my_idct_controller; + +typedef my_idct_controller * my_idct_ptr; + + +/* Allocated multiplier tables: big enough for any supported variant */ + +typedef union { + ISLOW_MULT_TYPE islow_array[DCTSIZE2]; +#ifdef DCT_IFAST_SUPPORTED + IFAST_MULT_TYPE ifast_array[DCTSIZE2]; +#endif +#ifdef DCT_FLOAT_SUPPORTED + FLOAT_MULT_TYPE float_array[DCTSIZE2]; +#endif +} multiplier_table; + + +/* The current scaled-IDCT routines require ISLOW-style multiplier tables, + * so be sure to compile that code if either ISLOW or SCALING is requested. + */ +#ifdef DCT_ISLOW_SUPPORTED +#define PROVIDE_ISLOW_TABLES +#else +#ifdef IDCT_SCALING_SUPPORTED +#define PROVIDE_ISLOW_TABLES +#endif +#endif + + +/* + * Prepare for an output pass. + * Here we select the proper IDCT routine for each component and build + * a matching multiplier table. + */ + +METHODDEF(void) +start_pass (j_decompress_ptr cinfo) +{ + my_idct_ptr idct = (my_idct_ptr) cinfo->idct; + int ci, i; + jpeg_component_info *compptr; + int method = 0; + inverse_DCT_method_ptr method_ptr = NULL; + JQUANT_TBL * qtbl; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Select the proper IDCT routine for this component's scaling */ + switch (compptr->DCT_scaled_size) { +#ifdef IDCT_SCALING_SUPPORTED + case 1: + method_ptr = jpeg_idct_1x1; + method = JDCT_ISLOW; /* jidctred uses islow-style table */ + break; + case 2: + method_ptr = jpeg_idct_2x2; + method = JDCT_ISLOW; /* jidctred uses islow-style table */ + break; + case 4: + method_ptr = jpeg_idct_4x4; + method = JDCT_ISLOW; /* jidctred uses islow-style table */ + break; +#endif + case DCTSIZE: + switch (cinfo->dct_method) { +#ifdef DCT_ISLOW_SUPPORTED + case JDCT_ISLOW: + method_ptr = jpeg_idct_islow; + method = JDCT_ISLOW; + break; +#endif +#ifdef DCT_IFAST_SUPPORTED + case JDCT_IFAST: + method_ptr = jpeg_idct_ifast; + method = JDCT_IFAST; + break; +#endif +#ifdef DCT_FLOAT_SUPPORTED + case JDCT_FLOAT: + method_ptr = jpeg_idct_float; + method = JDCT_FLOAT; + break; +#endif + default: + ERREXIT(cinfo, JERR_NOT_COMPILED); + break; + } + break; + default: + ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size); + break; + } + idct->pub.inverse_DCT[ci] = method_ptr; + /* Create multiplier table from quant table. + * However, we can skip this if the component is uninteresting + * or if we already built the table. Also, if no quant table + * has yet been saved for the component, we leave the + * multiplier table all-zero; we'll be reading zeroes from the + * coefficient controller's buffer anyway. + */ + if (! compptr->component_needed || idct->cur_method[ci] == method) + continue; + qtbl = compptr->quant_table; + if (qtbl == NULL) /* happens if no data yet for component */ + continue; + idct->cur_method[ci] = method; + switch (method) { +#ifdef PROVIDE_ISLOW_TABLES + case JDCT_ISLOW: + { + /* For LL&M IDCT method, multipliers are equal to raw quantization + * coefficients, but are stored as ints to ensure access efficiency. + */ + ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table; + for (i = 0; i < DCTSIZE2; i++) { + ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i]; + } + } + break; +#endif +#ifdef DCT_IFAST_SUPPORTED + case JDCT_IFAST: + { + /* For AA&N IDCT method, multipliers are equal to quantization + * coefficients scaled by scalefactor[row]*scalefactor[col], where + * scalefactor[0] = 1 + * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 + * For integer operation, the multiplier table is to be scaled by + * IFAST_SCALE_BITS. + */ + IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table; +#define CONST_BITS 14 + static const INT16 aanscales[DCTSIZE2] = { + /* precomputed values scaled up by 14 bits */ + 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, + 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270, + 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, + 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315, + 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, + 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552, + 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, + 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247 + }; + SHIFT_TEMPS + + for (i = 0; i < DCTSIZE2; i++) { + ifmtbl[i] = (IFAST_MULT_TYPE) + DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i], + (INT32) aanscales[i]), + CONST_BITS-IFAST_SCALE_BITS); + } + } + break; +#endif +#ifdef DCT_FLOAT_SUPPORTED + case JDCT_FLOAT: + { + /* For float AA&N IDCT method, multipliers are equal to quantization + * coefficients scaled by scalefactor[row]*scalefactor[col], where + * scalefactor[0] = 1 + * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 + */ + FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table; + int row, col; + static const double aanscalefactor[DCTSIZE] = { + 1.0, 1.387039845, 1.306562965, 1.175875602, + 1.0, 0.785694958, 0.541196100, 0.275899379 + }; + + i = 0; + for (row = 0; row < DCTSIZE; row++) { + for (col = 0; col < DCTSIZE; col++) { + fmtbl[i] = (FLOAT_MULT_TYPE) + ((double) qtbl->quantval[i] * + aanscalefactor[row] * aanscalefactor[col]); + i++; + } + } + } + break; +#endif + default: + ERREXIT(cinfo, JERR_NOT_COMPILED); + break; + } + } +} + + +/* + * Initialize IDCT manager. + */ + +GLOBAL(void) +jinit_inverse_dct (j_decompress_ptr cinfo) +{ + my_idct_ptr idct; + int ci; + jpeg_component_info *compptr; + + idct = (my_idct_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_idct_controller)); + cinfo->idct = (struct jpeg_inverse_dct *) idct; + idct->pub.start_pass = start_pass; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Allocate and pre-zero a multiplier table for each component */ + compptr->dct_table = + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(multiplier_table)); + MEMZERO(compptr->dct_table, SIZEOF(multiplier_table)); + /* Mark multiplier table not yet set up for any method */ + idct->cur_method[ci] = -1; + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdhuff.c b/SlnkDWFImpl/CxImage/jpeg/jdhuff.c new file mode 100644 index 0000000..6adc377 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdhuff.c @@ -0,0 +1,683 @@ +/* + * jdhuff.c + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains Huffman entropy decoding routines. + * + * Much of the complexity here has to do with supporting input suspension. + * If the data source module demands suspension, we want to be able to back + * up to the start of the current MCU. To do this, we copy state variables + * into local working storage, and update them back to the permanent + * storage only upon successful completion of an MCU. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdhuff.h" /* Declarations shared with jdphuff.c */ + + +/* + * Expanded entropy decoder object for Huffman decoding. + * + * The savable_state subrecord contains fields that change within an MCU, + * but must not be updated permanently until we complete the MCU. + */ + +typedef struct { + int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ +} savable_state; + +/* This macro is to work around compilers with missing or broken + * structure assignment. You'll need to fix this code if you have + * such a compiler and you change MAX_COMPS_IN_SCAN. + */ + +#ifndef NO_STRUCT_ASSIGN +#define ASSIGN_STATE(dest,src) ((dest) = (src)) +#else +#if MAX_COMPS_IN_SCAN == 4 +#define ASSIGN_STATE(dest,src) \ + ((dest).last_dc_val[0] = (src).last_dc_val[0], \ + (dest).last_dc_val[1] = (src).last_dc_val[1], \ + (dest).last_dc_val[2] = (src).last_dc_val[2], \ + (dest).last_dc_val[3] = (src).last_dc_val[3]) +#endif +#endif + + +typedef struct { + struct jpeg_entropy_decoder pub; /* public fields */ + + /* These fields are loaded into local variables at start of each MCU. + * In case of suspension, we exit WITHOUT updating them. + */ + bitread_perm_state bitstate; /* Bit buffer at start of MCU */ + savable_state saved; /* Other state at start of MCU */ + + /* These fields are NOT loaded into local working state. */ + unsigned int restarts_to_go; /* MCUs left in this restart interval */ + + /* Pointers to derived tables (these workspaces have image lifespan) */ + d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS]; + d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS]; + + /* Precalculated info set up by start_pass for use in decode_mcu: */ + + /* Pointers to derived tables to be used for each block within an MCU */ + d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU]; + d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU]; + /* Whether we care about the DC and AC coefficient values for each block */ + boolean dc_needed[D_MAX_BLOCKS_IN_MCU]; + boolean ac_needed[D_MAX_BLOCKS_IN_MCU]; +} huff_entropy_decoder; + +typedef huff_entropy_decoder * huff_entropy_ptr; + + +/* + * Initialize for a Huffman-compressed scan. + */ + +METHODDEF(void) +start_pass_huff_decoder (j_decompress_ptr cinfo) +{ + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; + int ci, blkn, dctbl, actbl; + jpeg_component_info * compptr; + + /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG. + * This ought to be an error condition, but we make it a warning because + * there are some baseline files out there with all zeroes in these bytes. + */ + if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 || + cinfo->Ah != 0 || cinfo->Al != 0) + WARNMS(cinfo, JWRN_NOT_SEQUENTIAL); + + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + dctbl = compptr->dc_tbl_no; + actbl = compptr->ac_tbl_no; + /* Compute derived values for Huffman tables */ + /* We may do this more than once for a table, but it's not expensive */ + jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl, + & entropy->dc_derived_tbls[dctbl]); + jpeg_make_d_derived_tbl(cinfo, FALSE, actbl, + & entropy->ac_derived_tbls[actbl]); + /* Initialize DC predictions to 0 */ + entropy->saved.last_dc_val[ci] = 0; + } + + /* Precalculate decoding info for each block in an MCU of this scan */ + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { + ci = cinfo->MCU_membership[blkn]; + compptr = cinfo->cur_comp_info[ci]; + /* Precalculate which table to use for each block */ + entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no]; + entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no]; + /* Decide whether we really care about the coefficient values */ + if (compptr->component_needed) { + entropy->dc_needed[blkn] = TRUE; + /* we don't need the ACs if producing a 1/8th-size image */ + entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1); + } else { + entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE; + } + } + + /* Initialize bitread state variables */ + entropy->bitstate.bits_left = 0; + entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ + entropy->pub.insufficient_data = FALSE; + + /* Initialize restart counter */ + entropy->restarts_to_go = cinfo->restart_interval; +} + + +/* + * Compute the derived values for a Huffman table. + * This routine also performs some validation checks on the table. + * + * Note this is also used by jdphuff.c. + */ + +GLOBAL(void) +jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno, + d_derived_tbl ** pdtbl) +{ + JHUFF_TBL *htbl; + d_derived_tbl *dtbl; + int p, i, l, si, numsymbols; + int lookbits, ctr; + char huffsize[257]; + unsigned int huffcode[257]; + unsigned int code; + + /* Note that huffsize[] and huffcode[] are filled in code-length order, + * paralleling the order of the symbols themselves in htbl->huffval[]. + */ + + /* Find the input Huffman table */ + if (tblno < 0 || tblno >= NUM_HUFF_TBLS) + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); + htbl = + isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno]; + if (htbl == NULL) + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); + + /* Allocate a workspace if we haven't already done so. */ + if (*pdtbl == NULL) + *pdtbl = (d_derived_tbl *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(d_derived_tbl)); + dtbl = *pdtbl; + dtbl->pub = htbl; /* fill in back link */ + + /* Figure C.1: make table of Huffman code length for each symbol */ + + p = 0; + for (l = 1; l <= 16; l++) { + i = (int) htbl->bits[l]; + if (i < 0 || p + i > 256) /* protect against table overrun */ + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + while (i--) + huffsize[p++] = (char) l; + } + huffsize[p] = 0; + numsymbols = p; + + /* Figure C.2: generate the codes themselves */ + /* We also validate that the counts represent a legal Huffman code tree. */ + + code = 0; + si = huffsize[0]; + p = 0; + while (huffsize[p]) { + while (((int) huffsize[p]) == si) { + huffcode[p++] = code; + code++; + } + /* code is now 1 more than the last code used for codelength si; but + * it must still fit in si bits, since no code is allowed to be all ones. + */ + if (((INT32) code) >= (((INT32) 1) << si)) + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + code <<= 1; + si++; + } + + /* Figure F.15: generate decoding tables for bit-sequential decoding */ + + p = 0; + for (l = 1; l <= 16; l++) { + if (htbl->bits[l]) { + /* valoffset[l] = huffval[] index of 1st symbol of code length l, + * minus the minimum code of length l + */ + dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p]; + p += htbl->bits[l]; + dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */ + } else { + dtbl->maxcode[l] = -1; /* -1 if no codes of this length */ + } + } + dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */ + + /* Compute lookahead tables to speed up decoding. + * First we set all the table entries to 0, indicating "too long"; + * then we iterate through the Huffman codes that are short enough and + * fill in all the entries that correspond to bit sequences starting + * with that code. + */ + + MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits)); + + p = 0; + for (l = 1; l <= HUFF_LOOKAHEAD; l++) { + for (i = 1; i <= (int) htbl->bits[l]; i++, p++) { + /* l = current code's length, p = its index in huffcode[] & huffval[]. */ + /* Generate left-justified code followed by all possible bit sequences */ + lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l); + for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) { + dtbl->look_nbits[lookbits] = l; + dtbl->look_sym[lookbits] = htbl->huffval[p]; + lookbits++; + } + } + } + + /* Validate symbols as being reasonable. + * For AC tables, we make no check, but accept all byte values 0..255. + * For DC tables, we require the symbols to be in range 0..15. + * (Tighter bounds could be applied depending on the data depth and mode, + * but this is sufficient to ensure safe decoding.) + */ + if (isDC) { + for (i = 0; i < numsymbols; i++) { + int sym = htbl->huffval[i]; + if (sym < 0 || sym > 15) + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + } + } +} + + +/* + * Out-of-line code for bit fetching (shared with jdphuff.c). + * See jdhuff.h for info about usage. + * Note: current values of get_buffer and bits_left are passed as parameters, + * but are returned in the corresponding fields of the state struct. + * + * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width + * of get_buffer to be used. (On machines with wider words, an even larger + * buffer could be used.) However, on some machines 32-bit shifts are + * quite slow and take time proportional to the number of places shifted. + * (This is true with most PC compilers, for instance.) In this case it may + * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the + * average shift distance at the cost of more calls to jpeg_fill_bit_buffer. + */ + +#ifdef SLOW_SHIFT_32 +#define MIN_GET_BITS 15 /* minimum allowable value */ +#else +#define MIN_GET_BITS (BIT_BUF_SIZE-7) +#endif + + +GLOBAL(boolean) +jpeg_fill_bit_buffer (bitread_working_state * state, + register bit_buf_type get_buffer, register int bits_left, + int nbits) +/* Load up the bit buffer to a depth of at least nbits */ +{ + /* Copy heavily used state fields into locals (hopefully registers) */ + register const JOCTET * next_input_byte = state->next_input_byte; + register size_t bytes_in_buffer = state->bytes_in_buffer; + j_decompress_ptr cinfo = state->cinfo; + + /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */ + /* (It is assumed that no request will be for more than that many bits.) */ + /* We fail to do so only if we hit a marker or are forced to suspend. */ + + if (cinfo->unread_marker == 0) { /* cannot advance past a marker */ + while (bits_left < MIN_GET_BITS) { + register int c; + + /* Attempt to read a byte */ + if (bytes_in_buffer == 0) { + if (! (*cinfo->src->fill_input_buffer) (cinfo)) + return FALSE; + next_input_byte = cinfo->src->next_input_byte; + bytes_in_buffer = cinfo->src->bytes_in_buffer; + } + bytes_in_buffer--; + c = GETJOCTET(*next_input_byte++); + + /* If it's 0xFF, check and discard stuffed zero byte */ + if (c == 0xFF) { + /* Loop here to discard any padding FF's on terminating marker, + * so that we can save a valid unread_marker value. NOTE: we will + * accept multiple FF's followed by a 0 as meaning a single FF data + * byte. This data pattern is not valid according to the standard. + */ + do { + if (bytes_in_buffer == 0) { + if (! (*cinfo->src->fill_input_buffer) (cinfo)) + return FALSE; + next_input_byte = cinfo->src->next_input_byte; + bytes_in_buffer = cinfo->src->bytes_in_buffer; + } + bytes_in_buffer--; + c = GETJOCTET(*next_input_byte++); + } while (c == 0xFF); + + if (c == 0) { + /* Found FF/00, which represents an FF data byte */ + c = 0xFF; + } else { + /* Oops, it's actually a marker indicating end of compressed data. + * Save the marker code for later use. + * Fine point: it might appear that we should save the marker into + * bitread working state, not straight into permanent state. But + * once we have hit a marker, we cannot need to suspend within the + * current MCU, because we will read no more bytes from the data + * source. So it is OK to update permanent state right away. + */ + cinfo->unread_marker = c; + /* See if we need to insert some fake zero bits. */ + goto no_more_bytes; + } + } + + /* OK, load c into get_buffer */ + get_buffer = (get_buffer << 8) | c; + bits_left += 8; + } /* end while */ + } else { + no_more_bytes: + /* We get here if we've read the marker that terminates the compressed + * data segment. There should be enough bits in the buffer register + * to satisfy the request; if so, no problem. + */ + if (nbits > bits_left) { + /* Uh-oh. Report corrupted data to user and stuff zeroes into + * the data stream, so that we can produce some kind of image. + * We use a nonvolatile flag to ensure that only one warning message + * appears per data segment. + */ + if (! cinfo->entropy->insufficient_data) { + WARNMS(cinfo, JWRN_HIT_MARKER); + cinfo->entropy->insufficient_data = TRUE; + } + /* Fill the buffer with zero bits */ + get_buffer <<= MIN_GET_BITS - bits_left; + bits_left = MIN_GET_BITS; + } + } + + /* Unload the local registers */ + state->next_input_byte = next_input_byte; + state->bytes_in_buffer = bytes_in_buffer; + state->get_buffer = get_buffer; + state->bits_left = bits_left; + + return TRUE; +} + + +/* + * Out-of-line code for Huffman code decoding. + * See jdhuff.h for info about usage. + */ + +GLOBAL(int) +jpeg_huff_decode (bitread_working_state * state, + register bit_buf_type get_buffer, register int bits_left, + d_derived_tbl * htbl, int min_bits) +{ + register int l = min_bits; + register INT32 code; + + /* HUFF_DECODE has determined that the code is at least min_bits */ + /* bits long, so fetch that many bits in one swoop. */ + + CHECK_BIT_BUFFER(*state, l, return -1); + code = GET_BITS(l); + + /* Collect the rest of the Huffman code one bit at a time. */ + /* This is per Figure F.16 in the JPEG spec. */ + + while (code > htbl->maxcode[l]) { + code <<= 1; + CHECK_BIT_BUFFER(*state, 1, return -1); + code |= GET_BITS(1); + l++; + } + + /* Unload the local registers */ + state->get_buffer = get_buffer; + state->bits_left = bits_left; + + /* With garbage input we may reach the sentinel value l = 17. */ + + if (l > 16) { + WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE); + return 0; /* fake a zero as the safest result */ + } + + return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ]; +} + + +/* + * Figure F.12: extend sign bit. + * On some machines, a shift and add will be faster than a table lookup. + */ + +#ifdef AVOID_TABLES + +#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x)) + +#else + +#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x)) + +static const int extend_test[16] = /* entry n is 2**(n-1) */ + { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, + 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 }; + +static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */ + { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1, + ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1, + ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1, + ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 }; + +#endif /* AVOID_TABLES */ + + +/* + * Check for a restart marker & resynchronize decoder. + * Returns FALSE if must suspend. + */ + +LOCAL(boolean) +process_restart (j_decompress_ptr cinfo) +{ + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; + int ci; + + /* Throw away any unused bits remaining in bit buffer; */ + /* include any full bytes in next_marker's count of discarded bytes */ + cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8; + entropy->bitstate.bits_left = 0; + + /* Advance past the RSTn marker */ + if (! (*cinfo->marker->read_restart_marker) (cinfo)) + return FALSE; + + /* Re-initialize DC predictions to 0 */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) + entropy->saved.last_dc_val[ci] = 0; + + /* Reset restart counter */ + entropy->restarts_to_go = cinfo->restart_interval; + + /* Reset out-of-data flag, unless read_restart_marker left us smack up + * against a marker. In that case we will end up treating the next data + * segment as empty, and we can avoid producing bogus output pixels by + * leaving the flag set. + */ + if (cinfo->unread_marker == 0) + entropy->pub.insufficient_data = FALSE; + + return TRUE; +} + + +/* + * Decode and return one MCU's worth of Huffman-compressed coefficients. + * The coefficients are reordered from zigzag order into natural array order, + * but are not dequantized. + * + * The i'th block of the MCU is stored into the block pointed to by + * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER. + * (Wholesale zeroing is usually a little faster than retail...) + * + * Returns FALSE if data source requested suspension. In that case no + * changes have been made to permanent state. (Exception: some output + * coefficients may already have been assigned. This is harmless for + * this module, since we'll just re-assign them on the next call.) + */ + +METHODDEF(boolean) +decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) +{ + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; + int blkn; + BITREAD_STATE_VARS; + savable_state state; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) + if (! process_restart(cinfo)) + return FALSE; + } + + /* If we've run out of data, just leave the MCU set to zeroes. + * This way, we return uniform gray for the remainder of the segment. + */ + if (! entropy->pub.insufficient_data) { + + /* Load up working state */ + BITREAD_LOAD_STATE(cinfo,entropy->bitstate); + ASSIGN_STATE(state, entropy->saved); + + /* Outer loop handles each block in the MCU */ + + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { + JBLOCKROW block = MCU_data[blkn]; + d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn]; + d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn]; + register int s, k, r; + + /* Decode a single block's worth of coefficients */ + + /* Section F.2.2.1: decode the DC coefficient difference */ + HUFF_DECODE(s, br_state, dctbl, return FALSE, label1); + if (s) { + CHECK_BIT_BUFFER(br_state, s, return FALSE); + r = GET_BITS(s); + s = HUFF_EXTEND(r, s); + } + + if (entropy->dc_needed[blkn]) { + /* Convert DC difference to actual value, update last_dc_val */ + int ci = cinfo->MCU_membership[blkn]; + s += state.last_dc_val[ci]; + state.last_dc_val[ci] = s; + /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */ + (*block)[0] = (JCOEF) s; + } + + if (entropy->ac_needed[blkn]) { + + /* Section F.2.2.2: decode the AC coefficients */ + /* Since zeroes are skipped, output area must be cleared beforehand */ + for (k = 1; k < DCTSIZE2; k++) { + HUFF_DECODE(s, br_state, actbl, return FALSE, label2); + + r = s >> 4; + s &= 15; + + if (s) { + k += r; + CHECK_BIT_BUFFER(br_state, s, return FALSE); + r = GET_BITS(s); + s = HUFF_EXTEND(r, s); + /* Output coefficient in natural (dezigzagged) order. + * Note: the extra entries in jpeg_natural_order[] will save us + * if k >= DCTSIZE2, which could happen if the data is corrupted. + */ + (*block)[jpeg_natural_order[k]] = (JCOEF) s; + } else { + if (r != 15) + break; + k += 15; + } + } + + } else { + + /* Section F.2.2.2: decode the AC coefficients */ + /* In this path we just discard the values */ + for (k = 1; k < DCTSIZE2; k++) { + HUFF_DECODE(s, br_state, actbl, return FALSE, label3); + + r = s >> 4; + s &= 15; + + if (s) { + k += r; + CHECK_BIT_BUFFER(br_state, s, return FALSE); + DROP_BITS(s); + } else { + if (r != 15) + break; + k += 15; + } + } + + } + } + + /* Completed MCU, so update state */ + BITREAD_SAVE_STATE(cinfo,entropy->bitstate); + ASSIGN_STATE(entropy->saved, state); + } + + /* Account for restart interval (no-op if not using restarts) */ + entropy->restarts_to_go--; + + return TRUE; +} + + +/* + * Module initialization routine for Huffman entropy decoding. + */ + +GLOBAL(void) +jinit_huff_decoder (j_decompress_ptr cinfo) +{ + huff_entropy_ptr entropy; + int i; + + entropy = (huff_entropy_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(huff_entropy_decoder)); + cinfo->entropy = (struct jpeg_entropy_decoder *) entropy; + entropy->pub.start_pass = start_pass_huff_decoder; + entropy->pub.decode_mcu = decode_mcu; + + /* Mark tables unallocated */ + for (i = 0; i < NUM_HUFF_TBLS; i++) { + entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL; + } +} +/* + * BEWARE OF KLUDGE: This subroutine is a hack for decoding illegal JPEG-in- + * TIFF encapsulations produced by Microsoft's Wang Imaging + * for Windows application with the public-domain TIFF Library. Based upon an + * examination of selected output files, this program apparently divides a JPEG + * bit-stream into consecutive horizontal TIFF "strips", such that the JPEG + * encoder's/decoder's DC coefficients for each image component are reset before + * each "strip". Moreover, a "strip" is not necessarily encoded in a multiple + * of 8 bits, so one must sometimes discard 1-7 bits at the end of each "strip" + * for alignment to the next input-Byte storage boundary. IJG JPEG Library + * decoder state is not normally exposed to client applications, so this sub- + * routine provides the TIFF Library with a "hook" to make these corrections. + * It should be called after "jpeg_start_decompress()" and before + * "jpeg_finish_decompress()", just before decoding each "strip" using + * "jpeg_read_raw_data()" or "jpeg_read_scanlines()". + * + * This kludge is not sanctioned or supported by the Independent JPEG Group, and + * future changes to the IJG JPEG Library might invalidate it. Do not send bug + * reports about this code to IJG developers. Instead, contact the author for + * advice: Scott B. Marovich , Hewlett-Packard Labs, 6/01. + */ +GLOBAL(void) +jpeg_reset_huff_decode (register j_decompress_ptr cinfo,register float *refbw) +{ register huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy; + register int ci = 0; + + /* Re-initialize DC predictions */ + do entropy->saved.last_dc_val[ci] = (int)-refbw[ci << 1]; + while (++ci < cinfo->comps_in_scan); + /* Discard encoded input bits, up to the next Byte boundary */ + entropy->bitstate.bits_left &= ~7; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdhuff.h b/SlnkDWFImpl/CxImage/jpeg/jdhuff.h new file mode 100644 index 0000000..12c0747 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdhuff.h @@ -0,0 +1,201 @@ +/* + * jdhuff.h + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains declarations for Huffman entropy decoding routines + * that are shared between the sequential decoder (jdhuff.c) and the + * progressive decoder (jdphuff.c). No other modules need to see these. + */ + +/* Short forms of external names for systems with brain-damaged linkers. */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jpeg_make_d_derived_tbl jMkDDerived +#define jpeg_fill_bit_buffer jFilBitBuf +#define jpeg_huff_decode jHufDecode +#endif /* NEED_SHORT_EXTERNAL_NAMES */ + + +/* Derived data constructed for each Huffman table */ + +#define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */ + +typedef struct { + /* Basic tables: (element [0] of each array is unused) */ + INT32 maxcode[18]; /* largest code of length k (-1 if none) */ + /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */ + INT32 valoffset[17]; /* huffval[] offset for codes of length k */ + /* valoffset[k] = huffval[] index of 1st symbol of code length k, less + * the smallest code of length k; so given a code of length k, the + * corresponding symbol is huffval[code + valoffset[k]] + */ + + /* Link to public Huffman table (needed only in jpeg_huff_decode) */ + JHUFF_TBL *pub; + + /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of + * the input data stream. If the next Huffman code is no more + * than HUFF_LOOKAHEAD bits long, we can obtain its length and + * the corresponding symbol directly from these tables. + */ + int look_nbits[1< 32 bits on your machine, and shifting/masking longs is + * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE + * appropriately should be a win. Unfortunately we can't define the size + * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8) + * because not all machines measure sizeof in 8-bit bytes. + */ + +typedef struct { /* Bitreading state saved across MCUs */ + bit_buf_type get_buffer; /* current bit-extraction buffer */ + int bits_left; /* # of unused bits in it */ +} bitread_perm_state; + +typedef struct { /* Bitreading working state within an MCU */ + /* Current data source location */ + /* We need a copy, rather than munging the original, in case of suspension */ + const JOCTET * next_input_byte; /* => next byte to read from source */ + size_t bytes_in_buffer; /* # of bytes remaining in source buffer */ + /* Bit input buffer --- note these values are kept in register variables, + * not in this struct, inside the inner loops. + */ + bit_buf_type get_buffer; /* current bit-extraction buffer */ + int bits_left; /* # of unused bits in it */ + /* Pointer needed by jpeg_fill_bit_buffer. */ + j_decompress_ptr cinfo; /* back link to decompress master record */ +} bitread_working_state; + +/* Macros to declare and load/save bitread local variables. */ +#define BITREAD_STATE_VARS \ + register bit_buf_type get_buffer; \ + register int bits_left; \ + bitread_working_state br_state + +#define BITREAD_LOAD_STATE(cinfop,permstate) \ + br_state.cinfo = cinfop; \ + br_state.next_input_byte = cinfop->src->next_input_byte; \ + br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \ + get_buffer = permstate.get_buffer; \ + bits_left = permstate.bits_left; + +#define BITREAD_SAVE_STATE(cinfop,permstate) \ + cinfop->src->next_input_byte = br_state.next_input_byte; \ + cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \ + permstate.get_buffer = get_buffer; \ + permstate.bits_left = bits_left + +/* + * These macros provide the in-line portion of bit fetching. + * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer + * before using GET_BITS, PEEK_BITS, or DROP_BITS. + * The variables get_buffer and bits_left are assumed to be locals, + * but the state struct might not be (jpeg_huff_decode needs this). + * CHECK_BIT_BUFFER(state,n,action); + * Ensure there are N bits in get_buffer; if suspend, take action. + * val = GET_BITS(n); + * Fetch next N bits. + * val = PEEK_BITS(n); + * Fetch next N bits without removing them from the buffer. + * DROP_BITS(n); + * Discard next N bits. + * The value N should be a simple variable, not an expression, because it + * is evaluated multiple times. + */ + +#define CHECK_BIT_BUFFER(state,nbits,action) \ + { if (bits_left < (nbits)) { \ + if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \ + { action; } \ + get_buffer = (state).get_buffer; bits_left = (state).bits_left; } } + +#define GET_BITS(nbits) \ + (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1)) + +#define PEEK_BITS(nbits) \ + (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1)) + +#define DROP_BITS(nbits) \ + (bits_left -= (nbits)) + +/* Load up the bit buffer to a depth of at least nbits */ +EXTERN(boolean) jpeg_fill_bit_buffer + JPP((bitread_working_state * state, register bit_buf_type get_buffer, + register int bits_left, int nbits)); + + +/* + * Code for extracting next Huffman-coded symbol from input bit stream. + * Again, this is time-critical and we make the main paths be macros. + * + * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits + * without looping. Usually, more than 95% of the Huffman codes will be 8 + * or fewer bits long. The few overlength codes are handled with a loop, + * which need not be inline code. + * + * Notes about the HUFF_DECODE macro: + * 1. Near the end of the data segment, we may fail to get enough bits + * for a lookahead. In that case, we do it the hard way. + * 2. If the lookahead table contains no entry, the next code must be + * more than HUFF_LOOKAHEAD bits long. + * 3. jpeg_huff_decode returns -1 if forced to suspend. + */ + +#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \ +{ register int nb, look; \ + if (bits_left < HUFF_LOOKAHEAD) { \ + if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \ + get_buffer = state.get_buffer; bits_left = state.bits_left; \ + if (bits_left < HUFF_LOOKAHEAD) { \ + nb = 1; goto slowlabel; \ + } \ + } \ + look = PEEK_BITS(HUFF_LOOKAHEAD); \ + if ((nb = htbl->look_nbits[look]) != 0) { \ + DROP_BITS(nb); \ + result = htbl->look_sym[look]; \ + } else { \ + nb = HUFF_LOOKAHEAD+1; \ +slowlabel: \ + if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \ + { failaction; } \ + get_buffer = state.get_buffer; bits_left = state.bits_left; \ + } \ +} + +/* Out-of-line case for Huffman code fetching */ +EXTERN(int) jpeg_huff_decode + JPP((bitread_working_state * state, register bit_buf_type get_buffer, + register int bits_left, d_derived_tbl * htbl, int min_bits)); diff --git a/SlnkDWFImpl/CxImage/jpeg/jdinput.c b/SlnkDWFImpl/CxImage/jpeg/jdinput.c new file mode 100644 index 0000000..2d5c747 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdinput.c @@ -0,0 +1,381 @@ +/* + * jdinput.c + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains input control logic for the JPEG decompressor. + * These routines are concerned with controlling the decompressor's input + * processing (marker reading and coefficient decoding). The actual input + * reading is done in jdmarker.c, jdhuff.c, and jdphuff.c. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Private state */ + +typedef struct { + struct jpeg_input_controller pub; /* public fields */ + + boolean inheaders; /* TRUE until first SOS is reached */ +} my_input_controller; + +typedef my_input_controller * my_inputctl_ptr; + + +/* Forward declarations */ +METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo)); + + +/* + * Routines to calculate various quantities related to the size of the image. + */ + +LOCAL(void) +initial_setup (j_decompress_ptr cinfo) +/* Called once, when first SOS marker is reached */ +{ + int ci; + jpeg_component_info *compptr; + + /* Make sure image isn't bigger than I can handle */ + if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION || + (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION) + ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); + + /* For now, precision must match compiled-in value... */ + if (cinfo->data_precision != BITS_IN_JSAMPLE) + ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision); + + /* Check that number of components won't exceed internal array sizes */ + if (cinfo->num_components > MAX_COMPONENTS) + ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, + MAX_COMPONENTS); + + /* Compute maximum sampling factors; check factor validity */ + cinfo->max_h_samp_factor = 1; + cinfo->max_v_samp_factor = 1; + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR || + compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR) + ERREXIT(cinfo, JERR_BAD_SAMPLING); + cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor, + compptr->h_samp_factor); + cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor, + compptr->v_samp_factor); + } + + /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE. + * In the full decompressor, this will be overridden by jdmaster.c; + * but in the transcoder, jdmaster.c is not used, so we must do it here. + */ + cinfo->min_DCT_scaled_size = DCTSIZE; + + /* Compute dimensions of components */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + compptr->DCT_scaled_size = DCTSIZE; + /* Size in DCT blocks */ + compptr->width_in_blocks = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, + (long) (cinfo->max_h_samp_factor * DCTSIZE)); + compptr->height_in_blocks = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, + (long) (cinfo->max_v_samp_factor * DCTSIZE)); + /* downsampled_width and downsampled_height will also be overridden by + * jdmaster.c if we are doing full decompression. The transcoder library + * doesn't use these values, but the calling application might. + */ + /* Size in samples */ + compptr->downsampled_width = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, + (long) cinfo->max_h_samp_factor); + compptr->downsampled_height = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, + (long) cinfo->max_v_samp_factor); + /* Mark component needed, until color conversion says otherwise */ + compptr->component_needed = TRUE; + /* Mark no quantization table yet saved for component */ + compptr->quant_table = NULL; + } + + /* Compute number of fully interleaved MCU rows. */ + cinfo->total_iMCU_rows = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height, + (long) (cinfo->max_v_samp_factor*DCTSIZE)); + + /* Decide whether file contains multiple scans */ + if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode) + cinfo->inputctl->has_multiple_scans = TRUE; + else + cinfo->inputctl->has_multiple_scans = FALSE; +} + + +LOCAL(void) +per_scan_setup (j_decompress_ptr cinfo) +/* Do computations that are needed before processing a JPEG scan */ +/* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */ +{ + int ci, mcublks, tmp; + jpeg_component_info *compptr; + + if (cinfo->comps_in_scan == 1) { + + /* Noninterleaved (single-component) scan */ + compptr = cinfo->cur_comp_info[0]; + + /* Overall image size in MCUs */ + cinfo->MCUs_per_row = compptr->width_in_blocks; + cinfo->MCU_rows_in_scan = compptr->height_in_blocks; + + /* For noninterleaved scan, always one block per MCU */ + compptr->MCU_width = 1; + compptr->MCU_height = 1; + compptr->MCU_blocks = 1; + compptr->MCU_sample_width = compptr->DCT_scaled_size; + compptr->last_col_width = 1; + /* For noninterleaved scans, it is convenient to define last_row_height + * as the number of block rows present in the last iMCU row. + */ + tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor); + if (tmp == 0) tmp = compptr->v_samp_factor; + compptr->last_row_height = tmp; + + /* Prepare array describing MCU composition */ + cinfo->blocks_in_MCU = 1; + cinfo->MCU_membership[0] = 0; + + } else { + + /* Interleaved (multi-component) scan */ + if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN) + ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan, + MAX_COMPS_IN_SCAN); + + /* Overall image size in MCUs */ + cinfo->MCUs_per_row = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width, + (long) (cinfo->max_h_samp_factor*DCTSIZE)); + cinfo->MCU_rows_in_scan = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height, + (long) (cinfo->max_v_samp_factor*DCTSIZE)); + + cinfo->blocks_in_MCU = 0; + + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + /* Sampling factors give # of blocks of component in each MCU */ + compptr->MCU_width = compptr->h_samp_factor; + compptr->MCU_height = compptr->v_samp_factor; + compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height; + compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size; + /* Figure number of non-dummy blocks in last MCU column & row */ + tmp = (int) (compptr->width_in_blocks % compptr->MCU_width); + if (tmp == 0) tmp = compptr->MCU_width; + compptr->last_col_width = tmp; + tmp = (int) (compptr->height_in_blocks % compptr->MCU_height); + if (tmp == 0) tmp = compptr->MCU_height; + compptr->last_row_height = tmp; + /* Prepare array describing MCU composition */ + mcublks = compptr->MCU_blocks; + if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU) + ERREXIT(cinfo, JERR_BAD_MCU_SIZE); + while (mcublks-- > 0) { + cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci; + } + } + + } +} + + +/* + * Save away a copy of the Q-table referenced by each component present + * in the current scan, unless already saved during a prior scan. + * + * In a multiple-scan JPEG file, the encoder could assign different components + * the same Q-table slot number, but change table definitions between scans + * so that each component uses a different Q-table. (The IJG encoder is not + * currently capable of doing this, but other encoders might.) Since we want + * to be able to dequantize all the components at the end of the file, this + * means that we have to save away the table actually used for each component. + * We do this by copying the table at the start of the first scan containing + * the component. + * The JPEG spec prohibits the encoder from changing the contents of a Q-table + * slot between scans of a component using that slot. If the encoder does so + * anyway, this decoder will simply use the Q-table values that were current + * at the start of the first scan for the component. + * + * The decompressor output side looks only at the saved quant tables, + * not at the current Q-table slots. + */ + +LOCAL(void) +latch_quant_tables (j_decompress_ptr cinfo) +{ + int ci, qtblno; + jpeg_component_info *compptr; + JQUANT_TBL * qtbl; + + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + /* No work if we already saved Q-table for this component */ + if (compptr->quant_table != NULL) + continue; + /* Make sure specified quantization table is present */ + qtblno = compptr->quant_tbl_no; + if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || + cinfo->quant_tbl_ptrs[qtblno] == NULL) + ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno); + /* OK, save away the quantization table */ + qtbl = (JQUANT_TBL *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(JQUANT_TBL)); + MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL)); + compptr->quant_table = qtbl; + } +} + + +/* + * Initialize the input modules to read a scan of compressed data. + * The first call to this is done by jdmaster.c after initializing + * the entire decompressor (during jpeg_start_decompress). + * Subsequent calls come from consume_markers, below. + */ + +METHODDEF(void) +start_input_pass (j_decompress_ptr cinfo) +{ + per_scan_setup(cinfo); + latch_quant_tables(cinfo); + (*cinfo->entropy->start_pass) (cinfo); + (*cinfo->coef->start_input_pass) (cinfo); + cinfo->inputctl->consume_input = cinfo->coef->consume_data; +} + + +/* + * Finish up after inputting a compressed-data scan. + * This is called by the coefficient controller after it's read all + * the expected data of the scan. + */ + +METHODDEF(void) +finish_input_pass (j_decompress_ptr cinfo) +{ + cinfo->inputctl->consume_input = consume_markers; +} + + +/* + * Read JPEG markers before, between, or after compressed-data scans. + * Change state as necessary when a new scan is reached. + * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. + * + * The consume_input method pointer points either here or to the + * coefficient controller's consume_data routine, depending on whether + * we are reading a compressed data segment or inter-segment markers. + */ + +METHODDEF(int) +consume_markers (j_decompress_ptr cinfo) +{ + my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl; + int val; + + if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */ + return JPEG_REACHED_EOI; + + val = (*cinfo->marker->read_markers) (cinfo); + + switch (val) { + case JPEG_REACHED_SOS: /* Found SOS */ + if (inputctl->inheaders) { /* 1st SOS */ + initial_setup(cinfo); + inputctl->inheaders = FALSE; + /* Note: start_input_pass must be called by jdmaster.c + * before any more input can be consumed. jdapimin.c is + * responsible for enforcing this sequencing. + */ + } else { /* 2nd or later SOS marker */ + if (! inputctl->pub.has_multiple_scans) + ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */ + start_input_pass(cinfo); + } + break; + case JPEG_REACHED_EOI: /* Found EOI */ + inputctl->pub.eoi_reached = TRUE; + if (inputctl->inheaders) { /* Tables-only datastream, apparently */ + if (cinfo->marker->saw_SOF) + ERREXIT(cinfo, JERR_SOF_NO_SOS); + } else { + /* Prevent infinite loop in coef ctlr's decompress_data routine + * if user set output_scan_number larger than number of scans. + */ + if (cinfo->output_scan_number > cinfo->input_scan_number) + cinfo->output_scan_number = cinfo->input_scan_number; + } + break; + case JPEG_SUSPENDED: + break; + } + + return val; +} + + +/* + * Reset state to begin a fresh datastream. + */ + +METHODDEF(void) +reset_input_controller (j_decompress_ptr cinfo) +{ + my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl; + + inputctl->pub.consume_input = consume_markers; + inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */ + inputctl->pub.eoi_reached = FALSE; + inputctl->inheaders = TRUE; + /* Reset other modules */ + (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo); + (*cinfo->marker->reset_marker_reader) (cinfo); + /* Reset progression state -- would be cleaner if entropy decoder did this */ + cinfo->coef_bits = NULL; +} + + +/* + * Initialize the input controller module. + * This is called only once, when the decompression object is created. + */ + +GLOBAL(void) +jinit_input_controller (j_decompress_ptr cinfo) +{ + my_inputctl_ptr inputctl; + + /* Create subobject in permanent pool */ + inputctl = (my_inputctl_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + SIZEOF(my_input_controller)); + cinfo->inputctl = (struct jpeg_input_controller *) inputctl; + /* Initialize method pointers */ + inputctl->pub.consume_input = consume_markers; + inputctl->pub.reset_input_controller = reset_input_controller; + inputctl->pub.start_input_pass = start_input_pass; + inputctl->pub.finish_input_pass = finish_input_pass; + /* Initialize state: can't use reset_input_controller since we don't + * want to try to reset other modules yet. + */ + inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */ + inputctl->pub.eoi_reached = FALSE; + inputctl->inheaders = TRUE; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdmainct.c b/SlnkDWFImpl/CxImage/jpeg/jdmainct.c new file mode 100644 index 0000000..6b0f06f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdmainct.c @@ -0,0 +1,512 @@ +/* + * jdmainct.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the main buffer controller for decompression. + * The main buffer lies between the JPEG decompressor proper and the + * post-processor; it holds downsampled data in the JPEG colorspace. + * + * Note that this code is bypassed in raw-data mode, since the application + * supplies the equivalent of the main buffer in that case. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* + * In the current system design, the main buffer need never be a full-image + * buffer; any full-height buffers will be found inside the coefficient or + * postprocessing controllers. Nonetheless, the main controller is not + * trivial. Its responsibility is to provide context rows for upsampling/ + * rescaling, and doing this in an efficient fashion is a bit tricky. + * + * Postprocessor input data is counted in "row groups". A row group + * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size) + * sample rows of each component. (We require DCT_scaled_size values to be + * chosen such that these numbers are integers. In practice DCT_scaled_size + * values will likely be powers of two, so we actually have the stronger + * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.) + * Upsampling will typically produce max_v_samp_factor pixel rows from each + * row group (times any additional scale factor that the upsampler is + * applying). + * + * The coefficient controller will deliver data to us one iMCU row at a time; + * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or + * exactly min_DCT_scaled_size row groups. (This amount of data corresponds + * to one row of MCUs when the image is fully interleaved.) Note that the + * number of sample rows varies across components, but the number of row + * groups does not. Some garbage sample rows may be included in the last iMCU + * row at the bottom of the image. + * + * Depending on the vertical scaling algorithm used, the upsampler may need + * access to the sample row(s) above and below its current input row group. + * The upsampler is required to set need_context_rows TRUE at global selection + * time if so. When need_context_rows is FALSE, this controller can simply + * obtain one iMCU row at a time from the coefficient controller and dole it + * out as row groups to the postprocessor. + * + * When need_context_rows is TRUE, this controller guarantees that the buffer + * passed to postprocessing contains at least one row group's worth of samples + * above and below the row group(s) being processed. Note that the context + * rows "above" the first passed row group appear at negative row offsets in + * the passed buffer. At the top and bottom of the image, the required + * context rows are manufactured by duplicating the first or last real sample + * row; this avoids having special cases in the upsampling inner loops. + * + * The amount of context is fixed at one row group just because that's a + * convenient number for this controller to work with. The existing + * upsamplers really only need one sample row of context. An upsampler + * supporting arbitrary output rescaling might wish for more than one row + * group of context when shrinking the image; tough, we don't handle that. + * (This is justified by the assumption that downsizing will be handled mostly + * by adjusting the DCT_scaled_size values, so that the actual scale factor at + * the upsample step needn't be much less than one.) + * + * To provide the desired context, we have to retain the last two row groups + * of one iMCU row while reading in the next iMCU row. (The last row group + * can't be processed until we have another row group for its below-context, + * and so we have to save the next-to-last group too for its above-context.) + * We could do this most simply by copying data around in our buffer, but + * that'd be very slow. We can avoid copying any data by creating a rather + * strange pointer structure. Here's how it works. We allocate a workspace + * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number + * of row groups per iMCU row). We create two sets of redundant pointers to + * the workspace. Labeling the physical row groups 0 to M+1, the synthesized + * pointer lists look like this: + * M+1 M-1 + * master pointer --> 0 master pointer --> 0 + * 1 1 + * ... ... + * M-3 M-3 + * M-2 M + * M-1 M+1 + * M M-2 + * M+1 M-1 + * 0 0 + * We read alternate iMCU rows using each master pointer; thus the last two + * row groups of the previous iMCU row remain un-overwritten in the workspace. + * The pointer lists are set up so that the required context rows appear to + * be adjacent to the proper places when we pass the pointer lists to the + * upsampler. + * + * The above pictures describe the normal state of the pointer lists. + * At top and bottom of the image, we diddle the pointer lists to duplicate + * the first or last sample row as necessary (this is cheaper than copying + * sample rows around). + * + * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that + * situation each iMCU row provides only one row group so the buffering logic + * must be different (eg, we must read two iMCU rows before we can emit the + * first row group). For now, we simply do not support providing context + * rows when min_DCT_scaled_size is 1. That combination seems unlikely to + * be worth providing --- if someone wants a 1/8th-size preview, they probably + * want it quick and dirty, so a context-free upsampler is sufficient. + */ + + +/* Private buffer controller object */ + +typedef struct { + struct jpeg_d_main_controller pub; /* public fields */ + + /* Pointer to allocated workspace (M or M+2 row groups). */ + JSAMPARRAY buffer[MAX_COMPONENTS]; + + boolean buffer_full; /* Have we gotten an iMCU row from decoder? */ + JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */ + + /* Remaining fields are only used in the context case. */ + + /* These are the master pointers to the funny-order pointer lists. */ + JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */ + + int whichptr; /* indicates which pointer set is now in use */ + int context_state; /* process_data state machine status */ + JDIMENSION rowgroups_avail; /* row groups available to postprocessor */ + JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */ +} my_main_controller; + +typedef my_main_controller * my_main_ptr; + +/* context_state values: */ +#define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */ +#define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */ +#define CTX_POSTPONED_ROW 2 /* feeding postponed row group */ + + +/* Forward declarations */ +METHODDEF(void) process_data_simple_main + JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf, + JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); +METHODDEF(void) process_data_context_main + JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf, + JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); +#ifdef QUANT_2PASS_SUPPORTED +METHODDEF(void) process_data_crank_post + JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf, + JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); +#endif + + +LOCAL(void) +alloc_funny_pointers (j_decompress_ptr cinfo) +/* Allocate space for the funny pointer lists. + * This is done only once, not once per pass. + */ +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + int ci, rgroup; + int M = cinfo->min_DCT_scaled_size; + jpeg_component_info *compptr; + JSAMPARRAY xbuf; + + /* Get top-level space for component array pointers. + * We alloc both arrays with one call to save a few cycles. + */ + main->xbuffer[0] = (JSAMPIMAGE) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + cinfo->num_components * 2 * SIZEOF(JSAMPARRAY)); + main->xbuffer[1] = main->xbuffer[0] + cinfo->num_components; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) / + cinfo->min_DCT_scaled_size; /* height of a row group of component */ + /* Get space for pointer lists --- M+4 row groups in each list. + * We alloc both pointer lists with one call to save a few cycles. + */ + xbuf = (JSAMPARRAY) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW)); + xbuf += rgroup; /* want one row group at negative offsets */ + main->xbuffer[0][ci] = xbuf; + xbuf += rgroup * (M + 4); + main->xbuffer[1][ci] = xbuf; + } +} + + +LOCAL(void) +make_funny_pointers (j_decompress_ptr cinfo) +/* Create the funny pointer lists discussed in the comments above. + * The actual workspace is already allocated (in main->buffer), + * and the space for the pointer lists is allocated too. + * This routine just fills in the curiously ordered lists. + * This will be repeated at the beginning of each pass. + */ +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + int ci, i, rgroup; + int M = cinfo->min_DCT_scaled_size; + jpeg_component_info *compptr; + JSAMPARRAY buf, xbuf0, xbuf1; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) / + cinfo->min_DCT_scaled_size; /* height of a row group of component */ + xbuf0 = main->xbuffer[0][ci]; + xbuf1 = main->xbuffer[1][ci]; + /* First copy the workspace pointers as-is */ + buf = main->buffer[ci]; + for (i = 0; i < rgroup * (M + 2); i++) { + xbuf0[i] = xbuf1[i] = buf[i]; + } + /* In the second list, put the last four row groups in swapped order */ + for (i = 0; i < rgroup * 2; i++) { + xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i]; + xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i]; + } + /* The wraparound pointers at top and bottom will be filled later + * (see set_wraparound_pointers, below). Initially we want the "above" + * pointers to duplicate the first actual data line. This only needs + * to happen in xbuffer[0]. + */ + for (i = 0; i < rgroup; i++) { + xbuf0[i - rgroup] = xbuf0[0]; + } + } +} + + +LOCAL(void) +set_wraparound_pointers (j_decompress_ptr cinfo) +/* Set up the "wraparound" pointers at top and bottom of the pointer lists. + * This changes the pointer list state from top-of-image to the normal state. + */ +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + int ci, i, rgroup; + int M = cinfo->min_DCT_scaled_size; + jpeg_component_info *compptr; + JSAMPARRAY xbuf0, xbuf1; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) / + cinfo->min_DCT_scaled_size; /* height of a row group of component */ + xbuf0 = main->xbuffer[0][ci]; + xbuf1 = main->xbuffer[1][ci]; + for (i = 0; i < rgroup; i++) { + xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i]; + xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i]; + xbuf0[rgroup*(M+2) + i] = xbuf0[i]; + xbuf1[rgroup*(M+2) + i] = xbuf1[i]; + } + } +} + + +LOCAL(void) +set_bottom_pointers (j_decompress_ptr cinfo) +/* Change the pointer lists to duplicate the last sample row at the bottom + * of the image. whichptr indicates which xbuffer holds the final iMCU row. + * Also sets rowgroups_avail to indicate number of nondummy row groups in row. + */ +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + int ci, i, rgroup, iMCUheight, rows_left; + jpeg_component_info *compptr; + JSAMPARRAY xbuf; + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Count sample rows in one iMCU row and in one row group */ + iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size; + rgroup = iMCUheight / cinfo->min_DCT_scaled_size; + /* Count nondummy sample rows remaining for this component */ + rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight); + if (rows_left == 0) rows_left = iMCUheight; + /* Count nondummy row groups. Should get same answer for each component, + * so we need only do it once. + */ + if (ci == 0) { + main->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1); + } + /* Duplicate the last real sample row rgroup*2 times; this pads out the + * last partial rowgroup and ensures at least one full rowgroup of context. + */ + xbuf = main->xbuffer[main->whichptr][ci]; + for (i = 0; i < rgroup * 2; i++) { + xbuf[rows_left + i] = xbuf[rows_left-1]; + } + } +} + + +/* + * Initialize for a processing pass. + */ + +METHODDEF(void) +start_pass_main (j_decompress_ptr cinfo, J_BUF_MODE pass_mode) +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + + switch (pass_mode) { + case JBUF_PASS_THRU: + if (cinfo->upsample->need_context_rows) { + main->pub.process_data = process_data_context_main; + make_funny_pointers(cinfo); /* Create the xbuffer[] lists */ + main->whichptr = 0; /* Read first iMCU row into xbuffer[0] */ + main->context_state = CTX_PREPARE_FOR_IMCU; + main->iMCU_row_ctr = 0; + } else { + /* Simple case with no context needed */ + main->pub.process_data = process_data_simple_main; + } + main->buffer_full = FALSE; /* Mark buffer empty */ + main->rowgroup_ctr = 0; + break; +#ifdef QUANT_2PASS_SUPPORTED + case JBUF_CRANK_DEST: + /* For last pass of 2-pass quantization, just crank the postprocessor */ + main->pub.process_data = process_data_crank_post; + break; +#endif + default: + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + break; + } +} + + +/* + * Process some data. + * This handles the simple case where no context is required. + */ + +METHODDEF(void) +process_data_simple_main (j_decompress_ptr cinfo, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + JDIMENSION rowgroups_avail; + + /* Read input data if we haven't filled the main buffer yet */ + if (! main->buffer_full) { + if (! (*cinfo->coef->decompress_data) (cinfo, main->buffer)) + return; /* suspension forced, can do nothing more */ + main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */ + } + + /* There are always min_DCT_scaled_size row groups in an iMCU row. */ + rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size; + /* Note: at the bottom of the image, we may pass extra garbage row groups + * to the postprocessor. The postprocessor has to check for bottom + * of image anyway (at row resolution), so no point in us doing it too. + */ + + /* Feed the postprocessor */ + (*cinfo->post->post_process_data) (cinfo, main->buffer, + &main->rowgroup_ctr, rowgroups_avail, + output_buf, out_row_ctr, out_rows_avail); + + /* Has postprocessor consumed all the data yet? If so, mark buffer empty */ + if (main->rowgroup_ctr >= rowgroups_avail) { + main->buffer_full = FALSE; + main->rowgroup_ctr = 0; + } +} + + +/* + * Process some data. + * This handles the case where context rows must be provided. + */ + +METHODDEF(void) +process_data_context_main (j_decompress_ptr cinfo, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +{ + my_main_ptr main = (my_main_ptr) cinfo->main; + + /* Read input data if we haven't filled the main buffer yet */ + if (! main->buffer_full) { + if (! (*cinfo->coef->decompress_data) (cinfo, + main->xbuffer[main->whichptr])) + return; /* suspension forced, can do nothing more */ + main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */ + main->iMCU_row_ctr++; /* count rows received */ + } + + /* Postprocessor typically will not swallow all the input data it is handed + * in one call (due to filling the output buffer first). Must be prepared + * to exit and restart. This switch lets us keep track of how far we got. + * Note that each case falls through to the next on successful completion. + */ + switch (main->context_state) { + case CTX_POSTPONED_ROW: + /* Call postprocessor using previously set pointers for postponed row */ + (*cinfo->post->post_process_data) (cinfo, main->xbuffer[main->whichptr], + &main->rowgroup_ctr, main->rowgroups_avail, + output_buf, out_row_ctr, out_rows_avail); + if (main->rowgroup_ctr < main->rowgroups_avail) + return; /* Need to suspend */ + main->context_state = CTX_PREPARE_FOR_IMCU; + if (*out_row_ctr >= out_rows_avail) + return; /* Postprocessor exactly filled output buf */ + /*FALLTHROUGH*/ + case CTX_PREPARE_FOR_IMCU: + /* Prepare to process first M-1 row groups of this iMCU row */ + main->rowgroup_ctr = 0; + main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1); + /* Check for bottom of image: if so, tweak pointers to "duplicate" + * the last sample row, and adjust rowgroups_avail to ignore padding rows. + */ + if (main->iMCU_row_ctr == cinfo->total_iMCU_rows) + set_bottom_pointers(cinfo); + main->context_state = CTX_PROCESS_IMCU; + /*FALLTHROUGH*/ + case CTX_PROCESS_IMCU: + /* Call postprocessor using previously set pointers */ + (*cinfo->post->post_process_data) (cinfo, main->xbuffer[main->whichptr], + &main->rowgroup_ctr, main->rowgroups_avail, + output_buf, out_row_ctr, out_rows_avail); + if (main->rowgroup_ctr < main->rowgroups_avail) + return; /* Need to suspend */ + /* After the first iMCU, change wraparound pointers to normal state */ + if (main->iMCU_row_ctr == 1) + set_wraparound_pointers(cinfo); + /* Prepare to load new iMCU row using other xbuffer list */ + main->whichptr ^= 1; /* 0=>1 or 1=>0 */ + main->buffer_full = FALSE; + /* Still need to process last row group of this iMCU row, */ + /* which is saved at index M+1 of the other xbuffer */ + main->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1); + main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2); + main->context_state = CTX_POSTPONED_ROW; + } +} + + +/* + * Process some data. + * Final pass of two-pass quantization: just call the postprocessor. + * Source data will be the postprocessor controller's internal buffer. + */ + +#ifdef QUANT_2PASS_SUPPORTED + +METHODDEF(void) +process_data_crank_post (j_decompress_ptr cinfo, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +{ + (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL, + (JDIMENSION *) NULL, (JDIMENSION) 0, + output_buf, out_row_ctr, out_rows_avail); +} + +#endif /* QUANT_2PASS_SUPPORTED */ + + +/* + * Initialize main buffer controller. + */ + +GLOBAL(void) +jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer) +{ + my_main_ptr main; + int ci, rgroup, ngroups; + jpeg_component_info *compptr; + + main = (my_main_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_main_controller)); + cinfo->main = (struct jpeg_d_main_controller *) main; + main->pub.start_pass = start_pass_main; + + if (need_full_buffer) /* shouldn't happen */ + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + + /* Allocate the workspace. + * ngroups is the number of row groups we need. + */ + if (cinfo->upsample->need_context_rows) { + if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */ + ERREXIT(cinfo, JERR_NOTIMPL); + alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */ + ngroups = cinfo->min_DCT_scaled_size + 2; + } else { + ngroups = cinfo->min_DCT_scaled_size; + } + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) / + cinfo->min_DCT_scaled_size; /* height of a row group of component */ + main->buffer[ci] = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + compptr->width_in_blocks * compptr->DCT_scaled_size, + (JDIMENSION) (rgroup * ngroups)); + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdmarker.c b/SlnkDWFImpl/CxImage/jpeg/jdmarker.c new file mode 100644 index 0000000..5d75af0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdmarker.c @@ -0,0 +1,1360 @@ +/* + * jdmarker.c + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains routines to decode JPEG datastream markers. + * Most of the complexity arises from our desire to support input + * suspension: if not all of the data for a marker is available, + * we must exit back to the application. On resumption, we reprocess + * the marker. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +typedef enum { /* JPEG marker codes */ + M_SOF0 = 0xc0, + M_SOF1 = 0xc1, + M_SOF2 = 0xc2, + M_SOF3 = 0xc3, + + M_SOF5 = 0xc5, + M_SOF6 = 0xc6, + M_SOF7 = 0xc7, + + M_JPG = 0xc8, + M_SOF9 = 0xc9, + M_SOF10 = 0xca, + M_SOF11 = 0xcb, + + M_SOF13 = 0xcd, + M_SOF14 = 0xce, + M_SOF15 = 0xcf, + + M_DHT = 0xc4, + + M_DAC = 0xcc, + + M_RST0 = 0xd0, + M_RST1 = 0xd1, + M_RST2 = 0xd2, + M_RST3 = 0xd3, + M_RST4 = 0xd4, + M_RST5 = 0xd5, + M_RST6 = 0xd6, + M_RST7 = 0xd7, + + M_SOI = 0xd8, + M_EOI = 0xd9, + M_SOS = 0xda, + M_DQT = 0xdb, + M_DNL = 0xdc, + M_DRI = 0xdd, + M_DHP = 0xde, + M_EXP = 0xdf, + + M_APP0 = 0xe0, + M_APP1 = 0xe1, + M_APP2 = 0xe2, + M_APP3 = 0xe3, + M_APP4 = 0xe4, + M_APP5 = 0xe5, + M_APP6 = 0xe6, + M_APP7 = 0xe7, + M_APP8 = 0xe8, + M_APP9 = 0xe9, + M_APP10 = 0xea, + M_APP11 = 0xeb, + M_APP12 = 0xec, + M_APP13 = 0xed, + M_APP14 = 0xee, + M_APP15 = 0xef, + + M_JPG0 = 0xf0, + M_JPG13 = 0xfd, + M_COM = 0xfe, + + M_TEM = 0x01, + + M_ERROR = 0x100 +} JPEG_MARKER; + + +/* Private state */ + +typedef struct { + struct jpeg_marker_reader pub; /* public fields */ + + /* Application-overridable marker processing methods */ + jpeg_marker_parser_method process_COM; + jpeg_marker_parser_method process_APPn[16]; + + /* Limit on marker data length to save for each marker type */ + unsigned int length_limit_COM; + unsigned int length_limit_APPn[16]; + + /* Status of COM/APPn marker saving */ + jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */ + unsigned int bytes_read; /* data bytes read so far in marker */ + /* Note: cur_marker is not linked into marker_list until it's all read. */ +} my_marker_reader; + +typedef my_marker_reader * my_marker_ptr; + + +/* + * Macros for fetching data from the data source module. + * + * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect + * the current restart point; we update them only when we have reached a + * suitable place to restart if a suspension occurs. + */ + +/* Declare and initialize local copies of input pointer/count */ +#define INPUT_VARS(cinfo) \ + struct jpeg_source_mgr * datasrc = (cinfo)->src; \ + const JOCTET * next_input_byte = datasrc->next_input_byte; \ + size_t bytes_in_buffer = datasrc->bytes_in_buffer + +/* Unload the local copies --- do this only at a restart boundary */ +#define INPUT_SYNC(cinfo) \ + ( datasrc->next_input_byte = next_input_byte, \ + datasrc->bytes_in_buffer = bytes_in_buffer ) + +/* Reload the local copies --- used only in MAKE_BYTE_AVAIL */ +#define INPUT_RELOAD(cinfo) \ + ( next_input_byte = datasrc->next_input_byte, \ + bytes_in_buffer = datasrc->bytes_in_buffer ) + +/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available. + * Note we do *not* do INPUT_SYNC before calling fill_input_buffer, + * but we must reload the local copies after a successful fill. + */ +#define MAKE_BYTE_AVAIL(cinfo,action) \ + if (bytes_in_buffer == 0) { \ + if (! (*datasrc->fill_input_buffer) (cinfo)) \ + { action; } \ + INPUT_RELOAD(cinfo); \ + } + +/* Read a byte into variable V. + * If must suspend, take the specified action (typically "return FALSE"). + */ +#define INPUT_BYTE(cinfo,V,action) \ + MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \ + bytes_in_buffer--; \ + V = GETJOCTET(*next_input_byte++); ) + +/* As above, but read two bytes interpreted as an unsigned 16-bit integer. + * V should be declared unsigned int or perhaps INT32. + */ +#define INPUT_2BYTES(cinfo,V,action) \ + MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \ + bytes_in_buffer--; \ + V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \ + MAKE_BYTE_AVAIL(cinfo,action); \ + bytes_in_buffer--; \ + V += GETJOCTET(*next_input_byte++); ) + + +/* + * Routines to process JPEG markers. + * + * Entry condition: JPEG marker itself has been read and its code saved + * in cinfo->unread_marker; input restart point is just after the marker. + * + * Exit: if return TRUE, have read and processed any parameters, and have + * updated the restart point to point after the parameters. + * If return FALSE, was forced to suspend before reaching end of + * marker parameters; restart point has not been moved. Same routine + * will be called again after application supplies more input data. + * + * This approach to suspension assumes that all of a marker's parameters + * can fit into a single input bufferload. This should hold for "normal" + * markers. Some COM/APPn markers might have large parameter segments + * that might not fit. If we are simply dropping such a marker, we use + * skip_input_data to get past it, and thereby put the problem on the + * source manager's shoulders. If we are saving the marker's contents + * into memory, we use a slightly different convention: when forced to + * suspend, the marker processor updates the restart point to the end of + * what it's consumed (ie, the end of the buffer) before returning FALSE. + * On resumption, cinfo->unread_marker still contains the marker code, + * but the data source will point to the next chunk of marker data. + * The marker processor must retain internal state to deal with this. + * + * Note that we don't bother to avoid duplicate trace messages if a + * suspension occurs within marker parameters. Other side effects + * require more care. + */ + + +LOCAL(boolean) +get_soi (j_decompress_ptr cinfo) +/* Process an SOI marker */ +{ + int i; + + TRACEMS(cinfo, 1, JTRC_SOI); + + if (cinfo->marker->saw_SOI && cinfo->global_state != DSTATE_INHEADER) + ERREXIT(cinfo, JERR_SOI_DUPLICATE); + + /* Reset all parameters that are defined to be reset by SOI */ + + for (i = 0; i < NUM_ARITH_TBLS; i++) { + cinfo->arith_dc_L[i] = 0; + cinfo->arith_dc_U[i] = 1; + cinfo->arith_ac_K[i] = 5; + } + cinfo->restart_interval = 0; + + /* Set initial assumptions for colorspace etc */ + + cinfo->jpeg_color_space = JCS_UNKNOWN; + cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */ + + cinfo->saw_JFIF_marker = FALSE; + cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */ + cinfo->JFIF_minor_version = 1; + cinfo->density_unit = 0; + cinfo->X_density = 1; + cinfo->Y_density = 1; + cinfo->saw_Adobe_marker = FALSE; + cinfo->Adobe_transform = 0; + + cinfo->marker->saw_SOI = TRUE; + + return TRUE; +} + + +LOCAL(boolean) +get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith) +/* Process a SOFn marker */ +{ + INT32 length; + int c, ci; + jpeg_component_info * compptr; + INPUT_VARS(cinfo); + + cinfo->progressive_mode = is_prog; + cinfo->arith_code = is_arith; + + INPUT_2BYTES(cinfo, length, return FALSE); + + INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE); + INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE); + INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE); + INPUT_BYTE(cinfo, cinfo->num_components, return FALSE); + + length -= 8; + + TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker, + (int) cinfo->image_width, (int) cinfo->image_height, + cinfo->num_components); + + if (cinfo->marker->saw_SOF && cinfo->global_state != DSTATE_INHEADER) + ERREXIT(cinfo, JERR_SOF_DUPLICATE); + + /* We don't support files in which the image height is initially specified */ + /* as 0 and is later redefined by DNL. As long as we have to check that, */ + /* might as well have a general sanity check. */ + if (cinfo->image_height <= 0 || cinfo->image_width <= 0 + || cinfo->num_components <= 0) + ERREXIT(cinfo, JERR_EMPTY_IMAGE); + + if (length != (cinfo->num_components * 3)) + ERREXIT(cinfo, JERR_BAD_LENGTH); + + if (cinfo->comp_info == NULL) /* do only once, even if suspend */ + cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + cinfo->num_components * SIZEOF(jpeg_component_info)); + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + compptr->component_index = ci; + INPUT_BYTE(cinfo, compptr->component_id, return FALSE); + INPUT_BYTE(cinfo, c, return FALSE); + compptr->h_samp_factor = (c >> 4) & 15; + compptr->v_samp_factor = (c ) & 15; + INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE); + + TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT, + compptr->component_id, compptr->h_samp_factor, + compptr->v_samp_factor, compptr->quant_tbl_no); + } + + cinfo->marker->saw_SOF = TRUE; + + INPUT_SYNC(cinfo); + return TRUE; +} + + +LOCAL(boolean) +get_sos (j_decompress_ptr cinfo) +/* Process a SOS marker */ +{ + INT32 length; + int i, ci, n, c, cc; + jpeg_component_info * compptr; + INPUT_VARS(cinfo); + + if (! cinfo->marker->saw_SOF) + ERREXIT(cinfo, JERR_SOS_NO_SOF); + + INPUT_2BYTES(cinfo, length, return FALSE); + + INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */ + + TRACEMS1(cinfo, 1, JTRC_SOS, n); + + if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN) + ERREXIT(cinfo, JERR_BAD_LENGTH); + + cinfo->comps_in_scan = n; + + /* Collect the component-spec parameters */ + + for (i = 0; i < n; i++) { + INPUT_BYTE(cinfo, cc, return FALSE); + INPUT_BYTE(cinfo, c, return FALSE); + + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + if (cc == compptr->component_id) + goto id_found; + } + + ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc); + + id_found: + + cinfo->cur_comp_info[i] = compptr; + compptr->dc_tbl_no = (c >> 4) & 15; + compptr->ac_tbl_no = (c ) & 15; + + TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc, + compptr->dc_tbl_no, compptr->ac_tbl_no); + } + + /* Collect the additional scan parameters Ss, Se, Ah/Al. */ + INPUT_BYTE(cinfo, c, return FALSE); + cinfo->Ss = c; + INPUT_BYTE(cinfo, c, return FALSE); + cinfo->Se = c; + INPUT_BYTE(cinfo, c, return FALSE); + cinfo->Ah = (c >> 4) & 15; + cinfo->Al = (c ) & 15; + + TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se, + cinfo->Ah, cinfo->Al); + + /* Prepare to scan data & restart markers */ + cinfo->marker->next_restart_num = 0; + + /* Count another SOS marker */ + cinfo->input_scan_number++; + + INPUT_SYNC(cinfo); + return TRUE; +} + + +#ifdef D_ARITH_CODING_SUPPORTED + +LOCAL(boolean) +get_dac (j_decompress_ptr cinfo) +/* Process a DAC marker */ +{ + INT32 length; + int index, val; + INPUT_VARS(cinfo); + + INPUT_2BYTES(cinfo, length, return FALSE); + length -= 2; + + while (length > 0) { + INPUT_BYTE(cinfo, index, return FALSE); + INPUT_BYTE(cinfo, val, return FALSE); + + length -= 2; + + TRACEMS2(cinfo, 1, JTRC_DAC, index, val); + + if (index < 0 || index >= (2*NUM_ARITH_TBLS)) + ERREXIT1(cinfo, JERR_DAC_INDEX, index); + + if (index >= NUM_ARITH_TBLS) { /* define AC table */ + cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val; + } else { /* define DC table */ + cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F); + cinfo->arith_dc_U[index] = (UINT8) (val >> 4); + if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index]) + ERREXIT1(cinfo, JERR_DAC_VALUE, val); + } + } + + if (length != 0) + ERREXIT(cinfo, JERR_BAD_LENGTH); + + INPUT_SYNC(cinfo); + return TRUE; +} + +#else /* ! D_ARITH_CODING_SUPPORTED */ + +#define get_dac(cinfo) skip_variable(cinfo) + +#endif /* D_ARITH_CODING_SUPPORTED */ + + +LOCAL(boolean) +get_dht (j_decompress_ptr cinfo) +/* Process a DHT marker */ +{ + INT32 length; + UINT8 bits[17]; + UINT8 huffval[256]; + int i, index, count; + JHUFF_TBL **htblptr; + INPUT_VARS(cinfo); + + INPUT_2BYTES(cinfo, length, return FALSE); + length -= 2; + + while (length > 16) { + INPUT_BYTE(cinfo, index, return FALSE); + + TRACEMS1(cinfo, 1, JTRC_DHT, index); + + bits[0] = 0; + count = 0; + for (i = 1; i <= 16; i++) { + INPUT_BYTE(cinfo, bits[i], return FALSE); + count += bits[i]; + } + + length -= 1 + 16; + + TRACEMS8(cinfo, 2, JTRC_HUFFBITS, + bits[1], bits[2], bits[3], bits[4], + bits[5], bits[6], bits[7], bits[8]); + TRACEMS8(cinfo, 2, JTRC_HUFFBITS, + bits[9], bits[10], bits[11], bits[12], + bits[13], bits[14], bits[15], bits[16]); + + /* Here we just do minimal validation of the counts to avoid walking + * off the end of our table space. jdhuff.c will check more carefully. + */ + if (count > 256 || ((INT32) count) > length) + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + + for (i = 0; i < count; i++) + INPUT_BYTE(cinfo, huffval[i], return FALSE); + + length -= count; + + if (index & 0x10) { /* AC table definition */ + index -= 0x10; + htblptr = &cinfo->ac_huff_tbl_ptrs[index]; + } else { /* DC table definition */ + htblptr = &cinfo->dc_huff_tbl_ptrs[index]; + } + + if (index < 0 || index >= NUM_HUFF_TBLS) + ERREXIT1(cinfo, JERR_DHT_INDEX, index); + + if (*htblptr == NULL) + *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); + + MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits)); + MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval)); + } + + if (length != 0) + ERREXIT(cinfo, JERR_BAD_LENGTH); + + INPUT_SYNC(cinfo); + return TRUE; +} + + +LOCAL(boolean) +get_dqt (j_decompress_ptr cinfo) +/* Process a DQT marker */ +{ + INT32 length; + int n, i, prec; + unsigned int tmp; + JQUANT_TBL *quant_ptr; + INPUT_VARS(cinfo); + + INPUT_2BYTES(cinfo, length, return FALSE); + length -= 2; + + while (length > 0) { + INPUT_BYTE(cinfo, n, return FALSE); + prec = n >> 4; + n &= 0x0F; + + TRACEMS2(cinfo, 1, JTRC_DQT, n, prec); + + if (n >= NUM_QUANT_TBLS) + ERREXIT1(cinfo, JERR_DQT_INDEX, n); + + if (cinfo->quant_tbl_ptrs[n] == NULL) + cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo); + quant_ptr = cinfo->quant_tbl_ptrs[n]; + + for (i = 0; i < DCTSIZE2; i++) { + if (prec) + INPUT_2BYTES(cinfo, tmp, return FALSE); + else + INPUT_BYTE(cinfo, tmp, return FALSE); + /* We convert the zigzag-order table to natural array order. */ + quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp; + } + + if (cinfo->err->trace_level >= 2) { + for (i = 0; i < DCTSIZE2; i += 8) { + TRACEMS8(cinfo, 2, JTRC_QUANTVALS, + quant_ptr->quantval[i], quant_ptr->quantval[i+1], + quant_ptr->quantval[i+2], quant_ptr->quantval[i+3], + quant_ptr->quantval[i+4], quant_ptr->quantval[i+5], + quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]); + } + } + + length -= DCTSIZE2+1; + if (prec) length -= DCTSIZE2; + } + + if (length != 0) + ERREXIT(cinfo, JERR_BAD_LENGTH); + + INPUT_SYNC(cinfo); + return TRUE; +} + + +LOCAL(boolean) +get_dri (j_decompress_ptr cinfo) +/* Process a DRI marker */ +{ + INT32 length; + unsigned int tmp; + INPUT_VARS(cinfo); + + INPUT_2BYTES(cinfo, length, return FALSE); + + if (length != 4) + ERREXIT(cinfo, JERR_BAD_LENGTH); + + INPUT_2BYTES(cinfo, tmp, return FALSE); + + TRACEMS1(cinfo, 1, JTRC_DRI, tmp); + + cinfo->restart_interval = tmp; + + INPUT_SYNC(cinfo); + return TRUE; +} + + +/* + * Routines for processing APPn and COM markers. + * These are either saved in memory or discarded, per application request. + * APP0 and APP14 are specially checked to see if they are + * JFIF and Adobe markers, respectively. + */ + +#define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */ +#define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */ +#define APPN_DATA_LEN 14 /* Must be the largest of the above!! */ + + +LOCAL(void) +examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data, + unsigned int datalen, INT32 remaining) +/* Examine first few bytes from an APP0. + * Take appropriate action if it is a JFIF marker. + * datalen is # of bytes at data[], remaining is length of rest of marker data. + */ +{ + INT32 totallen = (INT32) datalen + remaining; + + if (datalen >= APP0_DATA_LEN && + GETJOCTET(data[0]) == 0x4A && + GETJOCTET(data[1]) == 0x46 && + GETJOCTET(data[2]) == 0x49 && + GETJOCTET(data[3]) == 0x46 && + GETJOCTET(data[4]) == 0) { + /* Found JFIF APP0 marker: save info */ + cinfo->saw_JFIF_marker = TRUE; + cinfo->JFIF_major_version = GETJOCTET(data[5]); + cinfo->JFIF_minor_version = GETJOCTET(data[6]); + cinfo->density_unit = GETJOCTET(data[7]); + cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]); + cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]); + /* Check version. + * Major version must be 1, anything else signals an incompatible change. + * (We used to treat this as an error, but now it's a nonfatal warning, + * because some bozo at Hijaak couldn't read the spec.) + * Minor version should be 0..2, but process anyway if newer. + */ + if (cinfo->JFIF_major_version != 1) + WARNMS2(cinfo, JWRN_JFIF_MAJOR, + cinfo->JFIF_major_version, cinfo->JFIF_minor_version); + /* Generate trace messages */ + TRACEMS5(cinfo, 1, JTRC_JFIF, + cinfo->JFIF_major_version, cinfo->JFIF_minor_version, + cinfo->X_density, cinfo->Y_density, cinfo->density_unit); + /* Validate thumbnail dimensions and issue appropriate messages */ + if (GETJOCTET(data[12]) | GETJOCTET(data[13])) + TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, + GETJOCTET(data[12]), GETJOCTET(data[13])); + totallen -= APP0_DATA_LEN; + if (totallen != + ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3)) + TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen); + } else if (datalen >= 6 && + GETJOCTET(data[0]) == 0x4A && + GETJOCTET(data[1]) == 0x46 && + GETJOCTET(data[2]) == 0x58 && + GETJOCTET(data[3]) == 0x58 && + GETJOCTET(data[4]) == 0) { + /* Found JFIF "JFXX" extension APP0 marker */ + /* The library doesn't actually do anything with these, + * but we try to produce a helpful trace message. + */ + switch (GETJOCTET(data[5])) { + case 0x10: + TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen); + break; + case 0x11: + TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen); + break; + case 0x13: + TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen); + break; + default: + TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION, + GETJOCTET(data[5]), (int) totallen); + break; + } + } else { + /* Start of APP0 does not match "JFIF" or "JFXX", or too short */ + TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen); + } +} + + +LOCAL(void) +examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data, + unsigned int datalen, INT32 remaining) +/* Examine first few bytes from an APP14. + * Take appropriate action if it is an Adobe marker. + * datalen is # of bytes at data[], remaining is length of rest of marker data. + */ +{ + unsigned int version, flags0, flags1, transform; + + if (datalen >= APP14_DATA_LEN && + GETJOCTET(data[0]) == 0x41 && + GETJOCTET(data[1]) == 0x64 && + GETJOCTET(data[2]) == 0x6F && + GETJOCTET(data[3]) == 0x62 && + GETJOCTET(data[4]) == 0x65) { + /* Found Adobe APP14 marker */ + version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]); + flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]); + flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]); + transform = GETJOCTET(data[11]); + TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform); + cinfo->saw_Adobe_marker = TRUE; + cinfo->Adobe_transform = (UINT8) transform; + } else { + /* Start of APP14 does not match "Adobe", or too short */ + TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining)); + } +} + + +METHODDEF(boolean) +get_interesting_appn (j_decompress_ptr cinfo) +/* Process an APP0 or APP14 marker without saving it */ +{ + INT32 length; + JOCTET b[APPN_DATA_LEN]; + unsigned int i, numtoread; + INPUT_VARS(cinfo); + + INPUT_2BYTES(cinfo, length, return FALSE); + length -= 2; + + /* get the interesting part of the marker data */ + if (length >= APPN_DATA_LEN) + numtoread = APPN_DATA_LEN; + else if (length > 0) + numtoread = (unsigned int) length; + else + numtoread = 0; + for (i = 0; i < numtoread; i++) + INPUT_BYTE(cinfo, b[i], return FALSE); + length -= numtoread; + + /* process it */ + switch (cinfo->unread_marker) { + case M_APP0: + examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length); + break; + case M_APP14: + examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length); + break; + default: + /* can't get here unless jpeg_save_markers chooses wrong processor */ + ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker); + break; + } + + /* skip any remaining data -- could be lots */ + INPUT_SYNC(cinfo); + if (length > 0) + (*cinfo->src->skip_input_data) (cinfo, (long) length); + + return TRUE; +} + + +#ifdef SAVE_MARKERS_SUPPORTED + +METHODDEF(boolean) +save_marker (j_decompress_ptr cinfo) +/* Save an APPn or COM marker into the marker list */ +{ + my_marker_ptr marker = (my_marker_ptr) cinfo->marker; + jpeg_saved_marker_ptr cur_marker = marker->cur_marker; + unsigned int bytes_read, data_length; + JOCTET FAR * data; + INT32 length = 0; + INPUT_VARS(cinfo); + + if (cur_marker == NULL) { + /* begin reading a marker */ + INPUT_2BYTES(cinfo, length, return FALSE); + length -= 2; + if (length >= 0) { /* watch out for bogus length word */ + /* figure out how much we want to save */ + unsigned int limit; + if (cinfo->unread_marker == (int) M_COM) + limit = marker->length_limit_COM; + else + limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0]; + if ((unsigned int) length < limit) + limit = (unsigned int) length; + /* allocate and initialize the marker item */ + cur_marker = (jpeg_saved_marker_ptr) + (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(struct jpeg_marker_struct) + limit); + cur_marker->next = NULL; + cur_marker->marker = (UINT8) cinfo->unread_marker; + cur_marker->original_length = (unsigned int) length; + cur_marker->data_length = limit; + /* data area is just beyond the jpeg_marker_struct */ + data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1); + marker->cur_marker = cur_marker; + marker->bytes_read = 0; + bytes_read = 0; + data_length = limit; + } else { + /* deal with bogus length word */ + bytes_read = data_length = 0; + data = NULL; + } + } else { + /* resume reading a marker */ + bytes_read = marker->bytes_read; + data_length = cur_marker->data_length; + data = cur_marker->data + bytes_read; + } + + while (bytes_read < data_length) { + INPUT_SYNC(cinfo); /* move the restart point to here */ + marker->bytes_read = bytes_read; + /* If there's not at least one byte in buffer, suspend */ + MAKE_BYTE_AVAIL(cinfo, return FALSE); + /* Copy bytes with reasonable rapidity */ + while (bytes_read < data_length && bytes_in_buffer > 0) { + *data++ = *next_input_byte++; + bytes_in_buffer--; + bytes_read++; + } + } + + /* Done reading what we want to read */ + if (cur_marker != NULL) { /* will be NULL if bogus length word */ + /* Add new marker to end of list */ + if (cinfo->marker_list == NULL) { + cinfo->marker_list = cur_marker; + } else { + jpeg_saved_marker_ptr prev = cinfo->marker_list; + while (prev->next != NULL) + prev = prev->next; + prev->next = cur_marker; + } + /* Reset pointer & calc remaining data length */ + data = cur_marker->data; + length = cur_marker->original_length - data_length; + } + /* Reset to initial state for next marker */ + marker->cur_marker = NULL; + + /* Process the marker if interesting; else just make a generic trace msg */ + switch (cinfo->unread_marker) { + case M_APP0: + examine_app0(cinfo, data, data_length, length); + break; + case M_APP14: + examine_app14(cinfo, data, data_length, length); + break; + default: + TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, + (int) (data_length + length)); + break; + } + + /* skip any remaining data -- could be lots */ + INPUT_SYNC(cinfo); /* do before skip_input_data */ + if (length > 0) + (*cinfo->src->skip_input_data) (cinfo, (long) length); + + return TRUE; +} + +#endif /* SAVE_MARKERS_SUPPORTED */ + + +METHODDEF(boolean) +skip_variable (j_decompress_ptr cinfo) +/* Skip over an unknown or uninteresting variable-length marker */ +{ + INT32 length; + INPUT_VARS(cinfo); + + INPUT_2BYTES(cinfo, length, return FALSE); + length -= 2; + + TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length); + + INPUT_SYNC(cinfo); /* do before skip_input_data */ + if (length > 0) + (*cinfo->src->skip_input_data) (cinfo, (long) length); + + return TRUE; +} + + +/* + * Find the next JPEG marker, save it in cinfo->unread_marker. + * Returns FALSE if had to suspend before reaching a marker; + * in that case cinfo->unread_marker is unchanged. + * + * Note that the result might not be a valid marker code, + * but it will never be 0 or FF. + */ + +LOCAL(boolean) +next_marker (j_decompress_ptr cinfo) +{ + int c; + INPUT_VARS(cinfo); + + for (;;) { + INPUT_BYTE(cinfo, c, return FALSE); + /* Skip any non-FF bytes. + * This may look a bit inefficient, but it will not occur in a valid file. + * We sync after each discarded byte so that a suspending data source + * can discard the byte from its buffer. + */ + while (c != 0xFF) { + cinfo->marker->discarded_bytes++; + INPUT_SYNC(cinfo); + INPUT_BYTE(cinfo, c, return FALSE); + } + /* This loop swallows any duplicate FF bytes. Extra FFs are legal as + * pad bytes, so don't count them in discarded_bytes. We assume there + * will not be so many consecutive FF bytes as to overflow a suspending + * data source's input buffer. + */ + do { + INPUT_BYTE(cinfo, c, return FALSE); + } while (c == 0xFF); + if (c != 0) + break; /* found a valid marker, exit loop */ + /* Reach here if we found a stuffed-zero data sequence (FF/00). + * Discard it and loop back to try again. + */ + cinfo->marker->discarded_bytes += 2; + INPUT_SYNC(cinfo); + } + + if (cinfo->marker->discarded_bytes != 0) { + WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c); + cinfo->marker->discarded_bytes = 0; + } + + cinfo->unread_marker = c; + + INPUT_SYNC(cinfo); + return TRUE; +} + + +LOCAL(boolean) +first_marker (j_decompress_ptr cinfo) +/* Like next_marker, but used to obtain the initial SOI marker. */ +/* For this marker, we do not allow preceding garbage or fill; otherwise, + * we might well scan an entire input file before realizing it ain't JPEG. + * If an application wants to process non-JFIF files, it must seek to the + * SOI before calling the JPEG library. + */ +{ + int c, c2; + INPUT_VARS(cinfo); + + INPUT_BYTE(cinfo, c, return FALSE); + INPUT_BYTE(cinfo, c2, return FALSE); + if (c != 0xFF || c2 != (int) M_SOI) + ERREXIT2(cinfo, JERR_NO_SOI, c, c2); + + cinfo->unread_marker = c2; + + INPUT_SYNC(cinfo); + return TRUE; +} + + +/* + * Read markers until SOS or EOI. + * + * Returns same codes as are defined for jpeg_consume_input: + * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. + */ + +METHODDEF(int) +read_markers (j_decompress_ptr cinfo) +{ + /* Outer loop repeats once for each marker. */ + for (;;) { + /* Collect the marker proper, unless we already did. */ + /* NB: first_marker() enforces the requirement that SOI appear first. */ + if (cinfo->unread_marker == 0) { + if (! cinfo->marker->saw_SOI) { + if (! first_marker(cinfo)) + return JPEG_SUSPENDED; + } else { + if (! next_marker(cinfo)) + return JPEG_SUSPENDED; + } + } + /* At this point cinfo->unread_marker contains the marker code and the + * input point is just past the marker proper, but before any parameters. + * A suspension will cause us to return with this state still true. + */ + switch (cinfo->unread_marker) { + case M_SOI: + if (! get_soi(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_SOF0: /* Baseline */ + case M_SOF1: /* Extended sequential, Huffman */ + if (! get_sof(cinfo, FALSE, FALSE)) + return JPEG_SUSPENDED; + break; + + case M_SOF2: /* Progressive, Huffman */ + if (! get_sof(cinfo, TRUE, FALSE)) + return JPEG_SUSPENDED; + break; + + case M_SOF9: /* Extended sequential, arithmetic */ + if (! get_sof(cinfo, FALSE, TRUE)) + return JPEG_SUSPENDED; + break; + + case M_SOF10: /* Progressive, arithmetic */ + if (! get_sof(cinfo, TRUE, TRUE)) + return JPEG_SUSPENDED; + break; + + /* Currently unsupported SOFn types */ + case M_SOF3: /* Lossless, Huffman */ + case M_SOF5: /* Differential sequential, Huffman */ + case M_SOF6: /* Differential progressive, Huffman */ + case M_SOF7: /* Differential lossless, Huffman */ + case M_JPG: /* Reserved for JPEG extensions */ + case M_SOF11: /* Lossless, arithmetic */ + case M_SOF13: /* Differential sequential, arithmetic */ + case M_SOF14: /* Differential progressive, arithmetic */ + case M_SOF15: /* Differential lossless, arithmetic */ + ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker); + break; + + case M_SOS: + if (! get_sos(cinfo)) + return JPEG_SUSPENDED; + cinfo->unread_marker = 0; /* processed the marker */ + return JPEG_REACHED_SOS; + + case M_EOI: + TRACEMS(cinfo, 1, JTRC_EOI); + cinfo->unread_marker = 0; /* processed the marker */ + return JPEG_REACHED_EOI; + + case M_DAC: + if (! get_dac(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_DHT: + if (! get_dht(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_DQT: + if (! get_dqt(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_DRI: + if (! get_dri(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_APP0: + case M_APP1: + case M_APP2: + case M_APP3: + case M_APP4: + case M_APP5: + case M_APP6: + case M_APP7: + case M_APP8: + case M_APP9: + case M_APP10: + case M_APP11: + case M_APP12: + case M_APP13: + case M_APP14: + case M_APP15: + if (! (*((my_marker_ptr) cinfo->marker)->process_APPn[ + cinfo->unread_marker - (int) M_APP0]) (cinfo)) + return JPEG_SUSPENDED; + break; + + case M_COM: + if (! (*((my_marker_ptr) cinfo->marker)->process_COM) (cinfo)) + return JPEG_SUSPENDED; + break; + + case M_RST0: /* these are all parameterless */ + case M_RST1: + case M_RST2: + case M_RST3: + case M_RST4: + case M_RST5: + case M_RST6: + case M_RST7: + case M_TEM: + TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker); + break; + + case M_DNL: /* Ignore DNL ... perhaps the wrong thing */ + if (! skip_variable(cinfo)) + return JPEG_SUSPENDED; + break; + + default: /* must be DHP, EXP, JPGn, or RESn */ + /* For now, we treat the reserved markers as fatal errors since they are + * likely to be used to signal incompatible JPEG Part 3 extensions. + * Once the JPEG 3 version-number marker is well defined, this code + * ought to change! + */ + // ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker); + break; + } + /* Successfully processed marker, so reset state variable */ + cinfo->unread_marker = 0; + } /* end loop */ +} + + +/* + * Read a restart marker, which is expected to appear next in the datastream; + * if the marker is not there, take appropriate recovery action. + * Returns FALSE if suspension is required. + * + * This is called by the entropy decoder after it has read an appropriate + * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder + * has already read a marker from the data source. Under normal conditions + * cinfo->unread_marker will be reset to 0 before returning; if not reset, + * it holds a marker which the decoder will be unable to read past. + */ + +METHODDEF(boolean) +read_restart_marker (j_decompress_ptr cinfo) +{ + /* Obtain a marker unless we already did. */ + /* Note that next_marker will complain if it skips any data. */ + if (cinfo->unread_marker == 0) { + if (! next_marker(cinfo)) + return FALSE; + } + + if (cinfo->unread_marker == + ((int) M_RST0 + cinfo->marker->next_restart_num)) { + /* Normal case --- swallow the marker and let entropy decoder continue */ + TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num); + cinfo->unread_marker = 0; + } else { + /* Uh-oh, the restart markers have been messed up. */ + /* Let the data source manager determine how to resync. */ + if (! (*cinfo->src->resync_to_restart) (cinfo, + cinfo->marker->next_restart_num)) + return FALSE; + } + + /* Update next-restart state */ + cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7; + + return TRUE; +} + + +/* + * This is the default resync_to_restart method for data source managers + * to use if they don't have any better approach. Some data source managers + * may be able to back up, or may have additional knowledge about the data + * which permits a more intelligent recovery strategy; such managers would + * presumably supply their own resync method. + * + * read_restart_marker calls resync_to_restart if it finds a marker other than + * the restart marker it was expecting. (This code is *not* used unless + * a nonzero restart interval has been declared.) cinfo->unread_marker is + * the marker code actually found (might be anything, except 0 or FF). + * The desired restart marker number (0..7) is passed as a parameter. + * This routine is supposed to apply whatever error recovery strategy seems + * appropriate in order to position the input stream to the next data segment. + * Note that cinfo->unread_marker is treated as a marker appearing before + * the current data-source input point; usually it should be reset to zero + * before returning. + * Returns FALSE if suspension is required. + * + * This implementation is substantially constrained by wanting to treat the + * input as a data stream; this means we can't back up. Therefore, we have + * only the following actions to work with: + * 1. Simply discard the marker and let the entropy decoder resume at next + * byte of file. + * 2. Read forward until we find another marker, discarding intervening + * data. (In theory we could look ahead within the current bufferload, + * without having to discard data if we don't find the desired marker. + * This idea is not implemented here, in part because it makes behavior + * dependent on buffer size and chance buffer-boundary positions.) + * 3. Leave the marker unread (by failing to zero cinfo->unread_marker). + * This will cause the entropy decoder to process an empty data segment, + * inserting dummy zeroes, and then we will reprocess the marker. + * + * #2 is appropriate if we think the desired marker lies ahead, while #3 is + * appropriate if the found marker is a future restart marker (indicating + * that we have missed the desired restart marker, probably because it got + * corrupted). + * We apply #2 or #3 if the found marker is a restart marker no more than + * two counts behind or ahead of the expected one. We also apply #2 if the + * found marker is not a legal JPEG marker code (it's certainly bogus data). + * If the found marker is a restart marker more than 2 counts away, we do #1 + * (too much risk that the marker is erroneous; with luck we will be able to + * resync at some future point). + * For any valid non-restart JPEG marker, we apply #3. This keeps us from + * overrunning the end of a scan. An implementation limited to single-scan + * files might find it better to apply #2 for markers other than EOI, since + * any other marker would have to be bogus data in that case. + */ + +GLOBAL(boolean) +jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired) +{ + int marker = cinfo->unread_marker; + int action = 1; + + /* Always put up a warning. */ + WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired); + + /* Outer loop handles repeated decision after scanning forward. */ + for (;;) { + if (marker < (int) M_SOF0) + action = 2; /* invalid marker */ + else if (marker < (int) M_RST0 || marker > (int) M_RST7) + action = 3; /* valid non-restart marker */ + else { + if (marker == ((int) M_RST0 + ((desired+1) & 7)) || + marker == ((int) M_RST0 + ((desired+2) & 7))) + action = 3; /* one of the next two expected restarts */ + else if (marker == ((int) M_RST0 + ((desired-1) & 7)) || + marker == ((int) M_RST0 + ((desired-2) & 7))) + action = 2; /* a prior restart, so advance */ + else + action = 1; /* desired restart or too far away */ + } + TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action); + switch (action) { + case 1: + /* Discard marker and let entropy decoder resume processing. */ + cinfo->unread_marker = 0; + return TRUE; + case 2: + /* Scan to the next marker, and repeat the decision loop. */ + if (! next_marker(cinfo)) + return FALSE; + marker = cinfo->unread_marker; + break; + case 3: + /* Return without advancing past this marker. */ + /* Entropy decoder will be forced to process an empty segment. */ + return TRUE; + } + } /* end loop */ +} + + +/* + * Reset marker processing state to begin a fresh datastream. + */ + +METHODDEF(void) +reset_marker_reader (j_decompress_ptr cinfo) +{ + my_marker_ptr marker = (my_marker_ptr) cinfo->marker; + + cinfo->comp_info = NULL; /* until allocated by get_sof */ + cinfo->input_scan_number = 0; /* no SOS seen yet */ + cinfo->unread_marker = 0; /* no pending marker */ + marker->pub.saw_SOI = FALSE; /* set internal state too */ + marker->pub.saw_SOF = FALSE; + marker->pub.discarded_bytes = 0; + marker->cur_marker = NULL; +} + + +/* + * Initialize the marker reader module. + * This is called only once, when the decompression object is created. + */ + +GLOBAL(void) +jinit_marker_reader (j_decompress_ptr cinfo) +{ + my_marker_ptr marker; + int i; + + /* Create subobject in permanent pool */ + marker = (my_marker_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + SIZEOF(my_marker_reader)); + cinfo->marker = (struct jpeg_marker_reader *) marker; + /* Initialize public method pointers */ + marker->pub.reset_marker_reader = reset_marker_reader; + marker->pub.read_markers = read_markers; + marker->pub.read_restart_marker = read_restart_marker; + /* Initialize COM/APPn processing. + * By default, we examine and then discard APP0 and APP14, + * but simply discard COM and all other APPn. + */ + marker->process_COM = skip_variable; + marker->length_limit_COM = 0; + for (i = 0; i < 16; i++) { + marker->process_APPn[i] = skip_variable; + marker->length_limit_APPn[i] = 0; + } + marker->process_APPn[0] = get_interesting_appn; + marker->process_APPn[14] = get_interesting_appn; + /* Reset marker processing state */ + reset_marker_reader(cinfo); +} + + +/* + * Control saving of COM and APPn markers into marker_list. + */ + +#ifdef SAVE_MARKERS_SUPPORTED + +GLOBAL(void) +jpeg_save_markers (j_decompress_ptr cinfo, int marker_code, + unsigned int length_limit) +{ + my_marker_ptr marker = (my_marker_ptr) cinfo->marker; + long maxlength; + jpeg_marker_parser_method processor; + + /* Length limit mustn't be larger than what we can allocate + * (should only be a concern in a 16-bit environment). + */ + maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct); + if (((long) length_limit) > maxlength) + length_limit = (unsigned int) maxlength; + + /* Choose processor routine to use. + * APP0/APP14 have special requirements. + */ + if (length_limit) { + processor = save_marker; + /* If saving APP0/APP14, save at least enough for our internal use. */ + if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN) + length_limit = APP0_DATA_LEN; + else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN) + length_limit = APP14_DATA_LEN; + } else { + processor = skip_variable; + /* If discarding APP0/APP14, use our regular on-the-fly processor. */ + if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14) + processor = get_interesting_appn; + } + + if (marker_code == (int) M_COM) { + marker->process_COM = processor; + marker->length_limit_COM = length_limit; + } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) { + marker->process_APPn[marker_code - (int) M_APP0] = processor; + marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit; + } else + ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code); +} + +#endif /* SAVE_MARKERS_SUPPORTED */ + + +/* + * Install a special processing method for COM or APPn markers. + */ + +GLOBAL(void) +jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code, + jpeg_marker_parser_method routine) +{ + my_marker_ptr marker = (my_marker_ptr) cinfo->marker; + + if (marker_code == (int) M_COM) + marker->process_COM = routine; + else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) + marker->process_APPn[marker_code - (int) M_APP0] = routine; + else + ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code); +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdmaster.c b/SlnkDWFImpl/CxImage/jpeg/jdmaster.c new file mode 100644 index 0000000..eda4b3f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdmaster.c @@ -0,0 +1,557 @@ +/* + * jdmaster.c + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains master control logic for the JPEG decompressor. + * These routines are concerned with selecting the modules to be executed + * and with determining the number of passes and the work to be done in each + * pass. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Private state */ + +typedef struct { + struct jpeg_decomp_master pub; /* public fields */ + + int pass_number; /* # of passes completed */ + + boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */ + + /* Saved references to initialized quantizer modules, + * in case we need to switch modes. + */ + struct jpeg_color_quantizer * quantizer_1pass; + struct jpeg_color_quantizer * quantizer_2pass; +} my_decomp_master; + +typedef my_decomp_master * my_master_ptr; + + +/* + * Determine whether merged upsample/color conversion should be used. + * CRUCIAL: this must match the actual capabilities of jdmerge.c! + */ + +LOCAL(boolean) +use_merged_upsample (j_decompress_ptr cinfo) +{ +#ifdef UPSAMPLE_MERGING_SUPPORTED + /* Merging is the equivalent of plain box-filter upsampling */ + if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling) + return FALSE; + /* jdmerge.c only supports YCC=>RGB color conversion */ + if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 || + cinfo->out_color_space != JCS_RGB || + cinfo->out_color_components != RGB_PIXELSIZE) + return FALSE; + /* and it only handles 2h1v or 2h2v sampling ratios */ + if (cinfo->comp_info[0].h_samp_factor != 2 || + cinfo->comp_info[1].h_samp_factor != 1 || + cinfo->comp_info[2].h_samp_factor != 1 || + cinfo->comp_info[0].v_samp_factor > 2 || + cinfo->comp_info[1].v_samp_factor != 1 || + cinfo->comp_info[2].v_samp_factor != 1) + return FALSE; + /* furthermore, it doesn't work if we've scaled the IDCTs differently */ + if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size || + cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size || + cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size) + return FALSE; + /* ??? also need to test for upsample-time rescaling, when & if supported */ + return TRUE; /* by golly, it'll work... */ +#else + return FALSE; +#endif +} + + +/* + * Compute output image dimensions and related values. + * NOTE: this is exported for possible use by application. + * Hence it mustn't do anything that can't be done twice. + * Also note that it may be called before the master module is initialized! + */ + +GLOBAL(void) +jpeg_calc_output_dimensions (j_decompress_ptr cinfo) +/* Do computations that are needed before master selection phase */ +{ +#ifdef IDCT_SCALING_SUPPORTED + int ci; + jpeg_component_info *compptr; +#endif + + /* Prevent application from calling me at wrong times */ + if (cinfo->global_state != DSTATE_READY) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + +#ifdef IDCT_SCALING_SUPPORTED + + /* Compute actual output image dimensions and DCT scaling choices. */ + if (cinfo->scale_num * 8 <= cinfo->scale_denom) { + /* Provide 1/8 scaling */ + cinfo->output_width = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width, 8L); + cinfo->output_height = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height, 8L); + cinfo->min_DCT_scaled_size = 1; + } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) { + /* Provide 1/4 scaling */ + cinfo->output_width = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width, 4L); + cinfo->output_height = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height, 4L); + cinfo->min_DCT_scaled_size = 2; + } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) { + /* Provide 1/2 scaling */ + cinfo->output_width = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width, 2L); + cinfo->output_height = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height, 2L); + cinfo->min_DCT_scaled_size = 4; + } else { + /* Provide 1/1 scaling */ + cinfo->output_width = cinfo->image_width; + cinfo->output_height = cinfo->image_height; + cinfo->min_DCT_scaled_size = DCTSIZE; + } + /* In selecting the actual DCT scaling for each component, we try to + * scale up the chroma components via IDCT scaling rather than upsampling. + * This saves time if the upsampler gets to use 1:1 scaling. + * Note this code assumes that the supported DCT scalings are powers of 2. + */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + int ssize = cinfo->min_DCT_scaled_size; + while (ssize < DCTSIZE && + (compptr->h_samp_factor * ssize * 2 <= + cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) && + (compptr->v_samp_factor * ssize * 2 <= + cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) { + ssize = ssize * 2; + } + compptr->DCT_scaled_size = ssize; + } + + /* Recompute downsampled dimensions of components; + * application needs to know these if using raw downsampled data. + */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Size in samples, after IDCT scaling */ + compptr->downsampled_width = (JDIMENSION) + jdiv_round_up((long) cinfo->image_width * + (long) (compptr->h_samp_factor * compptr->DCT_scaled_size), + (long) (cinfo->max_h_samp_factor * DCTSIZE)); + compptr->downsampled_height = (JDIMENSION) + jdiv_round_up((long) cinfo->image_height * + (long) (compptr->v_samp_factor * compptr->DCT_scaled_size), + (long) (cinfo->max_v_samp_factor * DCTSIZE)); + } + +#else /* !IDCT_SCALING_SUPPORTED */ + + /* Hardwire it to "no scaling" */ + cinfo->output_width = cinfo->image_width; + cinfo->output_height = cinfo->image_height; + /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE, + * and has computed unscaled downsampled_width and downsampled_height. + */ + +#endif /* IDCT_SCALING_SUPPORTED */ + + /* Report number of components in selected colorspace. */ + /* Probably this should be in the color conversion module... */ + switch (cinfo->out_color_space) { + case JCS_GRAYSCALE: + cinfo->out_color_components = 1; + break; + case JCS_RGB: +#if RGB_PIXELSIZE != 3 + cinfo->out_color_components = RGB_PIXELSIZE; + break; +#endif /* else share code with YCbCr */ + case JCS_YCbCr: + cinfo->out_color_components = 3; + break; + case JCS_CMYK: + case JCS_YCCK: + cinfo->out_color_components = 4; + break; + default: /* else must be same colorspace as in file */ + cinfo->out_color_components = cinfo->num_components; + break; + } + cinfo->output_components = (cinfo->quantize_colors ? 1 : + cinfo->out_color_components); + + /* See if upsampler will want to emit more than one row at a time */ + if (use_merged_upsample(cinfo)) + cinfo->rec_outbuf_height = cinfo->max_v_samp_factor; + else + cinfo->rec_outbuf_height = 1; +} + + +/* + * Several decompression processes need to range-limit values to the range + * 0..MAXJSAMPLE; the input value may fall somewhat outside this range + * due to noise introduced by quantization, roundoff error, etc. These + * processes are inner loops and need to be as fast as possible. On most + * machines, particularly CPUs with pipelines or instruction prefetch, + * a (subscript-check-less) C table lookup + * x = sample_range_limit[x]; + * is faster than explicit tests + * if (x < 0) x = 0; + * else if (x > MAXJSAMPLE) x = MAXJSAMPLE; + * These processes all use a common table prepared by the routine below. + * + * For most steps we can mathematically guarantee that the initial value + * of x is within MAXJSAMPLE+1 of the legal range, so a table running from + * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial + * limiting step (just after the IDCT), a wildly out-of-range value is + * possible if the input data is corrupt. To avoid any chance of indexing + * off the end of memory and getting a bad-pointer trap, we perform the + * post-IDCT limiting thus: + * x = range_limit[x & MASK]; + * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit + * samples. Under normal circumstances this is more than enough range and + * a correct output will be generated; with bogus input data the mask will + * cause wraparound, and we will safely generate a bogus-but-in-range output. + * For the post-IDCT step, we want to convert the data from signed to unsigned + * representation by adding CENTERJSAMPLE at the same time that we limit it. + * So the post-IDCT limiting table ends up looking like this: + * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE, + * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times), + * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times), + * 0,1,...,CENTERJSAMPLE-1 + * Negative inputs select values from the upper half of the table after + * masking. + * + * We can save some space by overlapping the start of the post-IDCT table + * with the simpler range limiting table. The post-IDCT table begins at + * sample_range_limit + CENTERJSAMPLE. + * + * Note that the table is allocated in near data space on PCs; it's small + * enough and used often enough to justify this. + */ + +LOCAL(void) +prepare_range_limit_table (j_decompress_ptr cinfo) +/* Allocate and fill in the sample_range_limit table */ +{ + JSAMPLE * table; + int i; + + table = (JSAMPLE *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE)); + table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */ + cinfo->sample_range_limit = table; + /* First segment of "simple" table: limit[x] = 0 for x < 0 */ + MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE)); + /* Main part of "simple" table: limit[x] = x */ + for (i = 0; i <= MAXJSAMPLE; i++) + table[i] = (JSAMPLE) i; + table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */ + /* End of simple table, rest of first half of post-IDCT table */ + for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++) + table[i] = MAXJSAMPLE; + /* Second half of post-IDCT table */ + MEMZERO(table + (2 * (MAXJSAMPLE+1)), + (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE)); + MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE), + cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE)); +} + + +/* + * Master selection of decompression modules. + * This is done once at jpeg_start_decompress time. We determine + * which modules will be used and give them appropriate initialization calls. + * We also initialize the decompressor input side to begin consuming data. + * + * Since jpeg_read_header has finished, we know what is in the SOF + * and (first) SOS markers. We also have all the application parameter + * settings. + */ + +LOCAL(void) +master_selection (j_decompress_ptr cinfo) +{ + my_master_ptr master = (my_master_ptr) cinfo->master; + boolean use_c_buffer; + long samplesperrow; + JDIMENSION jd_samplesperrow; + + /* Initialize dimensions and other stuff */ + jpeg_calc_output_dimensions(cinfo); + prepare_range_limit_table(cinfo); + + /* Width of an output scanline must be representable as JDIMENSION. */ + samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components; + jd_samplesperrow = (JDIMENSION) samplesperrow; + if ((long) jd_samplesperrow != samplesperrow) + ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); + + /* Initialize my private state */ + master->pass_number = 0; + master->using_merged_upsample = use_merged_upsample(cinfo); + + /* Color quantizer selection */ + master->quantizer_1pass = NULL; + master->quantizer_2pass = NULL; + /* No mode changes if not using buffered-image mode. */ + if (! cinfo->quantize_colors || ! cinfo->buffered_image) { + cinfo->enable_1pass_quant = FALSE; + cinfo->enable_external_quant = FALSE; + cinfo->enable_2pass_quant = FALSE; + } + if (cinfo->quantize_colors) { + if (cinfo->raw_data_out) + ERREXIT(cinfo, JERR_NOTIMPL); + /* 2-pass quantizer only works in 3-component color space. */ + if (cinfo->out_color_components != 3) { + cinfo->enable_1pass_quant = TRUE; + cinfo->enable_external_quant = FALSE; + cinfo->enable_2pass_quant = FALSE; + cinfo->colormap = NULL; + } else if (cinfo->colormap != NULL) { + cinfo->enable_external_quant = TRUE; + } else if (cinfo->two_pass_quantize) { + cinfo->enable_2pass_quant = TRUE; + } else { + cinfo->enable_1pass_quant = TRUE; + } + + if (cinfo->enable_1pass_quant) { +#ifdef QUANT_1PASS_SUPPORTED + jinit_1pass_quantizer(cinfo); + master->quantizer_1pass = cinfo->cquantize; +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } + + /* We use the 2-pass code to map to external colormaps. */ + if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) { +#ifdef QUANT_2PASS_SUPPORTED + jinit_2pass_quantizer(cinfo); + master->quantizer_2pass = cinfo->cquantize; +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } + /* If both quantizers are initialized, the 2-pass one is left active; + * this is necessary for starting with quantization to an external map. + */ + } + + /* Post-processing: in particular, color conversion first */ + if (! cinfo->raw_data_out) { + if (master->using_merged_upsample) { +#ifdef UPSAMPLE_MERGING_SUPPORTED + jinit_merged_upsampler(cinfo); /* does color conversion too */ +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else { + jinit_color_deconverter(cinfo); + jinit_upsampler(cinfo); + } + jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant); + } + /* Inverse DCT */ + jinit_inverse_dct(cinfo); + /* Entropy decoding: either Huffman or arithmetic coding. */ + if (cinfo->arith_code) { + ERREXIT(cinfo, JERR_ARITH_NOTIMPL); + } else { + if (cinfo->progressive_mode) { +#ifdef D_PROGRESSIVE_SUPPORTED + jinit_phuff_decoder(cinfo); +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else + jinit_huff_decoder(cinfo); + } + + /* Initialize principal buffer controllers. */ + use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image; + jinit_d_coef_controller(cinfo, use_c_buffer); + + if (! cinfo->raw_data_out) + jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */); + + /* We can now tell the memory manager to allocate virtual arrays. */ + (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); + + /* Initialize input side of decompressor to consume first scan. */ + (*cinfo->inputctl->start_input_pass) (cinfo); + +#ifdef D_MULTISCAN_FILES_SUPPORTED + /* If jpeg_start_decompress will read the whole file, initialize + * progress monitoring appropriately. The input step is counted + * as one pass. + */ + if (cinfo->progress != NULL && ! cinfo->buffered_image && + cinfo->inputctl->has_multiple_scans) { + int nscans; + /* Estimate number of scans to set pass_limit. */ + if (cinfo->progressive_mode) { + /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ + nscans = 2 + 3 * cinfo->num_components; + } else { + /* For a nonprogressive multiscan file, estimate 1 scan per component. */ + nscans = cinfo->num_components; + } + cinfo->progress->pass_counter = 0L; + cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans; + cinfo->progress->completed_passes = 0; + cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2); + /* Count the input pass as done */ + master->pass_number++; + } +#endif /* D_MULTISCAN_FILES_SUPPORTED */ +} + + +/* + * Per-pass setup. + * This is called at the beginning of each output pass. We determine which + * modules will be active during this pass and give them appropriate + * start_pass calls. We also set is_dummy_pass to indicate whether this + * is a "real" output pass or a dummy pass for color quantization. + * (In the latter case, jdapistd.c will crank the pass to completion.) + */ + +METHODDEF(void) +prepare_for_output_pass (j_decompress_ptr cinfo) +{ + my_master_ptr master = (my_master_ptr) cinfo->master; + + if (master->pub.is_dummy_pass) { +#ifdef QUANT_2PASS_SUPPORTED + /* Final pass of 2-pass quantization */ + master->pub.is_dummy_pass = FALSE; + (*cinfo->cquantize->start_pass) (cinfo, FALSE); + (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST); + (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST); +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif /* QUANT_2PASS_SUPPORTED */ + } else { + if (cinfo->quantize_colors && cinfo->colormap == NULL) { + /* Select new quantization method */ + if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) { + cinfo->cquantize = master->quantizer_2pass; + master->pub.is_dummy_pass = TRUE; + } else if (cinfo->enable_1pass_quant) { + cinfo->cquantize = master->quantizer_1pass; + } else { + ERREXIT(cinfo, JERR_MODE_CHANGE); + } + } + (*cinfo->idct->start_pass) (cinfo); + (*cinfo->coef->start_output_pass) (cinfo); + if (! cinfo->raw_data_out) { + if (! master->using_merged_upsample) + (*cinfo->cconvert->start_pass) (cinfo); + (*cinfo->upsample->start_pass) (cinfo); + if (cinfo->quantize_colors) + (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass); + (*cinfo->post->start_pass) (cinfo, + (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU)); + (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU); + } + } + + /* Set up progress monitor's pass info if present */ + if (cinfo->progress != NULL) { + cinfo->progress->completed_passes = master->pass_number; + cinfo->progress->total_passes = master->pass_number + + (master->pub.is_dummy_pass ? 2 : 1); + /* In buffered-image mode, we assume one more output pass if EOI not + * yet reached, but no more passes if EOI has been reached. + */ + if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) { + cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1); + } + } +} + + +/* + * Finish up at end of an output pass. + */ + +METHODDEF(void) +finish_output_pass (j_decompress_ptr cinfo) +{ + my_master_ptr master = (my_master_ptr) cinfo->master; + + if (cinfo->quantize_colors) + (*cinfo->cquantize->finish_pass) (cinfo); + master->pass_number++; +} + + +#ifdef D_MULTISCAN_FILES_SUPPORTED + +/* + * Switch to a new external colormap between output passes. + */ + +GLOBAL(void) +jpeg_new_colormap (j_decompress_ptr cinfo) +{ + my_master_ptr master = (my_master_ptr) cinfo->master; + + /* Prevent application from calling me at wrong times */ + if (cinfo->global_state != DSTATE_BUFIMAGE) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + + if (cinfo->quantize_colors && cinfo->enable_external_quant && + cinfo->colormap != NULL) { + /* Select 2-pass quantizer for external colormap use */ + cinfo->cquantize = master->quantizer_2pass; + /* Notify quantizer of colormap change */ + (*cinfo->cquantize->new_color_map) (cinfo); + master->pub.is_dummy_pass = FALSE; /* just in case */ + } else + ERREXIT(cinfo, JERR_MODE_CHANGE); +} + +#endif /* D_MULTISCAN_FILES_SUPPORTED */ + + +/* + * Initialize master decompression control and select active modules. + * This is performed at the start of jpeg_start_decompress. + */ + +GLOBAL(void) +jinit_master_decompress (j_decompress_ptr cinfo) +{ + my_master_ptr master; + + master = (my_master_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_decomp_master)); + cinfo->master = (struct jpeg_decomp_master *) master; + master->pub.prepare_for_output_pass = prepare_for_output_pass; + master->pub.finish_output_pass = finish_output_pass; + + master->pub.is_dummy_pass = FALSE; + + master_selection(cinfo); +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdmerge.c b/SlnkDWFImpl/CxImage/jpeg/jdmerge.c new file mode 100644 index 0000000..9e3a595 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdmerge.c @@ -0,0 +1,400 @@ +/* + * jdmerge.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains code for merged upsampling/color conversion. + * + * This file combines functions from jdsample.c and jdcolor.c; + * read those files first to understand what's going on. + * + * When the chroma components are to be upsampled by simple replication + * (ie, box filtering), we can save some work in color conversion by + * calculating all the output pixels corresponding to a pair of chroma + * samples at one time. In the conversion equations + * R = Y + K1 * Cr + * G = Y + K2 * Cb + K3 * Cr + * B = Y + K4 * Cb + * only the Y term varies among the group of pixels corresponding to a pair + * of chroma samples, so the rest of the terms can be calculated just once. + * At typical sampling ratios, this eliminates half or three-quarters of the + * multiplications needed for color conversion. + * + * This file currently provides implementations for the following cases: + * YCbCr => RGB color conversion only. + * Sampling ratios of 2h1v or 2h2v. + * No scaling needed at upsample time. + * Corner-aligned (non-CCIR601) sampling alignment. + * Other special cases could be added, but in most applications these are + * the only common cases. (For uncommon cases we fall back on the more + * general code in jdsample.c and jdcolor.c.) + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + +#ifdef UPSAMPLE_MERGING_SUPPORTED + + +/* Private subobject */ + +typedef struct { + struct jpeg_upsampler pub; /* public fields */ + + /* Pointer to routine to do actual upsampling/conversion of one row group */ + JMETHOD(void, upmethod, (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr, + JSAMPARRAY output_buf)); + + /* Private state for YCC->RGB conversion */ + int * Cr_r_tab; /* => table for Cr to R conversion */ + int * Cb_b_tab; /* => table for Cb to B conversion */ + INT32 * Cr_g_tab; /* => table for Cr to G conversion */ + INT32 * Cb_g_tab; /* => table for Cb to G conversion */ + + /* For 2:1 vertical sampling, we produce two output rows at a time. + * We need a "spare" row buffer to hold the second output row if the + * application provides just a one-row buffer; we also use the spare + * to discard the dummy last row if the image height is odd. + */ + JSAMPROW spare_row; + boolean spare_full; /* T if spare buffer is occupied */ + + JDIMENSION out_row_width; /* samples per output row */ + JDIMENSION rows_to_go; /* counts rows remaining in image */ +} my_upsampler; + +typedef my_upsampler * my_upsample_ptr; + +#define SCALEBITS 16 /* speediest right-shift on some machines */ +#define ONE_HALF ((INT32) 1 << (SCALEBITS-1)) +#define FIX(x) ((INT32) ((x) * (1L<RGB colorspace conversion. + * This is taken directly from jdcolor.c; see that file for more info. + */ + +LOCAL(void) +build_ycc_rgb_table (j_decompress_ptr cinfo) +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + int i; + INT32 x; + SHIFT_TEMPS + + upsample->Cr_r_tab = (int *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (MAXJSAMPLE+1) * SIZEOF(int)); + upsample->Cb_b_tab = (int *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (MAXJSAMPLE+1) * SIZEOF(int)); + upsample->Cr_g_tab = (INT32 *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (MAXJSAMPLE+1) * SIZEOF(INT32)); + upsample->Cb_g_tab = (INT32 *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (MAXJSAMPLE+1) * SIZEOF(INT32)); + + for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) { + /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ + /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ + /* Cr=>R value is nearest int to 1.40200 * x */ + upsample->Cr_r_tab[i] = (int) + RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS); + /* Cb=>B value is nearest int to 1.77200 * x */ + upsample->Cb_b_tab[i] = (int) + RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS); + /* Cr=>G value is scaled-up -0.71414 * x */ + upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x; + /* Cb=>G value is scaled-up -0.34414 * x */ + /* We also add in ONE_HALF so that need not do it in inner loop */ + upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF; + } +} + + +/* + * Initialize for an upsampling pass. + */ + +METHODDEF(void) +start_pass_merged_upsample (j_decompress_ptr cinfo) +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + + /* Mark the spare buffer empty */ + upsample->spare_full = FALSE; + /* Initialize total-height counter for detecting bottom of image */ + upsample->rows_to_go = cinfo->output_height; +} + + +/* + * Control routine to do upsampling (and color conversion). + * + * The control routine just handles the row buffering considerations. + */ + +METHODDEF(void) +merged_2v_upsample (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +/* 2:1 vertical sampling case: may need a spare row. */ +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + JSAMPROW work_ptrs[2]; + JDIMENSION num_rows; /* number of rows returned to caller */ + + if (upsample->spare_full) { + /* If we have a spare row saved from a previous cycle, just return it. */ + jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0, + 1, upsample->out_row_width); + num_rows = 1; + upsample->spare_full = FALSE; + } else { + /* Figure number of rows to return to caller. */ + num_rows = 2; + /* Not more than the distance to the end of the image. */ + if (num_rows > upsample->rows_to_go) + num_rows = upsample->rows_to_go; + /* And not more than what the client can accept: */ + out_rows_avail -= *out_row_ctr; + if (num_rows > out_rows_avail) + num_rows = out_rows_avail; + /* Create output pointer array for upsampler. */ + work_ptrs[0] = output_buf[*out_row_ctr]; + if (num_rows > 1) { + work_ptrs[1] = output_buf[*out_row_ctr + 1]; + } else { + work_ptrs[1] = upsample->spare_row; + upsample->spare_full = TRUE; + } + /* Now do the upsampling. */ + (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs); + } + + /* Adjust counts */ + *out_row_ctr += num_rows; + upsample->rows_to_go -= num_rows; + /* When the buffer is emptied, declare this input row group consumed */ + if (! upsample->spare_full) + (*in_row_group_ctr)++; +} + + +METHODDEF(void) +merged_1v_upsample (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +/* 1:1 vertical sampling case: much easier, never need a spare row. */ +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + + /* Just do the upsampling. */ + (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, + output_buf + *out_row_ctr); + /* Adjust counts */ + (*out_row_ctr)++; + (*in_row_group_ctr)++; +} + + +/* + * These are the routines invoked by the control routines to do + * the actual upsampling/conversion. One row group is processed per call. + * + * Note: since we may be writing directly into application-supplied buffers, + * we have to be honest about the output width; we can't assume the buffer + * has been rounded up to an even width. + */ + + +/* + * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical. + */ + +METHODDEF(void) +h2v1_merged_upsample (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr, + JSAMPARRAY output_buf) +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + register int y, cred, cgreen, cblue; + int cb, cr; + register JSAMPROW outptr; + JSAMPROW inptr0, inptr1, inptr2; + JDIMENSION col; + /* copy these pointers into registers if possible */ + register JSAMPLE * range_limit = cinfo->sample_range_limit; + int * Crrtab = upsample->Cr_r_tab; + int * Cbbtab = upsample->Cb_b_tab; + INT32 * Crgtab = upsample->Cr_g_tab; + INT32 * Cbgtab = upsample->Cb_g_tab; + SHIFT_TEMPS + + inptr0 = input_buf[0][in_row_group_ctr]; + inptr1 = input_buf[1][in_row_group_ctr]; + inptr2 = input_buf[2][in_row_group_ctr]; + outptr = output_buf[0]; + /* Loop for each pair of output pixels */ + for (col = cinfo->output_width >> 1; col > 0; col--) { + /* Do the chroma part of the calculation */ + cb = GETJSAMPLE(*inptr1++); + cr = GETJSAMPLE(*inptr2++); + cred = Crrtab[cr]; + cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS); + cblue = Cbbtab[cb]; + /* Fetch 2 Y values and emit 2 pixels */ + y = GETJSAMPLE(*inptr0++); + outptr[RGB_RED] = range_limit[y + cred]; + outptr[RGB_GREEN] = range_limit[y + cgreen]; + outptr[RGB_BLUE] = range_limit[y + cblue]; + outptr += RGB_PIXELSIZE; + y = GETJSAMPLE(*inptr0++); + outptr[RGB_RED] = range_limit[y + cred]; + outptr[RGB_GREEN] = range_limit[y + cgreen]; + outptr[RGB_BLUE] = range_limit[y + cblue]; + outptr += RGB_PIXELSIZE; + } + /* If image width is odd, do the last output column separately */ + if (cinfo->output_width & 1) { + cb = GETJSAMPLE(*inptr1); + cr = GETJSAMPLE(*inptr2); + cred = Crrtab[cr]; + cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS); + cblue = Cbbtab[cb]; + y = GETJSAMPLE(*inptr0); + outptr[RGB_RED] = range_limit[y + cred]; + outptr[RGB_GREEN] = range_limit[y + cgreen]; + outptr[RGB_BLUE] = range_limit[y + cblue]; + } +} + + +/* + * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical. + */ + +METHODDEF(void) +h2v2_merged_upsample (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr, + JSAMPARRAY output_buf) +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + register int y, cred, cgreen, cblue; + int cb, cr; + register JSAMPROW outptr0, outptr1; + JSAMPROW inptr00, inptr01, inptr1, inptr2; + JDIMENSION col; + /* copy these pointers into registers if possible */ + register JSAMPLE * range_limit = cinfo->sample_range_limit; + int * Crrtab = upsample->Cr_r_tab; + int * Cbbtab = upsample->Cb_b_tab; + INT32 * Crgtab = upsample->Cr_g_tab; + INT32 * Cbgtab = upsample->Cb_g_tab; + SHIFT_TEMPS + + inptr00 = input_buf[0][in_row_group_ctr*2]; + inptr01 = input_buf[0][in_row_group_ctr*2 + 1]; + inptr1 = input_buf[1][in_row_group_ctr]; + inptr2 = input_buf[2][in_row_group_ctr]; + outptr0 = output_buf[0]; + outptr1 = output_buf[1]; + /* Loop for each group of output pixels */ + for (col = cinfo->output_width >> 1; col > 0; col--) { + /* Do the chroma part of the calculation */ + cb = GETJSAMPLE(*inptr1++); + cr = GETJSAMPLE(*inptr2++); + cred = Crrtab[cr]; + cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS); + cblue = Cbbtab[cb]; + /* Fetch 4 Y values and emit 4 pixels */ + y = GETJSAMPLE(*inptr00++); + outptr0[RGB_RED] = range_limit[y + cred]; + outptr0[RGB_GREEN] = range_limit[y + cgreen]; + outptr0[RGB_BLUE] = range_limit[y + cblue]; + outptr0 += RGB_PIXELSIZE; + y = GETJSAMPLE(*inptr00++); + outptr0[RGB_RED] = range_limit[y + cred]; + outptr0[RGB_GREEN] = range_limit[y + cgreen]; + outptr0[RGB_BLUE] = range_limit[y + cblue]; + outptr0 += RGB_PIXELSIZE; + y = GETJSAMPLE(*inptr01++); + outptr1[RGB_RED] = range_limit[y + cred]; + outptr1[RGB_GREEN] = range_limit[y + cgreen]; + outptr1[RGB_BLUE] = range_limit[y + cblue]; + outptr1 += RGB_PIXELSIZE; + y = GETJSAMPLE(*inptr01++); + outptr1[RGB_RED] = range_limit[y + cred]; + outptr1[RGB_GREEN] = range_limit[y + cgreen]; + outptr1[RGB_BLUE] = range_limit[y + cblue]; + outptr1 += RGB_PIXELSIZE; + } + /* If image width is odd, do the last output column separately */ + if (cinfo->output_width & 1) { + cb = GETJSAMPLE(*inptr1); + cr = GETJSAMPLE(*inptr2); + cred = Crrtab[cr]; + cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS); + cblue = Cbbtab[cb]; + y = GETJSAMPLE(*inptr00); + outptr0[RGB_RED] = range_limit[y + cred]; + outptr0[RGB_GREEN] = range_limit[y + cgreen]; + outptr0[RGB_BLUE] = range_limit[y + cblue]; + y = GETJSAMPLE(*inptr01); + outptr1[RGB_RED] = range_limit[y + cred]; + outptr1[RGB_GREEN] = range_limit[y + cgreen]; + outptr1[RGB_BLUE] = range_limit[y + cblue]; + } +} + + +/* + * Module initialization routine for merged upsampling/color conversion. + * + * NB: this is called under the conditions determined by use_merged_upsample() + * in jdmaster.c. That routine MUST correspond to the actual capabilities + * of this module; no safety checks are made here. + */ + +GLOBAL(void) +jinit_merged_upsampler (j_decompress_ptr cinfo) +{ + my_upsample_ptr upsample; + + upsample = (my_upsample_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_upsampler)); + cinfo->upsample = (struct jpeg_upsampler *) upsample; + upsample->pub.start_pass = start_pass_merged_upsample; + upsample->pub.need_context_rows = FALSE; + + upsample->out_row_width = cinfo->output_width * cinfo->out_color_components; + + if (cinfo->max_v_samp_factor == 2) { + upsample->pub.upsample = merged_2v_upsample; + upsample->upmethod = h2v2_merged_upsample; + /* Allocate a spare row buffer */ + upsample->spare_row = (JSAMPROW) + (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, + (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE))); + } else { + upsample->pub.upsample = merged_1v_upsample; + upsample->upmethod = h2v1_merged_upsample; + /* No spare row needed */ + upsample->spare_row = NULL; + } + + build_ycc_rgb_table(cinfo); +} + +#endif /* UPSAMPLE_MERGING_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jdphuff.c b/SlnkDWFImpl/CxImage/jpeg/jdphuff.c new file mode 100644 index 0000000..2404743 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdphuff.c @@ -0,0 +1,668 @@ +/* + * jdphuff.c + * + * Copyright (C) 1995-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains Huffman entropy decoding routines for progressive JPEG. + * + * Much of the complexity here has to do with supporting input suspension. + * If the data source module demands suspension, we want to be able to back + * up to the start of the current MCU. To do this, we copy state variables + * into local working storage, and update them back to the permanent + * storage only upon successful completion of an MCU. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdhuff.h" /* Declarations shared with jdhuff.c */ + + +#ifdef D_PROGRESSIVE_SUPPORTED + +/* + * Expanded entropy decoder object for progressive Huffman decoding. + * + * The savable_state subrecord contains fields that change within an MCU, + * but must not be updated permanently until we complete the MCU. + */ + +typedef struct { + unsigned int EOBRUN; /* remaining EOBs in EOBRUN */ + int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ +} savable_state; + +/* This macro is to work around compilers with missing or broken + * structure assignment. You'll need to fix this code if you have + * such a compiler and you change MAX_COMPS_IN_SCAN. + */ + +#ifndef NO_STRUCT_ASSIGN +#define ASSIGN_STATE(dest,src) ((dest) = (src)) +#else +#if MAX_COMPS_IN_SCAN == 4 +#define ASSIGN_STATE(dest,src) \ + ((dest).EOBRUN = (src).EOBRUN, \ + (dest).last_dc_val[0] = (src).last_dc_val[0], \ + (dest).last_dc_val[1] = (src).last_dc_val[1], \ + (dest).last_dc_val[2] = (src).last_dc_val[2], \ + (dest).last_dc_val[3] = (src).last_dc_val[3]) +#endif +#endif + + +typedef struct { + struct jpeg_entropy_decoder pub; /* public fields */ + + /* These fields are loaded into local variables at start of each MCU. + * In case of suspension, we exit WITHOUT updating them. + */ + bitread_perm_state bitstate; /* Bit buffer at start of MCU */ + savable_state saved; /* Other state at start of MCU */ + + /* These fields are NOT loaded into local working state. */ + unsigned int restarts_to_go; /* MCUs left in this restart interval */ + + /* Pointers to derived tables (these workspaces have image lifespan) */ + d_derived_tbl * derived_tbls[NUM_HUFF_TBLS]; + + d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */ +} phuff_entropy_decoder; + +typedef phuff_entropy_decoder * phuff_entropy_ptr; + +/* Forward declarations */ +METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo, + JBLOCKROW *MCU_data)); +METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo, + JBLOCKROW *MCU_data)); + + +/* + * Initialize for a Huffman-compressed scan. + */ + +METHODDEF(void) +start_pass_phuff_decoder (j_decompress_ptr cinfo) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + boolean is_DC_band, bad; + int ci, coefi, tbl; + int *coef_bit_ptr; + jpeg_component_info * compptr; + + is_DC_band = (cinfo->Ss == 0); + + /* Validate scan parameters */ + bad = FALSE; + if (is_DC_band) { + if (cinfo->Se != 0) + bad = TRUE; + } else { + /* need not check Ss/Se < 0 since they came from unsigned bytes */ + if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2) + bad = TRUE; + /* AC scans may have only one component */ + if (cinfo->comps_in_scan != 1) + bad = TRUE; + } + if (cinfo->Ah != 0) { + /* Successive approximation refinement scan: must have Al = Ah-1. */ + if (cinfo->Al != cinfo->Ah-1) + bad = TRUE; + } + if (cinfo->Al > 13) /* need not check for < 0 */ + bad = TRUE; + /* Arguably the maximum Al value should be less than 13 for 8-bit precision, + * but the spec doesn't say so, and we try to be liberal about what we + * accept. Note: large Al values could result in out-of-range DC + * coefficients during early scans, leading to bizarre displays due to + * overflows in the IDCT math. But we won't crash. + */ + if (bad) + ERREXIT4(cinfo, JERR_BAD_PROGRESSION, + cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al); + /* Update progression status, and verify that scan order is legal. + * Note that inter-scan inconsistencies are treated as warnings + * not fatal errors ... not clear if this is right way to behave. + */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + int cindex = cinfo->cur_comp_info[ci]->component_index; + coef_bit_ptr = & cinfo->coef_bits[cindex][0]; + if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */ + WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0); + for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) { + int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi]; + if (cinfo->Ah != expected) + WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi); + coef_bit_ptr[coefi] = cinfo->Al; + } + } + + /* Select MCU decoding routine */ + if (cinfo->Ah == 0) { + if (is_DC_band) + entropy->pub.decode_mcu = decode_mcu_DC_first; + else + entropy->pub.decode_mcu = decode_mcu_AC_first; + } else { + if (is_DC_band) + entropy->pub.decode_mcu = decode_mcu_DC_refine; + else + entropy->pub.decode_mcu = decode_mcu_AC_refine; + } + + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { + compptr = cinfo->cur_comp_info[ci]; + /* Make sure requested tables are present, and compute derived tables. + * We may build same derived table more than once, but it's not expensive. + */ + if (is_DC_band) { + if (cinfo->Ah == 0) { /* DC refinement needs no table */ + tbl = compptr->dc_tbl_no; + jpeg_make_d_derived_tbl(cinfo, TRUE, tbl, + & entropy->derived_tbls[tbl]); + } + } else { + tbl = compptr->ac_tbl_no; + jpeg_make_d_derived_tbl(cinfo, FALSE, tbl, + & entropy->derived_tbls[tbl]); + /* remember the single active table */ + entropy->ac_derived_tbl = entropy->derived_tbls[tbl]; + } + /* Initialize DC predictions to 0 */ + entropy->saved.last_dc_val[ci] = 0; + } + + /* Initialize bitread state variables */ + entropy->bitstate.bits_left = 0; + entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ + entropy->pub.insufficient_data = FALSE; + + /* Initialize private state variables */ + entropy->saved.EOBRUN = 0; + + /* Initialize restart counter */ + entropy->restarts_to_go = cinfo->restart_interval; +} + + +/* + * Figure F.12: extend sign bit. + * On some machines, a shift and add will be faster than a table lookup. + */ + +#ifdef AVOID_TABLES + +#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x)) + +#else + +#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x)) + +static const int extend_test[16] = /* entry n is 2**(n-1) */ + { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, + 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 }; + +static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */ + { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1, + ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1, + ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1, + ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 }; + +#endif /* AVOID_TABLES */ + + +/* + * Check for a restart marker & resynchronize decoder. + * Returns FALSE if must suspend. + */ + +LOCAL(boolean) +process_restart (j_decompress_ptr cinfo) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + int ci; + + /* Throw away any unused bits remaining in bit buffer; */ + /* include any full bytes in next_marker's count of discarded bytes */ + cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8; + entropy->bitstate.bits_left = 0; + + /* Advance past the RSTn marker */ + if (! (*cinfo->marker->read_restart_marker) (cinfo)) + return FALSE; + + /* Re-initialize DC predictions to 0 */ + for (ci = 0; ci < cinfo->comps_in_scan; ci++) + entropy->saved.last_dc_val[ci] = 0; + /* Re-init EOB run count, too */ + entropy->saved.EOBRUN = 0; + + /* Reset restart counter */ + entropy->restarts_to_go = cinfo->restart_interval; + + /* Reset out-of-data flag, unless read_restart_marker left us smack up + * against a marker. In that case we will end up treating the next data + * segment as empty, and we can avoid producing bogus output pixels by + * leaving the flag set. + */ + if (cinfo->unread_marker == 0) + entropy->pub.insufficient_data = FALSE; + + return TRUE; +} + + +/* + * Huffman MCU decoding. + * Each of these routines decodes and returns one MCU's worth of + * Huffman-compressed coefficients. + * The coefficients are reordered from zigzag order into natural array order, + * but are not dequantized. + * + * The i'th block of the MCU is stored into the block pointed to by + * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER. + * + * We return FALSE if data source requested suspension. In that case no + * changes have been made to permanent state. (Exception: some output + * coefficients may already have been assigned. This is harmless for + * spectral selection, since we'll just re-assign them on the next call. + * Successive approximation AC refinement has to be more careful, however.) + */ + +/* + * MCU decoding for DC initial scan (either spectral selection, + * or first pass of successive approximation). + */ + +METHODDEF(boolean) +decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + int Al = cinfo->Al; + register int s, r; + int blkn, ci; + JBLOCKROW block; + BITREAD_STATE_VARS; + savable_state state; + d_derived_tbl * tbl; + jpeg_component_info * compptr; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) + if (! process_restart(cinfo)) + return FALSE; + } + + /* If we've run out of data, just leave the MCU set to zeroes. + * This way, we return uniform gray for the remainder of the segment. + */ + if (! entropy->pub.insufficient_data) { + + /* Load up working state */ + BITREAD_LOAD_STATE(cinfo,entropy->bitstate); + ASSIGN_STATE(state, entropy->saved); + + /* Outer loop handles each block in the MCU */ + + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { + block = MCU_data[blkn]; + ci = cinfo->MCU_membership[blkn]; + compptr = cinfo->cur_comp_info[ci]; + tbl = entropy->derived_tbls[compptr->dc_tbl_no]; + + /* Decode a single block's worth of coefficients */ + + /* Section F.2.2.1: decode the DC coefficient difference */ + HUFF_DECODE(s, br_state, tbl, return FALSE, label1); + if (s) { + CHECK_BIT_BUFFER(br_state, s, return FALSE); + r = GET_BITS(s); + s = HUFF_EXTEND(r, s); + } + + /* Convert DC difference to actual value, update last_dc_val */ + s += state.last_dc_val[ci]; + state.last_dc_val[ci] = s; + /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */ + (*block)[0] = (JCOEF) (s << Al); + } + + /* Completed MCU, so update state */ + BITREAD_SAVE_STATE(cinfo,entropy->bitstate); + ASSIGN_STATE(entropy->saved, state); + } + + /* Account for restart interval (no-op if not using restarts) */ + entropy->restarts_to_go--; + + return TRUE; +} + + +/* + * MCU decoding for AC initial scan (either spectral selection, + * or first pass of successive approximation). + */ + +METHODDEF(boolean) +decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + int Se = cinfo->Se; + int Al = cinfo->Al; + register int s, k, r; + unsigned int EOBRUN; + JBLOCKROW block; + BITREAD_STATE_VARS; + d_derived_tbl * tbl; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) + if (! process_restart(cinfo)) + return FALSE; + } + + /* If we've run out of data, just leave the MCU set to zeroes. + * This way, we return uniform gray for the remainder of the segment. + */ + if (! entropy->pub.insufficient_data) { + + /* Load up working state. + * We can avoid loading/saving bitread state if in an EOB run. + */ + EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */ + + /* There is always only one block per MCU */ + + if (EOBRUN > 0) /* if it's a band of zeroes... */ + EOBRUN--; /* ...process it now (we do nothing) */ + else { + BITREAD_LOAD_STATE(cinfo,entropy->bitstate); + block = MCU_data[0]; + tbl = entropy->ac_derived_tbl; + + for (k = cinfo->Ss; k <= Se; k++) { + HUFF_DECODE(s, br_state, tbl, return FALSE, label2); + r = s >> 4; + s &= 15; + if (s) { + k += r; + CHECK_BIT_BUFFER(br_state, s, return FALSE); + r = GET_BITS(s); + s = HUFF_EXTEND(r, s); + /* Scale and output coefficient in natural (dezigzagged) order */ + (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al); + } else { + if (r == 15) { /* ZRL */ + k += 15; /* skip 15 zeroes in band */ + } else { /* EOBr, run length is 2^r + appended bits */ + EOBRUN = 1 << r; + if (r) { /* EOBr, r > 0 */ + CHECK_BIT_BUFFER(br_state, r, return FALSE); + r = GET_BITS(r); + EOBRUN += r; + } + EOBRUN--; /* this band is processed at this moment */ + break; /* force end-of-band */ + } + } + } + + BITREAD_SAVE_STATE(cinfo,entropy->bitstate); + } + + /* Completed MCU, so update state */ + entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */ + } + + /* Account for restart interval (no-op if not using restarts) */ + entropy->restarts_to_go--; + + return TRUE; +} + + +/* + * MCU decoding for DC successive approximation refinement scan. + * Note: we assume such scans can be multi-component, although the spec + * is not very clear on the point. + */ + +METHODDEF(boolean) +decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */ + int blkn; + JBLOCKROW block; + BITREAD_STATE_VARS; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) + if (! process_restart(cinfo)) + return FALSE; + } + + /* Not worth the cycles to check insufficient_data here, + * since we will not change the data anyway if we read zeroes. + */ + + /* Load up working state */ + BITREAD_LOAD_STATE(cinfo,entropy->bitstate); + + /* Outer loop handles each block in the MCU */ + + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { + block = MCU_data[blkn]; + + /* Encoded data is simply the next bit of the two's-complement DC value */ + CHECK_BIT_BUFFER(br_state, 1, return FALSE); + if (GET_BITS(1)) + (*block)[0] |= p1; + /* Note: since we use |=, repeating the assignment later is safe */ + } + + /* Completed MCU, so update state */ + BITREAD_SAVE_STATE(cinfo,entropy->bitstate); + + /* Account for restart interval (no-op if not using restarts) */ + entropy->restarts_to_go--; + + return TRUE; +} + + +/* + * MCU decoding for AC successive approximation refinement scan. + */ + +METHODDEF(boolean) +decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) +{ + phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy; + int Se = cinfo->Se; + int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */ + int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */ + register int s, k, r; + unsigned int EOBRUN; + JBLOCKROW block; + JCOEFPTR thiscoef; + BITREAD_STATE_VARS; + d_derived_tbl * tbl; + int num_newnz; + int newnz_pos[DCTSIZE2]; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo->restart_interval) { + if (entropy->restarts_to_go == 0) + if (! process_restart(cinfo)) + return FALSE; + } + + /* If we've run out of data, don't modify the MCU. + */ + if (! entropy->pub.insufficient_data) { + + /* Load up working state */ + BITREAD_LOAD_STATE(cinfo,entropy->bitstate); + EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */ + + /* There is always only one block per MCU */ + block = MCU_data[0]; + tbl = entropy->ac_derived_tbl; + + /* If we are forced to suspend, we must undo the assignments to any newly + * nonzero coefficients in the block, because otherwise we'd get confused + * next time about which coefficients were already nonzero. + * But we need not undo addition of bits to already-nonzero coefficients; + * instead, we can test the current bit to see if we already did it. + */ + num_newnz = 0; + + /* initialize coefficient loop counter to start of band */ + k = cinfo->Ss; + + if (EOBRUN == 0) { + for (; k <= Se; k++) { + HUFF_DECODE(s, br_state, tbl, goto undoit, label3); + r = s >> 4; + s &= 15; + if (s) { + if (s != 1) /* size of new coef should always be 1 */ + WARNMS(cinfo, JWRN_HUFF_BAD_CODE); + CHECK_BIT_BUFFER(br_state, 1, goto undoit); + if (GET_BITS(1)) + s = p1; /* newly nonzero coef is positive */ + else + s = m1; /* newly nonzero coef is negative */ + } else { + if (r != 15) { + EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */ + if (r) { + CHECK_BIT_BUFFER(br_state, r, goto undoit); + r = GET_BITS(r); + EOBRUN += r; + } + break; /* rest of block is handled by EOB logic */ + } + /* note s = 0 for processing ZRL */ + } + /* Advance over already-nonzero coefs and r still-zero coefs, + * appending correction bits to the nonzeroes. A correction bit is 1 + * if the absolute value of the coefficient must be increased. + */ + do { + thiscoef = *block + jpeg_natural_order[k]; + if (*thiscoef != 0) { + CHECK_BIT_BUFFER(br_state, 1, goto undoit); + if (GET_BITS(1)) { + if ((*thiscoef & p1) == 0) { /* do nothing if already set it */ + if (*thiscoef >= 0) + *thiscoef += p1; + else + *thiscoef += m1; + } + } + } else { + if (--r < 0) + break; /* reached target zero coefficient */ + } + k++; + } while (k <= Se); + if (s) { + int pos = jpeg_natural_order[k]; + /* Output newly nonzero coefficient */ + (*block)[pos] = (JCOEF) s; + /* Remember its position in case we have to suspend */ + newnz_pos[num_newnz++] = pos; + } + } + } + + if (EOBRUN > 0) { + /* Scan any remaining coefficient positions after the end-of-band + * (the last newly nonzero coefficient, if any). Append a correction + * bit to each already-nonzero coefficient. A correction bit is 1 + * if the absolute value of the coefficient must be increased. + */ + for (; k <= Se; k++) { + thiscoef = *block + jpeg_natural_order[k]; + if (*thiscoef != 0) { + CHECK_BIT_BUFFER(br_state, 1, goto undoit); + if (GET_BITS(1)) { + if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */ + if (*thiscoef >= 0) + *thiscoef += p1; + else + *thiscoef += m1; + } + } + } + } + /* Count one block completed in EOB run */ + EOBRUN--; + } + + /* Completed MCU, so update state */ + BITREAD_SAVE_STATE(cinfo,entropy->bitstate); + entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */ + } + + /* Account for restart interval (no-op if not using restarts) */ + entropy->restarts_to_go--; + + return TRUE; + +undoit: + /* Re-zero any output coefficients that we made newly nonzero */ + while (num_newnz > 0) + (*block)[newnz_pos[--num_newnz]] = 0; + + return FALSE; +} + + +/* + * Module initialization routine for progressive Huffman entropy decoding. + */ + +GLOBAL(void) +jinit_phuff_decoder (j_decompress_ptr cinfo) +{ + phuff_entropy_ptr entropy; + int *coef_bit_ptr; + int ci, i; + + entropy = (phuff_entropy_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(phuff_entropy_decoder)); + cinfo->entropy = (struct jpeg_entropy_decoder *) entropy; + entropy->pub.start_pass = start_pass_phuff_decoder; + + /* Mark derived tables unallocated */ + for (i = 0; i < NUM_HUFF_TBLS; i++) { + entropy->derived_tbls[i] = NULL; + } + + /* Create progression status table */ + cinfo->coef_bits = (int (*)[DCTSIZE2]) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + cinfo->num_components*DCTSIZE2*SIZEOF(int)); + coef_bit_ptr = & cinfo->coef_bits[0][0]; + for (ci = 0; ci < cinfo->num_components; ci++) + for (i = 0; i < DCTSIZE2; i++) + *coef_bit_ptr++ = -1; +} + +#endif /* D_PROGRESSIVE_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jdpostct.c b/SlnkDWFImpl/CxImage/jpeg/jdpostct.c new file mode 100644 index 0000000..7ba9eed --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdpostct.c @@ -0,0 +1,290 @@ +/* + * jdpostct.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the decompression postprocessing controller. + * This controller manages the upsampling, color conversion, and color + * quantization/reduction steps; specifically, it controls the buffering + * between upsample/color conversion and color quantization/reduction. + * + * If no color quantization/reduction is required, then this module has no + * work to do, and it just hands off to the upsample/color conversion code. + * An integrated upsample/convert/quantize process would replace this module + * entirely. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Private buffer controller object */ + +typedef struct { + struct jpeg_d_post_controller pub; /* public fields */ + + /* Color quantization source buffer: this holds output data from + * the upsample/color conversion step to be passed to the quantizer. + * For two-pass color quantization, we need a full-image buffer; + * for one-pass operation, a strip buffer is sufficient. + */ + jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */ + JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */ + JDIMENSION strip_height; /* buffer size in rows */ + /* for two-pass mode only: */ + JDIMENSION starting_row; /* row # of first row in current strip */ + JDIMENSION next_row; /* index of next row to fill/empty in strip */ +} my_post_controller; + +typedef my_post_controller * my_post_ptr; + + +/* Forward declarations */ +METHODDEF(void) post_process_1pass + JPP((j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail)); +#ifdef QUANT_2PASS_SUPPORTED +METHODDEF(void) post_process_prepass + JPP((j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail)); +METHODDEF(void) post_process_2pass + JPP((j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail)); +#endif + + +/* + * Initialize for a processing pass. + */ + +METHODDEF(void) +start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode) +{ + my_post_ptr post = (my_post_ptr) cinfo->post; + + switch (pass_mode) { + case JBUF_PASS_THRU: + if (cinfo->quantize_colors) { + /* Single-pass processing with color quantization. */ + post->pub.post_process_data = post_process_1pass; + /* We could be doing buffered-image output before starting a 2-pass + * color quantization; in that case, jinit_d_post_controller did not + * allocate a strip buffer. Use the virtual-array buffer as workspace. + */ + if (post->buffer == NULL) { + post->buffer = (*cinfo->mem->access_virt_sarray) + ((j_common_ptr) cinfo, post->whole_image, + (JDIMENSION) 0, post->strip_height, TRUE); + } + } else { + /* For single-pass processing without color quantization, + * I have no work to do; just call the upsampler directly. + */ + post->pub.post_process_data = cinfo->upsample->upsample; + } + break; +#ifdef QUANT_2PASS_SUPPORTED + case JBUF_SAVE_AND_PASS: + /* First pass of 2-pass quantization */ + if (post->whole_image == NULL) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + post->pub.post_process_data = post_process_prepass; + break; + case JBUF_CRANK_DEST: + /* Second pass of 2-pass quantization */ + if (post->whole_image == NULL) + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + post->pub.post_process_data = post_process_2pass; + break; +#endif /* QUANT_2PASS_SUPPORTED */ + default: + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + break; + } + post->starting_row = post->next_row = 0; +} + + +/* + * Process some data in the one-pass (strip buffer) case. + * This is used for color precision reduction as well as one-pass quantization. + */ + +METHODDEF(void) +post_process_1pass (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +{ + my_post_ptr post = (my_post_ptr) cinfo->post; + JDIMENSION num_rows, max_rows; + + /* Fill the buffer, but not more than what we can dump out in one go. */ + /* Note we rely on the upsampler to detect bottom of image. */ + max_rows = out_rows_avail - *out_row_ctr; + if (max_rows > post->strip_height) + max_rows = post->strip_height; + num_rows = 0; + (*cinfo->upsample->upsample) (cinfo, + input_buf, in_row_group_ctr, in_row_groups_avail, + post->buffer, &num_rows, max_rows); + /* Quantize and emit data. */ + (*cinfo->cquantize->color_quantize) (cinfo, + post->buffer, output_buf + *out_row_ctr, (int) num_rows); + *out_row_ctr += num_rows; +} + + +#ifdef QUANT_2PASS_SUPPORTED + +/* + * Process some data in the first pass of 2-pass quantization. + */ + +METHODDEF(void) +post_process_prepass (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +{ + my_post_ptr post = (my_post_ptr) cinfo->post; + JDIMENSION old_next_row, num_rows; + + /* Reposition virtual buffer if at start of strip. */ + if (post->next_row == 0) { + post->buffer = (*cinfo->mem->access_virt_sarray) + ((j_common_ptr) cinfo, post->whole_image, + post->starting_row, post->strip_height, TRUE); + } + + /* Upsample some data (up to a strip height's worth). */ + old_next_row = post->next_row; + (*cinfo->upsample->upsample) (cinfo, + input_buf, in_row_group_ctr, in_row_groups_avail, + post->buffer, &post->next_row, post->strip_height); + + /* Allow quantizer to scan new data. No data is emitted, */ + /* but we advance out_row_ctr so outer loop can tell when we're done. */ + if (post->next_row > old_next_row) { + num_rows = post->next_row - old_next_row; + (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row, + (JSAMPARRAY) NULL, (int) num_rows); + *out_row_ctr += num_rows; + } + + /* Advance if we filled the strip. */ + if (post->next_row >= post->strip_height) { + post->starting_row += post->strip_height; + post->next_row = 0; + } +} + + +/* + * Process some data in the second pass of 2-pass quantization. + */ + +METHODDEF(void) +post_process_2pass (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +{ + my_post_ptr post = (my_post_ptr) cinfo->post; + JDIMENSION num_rows, max_rows; + + /* Reposition virtual buffer if at start of strip. */ + if (post->next_row == 0) { + post->buffer = (*cinfo->mem->access_virt_sarray) + ((j_common_ptr) cinfo, post->whole_image, + post->starting_row, post->strip_height, FALSE); + } + + /* Determine number of rows to emit. */ + num_rows = post->strip_height - post->next_row; /* available in strip */ + max_rows = out_rows_avail - *out_row_ctr; /* available in output area */ + if (num_rows > max_rows) + num_rows = max_rows; + /* We have to check bottom of image here, can't depend on upsampler. */ + max_rows = cinfo->output_height - post->starting_row; + if (num_rows > max_rows) + num_rows = max_rows; + + /* Quantize and emit data. */ + (*cinfo->cquantize->color_quantize) (cinfo, + post->buffer + post->next_row, output_buf + *out_row_ctr, + (int) num_rows); + *out_row_ctr += num_rows; + + /* Advance if we filled the strip. */ + post->next_row += num_rows; + if (post->next_row >= post->strip_height) { + post->starting_row += post->strip_height; + post->next_row = 0; + } +} + +#endif /* QUANT_2PASS_SUPPORTED */ + + +/* + * Initialize postprocessing controller. + */ + +GLOBAL(void) +jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer) +{ + my_post_ptr post; + + post = (my_post_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_post_controller)); + cinfo->post = (struct jpeg_d_post_controller *) post; + post->pub.start_pass = start_pass_dpost; + post->whole_image = NULL; /* flag for no virtual arrays */ + post->buffer = NULL; /* flag for no strip buffer */ + + /* Create the quantization buffer, if needed */ + if (cinfo->quantize_colors) { + /* The buffer strip height is max_v_samp_factor, which is typically + * an efficient number of rows for upsampling to return. + * (In the presence of output rescaling, we might want to be smarter?) + */ + post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor; + if (need_full_buffer) { + /* Two-pass color quantization: need full-image storage. */ + /* We round up the number of rows to a multiple of the strip height. */ +#ifdef QUANT_2PASS_SUPPORTED + post->whole_image = (*cinfo->mem->request_virt_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, + cinfo->output_width * cinfo->out_color_components, + (JDIMENSION) jround_up((long) cinfo->output_height, + (long) post->strip_height), + post->strip_height); +#else + ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); +#endif /* QUANT_2PASS_SUPPORTED */ + } else { + /* One-pass color quantization: just make a strip buffer. */ + post->buffer = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + cinfo->output_width * cinfo->out_color_components, + post->strip_height); + } + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdsample.c b/SlnkDWFImpl/CxImage/jpeg/jdsample.c new file mode 100644 index 0000000..e0d9040 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdsample.c @@ -0,0 +1,478 @@ +/* + * jdsample.c + * + * Copyright (C) 1991-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains upsampling routines. + * + * Upsampling input data is counted in "row groups". A row group + * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size) + * sample rows of each component. Upsampling will normally produce + * max_v_samp_factor pixel rows from each row group (but this could vary + * if the upsampler is applying a scale factor of its own). + * + * An excellent reference for image resampling is + * Digital Image Warping, George Wolberg, 1990. + * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Pointer to routine to upsample a single component */ +typedef JMETHOD(void, upsample1_ptr, + (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)); + +/* Private subobject */ + +typedef struct { + struct jpeg_upsampler pub; /* public fields */ + + /* Color conversion buffer. When using separate upsampling and color + * conversion steps, this buffer holds one upsampled row group until it + * has been color converted and output. + * Note: we do not allocate any storage for component(s) which are full-size, + * ie do not need rescaling. The corresponding entry of color_buf[] is + * simply set to point to the input data array, thereby avoiding copying. + */ + JSAMPARRAY color_buf[MAX_COMPONENTS]; + + /* Per-component upsampling method pointers */ + upsample1_ptr methods[MAX_COMPONENTS]; + + int next_row_out; /* counts rows emitted from color_buf */ + JDIMENSION rows_to_go; /* counts rows remaining in image */ + + /* Height of an input row group for each component. */ + int rowgroup_height[MAX_COMPONENTS]; + + /* These arrays save pixel expansion factors so that int_expand need not + * recompute them each time. They are unused for other upsampling methods. + */ + UINT8 h_expand[MAX_COMPONENTS]; + UINT8 v_expand[MAX_COMPONENTS]; +} my_upsampler; + +typedef my_upsampler * my_upsample_ptr; + + +/* + * Initialize for an upsampling pass. + */ + +METHODDEF(void) +start_pass_upsample (j_decompress_ptr cinfo) +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + + /* Mark the conversion buffer empty */ + upsample->next_row_out = cinfo->max_v_samp_factor; + /* Initialize total-height counter for detecting bottom of image */ + upsample->rows_to_go = cinfo->output_height; +} + + +/* + * Control routine to do upsampling (and color conversion). + * + * In this version we upsample each component independently. + * We upsample one row group into the conversion buffer, then apply + * color conversion a row at a time. + */ + +METHODDEF(void) +sep_upsample (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail) +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + int ci; + jpeg_component_info * compptr; + JDIMENSION num_rows; + + /* Fill the conversion buffer, if it's empty */ + if (upsample->next_row_out >= cinfo->max_v_samp_factor) { + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Invoke per-component upsample method. Notice we pass a POINTER + * to color_buf[ci], so that fullsize_upsample can change it. + */ + (*upsample->methods[ci]) (cinfo, compptr, + input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]), + upsample->color_buf + ci); + } + upsample->next_row_out = 0; + } + + /* Color-convert and emit rows */ + + /* How many we have in the buffer: */ + num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out); + /* Not more than the distance to the end of the image. Need this test + * in case the image height is not a multiple of max_v_samp_factor: + */ + if (num_rows > upsample->rows_to_go) + num_rows = upsample->rows_to_go; + /* And not more than what the client can accept: */ + out_rows_avail -= *out_row_ctr; + if (num_rows > out_rows_avail) + num_rows = out_rows_avail; + + (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf, + (JDIMENSION) upsample->next_row_out, + output_buf + *out_row_ctr, + (int) num_rows); + + /* Adjust counts */ + *out_row_ctr += num_rows; + upsample->rows_to_go -= num_rows; + upsample->next_row_out += num_rows; + /* When the buffer is emptied, declare this input row group consumed */ + if (upsample->next_row_out >= cinfo->max_v_samp_factor) + (*in_row_group_ctr)++; +} + + +/* + * These are the routines invoked by sep_upsample to upsample pixel values + * of a single component. One row group is processed per call. + */ + + +/* + * For full-size components, we just make color_buf[ci] point at the + * input buffer, and thus avoid copying any data. Note that this is + * safe only because sep_upsample doesn't declare the input row group + * "consumed" until we are done color converting and emitting it. + */ + +METHODDEF(void) +fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) +{ + *output_data_ptr = input_data; +} + + +/* + * This is a no-op version used for "uninteresting" components. + * These components will not be referenced by color conversion. + */ + +METHODDEF(void) +noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) +{ + *output_data_ptr = NULL; /* safety check */ +} + + +/* + * This version handles any integral sampling ratios. + * This is not used for typical JPEG files, so it need not be fast. + * Nor, for that matter, is it particularly accurate: the algorithm is + * simple replication of the input pixel onto the corresponding output + * pixels. The hi-falutin sampling literature refers to this as a + * "box filter". A box filter tends to introduce visible artifacts, + * so if you are actually going to use 3:1 or 4:1 sampling ratios + * you would be well advised to improve this code. + */ + +METHODDEF(void) +int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) +{ + my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; + JSAMPARRAY output_data = *output_data_ptr; + register JSAMPROW inptr, outptr; + register JSAMPLE invalue; + register int h; + JSAMPROW outend; + int h_expand, v_expand; + int inrow, outrow; + + h_expand = upsample->h_expand[compptr->component_index]; + v_expand = upsample->v_expand[compptr->component_index]; + + inrow = outrow = 0; + while (outrow < cinfo->max_v_samp_factor) { + /* Generate one output row with proper horizontal expansion */ + inptr = input_data[inrow]; + outptr = output_data[outrow]; + outend = outptr + cinfo->output_width; + while (outptr < outend) { + invalue = *inptr++; /* don't need GETJSAMPLE() here */ + for (h = h_expand; h > 0; h--) { + *outptr++ = invalue; + } + } + /* Generate any additional output rows by duplicating the first one */ + if (v_expand > 1) { + jcopy_sample_rows(output_data, outrow, output_data, outrow+1, + v_expand-1, cinfo->output_width); + } + inrow++; + outrow += v_expand; + } +} + + +/* + * Fast processing for the common case of 2:1 horizontal and 1:1 vertical. + * It's still a box filter. + */ + +METHODDEF(void) +h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) +{ + JSAMPARRAY output_data = *output_data_ptr; + register JSAMPROW inptr, outptr; + register JSAMPLE invalue; + JSAMPROW outend; + int inrow; + + for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) { + inptr = input_data[inrow]; + outptr = output_data[inrow]; + outend = outptr + cinfo->output_width; + while (outptr < outend) { + invalue = *inptr++; /* don't need GETJSAMPLE() here */ + *outptr++ = invalue; + *outptr++ = invalue; + } + } +} + + +/* + * Fast processing for the common case of 2:1 horizontal and 2:1 vertical. + * It's still a box filter. + */ + +METHODDEF(void) +h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) +{ + JSAMPARRAY output_data = *output_data_ptr; + register JSAMPROW inptr, outptr; + register JSAMPLE invalue; + JSAMPROW outend; + int inrow, outrow; + + inrow = outrow = 0; + while (outrow < cinfo->max_v_samp_factor) { + inptr = input_data[inrow]; + outptr = output_data[outrow]; + outend = outptr + cinfo->output_width; + while (outptr < outend) { + invalue = *inptr++; /* don't need GETJSAMPLE() here */ + *outptr++ = invalue; + *outptr++ = invalue; + } + jcopy_sample_rows(output_data, outrow, output_data, outrow+1, + 1, cinfo->output_width); + inrow++; + outrow += 2; + } +} + + +/* + * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical. + * + * The upsampling algorithm is linear interpolation between pixel centers, + * also known as a "triangle filter". This is a good compromise between + * speed and visual quality. The centers of the output pixels are 1/4 and 3/4 + * of the way between input pixel centers. + * + * A note about the "bias" calculations: when rounding fractional values to + * integer, we do not want to always round 0.5 up to the next integer. + * If we did that, we'd introduce a noticeable bias towards larger values. + * Instead, this code is arranged so that 0.5 will be rounded up or down at + * alternate pixel locations (a simple ordered dither pattern). + */ + +METHODDEF(void) +h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) +{ + JSAMPARRAY output_data = *output_data_ptr; + register JSAMPROW inptr, outptr; + register int invalue; + register JDIMENSION colctr; + int inrow; + + for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) { + inptr = input_data[inrow]; + outptr = output_data[inrow]; + /* Special case for first column */ + invalue = GETJSAMPLE(*inptr++); + *outptr++ = (JSAMPLE) invalue; + *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2); + + for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) { + /* General case: 3/4 * nearer pixel + 1/4 * further pixel */ + invalue = GETJSAMPLE(*inptr++) * 3; + *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2); + *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2); + } + + /* Special case for last column */ + invalue = GETJSAMPLE(*inptr); + *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2); + *outptr++ = (JSAMPLE) invalue; + } +} + + +/* + * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical. + * Again a triangle filter; see comments for h2v1 case, above. + * + * It is OK for us to reference the adjacent input rows because we demanded + * context from the main buffer controller (see initialization code). + */ + +METHODDEF(void) +h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) +{ + JSAMPARRAY output_data = *output_data_ptr; + register JSAMPROW inptr0, inptr1, outptr; +#if BITS_IN_JSAMPLE == 8 + register int thiscolsum, lastcolsum, nextcolsum; +#else + register INT32 thiscolsum, lastcolsum, nextcolsum; +#endif + register JDIMENSION colctr; + int inrow, outrow, v; + + inrow = outrow = 0; + while (outrow < cinfo->max_v_samp_factor) { + for (v = 0; v < 2; v++) { + /* inptr0 points to nearest input row, inptr1 points to next nearest */ + inptr0 = input_data[inrow]; + if (v == 0) /* next nearest is row above */ + inptr1 = input_data[inrow-1]; + else /* next nearest is row below */ + inptr1 = input_data[inrow+1]; + outptr = output_data[outrow++]; + + /* Special case for first column */ + thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++); + nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++); + *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4); + *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4); + lastcolsum = thiscolsum; thiscolsum = nextcolsum; + + for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) { + /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */ + /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */ + nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++); + *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4); + *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4); + lastcolsum = thiscolsum; thiscolsum = nextcolsum; + } + + /* Special case for last column */ + *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4); + *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4); + } + inrow++; + } +} + + +/* + * Module initialization routine for upsampling. + */ + +GLOBAL(void) +jinit_upsampler (j_decompress_ptr cinfo) +{ + my_upsample_ptr upsample; + int ci; + jpeg_component_info * compptr; + boolean need_buffer, do_fancy; + int h_in_group, v_in_group, h_out_group, v_out_group; + + upsample = (my_upsample_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_upsampler)); + cinfo->upsample = (struct jpeg_upsampler *) upsample; + upsample->pub.start_pass = start_pass_upsample; + upsample->pub.upsample = sep_upsample; + upsample->pub.need_context_rows = FALSE; /* until we find out differently */ + + if (cinfo->CCIR601_sampling) /* this isn't supported */ + ERREXIT(cinfo, JERR_CCIR601_NOTIMPL); + + /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1, + * so don't ask for it. + */ + do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1; + + /* Verify we can handle the sampling factors, select per-component methods, + * and create storage as needed. + */ + for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; + ci++, compptr++) { + /* Compute size of an "input group" after IDCT scaling. This many samples + * are to be converted to max_h_samp_factor * max_v_samp_factor pixels. + */ + h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) / + cinfo->min_DCT_scaled_size; + v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) / + cinfo->min_DCT_scaled_size; + h_out_group = cinfo->max_h_samp_factor; + v_out_group = cinfo->max_v_samp_factor; + upsample->rowgroup_height[ci] = v_in_group; /* save for use later */ + need_buffer = TRUE; + if (! compptr->component_needed) { + /* Don't bother to upsample an uninteresting component. */ + upsample->methods[ci] = noop_upsample; + need_buffer = FALSE; + } else if (h_in_group == h_out_group && v_in_group == v_out_group) { + /* Fullsize components can be processed without any work. */ + upsample->methods[ci] = fullsize_upsample; + need_buffer = FALSE; + } else if (h_in_group * 2 == h_out_group && + v_in_group == v_out_group) { + /* Special cases for 2h1v upsampling */ + if (do_fancy && compptr->downsampled_width > 2) + upsample->methods[ci] = h2v1_fancy_upsample; + else + upsample->methods[ci] = h2v1_upsample; + } else if (h_in_group * 2 == h_out_group && + v_in_group * 2 == v_out_group) { + /* Special cases for 2h2v upsampling */ + if (do_fancy && compptr->downsampled_width > 2) { + upsample->methods[ci] = h2v2_fancy_upsample; + upsample->pub.need_context_rows = TRUE; + } else + upsample->methods[ci] = h2v2_upsample; + } else if ((h_out_group % h_in_group) == 0 && + (v_out_group % v_in_group) == 0) { + /* Generic integral-factors upsampling method */ + upsample->methods[ci] = int_upsample; + upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group); + upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group); + } else + ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL); + if (need_buffer) { + upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + (JDIMENSION) jround_up((long) cinfo->output_width, + (long) cinfo->max_h_samp_factor), + (JDIMENSION) cinfo->max_v_samp_factor); + } + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jdtrans.c b/SlnkDWFImpl/CxImage/jpeg/jdtrans.c new file mode 100644 index 0000000..12c193c --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jdtrans.c @@ -0,0 +1,143 @@ +/* + * jdtrans.c + * + * Copyright (C) 1995-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains library routines for transcoding decompression, + * that is, reading raw DCT coefficient arrays from an input JPEG file. + * The routines in jdapimin.c will also be needed by a transcoder. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Forward declarations */ +LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo)); + + +/* + * Read the coefficient arrays from a JPEG file. + * jpeg_read_header must be completed before calling this. + * + * The entire image is read into a set of virtual coefficient-block arrays, + * one per component. The return value is a pointer to the array of + * virtual-array descriptors. These can be manipulated directly via the + * JPEG memory manager, or handed off to jpeg_write_coefficients(). + * To release the memory occupied by the virtual arrays, call + * jpeg_finish_decompress() when done with the data. + * + * An alternative usage is to simply obtain access to the coefficient arrays + * during a buffered-image-mode decompression operation. This is allowed + * after any jpeg_finish_output() call. The arrays can be accessed until + * jpeg_finish_decompress() is called. (Note that any call to the library + * may reposition the arrays, so don't rely on access_virt_barray() results + * to stay valid across library calls.) + * + * Returns NULL if suspended. This case need be checked only if + * a suspending data source is used. + */ + +GLOBAL(jvirt_barray_ptr *) +jpeg_read_coefficients (j_decompress_ptr cinfo) +{ + if (cinfo->global_state == DSTATE_READY) { + /* First call: initialize active modules */ + transdecode_master_selection(cinfo); + cinfo->global_state = DSTATE_RDCOEFS; + } + if (cinfo->global_state == DSTATE_RDCOEFS) { + /* Absorb whole file into the coef buffer */ + for (;;) { + int retcode; + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) + (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); + /* Absorb some more input */ + retcode = (*cinfo->inputctl->consume_input) (cinfo); + if (retcode == JPEG_SUSPENDED) + return NULL; + if (retcode == JPEG_REACHED_EOI) + break; + /* Advance progress counter if appropriate */ + if (cinfo->progress != NULL && + (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) { + if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) { + /* startup underestimated number of scans; ratchet up one scan */ + cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows; + } + } + } + /* Set state so that jpeg_finish_decompress does the right thing */ + cinfo->global_state = DSTATE_STOPPING; + } + /* At this point we should be in state DSTATE_STOPPING if being used + * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access + * to the coefficients during a full buffered-image-mode decompression. + */ + if ((cinfo->global_state == DSTATE_STOPPING || + cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) { + return cinfo->coef->coef_arrays; + } + /* Oops, improper usage */ + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + return NULL; /* keep compiler happy */ +} + + +/* + * Master selection of decompression modules for transcoding. + * This substitutes for jdmaster.c's initialization of the full decompressor. + */ + +LOCAL(void) +transdecode_master_selection (j_decompress_ptr cinfo) +{ + /* This is effectively a buffered-image operation. */ + cinfo->buffered_image = TRUE; + + /* Entropy decoding: either Huffman or arithmetic coding. */ + if (cinfo->arith_code) { + ERREXIT(cinfo, JERR_ARITH_NOTIMPL); + } else { + if (cinfo->progressive_mode) { +#ifdef D_PROGRESSIVE_SUPPORTED + jinit_phuff_decoder(cinfo); +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif + } else + jinit_huff_decoder(cinfo); + } + + /* Always get a full-image coefficient buffer. */ + jinit_d_coef_controller(cinfo, TRUE); + + /* We can now tell the memory manager to allocate virtual arrays. */ + (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); + + /* Initialize input side of decompressor to consume first scan. */ + (*cinfo->inputctl->start_input_pass) (cinfo); + + /* Initialize progress monitoring. */ + if (cinfo->progress != NULL) { + int nscans; + /* Estimate number of scans to set pass_limit. */ + if (cinfo->progressive_mode) { + /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ + nscans = 2 + 3 * cinfo->num_components; + } else if (cinfo->inputctl->has_multiple_scans) { + /* For a nonprogressive multiscan file, estimate 1 scan per component. */ + nscans = cinfo->num_components; + } else { + nscans = 1; + } + cinfo->progress->pass_counter = 0L; + cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans; + cinfo->progress->completed_passes = 0; + cinfo->progress->total_passes = 1; + } +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jerror.c b/SlnkDWFImpl/CxImage/jpeg/jerror.c new file mode 100644 index 0000000..c98aed7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jerror.c @@ -0,0 +1,252 @@ +/* + * jerror.c + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains simple error-reporting and trace-message routines. + * These are suitable for Unix-like systems and others where writing to + * stderr is the right thing to do. Many applications will want to replace + * some or all of these routines. + * + * If you define USE_WINDOWS_MESSAGEBOX in jconfig.h or in the makefile, + * you get a Windows-specific hack to display error messages in a dialog box. + * It ain't much, but it beats dropping error messages into the bit bucket, + * which is what happens to output to stderr under most Windows C compilers. + * + * These routines are used by both the compression and decompression code. + */ + +/* this is not a core library module, so it doesn't define JPEG_INTERNALS */ +#include "jinclude.h" +#include "jpeglib.h" +#include "jversion.h" +#include "jerror.h" + +#ifdef USE_WINDOWS_MESSAGEBOX +#include +#endif + +#ifndef EXIT_FAILURE /* define exit() codes if not provided */ +#define EXIT_FAILURE 1 +#endif + + +/* + * Create the message string table. + * We do this from the master message list in jerror.h by re-reading + * jerror.h with a suitable definition for macro JMESSAGE. + * The message table is made an external symbol just in case any applications + * want to refer to it directly. + */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jpeg_std_message_table jMsgTable +#endif + +#define JMESSAGE(code,string) string , + +const char * const jpeg_std_message_table[] = { +#include "jerror.h" + NULL +}; + + +/* + * Error exit handler: must not return to caller. + * + * Applications may override this if they want to get control back after + * an error. Typically one would longjmp somewhere instead of exiting. + * The setjmp buffer can be made a private field within an expanded error + * handler object. Note that the info needed to generate an error message + * is stored in the error object, so you can generate the message now or + * later, at your convenience. + * You should make sure that the JPEG object is cleaned up (with jpeg_abort + * or jpeg_destroy) at some point. + */ + +METHODDEF(void) +error_exit (j_common_ptr cinfo) +{ + /* Always display the message */ + (*cinfo->err->output_message) (cinfo); + + /* Let the memory manager delete any temp files before we die */ + jpeg_destroy(cinfo); + + exit(EXIT_FAILURE); +} + + +/* + * Actual output of an error or trace message. + * Applications may override this method to send JPEG messages somewhere + * other than stderr. + * + * On Windows, printing to stderr is generally completely useless, + * so we provide optional code to produce an error-dialog popup. + * Most Windows applications will still prefer to override this routine, + * but if they don't, it'll do something at least marginally useful. + * + * NOTE: to use the library in an environment that doesn't support the + * C stdio library, you may have to delete the call to fprintf() entirely, + * not just not use this routine. + */ + +METHODDEF(void) +output_message (j_common_ptr cinfo) +{ + char buffer[JMSG_LENGTH_MAX]; + + /* Create the message */ + (*cinfo->err->format_message) (cinfo, buffer); + +#ifdef USE_WINDOWS_MESSAGEBOX + /* Display it in a message dialog box */ + MessageBox(GetActiveWindow(), buffer, "JPEG Library Error", + MB_OK | MB_ICONERROR); +#else + /* Send it to stderr, adding a newline */ + fprintf(stderr, "%s\n", buffer); +#endif +} + + +/* + * Decide whether to emit a trace or warning message. + * msg_level is one of: + * -1: recoverable corrupt-data warning, may want to abort. + * 0: important advisory messages (always display to user). + * 1: first level of tracing detail. + * 2,3,...: successively more detailed tracing messages. + * An application might override this method if it wanted to abort on warnings + * or change the policy about which messages to display. + */ + +METHODDEF(void) +emit_message (j_common_ptr cinfo, int msg_level) +{ + struct jpeg_error_mgr * err = cinfo->err; + + if (msg_level < 0) { + /* It's a warning message. Since corrupt files may generate many warnings, + * the policy implemented here is to show only the first warning, + * unless trace_level >= 3. + */ + if (err->num_warnings == 0 || err->trace_level >= 3) + (*err->output_message) (cinfo); + /* Always count warnings in num_warnings. */ + err->num_warnings++; + } else { + /* It's a trace message. Show it if trace_level >= msg_level. */ + if (err->trace_level >= msg_level) + (*err->output_message) (cinfo); + } +} + + +/* + * Format a message string for the most recent JPEG error or message. + * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX + * characters. Note that no '\n' character is added to the string. + * Few applications should need to override this method. + */ + +METHODDEF(void) +format_message (j_common_ptr cinfo, char * buffer) +{ + struct jpeg_error_mgr * err = cinfo->err; + int msg_code = err->msg_code; + const char * msgtext = NULL; + const char * msgptr; + char ch; + boolean isstring; + + /* Look up message string in proper table */ + if (msg_code > 0 && msg_code <= err->last_jpeg_message) { + msgtext = err->jpeg_message_table[msg_code]; + } else if (err->addon_message_table != NULL && + msg_code >= err->first_addon_message && + msg_code <= err->last_addon_message) { + msgtext = err->addon_message_table[msg_code - err->first_addon_message]; + } + + /* Defend against bogus message number */ + if (msgtext == NULL) { + err->msg_parm.i[0] = msg_code; + msgtext = err->jpeg_message_table[0]; + } + + /* Check for string parameter, as indicated by %s in the message text */ + isstring = FALSE; + msgptr = msgtext; + while ((ch = *msgptr++) != '\0') { + if (ch == '%') { + if (*msgptr == 's') isstring = TRUE; + break; + } + } + + /* Format the message into the passed buffer */ + if (isstring) + sprintf(buffer, msgtext, err->msg_parm.s); + else + sprintf(buffer, msgtext, + err->msg_parm.i[0], err->msg_parm.i[1], + err->msg_parm.i[2], err->msg_parm.i[3], + err->msg_parm.i[4], err->msg_parm.i[5], + err->msg_parm.i[6], err->msg_parm.i[7]); +} + + +/* + * Reset error state variables at start of a new image. + * This is called during compression startup to reset trace/error + * processing to default state, without losing any application-specific + * method pointers. An application might possibly want to override + * this method if it has additional error processing state. + */ + +METHODDEF(void) +reset_error_mgr (j_common_ptr cinfo) +{ + cinfo->err->num_warnings = 0; + /* trace_level is not reset since it is an application-supplied parameter */ + cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */ +} + + +/* + * Fill in the standard error-handling methods in a jpeg_error_mgr object. + * Typical call is: + * struct jpeg_compress_struct cinfo; + * struct jpeg_error_mgr err; + * + * cinfo.err = jpeg_std_error(&err); + * after which the application may override some of the methods. + */ + +GLOBAL(struct jpeg_error_mgr *) +jpeg_std_error (struct jpeg_error_mgr * err) +{ + err->error_exit = error_exit; + err->emit_message = emit_message; + err->output_message = output_message; + err->format_message = format_message; + err->reset_error_mgr = reset_error_mgr; + + err->trace_level = 0; /* default = no tracing */ + err->num_warnings = 0; /* no warnings emitted yet */ + err->msg_code = 0; /* may be useful as a flag for "no error" */ + + /* Initialize message table pointers */ + err->jpeg_message_table = jpeg_std_message_table; + err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1; + + err->addon_message_table = NULL; + err->first_addon_message = 0; /* for safety */ + err->last_addon_message = 0; + + return err; +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jerror.h b/SlnkDWFImpl/CxImage/jpeg/jerror.h new file mode 100644 index 0000000..79084f2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jerror.h @@ -0,0 +1,291 @@ +/* + * jerror.h + * + * Copyright (C) 1994-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file defines the error and message codes for the JPEG library. + * Edit this file to add new codes, or to translate the message strings to + * some other language. + * A set of error-reporting macros are defined too. Some applications using + * the JPEG library may wish to include this file to get the error codes + * and/or the macros. + */ + +/* + * To define the enum list of message codes, include this file without + * defining macro JMESSAGE. To create a message string table, include it + * again with a suitable JMESSAGE definition (see jerror.c for an example). + */ +#ifndef JMESSAGE +#ifndef JERROR_H +/* First time through, define the enum list */ +#define JMAKE_ENUM_LIST +#else +/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */ +#define JMESSAGE(code,string) +#endif /* JERROR_H */ +#endif /* JMESSAGE */ + +#ifdef JMAKE_ENUM_LIST + +typedef enum { + +#define JMESSAGE(code,string) code , + +#endif /* JMAKE_ENUM_LIST */ + +JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */ + +/* For maintenance convenience, list is alphabetical by message code name */ +JMESSAGE(JERR_ARITH_NOTIMPL, + "Sorry, there are legal restrictions on arithmetic coding") +JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix") +JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix") +JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode") +JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS") +JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range") +JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported") +JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition") +JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace") +JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace") +JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length") +JMESSAGE(JERR_BAD_LIB_VERSION, + "Wrong JPEG library version: library is %d, caller expects %d") +JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan") +JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d") +JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d") +JMESSAGE(JERR_BAD_PROGRESSION, + "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d") +JMESSAGE(JERR_BAD_PROG_SCRIPT, + "Invalid progressive parameters at scan script entry %d") +JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors") +JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d") +JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d") +JMESSAGE(JERR_BAD_STRUCT_SIZE, + "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u") +JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access") +JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small") +JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here") +JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet") +JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d") +JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request") +JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d") +JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x") +JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d") +JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d") +JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)") +JMESSAGE(JERR_EMS_READ, "Read from EMS failed") +JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed") +JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan") +JMESSAGE(JERR_FILE_READ, "Input file read error") +JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?") +JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet") +JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow") +JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry") +JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels") +JMESSAGE(JERR_INPUT_EMPTY, "Empty input file") +JMESSAGE(JERR_INPUT_EOF, "Premature end of input file") +JMESSAGE(JERR_MISMATCHED_QUANT_TABLE, + "Cannot transcode due to multiple use of quantization table %d") +JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data") +JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change") +JMESSAGE(JERR_NOTIMPL, "Not implemented yet") +JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time") +JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported") +JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined") +JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image") +JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined") +JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x") +JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)") +JMESSAGE(JERR_QUANT_COMPONENTS, + "Cannot quantize more than %d color components") +JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors") +JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors") +JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers") +JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker") +JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x") +JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers") +JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF") +JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s") +JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file") +JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file") +JMESSAGE(JERR_TFILE_WRITE, + "Write failed on temporary file --- out of disk space?") +JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines") +JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x") +JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up") +JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation") +JMESSAGE(JERR_XMS_READ, "Read from XMS failed") +JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed") +JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT) +JMESSAGE(JMSG_VERSION, JVERSION) +JMESSAGE(JTRC_16BIT_TABLES, + "Caution: quantization tables are too coarse for baseline JPEG") +JMESSAGE(JTRC_ADOBE, + "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d") +JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u") +JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u") +JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x") +JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x") +JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d") +JMESSAGE(JTRC_DRI, "Define Restart Interval %u") +JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u") +JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u") +JMESSAGE(JTRC_EOI, "End Of Image") +JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d") +JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d") +JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE, + "Warning: thumbnail image size does not match data length %u") +JMESSAGE(JTRC_JFIF_EXTENSION, + "JFIF extension marker: type 0x%02x, length %u") +JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image") +JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u") +JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x") +JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u") +JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors") +JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors") +JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization") +JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d") +JMESSAGE(JTRC_RST, "RST%d") +JMESSAGE(JTRC_SMOOTH_NOTIMPL, + "Smoothing not supported with nonstandard sampling ratios") +JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d") +JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d") +JMESSAGE(JTRC_SOI, "Start of Image") +JMESSAGE(JTRC_SOS, "Start Of Scan: %d components") +JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d") +JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d") +JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s") +JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s") +JMESSAGE(JTRC_THUMB_JPEG, + "JFIF extension marker: JPEG-compressed thumbnail image, length %u") +JMESSAGE(JTRC_THUMB_PALETTE, + "JFIF extension marker: palette thumbnail image, length %u") +JMESSAGE(JTRC_THUMB_RGB, + "JFIF extension marker: RGB thumbnail image, length %u") +JMESSAGE(JTRC_UNKNOWN_IDS, + "Unrecognized component IDs %d %d %d, assuming YCbCr") +JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u") +JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u") +JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d") +JMESSAGE(JWRN_BOGUS_PROGRESSION, + "Inconsistent progression sequence for component %d coefficient %d") +JMESSAGE(JWRN_EXTRANEOUS_DATA, + "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x") +JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment") +JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code") +JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d") +JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file") +JMESSAGE(JWRN_MUST_RESYNC, + "Corrupt JPEG data: found marker 0x%02x instead of RST%d") +JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG") +JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines") + +#ifdef JMAKE_ENUM_LIST + + JMSG_LASTMSGCODE +} J_MESSAGE_CODE; + +#undef JMAKE_ENUM_LIST +#endif /* JMAKE_ENUM_LIST */ + +/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */ +#undef JMESSAGE + + +#ifndef JERROR_H +#define JERROR_H + +/* Macros to simplify using the error and trace message stuff */ +/* The first parameter is either type of cinfo pointer */ + +/* Fatal errors (print message and exit) */ +#define ERREXIT(cinfo,code) \ + ((cinfo)->err->msg_code = (code), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT1(cinfo,code,p1) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT2(cinfo,code,p1,p2) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT3(cinfo,code,p1,p2,p3) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (cinfo)->err->msg_parm.i[2] = (p3), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT4(cinfo,code,p1,p2,p3,p4) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (cinfo)->err->msg_parm.i[2] = (p3), \ + (cinfo)->err->msg_parm.i[3] = (p4), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXITS(cinfo,code,str) \ + ((cinfo)->err->msg_code = (code), \ + strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) + +#define MAKESTMT(stuff) do { stuff } while (0) + +/* Nonfatal errors (we can keep going, but the data is probably corrupt) */ +#define WARNMS(cinfo,code) \ + ((cinfo)->err->msg_code = (code), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) +#define WARNMS1(cinfo,code,p1) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) +#define WARNMS2(cinfo,code,p1,p2) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) + +/* Informational/debugging messages */ +#define TRACEMS(cinfo,lvl,code) \ + ((cinfo)->err->msg_code = (code), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) +#define TRACEMS1(cinfo,lvl,code,p1) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) +#define TRACEMS2(cinfo,lvl,code,p1,p2) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) +#define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \ + MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ + _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \ + (cinfo)->err->msg_code = (code); \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) +#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \ + MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ + _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ + (cinfo)->err->msg_code = (code); \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) +#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \ + MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ + _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ + _mp[4] = (p5); \ + (cinfo)->err->msg_code = (code); \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) +#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \ + MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ + _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ + _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \ + (cinfo)->err->msg_code = (code); \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) +#define TRACEMSS(cinfo,lvl,code,str) \ + ((cinfo)->err->msg_code = (code), \ + strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) + +#endif /* JERROR_H */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jfdctflt.c b/SlnkDWFImpl/CxImage/jpeg/jfdctflt.c new file mode 100644 index 0000000..7ccfb38 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jfdctflt.c @@ -0,0 +1,168 @@ +/* + * jfdctflt.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains a floating-point implementation of the + * forward DCT (Discrete Cosine Transform). + * + * This implementation should be more accurate than either of the integer + * DCT implementations. However, it may not give the same results on all + * machines because of differences in roundoff behavior. Speed will depend + * on the hardware's floating point capacity. + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on Arai, Agui, and Nakajima's algorithm for + * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in + * Japanese, but the algorithm is described in the Pennebaker & Mitchell + * JPEG textbook (see REFERENCES section in file README). The following code + * is based directly on figure 4-8 in P&M. + * While an 8-point DCT cannot be done in less than 11 multiplies, it is + * possible to arrange the computation so that many of the multiplies are + * simple scalings of the final outputs. These multiplies can then be + * folded into the multiplications or divisions by the JPEG quantization + * table entries. The AA&N method leaves only 5 multiplies and 29 adds + * to be done in the DCT itself. + * The primary disadvantage of this method is that with a fixed-point + * implementation, accuracy is lost due to imprecise representation of the + * scaled quantization values. However, that problem does not arise if + * we use floating point arithmetic. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + +#ifdef DCT_FLOAT_SUPPORTED + + +/* + * This module is specialized to the case DCTSIZE = 8. + */ + +#if DCTSIZE != 8 + Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ +#endif + + +/* + * Perform the forward DCT on one block of samples. + */ + +GLOBAL(void) +jpeg_fdct_float (FAST_FLOAT * data) +{ + FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; + FAST_FLOAT tmp10, tmp11, tmp12, tmp13; + FAST_FLOAT z1, z2, z3, z4, z5, z11, z13; + FAST_FLOAT *dataptr; + int ctr; + + /* Pass 1: process rows. */ + + dataptr = data; + for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { + tmp0 = dataptr[0] + dataptr[7]; + tmp7 = dataptr[0] - dataptr[7]; + tmp1 = dataptr[1] + dataptr[6]; + tmp6 = dataptr[1] - dataptr[6]; + tmp2 = dataptr[2] + dataptr[5]; + tmp5 = dataptr[2] - dataptr[5]; + tmp3 = dataptr[3] + dataptr[4]; + tmp4 = dataptr[3] - dataptr[4]; + + /* Even part */ + + tmp10 = tmp0 + tmp3; /* phase 2 */ + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + dataptr[0] = tmp10 + tmp11; /* phase 3 */ + dataptr[4] = tmp10 - tmp11; + + z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */ + dataptr[2] = tmp13 + z1; /* phase 5 */ + dataptr[6] = tmp13 - z1; + + /* Odd part */ + + tmp10 = tmp4 + tmp5; /* phase 2 */ + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; + + /* The rotator is modified from fig 4-8 to avoid extra negations. */ + z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */ + z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */ + z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */ + z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */ + + z11 = tmp7 + z3; /* phase 5 */ + z13 = tmp7 - z3; + + dataptr[5] = z13 + z2; /* phase 6 */ + dataptr[3] = z13 - z2; + dataptr[1] = z11 + z4; + dataptr[7] = z11 - z4; + + dataptr += DCTSIZE; /* advance pointer to next row */ + } + + /* Pass 2: process columns. */ + + dataptr = data; + for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { + tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; + tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; + tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; + tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; + tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; + tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; + tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; + tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; + + /* Even part */ + + tmp10 = tmp0 + tmp3; /* phase 2 */ + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */ + dataptr[DCTSIZE*4] = tmp10 - tmp11; + + z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */ + dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */ + dataptr[DCTSIZE*6] = tmp13 - z1; + + /* Odd part */ + + tmp10 = tmp4 + tmp5; /* phase 2 */ + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; + + /* The rotator is modified from fig 4-8 to avoid extra negations. */ + z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */ + z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */ + z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */ + z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */ + + z11 = tmp7 + z3; /* phase 5 */ + z13 = tmp7 - z3; + + dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */ + dataptr[DCTSIZE*3] = z13 - z2; + dataptr[DCTSIZE*1] = z11 + z4; + dataptr[DCTSIZE*7] = z11 - z4; + + dataptr++; /* advance pointer to next column */ + } +} + +#endif /* DCT_FLOAT_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jfdctfst.c b/SlnkDWFImpl/CxImage/jpeg/jfdctfst.c new file mode 100644 index 0000000..005a74f --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jfdctfst.c @@ -0,0 +1,224 @@ +/* + * jfdctfst.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains a fast, not so accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on Arai, Agui, and Nakajima's algorithm for + * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in + * Japanese, but the algorithm is described in the Pennebaker & Mitchell + * JPEG textbook (see REFERENCES section in file README). The following code + * is based directly on figure 4-8 in P&M. + * While an 8-point DCT cannot be done in less than 11 multiplies, it is + * possible to arrange the computation so that many of the multiplies are + * simple scalings of the final outputs. These multiplies can then be + * folded into the multiplications or divisions by the JPEG quantization + * table entries. The AA&N method leaves only 5 multiplies and 29 adds + * to be done in the DCT itself. + * The primary disadvantage of this method is that with fixed-point math, + * accuracy is lost due to imprecise representation of the scaled + * quantization values. The smaller the quantization table entry, the less + * precise the scaled value, so this implementation does worse with high- + * quality-setting files than with low-quality ones. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + +#ifdef DCT_IFAST_SUPPORTED + + +/* + * This module is specialized to the case DCTSIZE = 8. + */ + +#if DCTSIZE != 8 + Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ +#endif + + +/* Scaling decisions are generally the same as in the LL&M algorithm; + * see jfdctint.c for more details. However, we choose to descale + * (right shift) multiplication products as soon as they are formed, + * rather than carrying additional fractional bits into subsequent additions. + * This compromises accuracy slightly, but it lets us save a few shifts. + * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples) + * everywhere except in the multiplications proper; this saves a good deal + * of work on 16-bit-int machines. + * + * Again to save a few shifts, the intermediate results between pass 1 and + * pass 2 are not upscaled, but are represented only to integral precision. + * + * A final compromise is to represent the multiplicative constants to only + * 8 fractional bits, rather than 13. This saves some shifting work on some + * machines, and may also reduce the cost of multiplication (since there + * are fewer one-bits in the constants). + */ + +#define CONST_BITS 8 + + +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus + * causing a lot of useless floating-point operations at run time. + * To get around this we use the following pre-calculated constants. + * If you change CONST_BITS you may want to add appropriate values. + * (With a reasonable C compiler, you can just rely on the FIX() macro...) + */ + +#if CONST_BITS == 8 +#define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */ +#define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */ +#define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */ +#define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */ +#else +#define FIX_0_382683433 FIX(0.382683433) +#define FIX_0_541196100 FIX(0.541196100) +#define FIX_0_707106781 FIX(0.707106781) +#define FIX_1_306562965 FIX(1.306562965) +#endif + + +/* We can gain a little more speed, with a further compromise in accuracy, + * by omitting the addition in a descaling shift. This yields an incorrectly + * rounded result half the time... + */ + +#ifndef USE_ACCURATE_ROUNDING +#undef DESCALE +#define DESCALE(x,n) RIGHT_SHIFT(x, n) +#endif + + +/* Multiply a DCTELEM variable by an INT32 constant, and immediately + * descale to yield a DCTELEM result. + */ + +#define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS)) + + +/* + * Perform the forward DCT on one block of samples. + */ + +GLOBAL(void) +jpeg_fdct_ifast (DCTELEM * data) +{ + DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; + DCTELEM tmp10, tmp11, tmp12, tmp13; + DCTELEM z1, z2, z3, z4, z5, z11, z13; + DCTELEM *dataptr; + int ctr; + SHIFT_TEMPS + + /* Pass 1: process rows. */ + + dataptr = data; + for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { + tmp0 = dataptr[0] + dataptr[7]; + tmp7 = dataptr[0] - dataptr[7]; + tmp1 = dataptr[1] + dataptr[6]; + tmp6 = dataptr[1] - dataptr[6]; + tmp2 = dataptr[2] + dataptr[5]; + tmp5 = dataptr[2] - dataptr[5]; + tmp3 = dataptr[3] + dataptr[4]; + tmp4 = dataptr[3] - dataptr[4]; + + /* Even part */ + + tmp10 = tmp0 + tmp3; /* phase 2 */ + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + dataptr[0] = tmp10 + tmp11; /* phase 3 */ + dataptr[4] = tmp10 - tmp11; + + z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */ + dataptr[2] = tmp13 + z1; /* phase 5 */ + dataptr[6] = tmp13 - z1; + + /* Odd part */ + + tmp10 = tmp4 + tmp5; /* phase 2 */ + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; + + /* The rotator is modified from fig 4-8 to avoid extra negations. */ + z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */ + z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */ + z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */ + z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */ + + z11 = tmp7 + z3; /* phase 5 */ + z13 = tmp7 - z3; + + dataptr[5] = z13 + z2; /* phase 6 */ + dataptr[3] = z13 - z2; + dataptr[1] = z11 + z4; + dataptr[7] = z11 - z4; + + dataptr += DCTSIZE; /* advance pointer to next row */ + } + + /* Pass 2: process columns. */ + + dataptr = data; + for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { + tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; + tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; + tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; + tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; + tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; + tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; + tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; + tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; + + /* Even part */ + + tmp10 = tmp0 + tmp3; /* phase 2 */ + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */ + dataptr[DCTSIZE*4] = tmp10 - tmp11; + + z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */ + dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */ + dataptr[DCTSIZE*6] = tmp13 - z1; + + /* Odd part */ + + tmp10 = tmp4 + tmp5; /* phase 2 */ + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; + + /* The rotator is modified from fig 4-8 to avoid extra negations. */ + z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */ + z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */ + z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */ + z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */ + + z11 = tmp7 + z3; /* phase 5 */ + z13 = tmp7 - z3; + + dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */ + dataptr[DCTSIZE*3] = z13 - z2; + dataptr[DCTSIZE*1] = z11 + z4; + dataptr[DCTSIZE*7] = z11 - z4; + + dataptr++; /* advance pointer to next column */ + } +} + +#endif /* DCT_IFAST_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jfdctint.c b/SlnkDWFImpl/CxImage/jpeg/jfdctint.c new file mode 100644 index 0000000..d626927 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jfdctint.c @@ -0,0 +1,283 @@ +/* + * jfdctint.c + * + * Copyright (C) 1991-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains a slow-but-accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + +#ifdef DCT_ISLOW_SUPPORTED + + +/* + * This module is specialized to the case DCTSIZE = 8. + */ + +#if DCTSIZE != 8 + Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ +#endif + + +/* + * The poop on this scaling stuff is as follows: + * + * Each 1-D DCT step produces outputs which are a factor of sqrt(N) + * larger than the true DCT outputs. The final outputs are therefore + * a factor of N larger than desired; since N=8 this can be cured by + * a simple right shift at the end of the algorithm. The advantage of + * this arrangement is that we save two multiplications per 1-D DCT, + * because the y0 and y4 outputs need not be divided by sqrt(N). + * In the IJG code, this factor of 8 is removed by the quantization step + * (in jcdctmgr.c), NOT in this module. + * + * We have to do addition and subtraction of the integer inputs, which + * is no problem, and multiplication by fractional constants, which is + * a problem to do in integer arithmetic. We multiply all the constants + * by CONST_SCALE and convert them to integer constants (thus retaining + * CONST_BITS bits of precision in the constants). After doing a + * multiplication we have to divide the product by CONST_SCALE, with proper + * rounding, to produce the correct output. This division can be done + * cheaply as a right shift of CONST_BITS bits. We postpone shifting + * as long as possible so that partial sums can be added together with + * full fractional precision. + * + * The outputs of the first pass are scaled up by PASS1_BITS bits so that + * they are represented to better-than-integral precision. These outputs + * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word + * with the recommended scaling. (For 12-bit sample data, the intermediate + * array is INT32 anyway.) + * + * To avoid overflow of the 32-bit intermediate results in pass 2, we must + * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis + * shows that the values given below are the most effective. + */ + +#if BITS_IN_JSAMPLE == 8 +#define CONST_BITS 13 +#define PASS1_BITS 2 +#else +#define CONST_BITS 13 +#define PASS1_BITS 1 /* lose a little precision to avoid overflow */ +#endif + +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus + * causing a lot of useless floating-point operations at run time. + * To get around this we use the following pre-calculated constants. + * If you change CONST_BITS you may want to add appropriate values. + * (With a reasonable C compiler, you can just rely on the FIX() macro...) + */ + +#if CONST_BITS == 13 +#define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */ +#define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */ +#define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */ +#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */ +#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */ +#define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */ +#define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */ +#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */ +#define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */ +#define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */ +#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */ +#define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */ +#else +#define FIX_0_298631336 FIX(0.298631336) +#define FIX_0_390180644 FIX(0.390180644) +#define FIX_0_541196100 FIX(0.541196100) +#define FIX_0_765366865 FIX(0.765366865) +#define FIX_0_899976223 FIX(0.899976223) +#define FIX_1_175875602 FIX(1.175875602) +#define FIX_1_501321110 FIX(1.501321110) +#define FIX_1_847759065 FIX(1.847759065) +#define FIX_1_961570560 FIX(1.961570560) +#define FIX_2_053119869 FIX(2.053119869) +#define FIX_2_562915447 FIX(2.562915447) +#define FIX_3_072711026 FIX(3.072711026) +#endif + + +/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. + * For 8-bit samples with the recommended scaling, all the variable + * and constant values involved are no more than 16 bits wide, so a + * 16x16->32 bit multiply can be used instead of a full 32x32 multiply. + * For 12-bit samples, a full 32-bit multiplication will be needed. + */ + +#if BITS_IN_JSAMPLE == 8 +#define MULTIPLY(var,const) MULTIPLY16C16(var,const) +#else +#define MULTIPLY(var,const) ((var) * (const)) +#endif + + +/* + * Perform the forward DCT on one block of samples. + */ + +GLOBAL(void) +jpeg_fdct_islow (DCTELEM * data) +{ + INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; + INT32 tmp10, tmp11, tmp12, tmp13; + INT32 z1, z2, z3, z4, z5; + DCTELEM *dataptr; + int ctr; + SHIFT_TEMPS + + /* Pass 1: process rows. */ + /* Note results are scaled up by sqrt(8) compared to a true DCT; */ + /* furthermore, we scale the results by 2**PASS1_BITS. */ + + dataptr = data; + for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { + tmp0 = dataptr[0] + dataptr[7]; + tmp7 = dataptr[0] - dataptr[7]; + tmp1 = dataptr[1] + dataptr[6]; + tmp6 = dataptr[1] - dataptr[6]; + tmp2 = dataptr[2] + dataptr[5]; + tmp5 = dataptr[2] - dataptr[5]; + tmp3 = dataptr[3] + dataptr[4]; + tmp4 = dataptr[3] - dataptr[4]; + + /* Even part per LL&M figure 1 --- note that published figure is faulty; + * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". + */ + + tmp10 = tmp0 + tmp3; + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS); + dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS); + + z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); + dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865), + CONST_BITS-PASS1_BITS); + dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065), + CONST_BITS-PASS1_BITS); + + /* Odd part per figure 8 --- note paper omits factor of sqrt(2). + * cK represents cos(K*pi/16). + * i0..i3 in the paper are tmp4..tmp7 here. + */ + + z1 = tmp4 + tmp7; + z2 = tmp5 + tmp6; + z3 = tmp4 + tmp6; + z4 = tmp5 + tmp7; + z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */ + + tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */ + tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */ + tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */ + tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */ + z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */ + z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */ + z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */ + z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */ + + z3 += z5; + z4 += z5; + + dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS); + dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS); + dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS); + dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS); + + dataptr += DCTSIZE; /* advance pointer to next row */ + } + + /* Pass 2: process columns. + * We remove the PASS1_BITS scaling, but leave the results scaled up + * by an overall factor of 8. + */ + + dataptr = data; + for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { + tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; + tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; + tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; + tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; + tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; + tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; + tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; + tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; + + /* Even part per LL&M figure 1 --- note that published figure is faulty; + * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". + */ + + tmp10 = tmp0 + tmp3; + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS); + dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS); + + z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); + dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865), + CONST_BITS+PASS1_BITS); + dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065), + CONST_BITS+PASS1_BITS); + + /* Odd part per figure 8 --- note paper omits factor of sqrt(2). + * cK represents cos(K*pi/16). + * i0..i3 in the paper are tmp4..tmp7 here. + */ + + z1 = tmp4 + tmp7; + z2 = tmp5 + tmp6; + z3 = tmp4 + tmp6; + z4 = tmp5 + tmp7; + z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */ + + tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */ + tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */ + tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */ + tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */ + z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */ + z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */ + z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */ + z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */ + + z3 += z5; + z4 += z5; + + dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, + CONST_BITS+PASS1_BITS); + dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, + CONST_BITS+PASS1_BITS); + dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, + CONST_BITS+PASS1_BITS); + dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, + CONST_BITS+PASS1_BITS); + + dataptr++; /* advance pointer to next column */ + } +} + +#endif /* DCT_ISLOW_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jidctflt.c b/SlnkDWFImpl/CxImage/jpeg/jidctflt.c new file mode 100644 index 0000000..5fea54c --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jidctflt.c @@ -0,0 +1,242 @@ +/* + * jidctflt.c + * + * Copyright (C) 1994-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains a floating-point implementation of the + * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine + * must also perform dequantization of the input coefficients. + * + * This implementation should be more accurate than either of the integer + * IDCT implementations. However, it may not give the same results on all + * machines because of differences in roundoff behavior. Speed will depend + * on the hardware's floating point capacity. + * + * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT + * on each row (or vice versa, but it's more convenient to emit a row at + * a time). Direct algorithms are also available, but they are much more + * complex and seem not to be any faster when reduced to code. + * + * This implementation is based on Arai, Agui, and Nakajima's algorithm for + * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in + * Japanese, but the algorithm is described in the Pennebaker & Mitchell + * JPEG textbook (see REFERENCES section in file README). The following code + * is based directly on figure 4-8 in P&M. + * While an 8-point DCT cannot be done in less than 11 multiplies, it is + * possible to arrange the computation so that many of the multiplies are + * simple scalings of the final outputs. These multiplies can then be + * folded into the multiplications or divisions by the JPEG quantization + * table entries. The AA&N method leaves only 5 multiplies and 29 adds + * to be done in the DCT itself. + * The primary disadvantage of this method is that with a fixed-point + * implementation, accuracy is lost due to imprecise representation of the + * scaled quantization values. However, that problem does not arise if + * we use floating point arithmetic. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + +#ifdef DCT_FLOAT_SUPPORTED + + +/* + * This module is specialized to the case DCTSIZE = 8. + */ + +#if DCTSIZE != 8 + Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ +#endif + + +/* Dequantize a coefficient by multiplying it by the multiplier-table + * entry; produce a float result. + */ + +#define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval)) + + +/* + * Perform dequantization and inverse DCT on one block of coefficients. + */ + +GLOBAL(void) +jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, + JSAMPARRAY output_buf, JDIMENSION output_col) +{ + FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; + FAST_FLOAT tmp10, tmp11, tmp12, tmp13; + FAST_FLOAT z5, z10, z11, z12, z13; + JCOEFPTR inptr; + FLOAT_MULT_TYPE * quantptr; + FAST_FLOAT * wsptr; + JSAMPROW outptr; + JSAMPLE *range_limit = IDCT_range_limit(cinfo); + int ctr; + FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */ + SHIFT_TEMPS + + /* Pass 1: process columns from input, store into work array. */ + + inptr = coef_block; + quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table; + wsptr = workspace; + for (ctr = DCTSIZE; ctr > 0; ctr--) { + /* Due to quantization, we will usually find that many of the input + * coefficients are zero, especially the AC terms. We can exploit this + * by short-circuiting the IDCT calculation for any column in which all + * the AC terms are zero. In that case each output is equal to the + * DC coefficient (with scale factor as needed). + * With typical images and quantization tables, half or more of the + * column DCT calculations can be simplified this way. + */ + + if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && + inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 && + inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 && + inptr[DCTSIZE*7] == 0) { + /* AC terms all zero */ + FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); + + wsptr[DCTSIZE*0] = dcval; + wsptr[DCTSIZE*1] = dcval; + wsptr[DCTSIZE*2] = dcval; + wsptr[DCTSIZE*3] = dcval; + wsptr[DCTSIZE*4] = dcval; + wsptr[DCTSIZE*5] = dcval; + wsptr[DCTSIZE*6] = dcval; + wsptr[DCTSIZE*7] = dcval; + + inptr++; /* advance pointers to next column */ + quantptr++; + wsptr++; + continue; + } + + /* Even part */ + + tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); + tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); + tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); + tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); + + tmp10 = tmp0 + tmp2; /* phase 3 */ + tmp11 = tmp0 - tmp2; + + tmp13 = tmp1 + tmp3; /* phases 5-3 */ + tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */ + + tmp0 = tmp10 + tmp13; /* phase 2 */ + tmp3 = tmp10 - tmp13; + tmp1 = tmp11 + tmp12; + tmp2 = tmp11 - tmp12; + + /* Odd part */ + + tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); + tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); + tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); + tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); + + z13 = tmp6 + tmp5; /* phase 6 */ + z10 = tmp6 - tmp5; + z11 = tmp4 + tmp7; + z12 = tmp4 - tmp7; + + tmp7 = z11 + z13; /* phase 5 */ + tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */ + + z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */ + tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */ + tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */ + + tmp6 = tmp12 - tmp7; /* phase 2 */ + tmp5 = tmp11 - tmp6; + tmp4 = tmp10 + tmp5; + + wsptr[DCTSIZE*0] = tmp0 + tmp7; + wsptr[DCTSIZE*7] = tmp0 - tmp7; + wsptr[DCTSIZE*1] = tmp1 + tmp6; + wsptr[DCTSIZE*6] = tmp1 - tmp6; + wsptr[DCTSIZE*2] = tmp2 + tmp5; + wsptr[DCTSIZE*5] = tmp2 - tmp5; + wsptr[DCTSIZE*4] = tmp3 + tmp4; + wsptr[DCTSIZE*3] = tmp3 - tmp4; + + inptr++; /* advance pointers to next column */ + quantptr++; + wsptr++; + } + + /* Pass 2: process rows from work array, store into output array. */ + /* Note that we must descale the results by a factor of 8 == 2**3. */ + + wsptr = workspace; + for (ctr = 0; ctr < DCTSIZE; ctr++) { + outptr = output_buf[ctr] + output_col; + /* Rows of zeroes can be exploited in the same way as we did with columns. + * However, the column calculation has created many nonzero AC terms, so + * the simplification applies less often (typically 5% to 10% of the time). + * And testing floats for zero is relatively expensive, so we don't bother. + */ + + /* Even part */ + + tmp10 = wsptr[0] + wsptr[4]; + tmp11 = wsptr[0] - wsptr[4]; + + tmp13 = wsptr[2] + wsptr[6]; + tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13; + + tmp0 = tmp10 + tmp13; + tmp3 = tmp10 - tmp13; + tmp1 = tmp11 + tmp12; + tmp2 = tmp11 - tmp12; + + /* Odd part */ + + z13 = wsptr[5] + wsptr[3]; + z10 = wsptr[5] - wsptr[3]; + z11 = wsptr[1] + wsptr[7]; + z12 = wsptr[1] - wsptr[7]; + + tmp7 = z11 + z13; + tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); + + z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */ + tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */ + tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */ + + tmp6 = tmp12 - tmp7; + tmp5 = tmp11 - tmp6; + tmp4 = tmp10 + tmp5; + + /* Final output stage: scale down by a factor of 8 and range-limit */ + + outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3) + & RANGE_MASK]; + outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3) + & RANGE_MASK]; + outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3) + & RANGE_MASK]; + outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3) + & RANGE_MASK]; + outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3) + & RANGE_MASK]; + outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3) + & RANGE_MASK]; + outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3) + & RANGE_MASK]; + outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3) + & RANGE_MASK]; + + wsptr += DCTSIZE; /* advance pointer to next row */ + } +} + +#endif /* DCT_FLOAT_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jidctfst.c b/SlnkDWFImpl/CxImage/jpeg/jidctfst.c new file mode 100644 index 0000000..078b8c4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jidctfst.c @@ -0,0 +1,368 @@ +/* + * jidctfst.c + * + * Copyright (C) 1994-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains a fast, not so accurate integer implementation of the + * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine + * must also perform dequantization of the input coefficients. + * + * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT + * on each row (or vice versa, but it's more convenient to emit a row at + * a time). Direct algorithms are also available, but they are much more + * complex and seem not to be any faster when reduced to code. + * + * This implementation is based on Arai, Agui, and Nakajima's algorithm for + * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in + * Japanese, but the algorithm is described in the Pennebaker & Mitchell + * JPEG textbook (see REFERENCES section in file README). The following code + * is based directly on figure 4-8 in P&M. + * While an 8-point DCT cannot be done in less than 11 multiplies, it is + * possible to arrange the computation so that many of the multiplies are + * simple scalings of the final outputs. These multiplies can then be + * folded into the multiplications or divisions by the JPEG quantization + * table entries. The AA&N method leaves only 5 multiplies and 29 adds + * to be done in the DCT itself. + * The primary disadvantage of this method is that with fixed-point math, + * accuracy is lost due to imprecise representation of the scaled + * quantization values. The smaller the quantization table entry, the less + * precise the scaled value, so this implementation does worse with high- + * quality-setting files than with low-quality ones. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + +#ifdef DCT_IFAST_SUPPORTED + + +/* + * This module is specialized to the case DCTSIZE = 8. + */ + +#if DCTSIZE != 8 + Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ +#endif + + +/* Scaling decisions are generally the same as in the LL&M algorithm; + * see jidctint.c for more details. However, we choose to descale + * (right shift) multiplication products as soon as they are formed, + * rather than carrying additional fractional bits into subsequent additions. + * This compromises accuracy slightly, but it lets us save a few shifts. + * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples) + * everywhere except in the multiplications proper; this saves a good deal + * of work on 16-bit-int machines. + * + * The dequantized coefficients are not integers because the AA&N scaling + * factors have been incorporated. We represent them scaled up by PASS1_BITS, + * so that the first and second IDCT rounds have the same input scaling. + * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to + * avoid a descaling shift; this compromises accuracy rather drastically + * for small quantization table entries, but it saves a lot of shifts. + * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway, + * so we use a much larger scaling factor to preserve accuracy. + * + * A final compromise is to represent the multiplicative constants to only + * 8 fractional bits, rather than 13. This saves some shifting work on some + * machines, and may also reduce the cost of multiplication (since there + * are fewer one-bits in the constants). + */ + +#if BITS_IN_JSAMPLE == 8 +#define CONST_BITS 8 +#define PASS1_BITS 2 +#else +#define CONST_BITS 8 +#define PASS1_BITS 1 /* lose a little precision to avoid overflow */ +#endif + +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus + * causing a lot of useless floating-point operations at run time. + * To get around this we use the following pre-calculated constants. + * If you change CONST_BITS you may want to add appropriate values. + * (With a reasonable C compiler, you can just rely on the FIX() macro...) + */ + +#if CONST_BITS == 8 +#define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */ +#define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */ +#define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */ +#define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */ +#else +#define FIX_1_082392200 FIX(1.082392200) +#define FIX_1_414213562 FIX(1.414213562) +#define FIX_1_847759065 FIX(1.847759065) +#define FIX_2_613125930 FIX(2.613125930) +#endif + + +/* We can gain a little more speed, with a further compromise in accuracy, + * by omitting the addition in a descaling shift. This yields an incorrectly + * rounded result half the time... + */ + +#ifndef USE_ACCURATE_ROUNDING +#undef DESCALE +#define DESCALE(x,n) RIGHT_SHIFT(x, n) +#endif + + +/* Multiply a DCTELEM variable by an INT32 constant, and immediately + * descale to yield a DCTELEM result. + */ + +#define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS)) + + +/* Dequantize a coefficient by multiplying it by the multiplier-table + * entry; produce a DCTELEM result. For 8-bit data a 16x16->16 + * multiplication will do. For 12-bit data, the multiplier table is + * declared INT32, so a 32-bit multiply will be used. + */ + +#if BITS_IN_JSAMPLE == 8 +#define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval)) +#else +#define DEQUANTIZE(coef,quantval) \ + DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS) +#endif + + +/* Like DESCALE, but applies to a DCTELEM and produces an int. + * We assume that int right shift is unsigned if INT32 right shift is. + */ + +#ifdef RIGHT_SHIFT_IS_UNSIGNED +#define ISHIFT_TEMPS DCTELEM ishift_temp; +#if BITS_IN_JSAMPLE == 8 +#define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */ +#else +#define DCTELEMBITS 32 /* DCTELEM must be 32 bits */ +#endif +#define IRIGHT_SHIFT(x,shft) \ + ((ishift_temp = (x)) < 0 ? \ + (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \ + (ishift_temp >> (shft))) +#else +#define ISHIFT_TEMPS +#define IRIGHT_SHIFT(x,shft) ((x) >> (shft)) +#endif + +#ifdef USE_ACCURATE_ROUNDING +#define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n)) +#else +#define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n)) +#endif + + +/* + * Perform dequantization and inverse DCT on one block of coefficients. + */ + +GLOBAL(void) +jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, + JSAMPARRAY output_buf, JDIMENSION output_col) +{ + DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; + DCTELEM tmp10, tmp11, tmp12, tmp13; + DCTELEM z5, z10, z11, z12, z13; + JCOEFPTR inptr; + IFAST_MULT_TYPE * quantptr; + int * wsptr; + JSAMPROW outptr; + JSAMPLE *range_limit = IDCT_range_limit(cinfo); + int ctr; + int workspace[DCTSIZE2]; /* buffers data between passes */ + SHIFT_TEMPS /* for DESCALE */ + ISHIFT_TEMPS /* for IDESCALE */ + + /* Pass 1: process columns from input, store into work array. */ + + inptr = coef_block; + quantptr = (IFAST_MULT_TYPE *) compptr->dct_table; + wsptr = workspace; + for (ctr = DCTSIZE; ctr > 0; ctr--) { + /* Due to quantization, we will usually find that many of the input + * coefficients are zero, especially the AC terms. We can exploit this + * by short-circuiting the IDCT calculation for any column in which all + * the AC terms are zero. In that case each output is equal to the + * DC coefficient (with scale factor as needed). + * With typical images and quantization tables, half or more of the + * column DCT calculations can be simplified this way. + */ + + if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && + inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 && + inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 && + inptr[DCTSIZE*7] == 0) { + /* AC terms all zero */ + int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); + + wsptr[DCTSIZE*0] = dcval; + wsptr[DCTSIZE*1] = dcval; + wsptr[DCTSIZE*2] = dcval; + wsptr[DCTSIZE*3] = dcval; + wsptr[DCTSIZE*4] = dcval; + wsptr[DCTSIZE*5] = dcval; + wsptr[DCTSIZE*6] = dcval; + wsptr[DCTSIZE*7] = dcval; + + inptr++; /* advance pointers to next column */ + quantptr++; + wsptr++; + continue; + } + + /* Even part */ + + tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); + tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); + tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); + tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); + + tmp10 = tmp0 + tmp2; /* phase 3 */ + tmp11 = tmp0 - tmp2; + + tmp13 = tmp1 + tmp3; /* phases 5-3 */ + tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */ + + tmp0 = tmp10 + tmp13; /* phase 2 */ + tmp3 = tmp10 - tmp13; + tmp1 = tmp11 + tmp12; + tmp2 = tmp11 - tmp12; + + /* Odd part */ + + tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); + tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); + tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); + tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); + + z13 = tmp6 + tmp5; /* phase 6 */ + z10 = tmp6 - tmp5; + z11 = tmp4 + tmp7; + z12 = tmp4 - tmp7; + + tmp7 = z11 + z13; /* phase 5 */ + tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */ + + z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */ + tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */ + tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */ + + tmp6 = tmp12 - tmp7; /* phase 2 */ + tmp5 = tmp11 - tmp6; + tmp4 = tmp10 + tmp5; + + wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7); + wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7); + wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6); + wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6); + wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5); + wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5); + wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4); + wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4); + + inptr++; /* advance pointers to next column */ + quantptr++; + wsptr++; + } + + /* Pass 2: process rows from work array, store into output array. */ + /* Note that we must descale the results by a factor of 8 == 2**3, */ + /* and also undo the PASS1_BITS scaling. */ + + wsptr = workspace; + for (ctr = 0; ctr < DCTSIZE; ctr++) { + outptr = output_buf[ctr] + output_col; + /* Rows of zeroes can be exploited in the same way as we did with columns. + * However, the column calculation has created many nonzero AC terms, so + * the simplification applies less often (typically 5% to 10% of the time). + * On machines with very fast multiplication, it's possible that the + * test takes more time than it's worth. In that case this section + * may be commented out. + */ + +#ifndef NO_ZERO_ROW_TEST + if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 && + wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) { + /* AC terms all zero */ + JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3) + & RANGE_MASK]; + + outptr[0] = dcval; + outptr[1] = dcval; + outptr[2] = dcval; + outptr[3] = dcval; + outptr[4] = dcval; + outptr[5] = dcval; + outptr[6] = dcval; + outptr[7] = dcval; + + wsptr += DCTSIZE; /* advance pointer to next row */ + continue; + } +#endif + + /* Even part */ + + tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]); + tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]); + + tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]); + tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562) + - tmp13; + + tmp0 = tmp10 + tmp13; + tmp3 = tmp10 - tmp13; + tmp1 = tmp11 + tmp12; + tmp2 = tmp11 - tmp12; + + /* Odd part */ + + z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3]; + z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3]; + z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7]; + z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7]; + + tmp7 = z11 + z13; /* phase 5 */ + tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */ + + z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */ + tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */ + tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */ + + tmp6 = tmp12 - tmp7; /* phase 2 */ + tmp5 = tmp11 - tmp6; + tmp4 = tmp10 + tmp5; + + /* Final output stage: scale down by a factor of 8 and range-limit */ + + outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3) + & RANGE_MASK]; + outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3) + & RANGE_MASK]; + outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3) + & RANGE_MASK]; + outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3) + & RANGE_MASK]; + outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3) + & RANGE_MASK]; + outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3) + & RANGE_MASK]; + outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3) + & RANGE_MASK]; + outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3) + & RANGE_MASK]; + + wsptr += DCTSIZE; /* advance pointer to next row */ + } +} + +#endif /* DCT_IFAST_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jidctint.c b/SlnkDWFImpl/CxImage/jpeg/jidctint.c new file mode 100644 index 0000000..4f47fe8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jidctint.c @@ -0,0 +1,389 @@ +/* + * jidctint.c + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains a slow-but-accurate integer implementation of the + * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine + * must also perform dequantization of the input coefficients. + * + * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT + * on each row (or vice versa, but it's more convenient to emit a row at + * a time). Direct algorithms are also available, but they are much more + * complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + +#ifdef DCT_ISLOW_SUPPORTED + + +/* + * This module is specialized to the case DCTSIZE = 8. + */ + +#if DCTSIZE != 8 + Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ +#endif + + +/* + * The poop on this scaling stuff is as follows: + * + * Each 1-D IDCT step produces outputs which are a factor of sqrt(N) + * larger than the true IDCT outputs. The final outputs are therefore + * a factor of N larger than desired; since N=8 this can be cured by + * a simple right shift at the end of the algorithm. The advantage of + * this arrangement is that we save two multiplications per 1-D IDCT, + * because the y0 and y4 inputs need not be divided by sqrt(N). + * + * We have to do addition and subtraction of the integer inputs, which + * is no problem, and multiplication by fractional constants, which is + * a problem to do in integer arithmetic. We multiply all the constants + * by CONST_SCALE and convert them to integer constants (thus retaining + * CONST_BITS bits of precision in the constants). After doing a + * multiplication we have to divide the product by CONST_SCALE, with proper + * rounding, to produce the correct output. This division can be done + * cheaply as a right shift of CONST_BITS bits. We postpone shifting + * as long as possible so that partial sums can be added together with + * full fractional precision. + * + * The outputs of the first pass are scaled up by PASS1_BITS bits so that + * they are represented to better-than-integral precision. These outputs + * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word + * with the recommended scaling. (To scale up 12-bit sample data further, an + * intermediate INT32 array would be needed.) + * + * To avoid overflow of the 32-bit intermediate results in pass 2, we must + * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis + * shows that the values given below are the most effective. + */ + +#if BITS_IN_JSAMPLE == 8 +#define CONST_BITS 13 +#define PASS1_BITS 2 +#else +#define CONST_BITS 13 +#define PASS1_BITS 1 /* lose a little precision to avoid overflow */ +#endif + +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus + * causing a lot of useless floating-point operations at run time. + * To get around this we use the following pre-calculated constants. + * If you change CONST_BITS you may want to add appropriate values. + * (With a reasonable C compiler, you can just rely on the FIX() macro...) + */ + +#if CONST_BITS == 13 +#define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */ +#define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */ +#define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */ +#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */ +#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */ +#define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */ +#define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */ +#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */ +#define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */ +#define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */ +#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */ +#define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */ +#else +#define FIX_0_298631336 FIX(0.298631336) +#define FIX_0_390180644 FIX(0.390180644) +#define FIX_0_541196100 FIX(0.541196100) +#define FIX_0_765366865 FIX(0.765366865) +#define FIX_0_899976223 FIX(0.899976223) +#define FIX_1_175875602 FIX(1.175875602) +#define FIX_1_501321110 FIX(1.501321110) +#define FIX_1_847759065 FIX(1.847759065) +#define FIX_1_961570560 FIX(1.961570560) +#define FIX_2_053119869 FIX(2.053119869) +#define FIX_2_562915447 FIX(2.562915447) +#define FIX_3_072711026 FIX(3.072711026) +#endif + + +/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. + * For 8-bit samples with the recommended scaling, all the variable + * and constant values involved are no more than 16 bits wide, so a + * 16x16->32 bit multiply can be used instead of a full 32x32 multiply. + * For 12-bit samples, a full 32-bit multiplication will be needed. + */ + +#if BITS_IN_JSAMPLE == 8 +#define MULTIPLY(var,const) MULTIPLY16C16(var,const) +#else +#define MULTIPLY(var,const) ((var) * (const)) +#endif + + +/* Dequantize a coefficient by multiplying it by the multiplier-table + * entry; produce an int result. In this module, both inputs and result + * are 16 bits or less, so either int or short multiply will work. + */ + +#define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval)) + + +/* + * Perform dequantization and inverse DCT on one block of coefficients. + */ + +GLOBAL(void) +jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, + JSAMPARRAY output_buf, JDIMENSION output_col) +{ + INT32 tmp0, tmp1, tmp2, tmp3; + INT32 tmp10, tmp11, tmp12, tmp13; + INT32 z1, z2, z3, z4, z5; + JCOEFPTR inptr; + ISLOW_MULT_TYPE * quantptr; + int * wsptr; + JSAMPROW outptr; + JSAMPLE *range_limit = IDCT_range_limit(cinfo); + int ctr; + int workspace[DCTSIZE2]; /* buffers data between passes */ + SHIFT_TEMPS + + /* Pass 1: process columns from input, store into work array. */ + /* Note results are scaled up by sqrt(8) compared to a true IDCT; */ + /* furthermore, we scale the results by 2**PASS1_BITS. */ + + inptr = coef_block; + quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; + wsptr = workspace; + for (ctr = DCTSIZE; ctr > 0; ctr--) { + /* Due to quantization, we will usually find that many of the input + * coefficients are zero, especially the AC terms. We can exploit this + * by short-circuiting the IDCT calculation for any column in which all + * the AC terms are zero. In that case each output is equal to the + * DC coefficient (with scale factor as needed). + * With typical images and quantization tables, half or more of the + * column DCT calculations can be simplified this way. + */ + + if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && + inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 && + inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 && + inptr[DCTSIZE*7] == 0) { + /* AC terms all zero */ + int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS; + + wsptr[DCTSIZE*0] = dcval; + wsptr[DCTSIZE*1] = dcval; + wsptr[DCTSIZE*2] = dcval; + wsptr[DCTSIZE*3] = dcval; + wsptr[DCTSIZE*4] = dcval; + wsptr[DCTSIZE*5] = dcval; + wsptr[DCTSIZE*6] = dcval; + wsptr[DCTSIZE*7] = dcval; + + inptr++; /* advance pointers to next column */ + quantptr++; + wsptr++; + continue; + } + + /* Even part: reverse the even part of the forward DCT. */ + /* The rotator is sqrt(2)*c(-6). */ + + z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); + z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); + + z1 = MULTIPLY(z2 + z3, FIX_0_541196100); + tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065); + tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865); + + z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); + z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); + + tmp0 = (z2 + z3) << CONST_BITS; + tmp1 = (z2 - z3) << CONST_BITS; + + tmp10 = tmp0 + tmp3; + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + /* Odd part per figure 8; the matrix is unitary and hence its + * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. + */ + + tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); + tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); + tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); + tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); + + z1 = tmp0 + tmp3; + z2 = tmp1 + tmp2; + z3 = tmp0 + tmp2; + z4 = tmp1 + tmp3; + z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */ + + tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */ + tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */ + tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */ + tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */ + z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */ + z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */ + z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */ + z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */ + + z3 += z5; + z4 += z5; + + tmp0 += z1 + z3; + tmp1 += z2 + z4; + tmp2 += z2 + z3; + tmp3 += z1 + z4; + + /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ + + wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS); + wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS); + wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS); + wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS); + wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS); + wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS); + wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS); + wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS); + + inptr++; /* advance pointers to next column */ + quantptr++; + wsptr++; + } + + /* Pass 2: process rows from work array, store into output array. */ + /* Note that we must descale the results by a factor of 8 == 2**3, */ + /* and also undo the PASS1_BITS scaling. */ + + wsptr = workspace; + for (ctr = 0; ctr < DCTSIZE; ctr++) { + outptr = output_buf[ctr] + output_col; + /* Rows of zeroes can be exploited in the same way as we did with columns. + * However, the column calculation has created many nonzero AC terms, so + * the simplification applies less often (typically 5% to 10% of the time). + * On machines with very fast multiplication, it's possible that the + * test takes more time than it's worth. In that case this section + * may be commented out. + */ + +#ifndef NO_ZERO_ROW_TEST + if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 && + wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) { + /* AC terms all zero */ + JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3) + & RANGE_MASK]; + + outptr[0] = dcval; + outptr[1] = dcval; + outptr[2] = dcval; + outptr[3] = dcval; + outptr[4] = dcval; + outptr[5] = dcval; + outptr[6] = dcval; + outptr[7] = dcval; + + wsptr += DCTSIZE; /* advance pointer to next row */ + continue; + } +#endif + + /* Even part: reverse the even part of the forward DCT. */ + /* The rotator is sqrt(2)*c(-6). */ + + z2 = (INT32) wsptr[2]; + z3 = (INT32) wsptr[6]; + + z1 = MULTIPLY(z2 + z3, FIX_0_541196100); + tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065); + tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865); + + tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS; + tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS; + + tmp10 = tmp0 + tmp3; + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + /* Odd part per figure 8; the matrix is unitary and hence its + * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. + */ + + tmp0 = (INT32) wsptr[7]; + tmp1 = (INT32) wsptr[5]; + tmp2 = (INT32) wsptr[3]; + tmp3 = (INT32) wsptr[1]; + + z1 = tmp0 + tmp3; + z2 = tmp1 + tmp2; + z3 = tmp0 + tmp2; + z4 = tmp1 + tmp3; + z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */ + + tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */ + tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */ + tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */ + tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */ + z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */ + z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */ + z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */ + z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */ + + z3 += z5; + z4 += z5; + + tmp0 += z1 + z3; + tmp1 += z2 + z4; + tmp2 += z2 + z3; + tmp3 += z1 + z4; + + /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ + + outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3, + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK]; + outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3, + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK]; + outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2, + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK]; + outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2, + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK]; + outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1, + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK]; + outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1, + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK]; + outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0, + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK]; + outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0, + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK]; + + wsptr += DCTSIZE; /* advance pointer to next row */ + } +} + +#endif /* DCT_ISLOW_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jidctred.c b/SlnkDWFImpl/CxImage/jpeg/jidctred.c new file mode 100644 index 0000000..911899b --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jidctred.c @@ -0,0 +1,398 @@ +/* + * jidctred.c + * + * Copyright (C) 1994-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains inverse-DCT routines that produce reduced-size output: + * either 4x4, 2x2, or 1x1 pixels from an 8x8 DCT block. + * + * The implementation is based on the Loeffler, Ligtenberg and Moschytz (LL&M) + * algorithm used in jidctint.c. We simply replace each 8-to-8 1-D IDCT step + * with an 8-to-4 step that produces the four averages of two adjacent outputs + * (or an 8-to-2 step producing two averages of four outputs, for 2x2 output). + * These steps were derived by computing the corresponding values at the end + * of the normal LL&M code, then simplifying as much as possible. + * + * 1x1 is trivial: just take the DC coefficient divided by 8. + * + * See jidctint.c for additional comments. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jdct.h" /* Private declarations for DCT subsystem */ + +#ifdef IDCT_SCALING_SUPPORTED + + +/* + * This module is specialized to the case DCTSIZE = 8. + */ + +#if DCTSIZE != 8 + Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ +#endif + + +/* Scaling is the same as in jidctint.c. */ + +#if BITS_IN_JSAMPLE == 8 +#define CONST_BITS 13 +#define PASS1_BITS 2 +#else +#define CONST_BITS 13 +#define PASS1_BITS 1 /* lose a little precision to avoid overflow */ +#endif + +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus + * causing a lot of useless floating-point operations at run time. + * To get around this we use the following pre-calculated constants. + * If you change CONST_BITS you may want to add appropriate values. + * (With a reasonable C compiler, you can just rely on the FIX() macro...) + */ + +#if CONST_BITS == 13 +#define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */ +#define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */ +#define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */ +#define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */ +#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */ +#define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */ +#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */ +#define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */ +#define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */ +#define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */ +#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */ +#define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */ +#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */ +#define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */ +#else +#define FIX_0_211164243 FIX(0.211164243) +#define FIX_0_509795579 FIX(0.509795579) +#define FIX_0_601344887 FIX(0.601344887) +#define FIX_0_720959822 FIX(0.720959822) +#define FIX_0_765366865 FIX(0.765366865) +#define FIX_0_850430095 FIX(0.850430095) +#define FIX_0_899976223 FIX(0.899976223) +#define FIX_1_061594337 FIX(1.061594337) +#define FIX_1_272758580 FIX(1.272758580) +#define FIX_1_451774981 FIX(1.451774981) +#define FIX_1_847759065 FIX(1.847759065) +#define FIX_2_172734803 FIX(2.172734803) +#define FIX_2_562915447 FIX(2.562915447) +#define FIX_3_624509785 FIX(3.624509785) +#endif + + +/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. + * For 8-bit samples with the recommended scaling, all the variable + * and constant values involved are no more than 16 bits wide, so a + * 16x16->32 bit multiply can be used instead of a full 32x32 multiply. + * For 12-bit samples, a full 32-bit multiplication will be needed. + */ + +#if BITS_IN_JSAMPLE == 8 +#define MULTIPLY(var,const) MULTIPLY16C16(var,const) +#else +#define MULTIPLY(var,const) ((var) * (const)) +#endif + + +/* Dequantize a coefficient by multiplying it by the multiplier-table + * entry; produce an int result. In this module, both inputs and result + * are 16 bits or less, so either int or short multiply will work. + */ + +#define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval)) + + +/* + * Perform dequantization and inverse DCT on one block of coefficients, + * producing a reduced-size 4x4 output block. + */ + +GLOBAL(void) +jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, + JSAMPARRAY output_buf, JDIMENSION output_col) +{ + INT32 tmp0, tmp2, tmp10, tmp12; + INT32 z1, z2, z3, z4; + JCOEFPTR inptr; + ISLOW_MULT_TYPE * quantptr; + int * wsptr; + JSAMPROW outptr; + JSAMPLE *range_limit = IDCT_range_limit(cinfo); + int ctr; + int workspace[DCTSIZE*4]; /* buffers data between passes */ + SHIFT_TEMPS + + /* Pass 1: process columns from input, store into work array. */ + + inptr = coef_block; + quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; + wsptr = workspace; + for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) { + /* Don't bother to process column 4, because second pass won't use it */ + if (ctr == DCTSIZE-4) + continue; + if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && + inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 && + inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) { + /* AC terms all zero; we need not examine term 4 for 4x4 output */ + int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS; + + wsptr[DCTSIZE*0] = dcval; + wsptr[DCTSIZE*1] = dcval; + wsptr[DCTSIZE*2] = dcval; + wsptr[DCTSIZE*3] = dcval; + + continue; + } + + /* Even part */ + + tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); + tmp0 <<= (CONST_BITS+1); + + z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); + z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); + + tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865); + + tmp10 = tmp0 + tmp2; + tmp12 = tmp0 - tmp2; + + /* Odd part */ + + z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); + z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); + z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); + z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); + + tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */ + + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */ + + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */ + + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */ + + tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */ + + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */ + + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */ + + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */ + + /* Final output stage */ + + wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1); + wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1); + wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1); + wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1); + } + + /* Pass 2: process 4 rows from work array, store into output array. */ + + wsptr = workspace; + for (ctr = 0; ctr < 4; ctr++) { + outptr = output_buf[ctr] + output_col; + /* It's not clear whether a zero row test is worthwhile here ... */ + +#ifndef NO_ZERO_ROW_TEST + if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && + wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) { + /* AC terms all zero */ + JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3) + & RANGE_MASK]; + + outptr[0] = dcval; + outptr[1] = dcval; + outptr[2] = dcval; + outptr[3] = dcval; + + wsptr += DCTSIZE; /* advance pointer to next row */ + continue; + } +#endif + + /* Even part */ + + tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1); + + tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065) + + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865); + + tmp10 = tmp0 + tmp2; + tmp12 = tmp0 - tmp2; + + /* Odd part */ + + z1 = (INT32) wsptr[7]; + z2 = (INT32) wsptr[5]; + z3 = (INT32) wsptr[3]; + z4 = (INT32) wsptr[1]; + + tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */ + + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */ + + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */ + + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */ + + tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */ + + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */ + + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */ + + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */ + + /* Final output stage */ + + outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2, + CONST_BITS+PASS1_BITS+3+1) + & RANGE_MASK]; + outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2, + CONST_BITS+PASS1_BITS+3+1) + & RANGE_MASK]; + outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0, + CONST_BITS+PASS1_BITS+3+1) + & RANGE_MASK]; + outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0, + CONST_BITS+PASS1_BITS+3+1) + & RANGE_MASK]; + + wsptr += DCTSIZE; /* advance pointer to next row */ + } +} + + +/* + * Perform dequantization and inverse DCT on one block of coefficients, + * producing a reduced-size 2x2 output block. + */ + +GLOBAL(void) +jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, + JSAMPARRAY output_buf, JDIMENSION output_col) +{ + INT32 tmp0, tmp10, z1; + JCOEFPTR inptr; + ISLOW_MULT_TYPE * quantptr; + int * wsptr; + JSAMPROW outptr; + JSAMPLE *range_limit = IDCT_range_limit(cinfo); + int ctr; + int workspace[DCTSIZE*2]; /* buffers data between passes */ + SHIFT_TEMPS + + /* Pass 1: process columns from input, store into work array. */ + + inptr = coef_block; + quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; + wsptr = workspace; + for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) { + /* Don't bother to process columns 2,4,6 */ + if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6) + continue; + if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 && + inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) { + /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */ + int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS; + + wsptr[DCTSIZE*0] = dcval; + wsptr[DCTSIZE*1] = dcval; + + continue; + } + + /* Even part */ + + z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); + tmp10 = z1 << (CONST_BITS+2); + + /* Odd part */ + + z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); + tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */ + z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); + tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */ + z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); + tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */ + z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); + tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */ + + /* Final output stage */ + + wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2); + wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2); + } + + /* Pass 2: process 2 rows from work array, store into output array. */ + + wsptr = workspace; + for (ctr = 0; ctr < 2; ctr++) { + outptr = output_buf[ctr] + output_col; + /* It's not clear whether a zero row test is worthwhile here ... */ + +#ifndef NO_ZERO_ROW_TEST + if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) { + /* AC terms all zero */ + JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3) + & RANGE_MASK]; + + outptr[0] = dcval; + outptr[1] = dcval; + + wsptr += DCTSIZE; /* advance pointer to next row */ + continue; + } +#endif + + /* Even part */ + + tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2); + + /* Odd part */ + + tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */ + + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */ + + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */ + + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */ + + /* Final output stage */ + + outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0, + CONST_BITS+PASS1_BITS+3+2) + & RANGE_MASK]; + outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0, + CONST_BITS+PASS1_BITS+3+2) + & RANGE_MASK]; + + wsptr += DCTSIZE; /* advance pointer to next row */ + } +} + + +/* + * Perform dequantization and inverse DCT on one block of coefficients, + * producing a reduced-size 1x1 output block. + */ + +GLOBAL(void) +jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, + JSAMPARRAY output_buf, JDIMENSION output_col) +{ + int dcval; + ISLOW_MULT_TYPE * quantptr; + JSAMPLE *range_limit = IDCT_range_limit(cinfo); + SHIFT_TEMPS + + /* We hardly need an inverse DCT routine for this: just take the + * average pixel value, which is one-eighth of the DC coefficient. + */ + quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; + dcval = DEQUANTIZE(coef_block[0], quantptr[0]); + dcval = (int) DESCALE((INT32) dcval, 3); + + output_buf[0][output_col] = range_limit[dcval & RANGE_MASK]; +} + +#endif /* IDCT_SCALING_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jinclude.h b/SlnkDWFImpl/CxImage/jpeg/jinclude.h new file mode 100644 index 0000000..5ff60fe --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jinclude.h @@ -0,0 +1,91 @@ +/* + * jinclude.h + * + * Copyright (C) 1991-1994, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file exists to provide a single place to fix any problems with + * including the wrong system include files. (Common problems are taken + * care of by the standard jconfig symbols, but on really weird systems + * you may have to edit this file.) + * + * NOTE: this file is NOT intended to be included by applications using the + * JPEG library. Most applications need only include jpeglib.h. + */ + + +/* Include auto-config file to find out which system include files we need. */ + +#include "jconfig.h" /* auto configuration options */ +#define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */ + +/* + * We need the NULL macro and size_t typedef. + * On an ANSI-conforming system it is sufficient to include . + * Otherwise, we get them from or ; we may have to + * pull in as well. + * Note that the core JPEG library does not require ; + * only the default error handler and data source/destination modules do. + * But we must pull it in because of the references to FILE in jpeglib.h. + * You can remove those references if you want to compile without . + */ + +#ifdef HAVE_STDDEF_H +#include +#endif + +#ifdef HAVE_STDLIB_H +#include +#endif + +#ifdef NEED_SYS_TYPES_H +#include +#endif + +#include + +/* + * We need memory copying and zeroing functions, plus strncpy(). + * ANSI and System V implementations declare these in . + * BSD doesn't have the mem() functions, but it does have bcopy()/bzero(). + * Some systems may declare memset and memcpy in . + * + * NOTE: we assume the size parameters to these functions are of type size_t. + * Change the casts in these macros if not! + */ + +#ifdef NEED_BSD_STRINGS + +#include +#define MEMZERO(target,size) bzero((void *)(target), (size_t)(size)) +#define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size)) + +#else /* not BSD, assume ANSI/SysV string lib */ + +#include +#define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size)) +#define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size)) + +#endif + +/* + * In ANSI C, and indeed any rational implementation, size_t is also the + * type returned by sizeof(). However, it seems there are some irrational + * implementations out there, in which sizeof() returns an int even though + * size_t is defined as long or unsigned long. To ensure consistent results + * we always use this SIZEOF() macro in place of using sizeof() directly. + */ + +#define SIZEOF(object) ((size_t) sizeof(object)) + +/* + * The modules that use fread() and fwrite() always invoke them through + * these macros. On some systems you may need to twiddle the argument casts. + * CAUTION: argument order is different from underlying functions! + */ + +#define JFREAD(file,buf,sizeofbuf) \ + ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file))) +#define JFWRITE(file,buf,sizeofbuf) \ + ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file))) diff --git a/SlnkDWFImpl/CxImage/jpeg/jmemmgr.c b/SlnkDWFImpl/CxImage/jpeg/jmemmgr.c new file mode 100644 index 0000000..b636f1b --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jmemmgr.c @@ -0,0 +1,1118 @@ +/* + * jmemmgr.c + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains the JPEG system-independent memory management + * routines. This code is usable across a wide variety of machines; most + * of the system dependencies have been isolated in a separate file. + * The major functions provided here are: + * * pool-based allocation and freeing of memory; + * * policy decisions about how to divide available memory among the + * virtual arrays; + * * control logic for swapping virtual arrays between main memory and + * backing storage. + * The separate system-dependent file provides the actual backing-storage + * access code, and it contains the policy decision about how much total + * main memory to use. + * This file is system-dependent in the sense that some of its functions + * are unnecessary in some systems. For example, if there is enough virtual + * memory so that backing storage will never be used, much of the virtual + * array control logic could be removed. (Of course, if you have that much + * memory then you shouldn't care about a little bit of unused code...) + */ + +#define JPEG_INTERNALS +#define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */ +#include "jinclude.h" +#include "jpeglib.h" +#include "jmemsys.h" /* import the system-dependent declarations */ + +#ifndef NO_GETENV +#ifndef HAVE_STDLIB_H /* should declare getenv() */ +extern char * getenv JPP((const char * name)); +#endif +#endif + + +/* + * Some important notes: + * The allocation routines provided here must never return NULL. + * They should exit to error_exit if unsuccessful. + * + * It's not a good idea to try to merge the sarray and barray routines, + * even though they are textually almost the same, because samples are + * usually stored as bytes while coefficients are shorts or ints. Thus, + * in machines where byte pointers have a different representation from + * word pointers, the resulting machine code could not be the same. + */ + + +/* + * Many machines require storage alignment: longs must start on 4-byte + * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc() + * always returns pointers that are multiples of the worst-case alignment + * requirement, and we had better do so too. + * There isn't any really portable way to determine the worst-case alignment + * requirement. This module assumes that the alignment requirement is + * multiples of sizeof(ALIGN_TYPE). + * By default, we define ALIGN_TYPE as double. This is necessary on some + * workstations (where doubles really do need 8-byte alignment) and will work + * fine on nearly everything. If your machine has lesser alignment needs, + * you can save a few bytes by making ALIGN_TYPE smaller. + * The only place I know of where this will NOT work is certain Macintosh + * 680x0 compilers that define double as a 10-byte IEEE extended float. + * Doing 10-byte alignment is counterproductive because longwords won't be + * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have + * such a compiler. + */ + +#ifndef ALIGN_TYPE /* so can override from jconfig.h */ +#define ALIGN_TYPE double +#endif + + +/* + * We allocate objects from "pools", where each pool is gotten with a single + * request to jpeg_get_small() or jpeg_get_large(). There is no per-object + * overhead within a pool, except for alignment padding. Each pool has a + * header with a link to the next pool of the same class. + * Small and large pool headers are identical except that the latter's + * link pointer must be FAR on 80x86 machines. + * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE + * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple + * of the alignment requirement of ALIGN_TYPE. + */ + +typedef union small_pool_struct * small_pool_ptr; + +typedef union small_pool_struct { + struct { + small_pool_ptr next; /* next in list of pools */ + size_t bytes_used; /* how many bytes already used within pool */ + size_t bytes_left; /* bytes still available in this pool */ + } hdr; + ALIGN_TYPE dummy; /* included in union to ensure alignment */ +} small_pool_hdr; + +typedef union large_pool_struct FAR * large_pool_ptr; + +typedef union large_pool_struct { + struct { + large_pool_ptr next; /* next in list of pools */ + size_t bytes_used; /* how many bytes already used within pool */ + size_t bytes_left; /* bytes still available in this pool */ + } hdr; + ALIGN_TYPE dummy; /* included in union to ensure alignment */ +} large_pool_hdr; + + +/* + * Here is the full definition of a memory manager object. + */ + +typedef struct { + struct jpeg_memory_mgr pub; /* public fields */ + + /* Each pool identifier (lifetime class) names a linked list of pools. */ + small_pool_ptr small_list[JPOOL_NUMPOOLS]; + large_pool_ptr large_list[JPOOL_NUMPOOLS]; + + /* Since we only have one lifetime class of virtual arrays, only one + * linked list is necessary (for each datatype). Note that the virtual + * array control blocks being linked together are actually stored somewhere + * in the small-pool list. + */ + jvirt_sarray_ptr virt_sarray_list; + jvirt_barray_ptr virt_barray_list; + + /* This counts total space obtained from jpeg_get_small/large */ + long total_space_allocated; + + /* alloc_sarray and alloc_barray set this value for use by virtual + * array routines. + */ + JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */ +} my_memory_mgr; + +typedef my_memory_mgr * my_mem_ptr; + + +/* + * The control blocks for virtual arrays. + * Note that these blocks are allocated in the "small" pool area. + * System-dependent info for the associated backing store (if any) is hidden + * inside the backing_store_info struct. + */ + +struct jvirt_sarray_control { + JSAMPARRAY mem_buffer; /* => the in-memory buffer */ + JDIMENSION rows_in_array; /* total virtual array height */ + JDIMENSION samplesperrow; /* width of array (and of memory buffer) */ + JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */ + JDIMENSION rows_in_mem; /* height of memory buffer */ + JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */ + JDIMENSION cur_start_row; /* first logical row # in the buffer */ + JDIMENSION first_undef_row; /* row # of first uninitialized row */ + boolean pre_zero; /* pre-zero mode requested? */ + boolean dirty; /* do current buffer contents need written? */ + boolean b_s_open; /* is backing-store data valid? */ + jvirt_sarray_ptr next; /* link to next virtual sarray control block */ + backing_store_info b_s_info; /* System-dependent control info */ +}; + +struct jvirt_barray_control { + JBLOCKARRAY mem_buffer; /* => the in-memory buffer */ + JDIMENSION rows_in_array; /* total virtual array height */ + JDIMENSION blocksperrow; /* width of array (and of memory buffer) */ + JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */ + JDIMENSION rows_in_mem; /* height of memory buffer */ + JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */ + JDIMENSION cur_start_row; /* first logical row # in the buffer */ + JDIMENSION first_undef_row; /* row # of first uninitialized row */ + boolean pre_zero; /* pre-zero mode requested? */ + boolean dirty; /* do current buffer contents need written? */ + boolean b_s_open; /* is backing-store data valid? */ + jvirt_barray_ptr next; /* link to next virtual barray control block */ + backing_store_info b_s_info; /* System-dependent control info */ +}; + + +#ifdef MEM_STATS /* optional extra stuff for statistics */ + +LOCAL(void) +print_mem_stats (j_common_ptr cinfo, int pool_id) +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + small_pool_ptr shdr_ptr; + large_pool_ptr lhdr_ptr; + + /* Since this is only a debugging stub, we can cheat a little by using + * fprintf directly rather than going through the trace message code. + * This is helpful because message parm array can't handle longs. + */ + fprintf(stderr, "Freeing pool %d, total space = %ld\n", + pool_id, mem->total_space_allocated); + + for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL; + lhdr_ptr = lhdr_ptr->hdr.next) { + fprintf(stderr, " Large chunk used %ld\n", + (long) lhdr_ptr->hdr.bytes_used); + } + + for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL; + shdr_ptr = shdr_ptr->hdr.next) { + fprintf(stderr, " Small chunk used %ld free %ld\n", + (long) shdr_ptr->hdr.bytes_used, + (long) shdr_ptr->hdr.bytes_left); + } +} + +#endif /* MEM_STATS */ + + +LOCAL(void) +out_of_memory (j_common_ptr cinfo, int which) +/* Report an out-of-memory error and stop execution */ +/* If we compiled MEM_STATS support, report alloc requests before dying */ +{ +#ifdef MEM_STATS + cinfo->err->trace_level = 2; /* force self_destruct to report stats */ +#endif + ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which); +} + + +/* + * Allocation of "small" objects. + * + * For these, we use pooled storage. When a new pool must be created, + * we try to get enough space for the current request plus a "slop" factor, + * where the slop will be the amount of leftover space in the new pool. + * The speed vs. space tradeoff is largely determined by the slop values. + * A different slop value is provided for each pool class (lifetime), + * and we also distinguish the first pool of a class from later ones. + * NOTE: the values given work fairly well on both 16- and 32-bit-int + * machines, but may be too small if longs are 64 bits or more. + */ + +static const size_t first_pool_slop[JPOOL_NUMPOOLS] = +{ + 1600, /* first PERMANENT pool */ + 16000 /* first IMAGE pool */ +}; + +static const size_t extra_pool_slop[JPOOL_NUMPOOLS] = +{ + 0, /* additional PERMANENT pools */ + 5000 /* additional IMAGE pools */ +}; + +#define MIN_SLOP 50 /* greater than 0 to avoid futile looping */ + + +METHODDEF(void *) +alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject) +/* Allocate a "small" object */ +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + small_pool_ptr hdr_ptr, prev_hdr_ptr; + char * data_ptr; + size_t odd_bytes, min_request, slop; + + /* Check for unsatisfiable request (do now to ensure no overflow below) */ + if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr))) + out_of_memory(cinfo, 1); /* request exceeds malloc's ability */ + + /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */ + odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE); + if (odd_bytes > 0) + sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes; + + /* See if space is available in any existing pool */ + if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS) + ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ + prev_hdr_ptr = NULL; + hdr_ptr = mem->small_list[pool_id]; + while (hdr_ptr != NULL) { + if (hdr_ptr->hdr.bytes_left >= sizeofobject) + break; /* found pool with enough space */ + prev_hdr_ptr = hdr_ptr; + hdr_ptr = hdr_ptr->hdr.next; + } + + /* Time to make a new pool? */ + if (hdr_ptr == NULL) { + /* min_request is what we need now, slop is what will be leftover */ + min_request = sizeofobject + SIZEOF(small_pool_hdr); + if (prev_hdr_ptr == NULL) /* first pool in class? */ + slop = first_pool_slop[pool_id]; + else + slop = extra_pool_slop[pool_id]; + /* Don't ask for more than MAX_ALLOC_CHUNK */ + if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request)) + slop = (size_t) (MAX_ALLOC_CHUNK-min_request); + /* Try to get space, if fail reduce slop and try again */ + for (;;) { + hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop); + if (hdr_ptr != NULL) + break; + slop /= 2; + if (slop < MIN_SLOP) /* give up when it gets real small */ + out_of_memory(cinfo, 2); /* jpeg_get_small failed */ + } + mem->total_space_allocated += min_request + slop; + /* Success, initialize the new pool header and add to end of list */ + hdr_ptr->hdr.next = NULL; + hdr_ptr->hdr.bytes_used = 0; + hdr_ptr->hdr.bytes_left = sizeofobject + slop; + if (prev_hdr_ptr == NULL) /* first pool in class? */ + mem->small_list[pool_id] = hdr_ptr; + else + prev_hdr_ptr->hdr.next = hdr_ptr; + } + + /* OK, allocate the object from the current pool */ + data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */ + data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */ + hdr_ptr->hdr.bytes_used += sizeofobject; + hdr_ptr->hdr.bytes_left -= sizeofobject; + + return (void *) data_ptr; +} + + +/* + * Allocation of "large" objects. + * + * The external semantics of these are the same as "small" objects, + * except that FAR pointers are used on 80x86. However the pool + * management heuristics are quite different. We assume that each + * request is large enough that it may as well be passed directly to + * jpeg_get_large; the pool management just links everything together + * so that we can free it all on demand. + * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY + * structures. The routines that create these structures (see below) + * deliberately bunch rows together to ensure a large request size. + */ + +METHODDEF(void FAR *) +alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject) +/* Allocate a "large" object */ +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + large_pool_ptr hdr_ptr; + size_t odd_bytes; + + /* Check for unsatisfiable request (do now to ensure no overflow below) */ + if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr))) + out_of_memory(cinfo, 3); /* request exceeds malloc's ability */ + + /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */ + odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE); + if (odd_bytes > 0) + sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes; + + /* Always make a new pool */ + if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS) + ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ + + hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject + + SIZEOF(large_pool_hdr)); + if (hdr_ptr == NULL) + out_of_memory(cinfo, 4); /* jpeg_get_large failed */ + mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr); + + /* Success, initialize the new pool header and add to list */ + hdr_ptr->hdr.next = mem->large_list[pool_id]; + /* We maintain space counts in each pool header for statistical purposes, + * even though they are not needed for allocation. + */ + hdr_ptr->hdr.bytes_used = sizeofobject; + hdr_ptr->hdr.bytes_left = 0; + mem->large_list[pool_id] = hdr_ptr; + + return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */ +} + + +/* + * Creation of 2-D sample arrays. + * The pointers are in near heap, the samples themselves in FAR heap. + * + * To minimize allocation overhead and to allow I/O of large contiguous + * blocks, we allocate the sample rows in groups of as many rows as possible + * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request. + * NB: the virtual array control routines, later in this file, know about + * this chunking of rows. The rowsperchunk value is left in the mem manager + * object so that it can be saved away if this sarray is the workspace for + * a virtual array. + */ + +METHODDEF(JSAMPARRAY) +alloc_sarray (j_common_ptr cinfo, int pool_id, + JDIMENSION samplesperrow, JDIMENSION numrows) +/* Allocate a 2-D sample array */ +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + JSAMPARRAY result; + JSAMPROW workspace; + JDIMENSION rowsperchunk, currow, i; + long ltemp; + + /* Calculate max # of rows allowed in one allocation chunk */ + ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) / + ((long) samplesperrow * SIZEOF(JSAMPLE)); + if (ltemp <= 0) + ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); + if (ltemp < (long) numrows) + rowsperchunk = (JDIMENSION) ltemp; + else + rowsperchunk = numrows; + mem->last_rowsperchunk = rowsperchunk; + + /* Get space for row pointers (small object) */ + result = (JSAMPARRAY) alloc_small(cinfo, pool_id, + (size_t) (numrows * SIZEOF(JSAMPROW))); + + /* Get the rows themselves (large objects) */ + currow = 0; + while (currow < numrows) { + rowsperchunk = MIN(rowsperchunk, numrows - currow); + workspace = (JSAMPROW) alloc_large(cinfo, pool_id, + (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow + * SIZEOF(JSAMPLE))); + for (i = rowsperchunk; i > 0; i--) { + result[currow++] = workspace; + workspace += samplesperrow; + } + } + + return result; +} + + +/* + * Creation of 2-D coefficient-block arrays. + * This is essentially the same as the code for sample arrays, above. + */ + +METHODDEF(JBLOCKARRAY) +alloc_barray (j_common_ptr cinfo, int pool_id, + JDIMENSION blocksperrow, JDIMENSION numrows) +/* Allocate a 2-D coefficient-block array */ +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + JBLOCKARRAY result; + JBLOCKROW workspace; + JDIMENSION rowsperchunk, currow, i; + long ltemp; + + /* Calculate max # of rows allowed in one allocation chunk */ + ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) / + ((long) blocksperrow * SIZEOF(JBLOCK)); + if (ltemp <= 0) + ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); + if (ltemp < (long) numrows) + rowsperchunk = (JDIMENSION) ltemp; + else + rowsperchunk = numrows; + mem->last_rowsperchunk = rowsperchunk; + + /* Get space for row pointers (small object) */ + result = (JBLOCKARRAY) alloc_small(cinfo, pool_id, + (size_t) (numrows * SIZEOF(JBLOCKROW))); + + /* Get the rows themselves (large objects) */ + currow = 0; + while (currow < numrows) { + rowsperchunk = MIN(rowsperchunk, numrows - currow); + workspace = (JBLOCKROW) alloc_large(cinfo, pool_id, + (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow + * SIZEOF(JBLOCK))); + for (i = rowsperchunk; i > 0; i--) { + result[currow++] = workspace; + workspace += blocksperrow; + } + } + + return result; +} + + +/* + * About virtual array management: + * + * The above "normal" array routines are only used to allocate strip buffers + * (as wide as the image, but just a few rows high). Full-image-sized buffers + * are handled as "virtual" arrays. The array is still accessed a strip at a + * time, but the memory manager must save the whole array for repeated + * accesses. The intended implementation is that there is a strip buffer in + * memory (as high as is possible given the desired memory limit), plus a + * backing file that holds the rest of the array. + * + * The request_virt_array routines are told the total size of the image and + * the maximum number of rows that will be accessed at once. The in-memory + * buffer must be at least as large as the maxaccess value. + * + * The request routines create control blocks but not the in-memory buffers. + * That is postponed until realize_virt_arrays is called. At that time the + * total amount of space needed is known (approximately, anyway), so free + * memory can be divided up fairly. + * + * The access_virt_array routines are responsible for making a specific strip + * area accessible (after reading or writing the backing file, if necessary). + * Note that the access routines are told whether the caller intends to modify + * the accessed strip; during a read-only pass this saves having to rewrite + * data to disk. The access routines are also responsible for pre-zeroing + * any newly accessed rows, if pre-zeroing was requested. + * + * In current usage, the access requests are usually for nonoverlapping + * strips; that is, successive access start_row numbers differ by exactly + * num_rows = maxaccess. This means we can get good performance with simple + * buffer dump/reload logic, by making the in-memory buffer be a multiple + * of the access height; then there will never be accesses across bufferload + * boundaries. The code will still work with overlapping access requests, + * but it doesn't handle bufferload overlaps very efficiently. + */ + + +METHODDEF(jvirt_sarray_ptr) +request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero, + JDIMENSION samplesperrow, JDIMENSION numrows, + JDIMENSION maxaccess) +/* Request a virtual 2-D sample array */ +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + jvirt_sarray_ptr result; + + /* Only IMAGE-lifetime virtual arrays are currently supported */ + if (pool_id != JPOOL_IMAGE) + ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ + + /* get control block */ + result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id, + SIZEOF(struct jvirt_sarray_control)); + + result->mem_buffer = NULL; /* marks array not yet realized */ + result->rows_in_array = numrows; + result->samplesperrow = samplesperrow; + result->maxaccess = maxaccess; + result->pre_zero = pre_zero; + result->b_s_open = FALSE; /* no associated backing-store object */ + result->next = mem->virt_sarray_list; /* add to list of virtual arrays */ + mem->virt_sarray_list = result; + + return result; +} + + +METHODDEF(jvirt_barray_ptr) +request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero, + JDIMENSION blocksperrow, JDIMENSION numrows, + JDIMENSION maxaccess) +/* Request a virtual 2-D coefficient-block array */ +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + jvirt_barray_ptr result; + + /* Only IMAGE-lifetime virtual arrays are currently supported */ + if (pool_id != JPOOL_IMAGE) + ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ + + /* get control block */ + result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id, + SIZEOF(struct jvirt_barray_control)); + + result->mem_buffer = NULL; /* marks array not yet realized */ + result->rows_in_array = numrows; + result->blocksperrow = blocksperrow; + result->maxaccess = maxaccess; + result->pre_zero = pre_zero; + result->b_s_open = FALSE; /* no associated backing-store object */ + result->next = mem->virt_barray_list; /* add to list of virtual arrays */ + mem->virt_barray_list = result; + + return result; +} + + +METHODDEF(void) +realize_virt_arrays (j_common_ptr cinfo) +/* Allocate the in-memory buffers for any unrealized virtual arrays */ +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + long space_per_minheight, maximum_space, avail_mem; + long minheights, max_minheights; + jvirt_sarray_ptr sptr; + jvirt_barray_ptr bptr; + + /* Compute the minimum space needed (maxaccess rows in each buffer) + * and the maximum space needed (full image height in each buffer). + * These may be of use to the system-dependent jpeg_mem_available routine. + */ + space_per_minheight = 0; + maximum_space = 0; + for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) { + if (sptr->mem_buffer == NULL) { /* if not realized yet */ + space_per_minheight += (long) sptr->maxaccess * + (long) sptr->samplesperrow * SIZEOF(JSAMPLE); + maximum_space += (long) sptr->rows_in_array * + (long) sptr->samplesperrow * SIZEOF(JSAMPLE); + } + } + for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) { + if (bptr->mem_buffer == NULL) { /* if not realized yet */ + space_per_minheight += (long) bptr->maxaccess * + (long) bptr->blocksperrow * SIZEOF(JBLOCK); + maximum_space += (long) bptr->rows_in_array * + (long) bptr->blocksperrow * SIZEOF(JBLOCK); + } + } + + if (space_per_minheight <= 0) + return; /* no unrealized arrays, no work */ + + /* Determine amount of memory to actually use; this is system-dependent. */ + avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space, + mem->total_space_allocated); + + /* If the maximum space needed is available, make all the buffers full + * height; otherwise parcel it out with the same number of minheights + * in each buffer. + */ + if (avail_mem >= maximum_space) + max_minheights = 1000000000L; + else { + max_minheights = avail_mem / space_per_minheight; + /* If there doesn't seem to be enough space, try to get the minimum + * anyway. This allows a "stub" implementation of jpeg_mem_available(). + */ + if (max_minheights <= 0) + max_minheights = 1; + } + + /* Allocate the in-memory buffers and initialize backing store as needed. */ + + for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) { + if (sptr->mem_buffer == NULL) { /* if not realized yet */ + minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L; + if (minheights <= max_minheights) { + /* This buffer fits in memory */ + sptr->rows_in_mem = sptr->rows_in_array; + } else { + /* It doesn't fit in memory, create backing store. */ + sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess); + jpeg_open_backing_store(cinfo, & sptr->b_s_info, + (long) sptr->rows_in_array * + (long) sptr->samplesperrow * + (long) SIZEOF(JSAMPLE)); + sptr->b_s_open = TRUE; + } + sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE, + sptr->samplesperrow, sptr->rows_in_mem); + sptr->rowsperchunk = mem->last_rowsperchunk; + sptr->cur_start_row = 0; + sptr->first_undef_row = 0; + sptr->dirty = FALSE; + } + } + + for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) { + if (bptr->mem_buffer == NULL) { /* if not realized yet */ + minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L; + if (minheights <= max_minheights) { + /* This buffer fits in memory */ + bptr->rows_in_mem = bptr->rows_in_array; + } else { + /* It doesn't fit in memory, create backing store. */ + bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess); + jpeg_open_backing_store(cinfo, & bptr->b_s_info, + (long) bptr->rows_in_array * + (long) bptr->blocksperrow * + (long) SIZEOF(JBLOCK)); + bptr->b_s_open = TRUE; + } + bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE, + bptr->blocksperrow, bptr->rows_in_mem); + bptr->rowsperchunk = mem->last_rowsperchunk; + bptr->cur_start_row = 0; + bptr->first_undef_row = 0; + bptr->dirty = FALSE; + } + } +} + + +LOCAL(void) +do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing) +/* Do backing store read or write of a virtual sample array */ +{ + long bytesperrow, file_offset, byte_count, rows, thisrow, i; + + bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE); + file_offset = ptr->cur_start_row * bytesperrow; + /* Loop to read or write each allocation chunk in mem_buffer */ + for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) { + /* One chunk, but check for short chunk at end of buffer */ + rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i); + /* Transfer no more than is currently defined */ + thisrow = (long) ptr->cur_start_row + i; + rows = MIN(rows, (long) ptr->first_undef_row - thisrow); + /* Transfer no more than fits in file */ + rows = MIN(rows, (long) ptr->rows_in_array - thisrow); + if (rows <= 0) /* this chunk might be past end of file! */ + break; + byte_count = rows * bytesperrow; + if (writing) + (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info, + (void FAR *) ptr->mem_buffer[i], + file_offset, byte_count); + else + (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info, + (void FAR *) ptr->mem_buffer[i], + file_offset, byte_count); + file_offset += byte_count; + } +} + + +LOCAL(void) +do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing) +/* Do backing store read or write of a virtual coefficient-block array */ +{ + long bytesperrow, file_offset, byte_count, rows, thisrow, i; + + bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK); + file_offset = ptr->cur_start_row * bytesperrow; + /* Loop to read or write each allocation chunk in mem_buffer */ + for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) { + /* One chunk, but check for short chunk at end of buffer */ + rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i); + /* Transfer no more than is currently defined */ + thisrow = (long) ptr->cur_start_row + i; + rows = MIN(rows, (long) ptr->first_undef_row - thisrow); + /* Transfer no more than fits in file */ + rows = MIN(rows, (long) ptr->rows_in_array - thisrow); + if (rows <= 0) /* this chunk might be past end of file! */ + break; + byte_count = rows * bytesperrow; + if (writing) + (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info, + (void FAR *) ptr->mem_buffer[i], + file_offset, byte_count); + else + (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info, + (void FAR *) ptr->mem_buffer[i], + file_offset, byte_count); + file_offset += byte_count; + } +} + + +METHODDEF(JSAMPARRAY) +access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr, + JDIMENSION start_row, JDIMENSION num_rows, + boolean writable) +/* Access the part of a virtual sample array starting at start_row */ +/* and extending for num_rows rows. writable is true if */ +/* caller intends to modify the accessed area. */ +{ + JDIMENSION end_row = start_row + num_rows; + JDIMENSION undef_row; + + /* debugging check */ + if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess || + ptr->mem_buffer == NULL) + ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); + + /* Make the desired part of the virtual array accessible */ + if (start_row < ptr->cur_start_row || + end_row > ptr->cur_start_row+ptr->rows_in_mem) { + if (! ptr->b_s_open) + ERREXIT(cinfo, JERR_VIRTUAL_BUG); + /* Flush old buffer contents if necessary */ + if (ptr->dirty) { + do_sarray_io(cinfo, ptr, TRUE); + ptr->dirty = FALSE; + } + /* Decide what part of virtual array to access. + * Algorithm: if target address > current window, assume forward scan, + * load starting at target address. If target address < current window, + * assume backward scan, load so that target area is top of window. + * Note that when switching from forward write to forward read, will have + * start_row = 0, so the limiting case applies and we load from 0 anyway. + */ + if (start_row > ptr->cur_start_row) { + ptr->cur_start_row = start_row; + } else { + /* use long arithmetic here to avoid overflow & unsigned problems */ + long ltemp; + + ltemp = (long) end_row - (long) ptr->rows_in_mem; + if (ltemp < 0) + ltemp = 0; /* don't fall off front end of file */ + ptr->cur_start_row = (JDIMENSION) ltemp; + } + /* Read in the selected part of the array. + * During the initial write pass, we will do no actual read + * because the selected part is all undefined. + */ + do_sarray_io(cinfo, ptr, FALSE); + } + /* Ensure the accessed part of the array is defined; prezero if needed. + * To improve locality of access, we only prezero the part of the array + * that the caller is about to access, not the entire in-memory array. + */ + if (ptr->first_undef_row < end_row) { + if (ptr->first_undef_row < start_row) { + if (writable) /* writer skipped over a section of array */ + ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); + undef_row = start_row; /* but reader is allowed to read ahead */ + } else { + undef_row = ptr->first_undef_row; + } + if (writable) + ptr->first_undef_row = end_row; + if (ptr->pre_zero) { + size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE); + undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */ + end_row -= ptr->cur_start_row; + while (undef_row < end_row) { + jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow); + undef_row++; + } + } else { + if (! writable) /* reader looking at undefined data */ + ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); + } + } + /* Flag the buffer dirty if caller will write in it */ + if (writable) + ptr->dirty = TRUE; + /* Return address of proper part of the buffer */ + return ptr->mem_buffer + (start_row - ptr->cur_start_row); +} + + +METHODDEF(JBLOCKARRAY) +access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr, + JDIMENSION start_row, JDIMENSION num_rows, + boolean writable) +/* Access the part of a virtual block array starting at start_row */ +/* and extending for num_rows rows. writable is true if */ +/* caller intends to modify the accessed area. */ +{ + JDIMENSION end_row = start_row + num_rows; + JDIMENSION undef_row; + + /* debugging check */ + if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess || + ptr->mem_buffer == NULL) + ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); + + /* Make the desired part of the virtual array accessible */ + if (start_row < ptr->cur_start_row || + end_row > ptr->cur_start_row+ptr->rows_in_mem) { + if (! ptr->b_s_open) + ERREXIT(cinfo, JERR_VIRTUAL_BUG); + /* Flush old buffer contents if necessary */ + if (ptr->dirty) { + do_barray_io(cinfo, ptr, TRUE); + ptr->dirty = FALSE; + } + /* Decide what part of virtual array to access. + * Algorithm: if target address > current window, assume forward scan, + * load starting at target address. If target address < current window, + * assume backward scan, load so that target area is top of window. + * Note that when switching from forward write to forward read, will have + * start_row = 0, so the limiting case applies and we load from 0 anyway. + */ + if (start_row > ptr->cur_start_row) { + ptr->cur_start_row = start_row; + } else { + /* use long arithmetic here to avoid overflow & unsigned problems */ + long ltemp; + + ltemp = (long) end_row - (long) ptr->rows_in_mem; + if (ltemp < 0) + ltemp = 0; /* don't fall off front end of file */ + ptr->cur_start_row = (JDIMENSION) ltemp; + } + /* Read in the selected part of the array. + * During the initial write pass, we will do no actual read + * because the selected part is all undefined. + */ + do_barray_io(cinfo, ptr, FALSE); + } + /* Ensure the accessed part of the array is defined; prezero if needed. + * To improve locality of access, we only prezero the part of the array + * that the caller is about to access, not the entire in-memory array. + */ + if (ptr->first_undef_row < end_row) { + if (ptr->first_undef_row < start_row) { + if (writable) /* writer skipped over a section of array */ + ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); + undef_row = start_row; /* but reader is allowed to read ahead */ + } else { + undef_row = ptr->first_undef_row; + } + if (writable) + ptr->first_undef_row = end_row; + if (ptr->pre_zero) { + size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK); + undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */ + end_row -= ptr->cur_start_row; + while (undef_row < end_row) { + jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow); + undef_row++; + } + } else { + if (! writable) /* reader looking at undefined data */ + ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); + } + } + /* Flag the buffer dirty if caller will write in it */ + if (writable) + ptr->dirty = TRUE; + /* Return address of proper part of the buffer */ + return ptr->mem_buffer + (start_row - ptr->cur_start_row); +} + + +/* + * Release all objects belonging to a specified pool. + */ + +METHODDEF(void) +free_pool (j_common_ptr cinfo, int pool_id) +{ + my_mem_ptr mem = (my_mem_ptr) cinfo->mem; + small_pool_ptr shdr_ptr; + large_pool_ptr lhdr_ptr; + size_t space_freed; + + if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS) + ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ + +#ifdef MEM_STATS + if (cinfo->err->trace_level > 1) + print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */ +#endif + + /* If freeing IMAGE pool, close any virtual arrays first */ + if (pool_id == JPOOL_IMAGE) { + jvirt_sarray_ptr sptr; + jvirt_barray_ptr bptr; + + for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) { + if (sptr->b_s_open) { /* there may be no backing store */ + sptr->b_s_open = FALSE; /* prevent recursive close if error */ + (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info); + } + } + mem->virt_sarray_list = NULL; + for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) { + if (bptr->b_s_open) { /* there may be no backing store */ + bptr->b_s_open = FALSE; /* prevent recursive close if error */ + (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info); + } + } + mem->virt_barray_list = NULL; + } + + /* Release large objects */ + lhdr_ptr = mem->large_list[pool_id]; + mem->large_list[pool_id] = NULL; + + while (lhdr_ptr != NULL) { + large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next; + space_freed = lhdr_ptr->hdr.bytes_used + + lhdr_ptr->hdr.bytes_left + + SIZEOF(large_pool_hdr); + jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed); + mem->total_space_allocated -= space_freed; + lhdr_ptr = next_lhdr_ptr; + } + + /* Release small objects */ + shdr_ptr = mem->small_list[pool_id]; + mem->small_list[pool_id] = NULL; + + while (shdr_ptr != NULL) { + small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next; + space_freed = shdr_ptr->hdr.bytes_used + + shdr_ptr->hdr.bytes_left + + SIZEOF(small_pool_hdr); + jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed); + mem->total_space_allocated -= space_freed; + shdr_ptr = next_shdr_ptr; + } +} + + +/* + * Close up shop entirely. + * Note that this cannot be called unless cinfo->mem is non-NULL. + */ + +METHODDEF(void) +self_destruct (j_common_ptr cinfo) +{ + int pool; + + /* Close all backing store, release all memory. + * Releasing pools in reverse order might help avoid fragmentation + * with some (brain-damaged) malloc libraries. + */ + for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) { + free_pool(cinfo, pool); + } + + /* Release the memory manager control block too. */ + jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr)); + cinfo->mem = NULL; /* ensures I will be called only once */ + + jpeg_mem_term(cinfo); /* system-dependent cleanup */ +} + + +/* + * Memory manager initialization. + * When this is called, only the error manager pointer is valid in cinfo! + */ + +GLOBAL(void) +jinit_memory_mgr (j_common_ptr cinfo) +{ + my_mem_ptr mem; + long max_to_use; + int pool; + size_t test_mac; + + cinfo->mem = NULL; /* for safety if init fails */ + + /* Check for configuration errors. + * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably + * doesn't reflect any real hardware alignment requirement. + * The test is a little tricky: for X>0, X and X-1 have no one-bits + * in common if and only if X is a power of 2, ie has only one one-bit. + * Some compilers may give an "unreachable code" warning here; ignore it. + */ + if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0) + ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE); + /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be + * a multiple of SIZEOF(ALIGN_TYPE). + * Again, an "unreachable code" warning may be ignored here. + * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK. + */ + test_mac = (size_t) MAX_ALLOC_CHUNK; + if ((long) test_mac != MAX_ALLOC_CHUNK || + (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0) + ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK); + + max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */ + + /* Attempt to allocate memory manager's control block */ + mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr)); + + if (mem == NULL) { + jpeg_mem_term(cinfo); /* system-dependent cleanup */ + ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0); + } + + /* OK, fill in the method pointers */ + mem->pub.alloc_small = alloc_small; + mem->pub.alloc_large = alloc_large; + mem->pub.alloc_sarray = alloc_sarray; + mem->pub.alloc_barray = alloc_barray; + mem->pub.request_virt_sarray = request_virt_sarray; + mem->pub.request_virt_barray = request_virt_barray; + mem->pub.realize_virt_arrays = realize_virt_arrays; + mem->pub.access_virt_sarray = access_virt_sarray; + mem->pub.access_virt_barray = access_virt_barray; + mem->pub.free_pool = free_pool; + mem->pub.self_destruct = self_destruct; + + /* Make MAX_ALLOC_CHUNK accessible to other modules */ + mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK; + + /* Initialize working state */ + mem->pub.max_memory_to_use = max_to_use; + + for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) { + mem->small_list[pool] = NULL; + mem->large_list[pool] = NULL; + } + mem->virt_sarray_list = NULL; + mem->virt_barray_list = NULL; + + mem->total_space_allocated = SIZEOF(my_memory_mgr); + + /* Declare ourselves open for business */ + cinfo->mem = & mem->pub; + + /* Check for an environment variable JPEGMEM; if found, override the + * default max_memory setting from jpeg_mem_init. Note that the + * surrounding application may again override this value. + * If your system doesn't support getenv(), define NO_GETENV to disable + * this feature. + */ +#ifndef NO_GETENV + { char * memenv; + + if ((memenv = getenv("JPEGMEM")) != NULL) { + char ch = 'x'; + + if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) { + if (ch == 'm' || ch == 'M') + max_to_use *= 1000L; + mem->pub.max_memory_to_use = max_to_use * 1000L; + } + } + } +#endif + +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jmemnobs.c b/SlnkDWFImpl/CxImage/jpeg/jmemnobs.c new file mode 100644 index 0000000..6aa1e92 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jmemnobs.c @@ -0,0 +1,109 @@ +/* + * jmemnobs.c + * + * Copyright (C) 1992-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file provides a really simple implementation of the system- + * dependent portion of the JPEG memory manager. This implementation + * assumes that no backing-store files are needed: all required space + * can be obtained from malloc(). + * This is very portable in the sense that it'll compile on almost anything, + * but you'd better have lots of main memory (or virtual memory) if you want + * to process big images. + * Note that the max_memory_to_use option is ignored by this implementation. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jmemsys.h" /* import the system-dependent declarations */ + +#ifndef HAVE_STDLIB_H /* should declare malloc(),free() */ +extern void * malloc JPP((size_t size)); +extern void free JPP((void *ptr)); +#endif + + +/* + * Memory allocation and freeing are controlled by the regular library + * routines malloc() and free(). + */ + +GLOBAL(void *) +jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject) +{ + return (void *) malloc(sizeofobject); +} + +GLOBAL(void) +jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject) +{ + free(object); +} + + +/* + * "Large" objects are treated the same as "small" ones. + * NB: although we include FAR keywords in the routine declarations, + * this file won't actually work in 80x86 small/medium model; at least, + * you probably won't be able to process useful-size images in only 64KB. + */ + +GLOBAL(void FAR *) +jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject) +{ + return (void FAR *) malloc(sizeofobject); +} + +GLOBAL(void) +jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject) +{ + free(object); +} + + +/* + * This routine computes the total memory space available for allocation. + * Here we always say, "we got all you want bud!" + */ + +GLOBAL(long) +jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed, + long max_bytes_needed, long already_allocated) +{ + return max_bytes_needed; +} + + +/* + * Backing store (temporary file) management. + * Since jpeg_mem_available always promised the moon, + * this should never be called and we can just error out. + */ + +GLOBAL(void) +jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info, + long total_bytes_needed) +{ + ERREXIT(cinfo, JERR_NO_BACKING_STORE); +} + + +/* + * These routines take care of any system-dependent initialization and + * cleanup required. Here, there isn't any. + */ + +GLOBAL(long) +jpeg_mem_init (j_common_ptr cinfo) +{ + return 0; /* just set max_memory_to_use to 0 */ +} + +GLOBAL(void) +jpeg_mem_term (j_common_ptr cinfo) +{ + /* no work */ +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jmemsys.h b/SlnkDWFImpl/CxImage/jpeg/jmemsys.h new file mode 100644 index 0000000..2a87961 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jmemsys.h @@ -0,0 +1,198 @@ +/* + * jmemsys.h + * + * Copyright (C) 1992-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This include file defines the interface between the system-independent + * and system-dependent portions of the JPEG memory manager. No other + * modules need include it. (The system-independent portion is jmemmgr.c; + * there are several different versions of the system-dependent portion.) + * + * This file works as-is for the system-dependent memory managers supplied + * in the IJG distribution. You may need to modify it if you write a + * custom memory manager. If system-dependent changes are needed in + * this file, the best method is to #ifdef them based on a configuration + * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR + * and USE_MAC_MEMMGR. + */ + + +/* Short forms of external names for systems with brain-damaged linkers. */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jpeg_get_small jGetSmall +#define jpeg_free_small jFreeSmall +#define jpeg_get_large jGetLarge +#define jpeg_free_large jFreeLarge +#define jpeg_mem_available jMemAvail +#define jpeg_open_backing_store jOpenBackStore +#define jpeg_mem_init jMemInit +#define jpeg_mem_term jMemTerm +#endif /* NEED_SHORT_EXTERNAL_NAMES */ + + +/* + * These two functions are used to allocate and release small chunks of + * memory. (Typically the total amount requested through jpeg_get_small is + * no more than 20K or so; this will be requested in chunks of a few K each.) + * Behavior should be the same as for the standard library functions malloc + * and free; in particular, jpeg_get_small must return NULL on failure. + * On most systems, these ARE malloc and free. jpeg_free_small is passed the + * size of the object being freed, just in case it's needed. + * On an 80x86 machine using small-data memory model, these manage near heap. + */ + +EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject)); +EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object, + size_t sizeofobject)); + +/* + * These two functions are used to allocate and release large chunks of + * memory (up to the total free space designated by jpeg_mem_available). + * The interface is the same as above, except that on an 80x86 machine, + * far pointers are used. On most other machines these are identical to + * the jpeg_get/free_small routines; but we keep them separate anyway, + * in case a different allocation strategy is desirable for large chunks. + */ + +EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo, + size_t sizeofobject)); +EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object, + size_t sizeofobject)); + +/* + * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may + * be requested in a single call to jpeg_get_large (and jpeg_get_small for that + * matter, but that case should never come into play). This macro is needed + * to model the 64Kb-segment-size limit of far addressing on 80x86 machines. + * On those machines, we expect that jconfig.h will provide a proper value. + * On machines with 32-bit flat address spaces, any large constant may be used. + * + * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type + * size_t and will be a multiple of sizeof(align_type). + */ + +#ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */ +#define MAX_ALLOC_CHUNK 1000000000L +#endif + +/* + * This routine computes the total space still available for allocation by + * jpeg_get_large. If more space than this is needed, backing store will be + * used. NOTE: any memory already allocated must not be counted. + * + * There is a minimum space requirement, corresponding to the minimum + * feasible buffer sizes; jmemmgr.c will request that much space even if + * jpeg_mem_available returns zero. The maximum space needed, enough to hold + * all working storage in memory, is also passed in case it is useful. + * Finally, the total space already allocated is passed. If no better + * method is available, cinfo->mem->max_memory_to_use - already_allocated + * is often a suitable calculation. + * + * It is OK for jpeg_mem_available to underestimate the space available + * (that'll just lead to more backing-store access than is really necessary). + * However, an overestimate will lead to failure. Hence it's wise to subtract + * a slop factor from the true available space. 5% should be enough. + * + * On machines with lots of virtual memory, any large constant may be returned. + * Conversely, zero may be returned to always use the minimum amount of memory. + */ + +EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo, + long min_bytes_needed, + long max_bytes_needed, + long already_allocated)); + + +/* + * This structure holds whatever state is needed to access a single + * backing-store object. The read/write/close method pointers are called + * by jmemmgr.c to manipulate the backing-store object; all other fields + * are private to the system-dependent backing store routines. + */ + +#define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */ + + +#ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */ + +typedef unsigned short XMSH; /* type of extended-memory handles */ +typedef unsigned short EMSH; /* type of expanded-memory handles */ + +typedef union { + short file_handle; /* DOS file handle if it's a temp file */ + XMSH xms_handle; /* handle if it's a chunk of XMS */ + EMSH ems_handle; /* handle if it's a chunk of EMS */ +} handle_union; + +#endif /* USE_MSDOS_MEMMGR */ + +#ifdef USE_MAC_MEMMGR /* Mac-specific junk */ +#include +#endif /* USE_MAC_MEMMGR */ + + +typedef struct backing_store_struct * backing_store_ptr; + +typedef struct backing_store_struct { + /* Methods for reading/writing/closing this backing-store object */ + JMETHOD(void, read_backing_store, (j_common_ptr cinfo, + backing_store_ptr info, + void FAR * buffer_address, + long file_offset, long byte_count)); + JMETHOD(void, write_backing_store, (j_common_ptr cinfo, + backing_store_ptr info, + void FAR * buffer_address, + long file_offset, long byte_count)); + JMETHOD(void, close_backing_store, (j_common_ptr cinfo, + backing_store_ptr info)); + + /* Private fields for system-dependent backing-store management */ +#ifdef USE_MSDOS_MEMMGR + /* For the MS-DOS manager (jmemdos.c), we need: */ + handle_union handle; /* reference to backing-store storage object */ + char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */ +#else +#ifdef USE_MAC_MEMMGR + /* For the Mac manager (jmemmac.c), we need: */ + short temp_file; /* file reference number to temp file */ + FSSpec tempSpec; /* the FSSpec for the temp file */ + char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */ +#else + /* For a typical implementation with temp files, we need: */ + FILE * temp_file; /* stdio reference to temp file */ + char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */ +#endif +#endif +} backing_store_info; + + +/* + * Initial opening of a backing-store object. This must fill in the + * read/write/close pointers in the object. The read/write routines + * may take an error exit if the specified maximum file size is exceeded. + * (If jpeg_mem_available always returns a large value, this routine can + * just take an error exit.) + */ + +EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo, + backing_store_ptr info, + long total_bytes_needed)); + + +/* + * These routines take care of any system-dependent initialization and + * cleanup required. jpeg_mem_init will be called before anything is + * allocated (and, therefore, nothing in cinfo is of use except the error + * manager pointer). It should return a suitable default value for + * max_memory_to_use; this may subsequently be overridden by the surrounding + * application. (Note that max_memory_to_use is only important if + * jpeg_mem_available chooses to consult it ... no one else will.) + * jpeg_mem_term may assume that all requested memory has been freed and that + * all opened backing-store objects have been closed. + */ + +EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo)); +EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo)); diff --git a/SlnkDWFImpl/CxImage/jpeg/jmorecfg.h b/SlnkDWFImpl/CxImage/jpeg/jmorecfg.h new file mode 100644 index 0000000..d82c9be --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jmorecfg.h @@ -0,0 +1,371 @@ +/* + * jmorecfg.h + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains additional configuration options that customize the + * JPEG software for special applications or support machine-dependent + * optimizations. Most users will not need to touch this file. + */ + + +/* + * Define BITS_IN_JSAMPLE as either + * 8 for 8-bit sample values (the usual setting) + * 12 for 12-bit sample values + * Only 8 and 12 are legal data precisions for lossy JPEG according to the + * JPEG standard, and the IJG code does not support anything else! + * We do not support run-time selection of data precision, sorry. + */ + +#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */ + + +/* + * Maximum number of components (color channels) allowed in JPEG image. + * To meet the letter of the JPEG spec, set this to 255. However, darn + * few applications need more than 4 channels (maybe 5 for CMYK + alpha + * mask). We recommend 10 as a reasonable compromise; use 4 if you are + * really short on memory. (Each allowed component costs a hundred or so + * bytes of storage, whether actually used in an image or not.) + */ + +#define MAX_COMPONENTS 10 /* maximum number of image components */ + + +/* + * Basic data types. + * You may need to change these if you have a machine with unusual data + * type sizes; for example, "char" not 8 bits, "short" not 16 bits, + * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits, + * but it had better be at least 16. + */ + +/* Representation of a single sample (pixel element value). + * We frequently allocate large arrays of these, so it's important to keep + * them small. But if you have memory to burn and access to char or short + * arrays is very slow on your hardware, you might want to change these. + */ + +#if BITS_IN_JSAMPLE == 8 +/* JSAMPLE should be the smallest type that will hold the values 0..255. + * You can use a signed char by having GETJSAMPLE mask it with 0xFF. + */ + +#ifdef HAVE_UNSIGNED_CHAR + +typedef unsigned char JSAMPLE; +#define GETJSAMPLE(value) ((int) (value)) + +#else /* not HAVE_UNSIGNED_CHAR */ + +typedef char JSAMPLE; +#ifdef CHAR_IS_UNSIGNED +#define GETJSAMPLE(value) ((int) (value)) +#else +#define GETJSAMPLE(value) ((int) (value) & 0xFF) +#endif /* CHAR_IS_UNSIGNED */ + +#endif /* HAVE_UNSIGNED_CHAR */ + +#define MAXJSAMPLE 255 +#define CENTERJSAMPLE 128 + +#endif /* BITS_IN_JSAMPLE == 8 */ + + +#if BITS_IN_JSAMPLE == 12 +/* JSAMPLE should be the smallest type that will hold the values 0..4095. + * On nearly all machines "short" will do nicely. + */ + +typedef short JSAMPLE; +#define GETJSAMPLE(value) ((int) (value)) + +#define MAXJSAMPLE 4095 +#define CENTERJSAMPLE 2048 + +#endif /* BITS_IN_JSAMPLE == 12 */ + + +/* Representation of a DCT frequency coefficient. + * This should be a signed value of at least 16 bits; "short" is usually OK. + * Again, we allocate large arrays of these, but you can change to int + * if you have memory to burn and "short" is really slow. + */ + +typedef short JCOEF; + + +/* Compressed datastreams are represented as arrays of JOCTET. + * These must be EXACTLY 8 bits wide, at least once they are written to + * external storage. Note that when using the stdio data source/destination + * managers, this is also the data type passed to fread/fwrite. + */ + +#ifdef HAVE_UNSIGNED_CHAR + +typedef unsigned char JOCTET; +#define GETJOCTET(value) (value) + +#else /* not HAVE_UNSIGNED_CHAR */ + +typedef char JOCTET; +#ifdef CHAR_IS_UNSIGNED +#define GETJOCTET(value) (value) +#else +#define GETJOCTET(value) ((value) & 0xFF) +#endif /* CHAR_IS_UNSIGNED */ + +#endif /* HAVE_UNSIGNED_CHAR */ + + +/* These typedefs are used for various table entries and so forth. + * They must be at least as wide as specified; but making them too big + * won't cost a huge amount of memory, so we don't provide special + * extraction code like we did for JSAMPLE. (In other words, these + * typedefs live at a different point on the speed/space tradeoff curve.) + */ + +/* UINT8 must hold at least the values 0..255. */ + +#ifdef HAVE_UNSIGNED_CHAR +typedef unsigned char UINT8; +#else /* not HAVE_UNSIGNED_CHAR */ +#ifdef CHAR_IS_UNSIGNED +typedef char UINT8; +#else /* not CHAR_IS_UNSIGNED */ +typedef short UINT8; +#endif /* CHAR_IS_UNSIGNED */ +#endif /* HAVE_UNSIGNED_CHAR */ + +/* UINT16 must hold at least the values 0..65535. */ + +#ifdef HAVE_UNSIGNED_SHORT +typedef unsigned short UINT16; +#else /* not HAVE_UNSIGNED_SHORT */ +typedef unsigned int UINT16; +#endif /* HAVE_UNSIGNED_SHORT */ + +/* INT16 must hold at least the values -32768..32767. */ + +#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */ +typedef short INT16; +#endif + +/* INT32 must hold at least signed 32-bit values. */ + +#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */ +/* typedef long INT32; Davide Pizzolato: wrong type definition for VC6 */ +#if defined(WIN32) && (!defined(__BORLANDC__) || (defined(__BORLANDC__) && (__BORLANDC__ > 0x0530))) +#include /* Davide Pizzolato: correct type definition for VC6 */ +#else +typedef long INT32; +#endif +#endif + +/* Datatype used for image dimensions. The JPEG standard only supports + * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore + * "unsigned int" is sufficient on all machines. However, if you need to + * handle larger images and you don't mind deviating from the spec, you + * can change this datatype. + */ + +typedef unsigned int JDIMENSION; + +#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */ + + +/* These macros are used in all function definitions and extern declarations. + * You could modify them if you need to change function linkage conventions; + * in particular, you'll need to do that to make the library a Windows DLL. + * Another application is to make all functions global for use with debuggers + * or code profilers that require it. + */ + +/* a function called through method pointers: */ +#define METHODDEF(type) static type +/* a function used only in its module: */ +#define LOCAL(type) static type +/* a function referenced thru EXTERNs: */ +#define GLOBAL(type) type +/* a reference to a GLOBAL function: */ +#define EXTERN(type) extern type + + +/* This macro is used to declare a "method", that is, a function pointer. + * We want to supply prototype parameters if the compiler can cope. + * Note that the arglist parameter must be parenthesized! + * Again, you can customize this if you need special linkage keywords. + */ + +#ifdef HAVE_PROTOTYPES +#define JMETHOD(type,methodname,arglist) type (*methodname) arglist +#else +#define JMETHOD(type,methodname,arglist) type (*methodname) () +#endif + + +/* Here is the pseudo-keyword for declaring pointers that must be "far" + * on 80x86 machines. Most of the specialized coding for 80x86 is handled + * by just saying "FAR *" where such a pointer is needed. In a few places + * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol. + */ + +#ifdef NEED_FAR_POINTERS +#define FAR far +#else +#ifndef FAR +#define FAR +#endif +#endif + + + +/* + * On a few systems, type boolean and/or its values FALSE, TRUE may appear + * in standard header files. Or you may have conflicts with application- + * specific header files that you want to include together with these files. + * Defining HAVE_BOOLEAN before including jpeglib.h should make it work. + */ + +#ifndef HAVE_BOOLEAN +typedef int boolean; +#endif +#ifndef FALSE /* in case these macros already exist */ +#define FALSE 0 /* values of boolean */ +#endif +#ifndef TRUE +#define TRUE 1 +#endif + + +/* + * The remaining options affect code selection within the JPEG library, + * but they don't need to be visible to most applications using the library. + * To minimize application namespace pollution, the symbols won't be + * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined. + */ + +#ifdef JPEG_INTERNALS +#define JPEG_INTERNAL_OPTIONS +#endif + +#ifdef JPEG_INTERNAL_OPTIONS + + +/* + * These defines indicate whether to include various optional functions. + * Undefining some of these symbols will produce a smaller but less capable + * library. Note that you can leave certain source files out of the + * compilation/linking process if you've #undef'd the corresponding symbols. + * (You may HAVE to do that if your compiler doesn't like null source files.) + */ + +/* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */ + +/* Capability options common to encoder and decoder: */ + +#define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */ +#define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */ +#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */ + +/* Encoder capability options: */ + +#undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ +#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ +#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ +#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */ +/* Note: if you selected 12-bit data precision, it is dangerous to turn off + * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit + * precision, so jchuff.c normally uses entropy optimization to compute + * usable tables for higher precision. If you don't want to do optimization, + * you'll have to supply different default Huffman tables. + * The exact same statements apply for progressive JPEG: the default tables + * don't work for progressive mode. (This may get fixed, however.) + */ +#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */ + +/* Decoder capability options: */ + +#undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ +#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ +#define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ +#define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */ +#define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */ +#define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */ +#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */ +#define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */ +#define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */ +#define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */ + +/* more capability options later, no doubt */ + + +/* + * Ordering of RGB data in scanlines passed to or from the application. + * If your application wants to deal with data in the order B,G,R, just + * change these macros. You can also deal with formats such as R,G,B,X + * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing + * the offsets will also change the order in which colormap data is organized. + * RESTRICTIONS: + * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats. + * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not + * useful if you are using JPEG color spaces other than YCbCr or grayscale. + * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE + * is not 3 (they don't understand about dummy color components!). So you + * can't use color quantization if you change that value. + */ + +#define RGB_RED 0 /* Offset of Red in an RGB scanline element */ +#define RGB_GREEN 1 /* Offset of Green */ +#define RGB_BLUE 2 /* Offset of Blue */ +#define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */ + + +/* Definitions for speed-related optimizations. */ + + +/* If your compiler supports inline functions, define INLINE + * as the inline keyword; otherwise define it as empty. + */ + +#ifndef INLINE +#ifdef __GNUC__ /* for instance, GNU C knows about inline */ +#define INLINE __inline__ +#endif +#ifndef INLINE +#define INLINE /* default is to define it as empty */ +#endif +#endif + + +/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying + * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER + * as short on such a machine. MULTIPLIER must be at least 16 bits wide. + */ + +#ifndef MULTIPLIER +#define MULTIPLIER int /* type for fastest integer multiply */ +#endif + + +/* FAST_FLOAT should be either float or double, whichever is done faster + * by your compiler. (Note that this type is only used in the floating point + * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.) + * Typically, float is faster in ANSI C compilers, while double is faster in + * pre-ANSI compilers (because they insist on converting to double anyway). + * The code below therefore chooses float if we have ANSI-style prototypes. + */ + +#ifndef FAST_FLOAT +#ifdef HAVE_PROTOTYPES +#define FAST_FLOAT float +#else +#define FAST_FLOAT double +#endif +#endif + +#endif /* JPEG_INTERNAL_OPTIONS */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jpegint.h b/SlnkDWFImpl/CxImage/jpeg/jpegint.h new file mode 100644 index 0000000..685a361 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jpegint.h @@ -0,0 +1,392 @@ +/* + * jpegint.h + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file provides common declarations for the various JPEG modules. + * These declarations are considered internal to the JPEG library; most + * applications using the library shouldn't need to include this file. + */ + + +/* Declarations for both compression & decompression */ + +typedef enum { /* Operating modes for buffer controllers */ + JBUF_PASS_THRU, /* Plain stripwise operation */ + /* Remaining modes require a full-image buffer to have been created */ + JBUF_SAVE_SOURCE, /* Run source subobject only, save output */ + JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */ + JBUF_SAVE_AND_PASS /* Run both subobjects, save output */ +} J_BUF_MODE; + +/* Values of global_state field (jdapi.c has some dependencies on ordering!) */ +#define CSTATE_START 100 /* after create_compress */ +#define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */ +#define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */ +#define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */ +#define DSTATE_START 200 /* after create_decompress */ +#define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */ +#define DSTATE_READY 202 /* found SOS, ready for start_decompress */ +#define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/ +#define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */ +#define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */ +#define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */ +#define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */ +#define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */ +#define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */ +#define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */ + + +/* Declarations for compression modules */ + +/* Master control module */ +struct jpeg_comp_master { + JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo)); + JMETHOD(void, pass_startup, (j_compress_ptr cinfo)); + JMETHOD(void, finish_pass, (j_compress_ptr cinfo)); + + /* State variables made visible to other modules */ + boolean call_pass_startup; /* True if pass_startup must be called */ + boolean is_last_pass; /* True during last pass */ +}; + +/* Main buffer control (downsampled-data buffer) */ +struct jpeg_c_main_controller { + JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode)); + JMETHOD(void, process_data, (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, + JDIMENSION in_rows_avail)); +}; + +/* Compression preprocessing (downsampling input buffer control) */ +struct jpeg_c_prep_controller { + JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode)); + JMETHOD(void, pre_process_data, (j_compress_ptr cinfo, + JSAMPARRAY input_buf, + JDIMENSION *in_row_ctr, + JDIMENSION in_rows_avail, + JSAMPIMAGE output_buf, + JDIMENSION *out_row_group_ctr, + JDIMENSION out_row_groups_avail)); +}; + +/* Coefficient buffer control */ +struct jpeg_c_coef_controller { + JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode)); + JMETHOD(boolean, compress_data, (j_compress_ptr cinfo, + JSAMPIMAGE input_buf)); +}; + +/* Colorspace conversion */ +struct jpeg_color_converter { + JMETHOD(void, start_pass, (j_compress_ptr cinfo)); + JMETHOD(void, color_convert, (j_compress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPIMAGE output_buf, + JDIMENSION output_row, int num_rows)); +}; + +/* Downsampling */ +struct jpeg_downsampler { + JMETHOD(void, start_pass, (j_compress_ptr cinfo)); + JMETHOD(void, downsample, (j_compress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION in_row_index, + JSAMPIMAGE output_buf, + JDIMENSION out_row_group_index)); + + boolean need_context_rows; /* TRUE if need rows above & below */ +}; + +/* Forward DCT (also controls coefficient quantization) */ +struct jpeg_forward_dct { + JMETHOD(void, start_pass, (j_compress_ptr cinfo)); + /* perhaps this should be an array??? */ + JMETHOD(void, forward_DCT, (j_compress_ptr cinfo, + jpeg_component_info * compptr, + JSAMPARRAY sample_data, JBLOCKROW coef_blocks, + JDIMENSION start_row, JDIMENSION start_col, + JDIMENSION num_blocks)); +}; + +/* Entropy encoding */ +struct jpeg_entropy_encoder { + JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics)); + JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data)); + JMETHOD(void, finish_pass, (j_compress_ptr cinfo)); +}; + +/* Marker writing */ +struct jpeg_marker_writer { + JMETHOD(void, write_file_header, (j_compress_ptr cinfo)); + JMETHOD(void, write_frame_header, (j_compress_ptr cinfo)); + JMETHOD(void, write_scan_header, (j_compress_ptr cinfo)); + JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo)); + JMETHOD(void, write_tables_only, (j_compress_ptr cinfo)); + /* These routines are exported to allow insertion of extra markers */ + /* Probably only COM and APPn markers should be written this way */ + JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker, + unsigned int datalen)); + JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val)); +}; + + +/* Declarations for decompression modules */ + +/* Master control module */ +struct jpeg_decomp_master { + JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo)); + JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo)); + + /* State variables made visible to other modules */ + boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */ +}; + +/* Input control module */ +struct jpeg_input_controller { + JMETHOD(int, consume_input, (j_decompress_ptr cinfo)); + JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo)); + JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo)); + JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo)); + + /* State variables made visible to other modules */ + boolean has_multiple_scans; /* True if file has multiple scans */ + boolean eoi_reached; /* True when EOI has been consumed */ +}; + +/* Main buffer control (downsampled-data buffer) */ +struct jpeg_d_main_controller { + JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)); + JMETHOD(void, process_data, (j_decompress_ptr cinfo, + JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail)); +}; + +/* Coefficient buffer control */ +struct jpeg_d_coef_controller { + JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo)); + JMETHOD(int, consume_data, (j_decompress_ptr cinfo)); + JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo)); + JMETHOD(int, decompress_data, (j_decompress_ptr cinfo, + JSAMPIMAGE output_buf)); + /* Pointer to array of coefficient virtual arrays, or NULL if none */ + jvirt_barray_ptr *coef_arrays; +}; + +/* Decompression postprocessing (color quantization buffer control) */ +struct jpeg_d_post_controller { + JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)); + JMETHOD(void, post_process_data, (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, + JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, + JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail)); +}; + +/* Marker reading & parsing */ +struct jpeg_marker_reader { + JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo)); + /* Read markers until SOS or EOI. + * Returns same codes as are defined for jpeg_consume_input: + * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. + */ + JMETHOD(int, read_markers, (j_decompress_ptr cinfo)); + /* Read a restart marker --- exported for use by entropy decoder only */ + jpeg_marker_parser_method read_restart_marker; + + /* State of marker reader --- nominally internal, but applications + * supplying COM or APPn handlers might like to know the state. + */ + boolean saw_SOI; /* found SOI? */ + boolean saw_SOF; /* found SOF? */ + int next_restart_num; /* next restart number expected (0-7) */ + unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */ +}; + +/* Entropy decoding */ +struct jpeg_entropy_decoder { + JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); + JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo, + JBLOCKROW *MCU_data)); + + /* This is here to share code between baseline and progressive decoders; */ + /* other modules probably should not use it */ + boolean insufficient_data; /* set TRUE after emitting warning */ +}; + +/* Inverse DCT (also performs dequantization) */ +typedef JMETHOD(void, inverse_DCT_method_ptr, + (j_decompress_ptr cinfo, jpeg_component_info * compptr, + JCOEFPTR coef_block, + JSAMPARRAY output_buf, JDIMENSION output_col)); + +struct jpeg_inverse_dct { + JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); + /* It is useful to allow each component to have a separate IDCT method. */ + inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS]; +}; + +/* Upsampling (note that upsampler must also call color converter) */ +struct jpeg_upsampler { + JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); + JMETHOD(void, upsample, (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, + JDIMENSION *in_row_group_ctr, + JDIMENSION in_row_groups_avail, + JSAMPARRAY output_buf, + JDIMENSION *out_row_ctr, + JDIMENSION out_rows_avail)); + + boolean need_context_rows; /* TRUE if need rows above & below */ +}; + +/* Colorspace conversion */ +struct jpeg_color_deconverter { + JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); + JMETHOD(void, color_convert, (j_decompress_ptr cinfo, + JSAMPIMAGE input_buf, JDIMENSION input_row, + JSAMPARRAY output_buf, int num_rows)); +}; + +/* Color quantization or color precision reduction */ +struct jpeg_color_quantizer { + JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan)); + JMETHOD(void, color_quantize, (j_decompress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPARRAY output_buf, + int num_rows)); + JMETHOD(void, finish_pass, (j_decompress_ptr cinfo)); + JMETHOD(void, new_color_map, (j_decompress_ptr cinfo)); +}; + + +/* Miscellaneous useful macros */ + +#undef MAX +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#undef MIN +#define MIN(a,b) ((a) < (b) ? (a) : (b)) + + +/* We assume that right shift corresponds to signed division by 2 with + * rounding towards minus infinity. This is correct for typical "arithmetic + * shift" instructions that shift in copies of the sign bit. But some + * C compilers implement >> with an unsigned shift. For these machines you + * must define RIGHT_SHIFT_IS_UNSIGNED. + * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity. + * It is only applied with constant shift counts. SHIFT_TEMPS must be + * included in the variables of any routine using RIGHT_SHIFT. + */ + +#ifdef RIGHT_SHIFT_IS_UNSIGNED +#define SHIFT_TEMPS INT32 shift_temp; +#define RIGHT_SHIFT(x,shft) \ + ((shift_temp = (x)) < 0 ? \ + (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \ + (shift_temp >> (shft))) +#else +#define SHIFT_TEMPS +#define RIGHT_SHIFT(x,shft) ((x) >> (shft)) +#endif + + +/* Short forms of external names for systems with brain-damaged linkers. */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jinit_compress_master jICompress +#define jinit_c_master_control jICMaster +#define jinit_c_main_controller jICMainC +#define jinit_c_prep_controller jICPrepC +#define jinit_c_coef_controller jICCoefC +#define jinit_color_converter jICColor +#define jinit_downsampler jIDownsampler +#define jinit_forward_dct jIFDCT +#define jinit_huff_encoder jIHEncoder +#define jinit_phuff_encoder jIPHEncoder +#define jinit_marker_writer jIMWriter +#define jinit_master_decompress jIDMaster +#define jinit_d_main_controller jIDMainC +#define jinit_d_coef_controller jIDCoefC +#define jinit_d_post_controller jIDPostC +#define jinit_input_controller jIInCtlr +#define jinit_marker_reader jIMReader +#define jinit_huff_decoder jIHDecoder +#define jinit_phuff_decoder jIPHDecoder +#define jinit_inverse_dct jIIDCT +#define jinit_upsampler jIUpsampler +#define jinit_color_deconverter jIDColor +#define jinit_1pass_quantizer jI1Quant +#define jinit_2pass_quantizer jI2Quant +#define jinit_merged_upsampler jIMUpsampler +#define jinit_memory_mgr jIMemMgr +#define jdiv_round_up jDivRound +#define jround_up jRound +#define jcopy_sample_rows jCopySamples +#define jcopy_block_row jCopyBlocks +#define jzero_far jZeroFar +#define jpeg_zigzag_order jZIGTable +#define jpeg_natural_order jZAGTable +#endif /* NEED_SHORT_EXTERNAL_NAMES */ + + +/* Compression module initialization routines */ +EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo)); +EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo, + boolean transcode_only)); +EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo, + boolean need_full_buffer)); +EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo, + boolean need_full_buffer)); +EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo, + boolean need_full_buffer)); +EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo)); +EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo)); +EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo)); +EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo)); +EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo)); +EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo)); +/* Decompression module initialization routines */ +EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo, + boolean need_full_buffer)); +EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo, + boolean need_full_buffer)); +EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo, + boolean need_full_buffer)); +EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo)); +EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo)); +/* Memory manager initialization */ +EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo)); + +/* Utility routines in jutils.c */ +EXTERN(long) jdiv_round_up JPP((long a, long b)); +EXTERN(long) jround_up JPP((long a, long b)); +EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row, + JSAMPARRAY output_array, int dest_row, + int num_rows, JDIMENSION num_cols)); +EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row, + JDIMENSION num_blocks)); +EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero)); +/* Constant tables in jutils.c */ +#if 0 /* This table is not actually needed in v6a */ +extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */ +#endif +extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */ + +/* Suppress undefined-structure complaints if necessary. */ + +#ifdef INCOMPLETE_TYPES_BROKEN +#ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */ +struct jvirt_sarray_control { long dummy; }; +struct jvirt_barray_control { long dummy; }; +#endif +#endif /* INCOMPLETE_TYPES_BROKEN */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jpeglib.h b/SlnkDWFImpl/CxImage/jpeg/jpeglib.h new file mode 100644 index 0000000..b9356f3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jpeglib.h @@ -0,0 +1,1096 @@ +/* + * jpeglib.h + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file defines the application interface for the JPEG library. + * Most applications using the library need only include this file, + * and perhaps jerror.h if they want to know the exact error codes. + */ + +#ifndef JPEGLIB_H +#define JPEGLIB_H + +/* + * First we include the configuration files that record how this + * installation of the JPEG library is set up. jconfig.h can be + * generated automatically for many systems. jmorecfg.h contains + * manual configuration options that most people need not worry about. + */ + +#ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */ +#include "jconfig.h" /* widely used configuration options */ +#endif +#include "jmorecfg.h" /* seldom changed options */ + + +/* Version ID for the JPEG library. + * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60". + */ + +#define JPEG_LIB_VERSION 62 /* Version 6b */ + + +/* Various constants determining the sizes of things. + * All of these are specified by the JPEG standard, so don't change them + * if you want to be compatible. + */ + +#define DCTSIZE 8 /* The basic DCT block is 8x8 samples */ +#define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */ +#define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */ +#define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */ +#define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */ +#define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */ +#define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */ +/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; + * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. + * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU + * to handle it. We even let you do this from the jconfig.h file. However, + * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe + * sometimes emits noncompliant files doesn't mean you should too. + */ +#define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */ +#ifndef D_MAX_BLOCKS_IN_MCU +#define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */ +#endif + + +/* Data structures for images (arrays of samples and of DCT coefficients). + * On 80x86 machines, the image arrays are too big for near pointers, + * but the pointer arrays can fit in near memory. + */ + +typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */ +typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */ +typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */ + +typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */ +typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */ +typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */ +typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */ + +typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */ + + +/* Types for JPEG compression parameters and working tables. */ + + +/* DCT coefficient quantization tables. */ + +typedef struct { + /* This array gives the coefficient quantizers in natural array order + * (not the zigzag order in which they are stored in a JPEG DQT marker). + * CAUTION: IJG versions prior to v6a kept this array in zigzag order. + */ + UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */ + /* This field is used only during compression. It's initialized FALSE when + * the table is created, and set TRUE when it's been output to the file. + * You could suppress output of a table by setting this to TRUE. + * (See jpeg_suppress_tables for an example.) + */ + boolean sent_table; /* TRUE when table has been output */ +} JQUANT_TBL; + + +/* Huffman coding tables. */ + +typedef struct { + /* These two fields directly represent the contents of a JPEG DHT marker */ + UINT8 bits[17]; /* bits[k] = # of symbols with codes of */ + /* length k bits; bits[0] is unused */ + UINT8 huffval[256]; /* The symbols, in order of incr code length */ + /* This field is used only during compression. It's initialized FALSE when + * the table is created, and set TRUE when it's been output to the file. + * You could suppress output of a table by setting this to TRUE. + * (See jpeg_suppress_tables for an example.) + */ + boolean sent_table; /* TRUE when table has been output */ +} JHUFF_TBL; + + +/* Basic info about one component (color channel). */ + +typedef struct { + /* These values are fixed over the whole image. */ + /* For compression, they must be supplied by parameter setup; */ + /* for decompression, they are read from the SOF marker. */ + int component_id; /* identifier for this component (0..255) */ + int component_index; /* its index in SOF or cinfo->comp_info[] */ + int h_samp_factor; /* horizontal sampling factor (1..4) */ + int v_samp_factor; /* vertical sampling factor (1..4) */ + int quant_tbl_no; /* quantization table selector (0..3) */ + /* These values may vary between scans. */ + /* For compression, they must be supplied by parameter setup; */ + /* for decompression, they are read from the SOS marker. */ + /* The decompressor output side may not use these variables. */ + int dc_tbl_no; /* DC entropy table selector (0..3) */ + int ac_tbl_no; /* AC entropy table selector (0..3) */ + + /* Remaining fields should be treated as private by applications. */ + + /* These values are computed during compression or decompression startup: */ + /* Component's size in DCT blocks. + * Any dummy blocks added to complete an MCU are not counted; therefore + * these values do not depend on whether a scan is interleaved or not. + */ + JDIMENSION width_in_blocks; + JDIMENSION height_in_blocks; + /* Size of a DCT block in samples. Always DCTSIZE for compression. + * For decompression this is the size of the output from one DCT block, + * reflecting any scaling we choose to apply during the IDCT step. + * Values of 1,2,4,8 are likely to be supported. Note that different + * components may receive different IDCT scalings. + */ + int DCT_scaled_size; + /* The downsampled dimensions are the component's actual, unpadded number + * of samples at the main buffer (preprocessing/compression interface), thus + * downsampled_width = ceil(image_width * Hi/Hmax) + * and similarly for height. For decompression, IDCT scaling is included, so + * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE) + */ + JDIMENSION downsampled_width; /* actual width in samples */ + JDIMENSION downsampled_height; /* actual height in samples */ + /* This flag is used only for decompression. In cases where some of the + * components will be ignored (eg grayscale output from YCbCr image), + * we can skip most computations for the unused components. + */ + boolean component_needed; /* do we need the value of this component? */ + + /* These values are computed before starting a scan of the component. */ + /* The decompressor output side may not use these variables. */ + int MCU_width; /* number of blocks per MCU, horizontally */ + int MCU_height; /* number of blocks per MCU, vertically */ + int MCU_blocks; /* MCU_width * MCU_height */ + int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */ + int last_col_width; /* # of non-dummy blocks across in last MCU */ + int last_row_height; /* # of non-dummy blocks down in last MCU */ + + /* Saved quantization table for component; NULL if none yet saved. + * See jdinput.c comments about the need for this information. + * This field is currently used only for decompression. + */ + JQUANT_TBL * quant_table; + + /* Private per-component storage for DCT or IDCT subsystem. */ + void * dct_table; +} jpeg_component_info; + + +/* The script for encoding a multiple-scan file is an array of these: */ + +typedef struct { + int comps_in_scan; /* number of components encoded in this scan */ + int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */ + int Ss, Se; /* progressive JPEG spectral selection parms */ + int Ah, Al; /* progressive JPEG successive approx. parms */ +} jpeg_scan_info; + +/* The decompressor can save APPn and COM markers in a list of these: */ + +typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr; + +struct jpeg_marker_struct { + jpeg_saved_marker_ptr next; /* next in list, or NULL */ + UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */ + unsigned int original_length; /* # bytes of data in the file */ + unsigned int data_length; /* # bytes of data saved at data[] */ + JOCTET FAR * data; /* the data contained in the marker */ + /* the marker length word is not counted in data_length or original_length */ +}; + +/* Known color spaces. */ + +typedef enum { + JCS_UNKNOWN, /* error/unspecified */ + JCS_GRAYSCALE, /* monochrome */ + JCS_RGB, /* red/green/blue */ + JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */ + JCS_CMYK, /* C/M/Y/K */ + JCS_YCCK /* Y/Cb/Cr/K */ +} J_COLOR_SPACE; + +/* DCT/IDCT algorithm options. */ + +typedef enum { + JDCT_ISLOW, /* slow but accurate integer algorithm */ + JDCT_IFAST, /* faster, less accurate integer method */ + JDCT_FLOAT /* floating-point: accurate, fast on fast HW */ +} J_DCT_METHOD; + +#ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */ +#define JDCT_DEFAULT JDCT_ISLOW +#endif +#ifndef JDCT_FASTEST /* may be overridden in jconfig.h */ +#define JDCT_FASTEST JDCT_IFAST +#endif + +/* Dithering options for decompression. */ + +typedef enum { + JDITHER_NONE, /* no dithering */ + JDITHER_ORDERED, /* simple ordered dither */ + JDITHER_FS /* Floyd-Steinberg error diffusion dither */ +} J_DITHER_MODE; + + +/* Common fields between JPEG compression and decompression master structs. */ + +#define jpeg_common_fields \ + struct jpeg_error_mgr * err; /* Error handler module */\ + struct jpeg_memory_mgr * mem; /* Memory manager module */\ + struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\ + void * client_data; /* Available for use by application */\ + boolean is_decompressor; /* So common code can tell which is which */\ + int global_state /* For checking call sequence validity */ + +/* Routines that are to be used by both halves of the library are declared + * to receive a pointer to this structure. There are no actual instances of + * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct. + */ +struct jpeg_common_struct { + jpeg_common_fields; /* Fields common to both master struct types */ + /* Additional fields follow in an actual jpeg_compress_struct or + * jpeg_decompress_struct. All three structs must agree on these + * initial fields! (This would be a lot cleaner in C++.) + */ +}; + +typedef struct jpeg_common_struct * j_common_ptr; +typedef struct jpeg_compress_struct * j_compress_ptr; +typedef struct jpeg_decompress_struct * j_decompress_ptr; + + +/* Master record for a compression instance */ + +struct jpeg_compress_struct { + jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */ + + /* Destination for compressed data */ + struct jpeg_destination_mgr * dest; + + /* Description of source image --- these fields must be filled in by + * outer application before starting compression. in_color_space must + * be correct before you can even call jpeg_set_defaults(). + */ + + JDIMENSION image_width; /* input image width */ + JDIMENSION image_height; /* input image height */ + int input_components; /* # of color components in input image */ + J_COLOR_SPACE in_color_space; /* colorspace of input image */ + + double input_gamma; /* image gamma of input image */ + + /* Compression parameters --- these fields must be set before calling + * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to + * initialize everything to reasonable defaults, then changing anything + * the application specifically wants to change. That way you won't get + * burnt when new parameters are added. Also note that there are several + * helper routines to simplify changing parameters. + */ + + int data_precision; /* bits of precision in image data */ + + int num_components; /* # of color components in JPEG image */ + J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ + + jpeg_component_info * comp_info; + /* comp_info[i] describes component that appears i'th in SOF */ + + JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; + /* ptrs to coefficient quantization tables, or NULL if not defined */ + + JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; + JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; + /* ptrs to Huffman coding tables, or NULL if not defined */ + + UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ + UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ + UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ + + int num_scans; /* # of entries in scan_info array */ + const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */ + /* The default value of scan_info is NULL, which causes a single-scan + * sequential JPEG file to be emitted. To create a multi-scan file, + * set num_scans and scan_info to point to an array of scan definitions. + */ + + boolean raw_data_in; /* TRUE=caller supplies downsampled data */ + boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ + boolean optimize_coding; /* TRUE=optimize entropy encoding parms */ + boolean CCIR601_sampling; /* TRUE=first samples are cosited */ + int smoothing_factor; /* 1..100, or 0 for no input smoothing */ + J_DCT_METHOD dct_method; /* DCT algorithm selector */ + + /* The restart interval can be specified in absolute MCUs by setting + * restart_interval, or in MCU rows by setting restart_in_rows + * (in which case the correct restart_interval will be figured + * for each scan). + */ + unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */ + int restart_in_rows; /* if > 0, MCU rows per restart interval */ + + /* Parameters controlling emission of special markers. */ + + boolean write_JFIF_header; /* should a JFIF marker be written? */ + UINT8 JFIF_major_version; /* What to write for the JFIF version number */ + UINT8 JFIF_minor_version; + /* These three values are not used by the JPEG code, merely copied */ + /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */ + /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */ + /* ratio is defined by X_density/Y_density even when density_unit=0. */ + UINT8 density_unit; /* JFIF code for pixel size units */ + UINT16 X_density; /* Horizontal pixel density */ + UINT16 Y_density; /* Vertical pixel density */ + boolean write_Adobe_marker; /* should an Adobe marker be written? */ + + /* State variable: index of next scanline to be written to + * jpeg_write_scanlines(). Application may use this to control its + * processing loop, e.g., "while (next_scanline < image_height)". + */ + + JDIMENSION next_scanline; /* 0 .. image_height-1 */ + + /* Remaining fields are known throughout compressor, but generally + * should not be touched by a surrounding application. + */ + + /* + * These fields are computed during compression startup + */ + boolean progressive_mode; /* TRUE if scan script uses progressive mode */ + int max_h_samp_factor; /* largest h_samp_factor */ + int max_v_samp_factor; /* largest v_samp_factor */ + + JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */ + /* The coefficient controller receives data in units of MCU rows as defined + * for fully interleaved scans (whether the JPEG file is interleaved or not). + * There are v_samp_factor * DCTSIZE sample rows of each component in an + * "iMCU" (interleaved MCU) row. + */ + + /* + * These fields are valid during any one scan. + * They describe the components and MCUs actually appearing in the scan. + */ + int comps_in_scan; /* # of JPEG components in this scan */ + jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; + /* *cur_comp_info[i] describes component that appears i'th in SOS */ + + JDIMENSION MCUs_per_row; /* # of MCUs across the image */ + JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ + + int blocks_in_MCU; /* # of DCT blocks per MCU */ + int MCU_membership[C_MAX_BLOCKS_IN_MCU]; + /* MCU_membership[i] is index in cur_comp_info of component owning */ + /* i'th block in an MCU */ + + int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ + + /* + * Links to compression subobjects (methods and private variables of modules) + */ + struct jpeg_comp_master * master; + struct jpeg_c_main_controller * main; + struct jpeg_c_prep_controller * prep; + struct jpeg_c_coef_controller * coef; + struct jpeg_marker_writer * marker; + struct jpeg_color_converter * cconvert; + struct jpeg_downsampler * downsample; + struct jpeg_forward_dct * fdct; + struct jpeg_entropy_encoder * entropy; + jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */ + int script_space_size; +}; + + +/* Master record for a decompression instance */ + +struct jpeg_decompress_struct { + jpeg_common_fields; /* Fields shared with jpeg_compress_struct */ + + /* Source of compressed data */ + struct jpeg_source_mgr * src; + + /* Basic description of image --- filled in by jpeg_read_header(). */ + /* Application may inspect these values to decide how to process image. */ + + JDIMENSION image_width; /* nominal image width (from SOF marker) */ + JDIMENSION image_height; /* nominal image height */ + int num_components; /* # of color components in JPEG image */ + J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ + + /* Decompression processing parameters --- these fields must be set before + * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes + * them to default values. + */ + + J_COLOR_SPACE out_color_space; /* colorspace for output */ + + unsigned int scale_num, scale_denom; /* fraction by which to scale image */ + + double output_gamma; /* image gamma wanted in output */ + + boolean buffered_image; /* TRUE=multiple output passes */ + boolean raw_data_out; /* TRUE=downsampled data wanted */ + + J_DCT_METHOD dct_method; /* IDCT algorithm selector */ + boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */ + boolean do_block_smoothing; /* TRUE=apply interblock smoothing */ + + boolean quantize_colors; /* TRUE=colormapped output wanted */ + /* the following are ignored if not quantize_colors: */ + J_DITHER_MODE dither_mode; /* type of color dithering to use */ + boolean two_pass_quantize; /* TRUE=use two-pass color quantization */ + int desired_number_of_colors; /* max # colors to use in created colormap */ + /* these are significant only in buffered-image mode: */ + boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */ + boolean enable_external_quant;/* enable future use of external colormap */ + boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */ + + /* Description of actual output image that will be returned to application. + * These fields are computed by jpeg_start_decompress(). + * You can also use jpeg_calc_output_dimensions() to determine these values + * in advance of calling jpeg_start_decompress(). + */ + + JDIMENSION output_width; /* scaled image width */ + JDIMENSION output_height; /* scaled image height */ + int out_color_components; /* # of color components in out_color_space */ + int output_components; /* # of color components returned */ + /* output_components is 1 (a colormap index) when quantizing colors; + * otherwise it equals out_color_components. + */ + int rec_outbuf_height; /* min recommended height of scanline buffer */ + /* If the buffer passed to jpeg_read_scanlines() is less than this many rows + * high, space and time will be wasted due to unnecessary data copying. + * Usually rec_outbuf_height will be 1 or 2, at most 4. + */ + + /* When quantizing colors, the output colormap is described by these fields. + * The application can supply a colormap by setting colormap non-NULL before + * calling jpeg_start_decompress; otherwise a colormap is created during + * jpeg_start_decompress or jpeg_start_output. + * The map has out_color_components rows and actual_number_of_colors columns. + */ + int actual_number_of_colors; /* number of entries in use */ + JSAMPARRAY colormap; /* The color map as a 2-D pixel array */ + + /* State variables: these variables indicate the progress of decompression. + * The application may examine these but must not modify them. + */ + + /* Row index of next scanline to be read from jpeg_read_scanlines(). + * Application may use this to control its processing loop, e.g., + * "while (output_scanline < output_height)". + */ + JDIMENSION output_scanline; /* 0 .. output_height-1 */ + + /* Current input scan number and number of iMCU rows completed in scan. + * These indicate the progress of the decompressor input side. + */ + int input_scan_number; /* Number of SOS markers seen so far */ + JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */ + + /* The "output scan number" is the notional scan being displayed by the + * output side. The decompressor will not allow output scan/row number + * to get ahead of input scan/row, but it can fall arbitrarily far behind. + */ + int output_scan_number; /* Nominal scan number being displayed */ + JDIMENSION output_iMCU_row; /* Number of iMCU rows read */ + + /* Current progression status. coef_bits[c][i] indicates the precision + * with which component c's DCT coefficient i (in zigzag order) is known. + * It is -1 when no data has yet been received, otherwise it is the point + * transform (shift) value for the most recent scan of the coefficient + * (thus, 0 at completion of the progression). + * This pointer is NULL when reading a non-progressive file. + */ + int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */ + + /* Internal JPEG parameters --- the application usually need not look at + * these fields. Note that the decompressor output side may not use + * any parameters that can change between scans. + */ + + /* Quantization and Huffman tables are carried forward across input + * datastreams when processing abbreviated JPEG datastreams. + */ + + JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; + /* ptrs to coefficient quantization tables, or NULL if not defined */ + + JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; + JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; + /* ptrs to Huffman coding tables, or NULL if not defined */ + + /* These parameters are never carried across datastreams, since they + * are given in SOF/SOS markers or defined to be reset by SOI. + */ + + int data_precision; /* bits of precision in image data */ + + jpeg_component_info * comp_info; + /* comp_info[i] describes component that appears i'th in SOF */ + + boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */ + boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ + + UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ + UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ + UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ + + unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */ + + /* These fields record data obtained from optional markers recognized by + * the JPEG library. + */ + boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */ + /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */ + UINT8 JFIF_major_version; /* JFIF version number */ + UINT8 JFIF_minor_version; + UINT8 density_unit; /* JFIF code for pixel size units */ + UINT16 X_density; /* Horizontal pixel density */ + UINT16 Y_density; /* Vertical pixel density */ + boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */ + UINT8 Adobe_transform; /* Color transform code from Adobe marker */ + + boolean CCIR601_sampling; /* TRUE=first samples are cosited */ + + /* Aside from the specific data retained from APPn markers known to the + * library, the uninterpreted contents of any or all APPn and COM markers + * can be saved in a list for examination by the application. + */ + jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */ + + /* Remaining fields are known throughout decompressor, but generally + * should not be touched by a surrounding application. + */ + + /* + * These fields are computed during decompression startup + */ + int max_h_samp_factor; /* largest h_samp_factor */ + int max_v_samp_factor; /* largest v_samp_factor */ + + int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */ + + JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */ + /* The coefficient controller's input and output progress is measured in + * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows + * in fully interleaved JPEG scans, but are used whether the scan is + * interleaved or not. We define an iMCU row as v_samp_factor DCT block + * rows of each component. Therefore, the IDCT output contains + * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row. + */ + + JSAMPLE * sample_range_limit; /* table for fast range-limiting */ + + /* + * These fields are valid during any one scan. + * They describe the components and MCUs actually appearing in the scan. + * Note that the decompressor output side must not use these fields. + */ + int comps_in_scan; /* # of JPEG components in this scan */ + jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; + /* *cur_comp_info[i] describes component that appears i'th in SOS */ + + JDIMENSION MCUs_per_row; /* # of MCUs across the image */ + JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ + + int blocks_in_MCU; /* # of DCT blocks per MCU */ + int MCU_membership[D_MAX_BLOCKS_IN_MCU]; + /* MCU_membership[i] is index in cur_comp_info of component owning */ + /* i'th block in an MCU */ + + int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ + + /* This field is shared between entropy decoder and marker parser. + * It is either zero or the code of a JPEG marker that has been + * read from the data source, but has not yet been processed. + */ + int unread_marker; + + /* + * Links to decompression subobjects (methods, private variables of modules) + */ + struct jpeg_decomp_master * master; + struct jpeg_d_main_controller * main; + struct jpeg_d_coef_controller * coef; + struct jpeg_d_post_controller * post; + struct jpeg_input_controller * inputctl; + struct jpeg_marker_reader * marker; + struct jpeg_entropy_decoder * entropy; + struct jpeg_inverse_dct * idct; + struct jpeg_upsampler * upsample; + struct jpeg_color_deconverter * cconvert; + struct jpeg_color_quantizer * cquantize; +}; + + +/* "Object" declarations for JPEG modules that may be supplied or called + * directly by the surrounding application. + * As with all objects in the JPEG library, these structs only define the + * publicly visible methods and state variables of a module. Additional + * private fields may exist after the public ones. + */ + + +/* Error handler object */ + +struct jpeg_error_mgr { + /* Error exit handler: does not return to caller */ + JMETHOD(void, error_exit, (j_common_ptr cinfo)); + /* Conditionally emit a trace or warning message */ + JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level)); + /* Routine that actually outputs a trace or error message */ + JMETHOD(void, output_message, (j_common_ptr cinfo)); + /* Format a message string for the most recent JPEG error or message */ + JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer)); +#define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */ + /* Reset error state variables at start of a new image */ + JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo)); + + /* The message ID code and any parameters are saved here. + * A message can have one string parameter or up to 8 int parameters. + */ + int msg_code; +#define JMSG_STR_PARM_MAX 80 + union { + int i[8]; + char s[JMSG_STR_PARM_MAX]; + } msg_parm; + + /* Standard state variables for error facility */ + + int trace_level; /* max msg_level that will be displayed */ + + /* For recoverable corrupt-data errors, we emit a warning message, + * but keep going unless emit_message chooses to abort. emit_message + * should count warnings in num_warnings. The surrounding application + * can check for bad data by seeing if num_warnings is nonzero at the + * end of processing. + */ + long num_warnings; /* number of corrupt-data warnings */ + + /* These fields point to the table(s) of error message strings. + * An application can change the table pointer to switch to a different + * message list (typically, to change the language in which errors are + * reported). Some applications may wish to add additional error codes + * that will be handled by the JPEG library error mechanism; the second + * table pointer is used for this purpose. + * + * First table includes all errors generated by JPEG library itself. + * Error code 0 is reserved for a "no such error string" message. + */ + const char * const * jpeg_message_table; /* Library errors */ + int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */ + /* Second table can be added by application (see cjpeg/djpeg for example). + * It contains strings numbered first_addon_message..last_addon_message. + */ + const char * const * addon_message_table; /* Non-library errors */ + int first_addon_message; /* code for first string in addon table */ + int last_addon_message; /* code for last string in addon table */ +}; + + +/* Progress monitor object */ + +struct jpeg_progress_mgr { + JMETHOD(void, progress_monitor, (j_common_ptr cinfo)); + + long pass_counter; /* work units completed in this pass */ + long pass_limit; /* total number of work units in this pass */ + int completed_passes; /* passes completed so far */ + int total_passes; /* total number of passes expected */ +}; + + +/* Data destination object for compression */ + +struct jpeg_destination_mgr { + JOCTET * next_output_byte; /* => next byte to write in buffer */ + size_t free_in_buffer; /* # of byte spaces remaining in buffer */ + + JMETHOD(void, init_destination, (j_compress_ptr cinfo)); + JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo)); + JMETHOD(void, term_destination, (j_compress_ptr cinfo)); +}; + + +/* Data source object for decompression */ + +struct jpeg_source_mgr { + const JOCTET * next_input_byte; /* => next byte to read from buffer */ + size_t bytes_in_buffer; /* # of bytes remaining in buffer */ + + JMETHOD(void, init_source, (j_decompress_ptr cinfo)); + JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo)); + JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes)); + JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired)); + JMETHOD(void, term_source, (j_decompress_ptr cinfo)); +}; + + +/* Memory manager object. + * Allocates "small" objects (a few K total), "large" objects (tens of K), + * and "really big" objects (virtual arrays with backing store if needed). + * The memory manager does not allow individual objects to be freed; rather, + * each created object is assigned to a pool, and whole pools can be freed + * at once. This is faster and more convenient than remembering exactly what + * to free, especially where malloc()/free() are not too speedy. + * NB: alloc routines never return NULL. They exit to error_exit if not + * successful. + */ + +#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */ +#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */ +#define JPOOL_NUMPOOLS 2 + +typedef struct jvirt_sarray_control * jvirt_sarray_ptr; +typedef struct jvirt_barray_control * jvirt_barray_ptr; + + +struct jpeg_memory_mgr { + /* Method pointers */ + JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id, + size_t sizeofobject)); + JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id, + size_t sizeofobject)); + JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id, + JDIMENSION samplesperrow, + JDIMENSION numrows)); + JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id, + JDIMENSION blocksperrow, + JDIMENSION numrows)); + JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo, + int pool_id, + boolean pre_zero, + JDIMENSION samplesperrow, + JDIMENSION numrows, + JDIMENSION maxaccess)); + JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo, + int pool_id, + boolean pre_zero, + JDIMENSION blocksperrow, + JDIMENSION numrows, + JDIMENSION maxaccess)); + JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo)); + JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo, + jvirt_sarray_ptr ptr, + JDIMENSION start_row, + JDIMENSION num_rows, + boolean writable)); + JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo, + jvirt_barray_ptr ptr, + JDIMENSION start_row, + JDIMENSION num_rows, + boolean writable)); + JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id)); + JMETHOD(void, self_destruct, (j_common_ptr cinfo)); + + /* Limit on memory allocation for this JPEG object. (Note that this is + * merely advisory, not a guaranteed maximum; it only affects the space + * used for virtual-array buffers.) May be changed by outer application + * after creating the JPEG object. + */ + long max_memory_to_use; + + /* Maximum allocation request accepted by alloc_large. */ + long max_alloc_chunk; +}; + + +/* Routine signature for application-supplied marker processing methods. + * Need not pass marker code since it is stored in cinfo->unread_marker. + */ +typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo)); + + +/* Declarations for routines called by application. + * The JPP macro hides prototype parameters from compilers that can't cope. + * Note JPP requires double parentheses. + */ + +#ifdef HAVE_PROTOTYPES +#define JPP(arglist) arglist +#else +#define JPP(arglist) () +#endif + + +/* Short forms of external names for systems with brain-damaged linkers. + * We shorten external names to be unique in the first six letters, which + * is good enough for all known systems. + * (If your compiler itself needs names to be unique in less than 15 + * characters, you are out of luck. Get a better compiler.) + */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jpeg_std_error jStdError +#define jpeg_CreateCompress jCreaCompress +#define jpeg_CreateDecompress jCreaDecompress +#define jpeg_destroy_compress jDestCompress +#define jpeg_destroy_decompress jDestDecompress +#define jpeg_stdio_dest jStdDest +#define jpeg_stdio_src jStdSrc +#define jpeg_set_defaults jSetDefaults +#define jpeg_set_colorspace jSetColorspace +#define jpeg_default_colorspace jDefColorspace +#define jpeg_set_quality jSetQuality +#define jpeg_set_linear_quality jSetLQuality +#define jpeg_add_quant_table jAddQuantTable +#define jpeg_quality_scaling jQualityScaling +#define jpeg_simple_progression jSimProgress +#define jpeg_suppress_tables jSuppressTables +#define jpeg_alloc_quant_table jAlcQTable +#define jpeg_alloc_huff_table jAlcHTable +#define jpeg_start_compress jStrtCompress +#define jpeg_write_scanlines jWrtScanlines +#define jpeg_finish_compress jFinCompress +#define jpeg_write_raw_data jWrtRawData +#define jpeg_write_marker jWrtMarker +#define jpeg_write_m_header jWrtMHeader +#define jpeg_write_m_byte jWrtMByte +#define jpeg_write_tables jWrtTables +#define jpeg_read_header jReadHeader +#define jpeg_start_decompress jStrtDecompress +#define jpeg_read_scanlines jReadScanlines +#define jpeg_finish_decompress jFinDecompress +#define jpeg_read_raw_data jReadRawData +#define jpeg_has_multiple_scans jHasMultScn +#define jpeg_start_output jStrtOutput +#define jpeg_finish_output jFinOutput +#define jpeg_input_complete jInComplete +#define jpeg_new_colormap jNewCMap +#define jpeg_consume_input jConsumeInput +#define jpeg_calc_output_dimensions jCalcDimensions +#define jpeg_save_markers jSaveMarkers +#define jpeg_set_marker_processor jSetMarker +#define jpeg_read_coefficients jReadCoefs +#define jpeg_write_coefficients jWrtCoefs +#define jpeg_copy_critical_parameters jCopyCrit +#define jpeg_abort_compress jAbrtCompress +#define jpeg_abort_decompress jAbrtDecompress +#define jpeg_abort jAbort +#define jpeg_destroy jDestroy +#define jpeg_resync_to_restart jResyncRestart +#endif /* NEED_SHORT_EXTERNAL_NAMES */ + + +/* Default error-management setup */ +EXTERN(struct jpeg_error_mgr *) jpeg_std_error + JPP((struct jpeg_error_mgr * err)); + +/* Initialization of JPEG compression objects. + * jpeg_create_compress() and jpeg_create_decompress() are the exported + * names that applications should call. These expand to calls on + * jpeg_CreateCompress and jpeg_CreateDecompress with additional information + * passed for version mismatch checking. + * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx. + */ +#define jpeg_create_compress(cinfo) \ + jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \ + (size_t) sizeof(struct jpeg_compress_struct)) +#define jpeg_create_decompress(cinfo) \ + jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \ + (size_t) sizeof(struct jpeg_decompress_struct)) +EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo, + int version, size_t structsize)); +EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo, + int version, size_t structsize)); +/* Destruction of JPEG compression objects */ +EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo)); + +/* Standard data source and destination managers: stdio streams. */ +/* Caller is responsible for opening the file before and closing after. */ +EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile)); +EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile)); + +/* Default parameter setup for compression */ +EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo)); +/* Compression parameter setup aids */ +EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo, + J_COLOR_SPACE colorspace)); +EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality, + boolean force_baseline)); +EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo, + int scale_factor, + boolean force_baseline)); +EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl, + const unsigned int *basic_table, + int scale_factor, + boolean force_baseline)); +EXTERN(int) jpeg_quality_scaling JPP((int quality)); +EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo, + boolean suppress)); +EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo)); +EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo)); + +/* Main entry points for compression */ +EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo, + boolean write_all_tables)); +EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo, + JSAMPARRAY scanlines, + JDIMENSION num_lines)); +EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo)); + +/* Replaces jpeg_write_scanlines when writing raw downsampled data. */ +EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo, + JSAMPIMAGE data, + JDIMENSION num_lines)); + +/* Write a special marker. See libjpeg.doc concerning safe usage. */ +EXTERN(void) jpeg_write_marker + JPP((j_compress_ptr cinfo, int marker, + const JOCTET * dataptr, unsigned int datalen)); +/* Same, but piecemeal. */ +EXTERN(void) jpeg_write_m_header + JPP((j_compress_ptr cinfo, int marker, unsigned int datalen)); +EXTERN(void) jpeg_write_m_byte + JPP((j_compress_ptr cinfo, int val)); + +/* Alternate compression function: just write an abbreviated table file */ +EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo)); + +/* Decompression startup: read start of JPEG datastream to see what's there */ +EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo, + boolean require_image)); +/* Return value is one of: */ +#define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */ +#define JPEG_HEADER_OK 1 /* Found valid image datastream */ +#define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */ +/* If you pass require_image = TRUE (normal case), you need not check for + * a TABLES_ONLY return code; an abbreviated file will cause an error exit. + * JPEG_SUSPENDED is only possible if you use a data source module that can + * give a suspension return (the stdio source module doesn't). + */ + +/* Main entry points for decompression */ +EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo)); +EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo, + JSAMPARRAY scanlines, + JDIMENSION max_lines)); +EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo)); + +/* Replaces jpeg_read_scanlines when reading raw downsampled data. */ +EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo, + JSAMPIMAGE data, + JDIMENSION max_lines)); + +/* Additional entry points for buffered-image mode. */ +EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo)); +EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo, + int scan_number)); +EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo)); +EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo)); +EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo)); +EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo)); +/* Return value is one of: */ +/* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ +#define JPEG_REACHED_SOS 1 /* Reached start of new scan */ +#define JPEG_REACHED_EOI 2 /* Reached end of image */ +#define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */ +#define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */ + +/* Precalculate output dimensions for current decompression parameters. */ +EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo)); + +/* Control saving of COM and APPn markers into marker_list. */ +EXTERN(void) jpeg_save_markers + JPP((j_decompress_ptr cinfo, int marker_code, + unsigned int length_limit)); + +/* Install a special processing method for COM or APPn markers. */ +EXTERN(void) jpeg_set_marker_processor + JPP((j_decompress_ptr cinfo, int marker_code, + jpeg_marker_parser_method routine)); + +/* Read or write raw DCT coefficients --- useful for lossless transcoding. */ +EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo)); +EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo, + jvirt_barray_ptr * coef_arrays)); +EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo, + j_compress_ptr dstinfo)); + +/* If you choose to abort compression or decompression before completing + * jpeg_finish_(de)compress, then you need to clean up to release memory, + * temporary files, etc. You can just call jpeg_destroy_(de)compress + * if you're done with the JPEG object, but if you want to clean it up and + * reuse it, call this: + */ +EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo)); + +/* Generic versions of jpeg_abort and jpeg_destroy that work on either + * flavor of JPEG object. These may be more convenient in some places. + */ +EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo)); +EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo)); + +/* Default restart-marker-resync procedure for use by data source modules */ +EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo, + int desired)); + + +/* These marker codes are exported since applications and data source modules + * are likely to want to use them. + */ + +#define JPEG_RST0 0xD0 /* RST0 marker code */ +#define JPEG_EOI 0xD9 /* EOI marker code */ +#define JPEG_APP0 0xE0 /* APP0 marker code */ +#define JPEG_COM 0xFE /* COM marker code */ + + +/* If we have a brain-damaged compiler that emits warnings (or worse, errors) + * for structure definitions that are never filled in, keep it quiet by + * supplying dummy definitions for the various substructures. + */ + +#ifdef INCOMPLETE_TYPES_BROKEN +#ifndef JPEG_INTERNALS /* will be defined in jpegint.h */ +struct jvirt_sarray_control { long dummy; }; +struct jvirt_barray_control { long dummy; }; +struct jpeg_comp_master { long dummy; }; +struct jpeg_c_main_controller { long dummy; }; +struct jpeg_c_prep_controller { long dummy; }; +struct jpeg_c_coef_controller { long dummy; }; +struct jpeg_marker_writer { long dummy; }; +struct jpeg_color_converter { long dummy; }; +struct jpeg_downsampler { long dummy; }; +struct jpeg_forward_dct { long dummy; }; +struct jpeg_entropy_encoder { long dummy; }; +struct jpeg_decomp_master { long dummy; }; +struct jpeg_d_main_controller { long dummy; }; +struct jpeg_d_coef_controller { long dummy; }; +struct jpeg_d_post_controller { long dummy; }; +struct jpeg_input_controller { long dummy; }; +struct jpeg_marker_reader { long dummy; }; +struct jpeg_entropy_decoder { long dummy; }; +struct jpeg_inverse_dct { long dummy; }; +struct jpeg_upsampler { long dummy; }; +struct jpeg_color_deconverter { long dummy; }; +struct jpeg_color_quantizer { long dummy; }; +#endif /* JPEG_INTERNALS */ +#endif /* INCOMPLETE_TYPES_BROKEN */ + + +/* + * The JPEG library modules define JPEG_INTERNALS before including this file. + * The internal structure declarations are read only when that is true. + * Applications using the library should not include jpegint.h, but may wish + * to include jerror.h. + */ + +#ifdef JPEG_INTERNALS +#include "jpegint.h" /* fetch private declarations */ +#include "jerror.h" /* fetch error codes too */ +#endif + +#endif /* JPEGLIB_H */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jquant1.c b/SlnkDWFImpl/CxImage/jpeg/jquant1.c new file mode 100644 index 0000000..aaa34a1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jquant1.c @@ -0,0 +1,856 @@ +/* + * jquant1.c + * + * Copyright (C) 1991-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains 1-pass color quantization (color mapping) routines. + * These routines provide mapping to a fixed color map using equally spaced + * color values. Optional Floyd-Steinberg or ordered dithering is available. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + +#ifdef QUANT_1PASS_SUPPORTED + + +/* + * The main purpose of 1-pass quantization is to provide a fast, if not very + * high quality, colormapped output capability. A 2-pass quantizer usually + * gives better visual quality; however, for quantized grayscale output this + * quantizer is perfectly adequate. Dithering is highly recommended with this + * quantizer, though you can turn it off if you really want to. + * + * In 1-pass quantization the colormap must be chosen in advance of seeing the + * image. We use a map consisting of all combinations of Ncolors[i] color + * values for the i'th component. The Ncolors[] values are chosen so that + * their product, the total number of colors, is no more than that requested. + * (In most cases, the product will be somewhat less.) + * + * Since the colormap is orthogonal, the representative value for each color + * component can be determined without considering the other components; + * then these indexes can be combined into a colormap index by a standard + * N-dimensional-array-subscript calculation. Most of the arithmetic involved + * can be precalculated and stored in the lookup table colorindex[]. + * colorindex[i][j] maps pixel value j in component i to the nearest + * representative value (grid plane) for that component; this index is + * multiplied by the array stride for component i, so that the + * index of the colormap entry closest to a given pixel value is just + * sum( colorindex[component-number][pixel-component-value] ) + * Aside from being fast, this scheme allows for variable spacing between + * representative values with no additional lookup cost. + * + * If gamma correction has been applied in color conversion, it might be wise + * to adjust the color grid spacing so that the representative colors are + * equidistant in linear space. At this writing, gamma correction is not + * implemented by jdcolor, so nothing is done here. + */ + + +/* Declarations for ordered dithering. + * + * We use a standard 16x16 ordered dither array. The basic concept of ordered + * dithering is described in many references, for instance Dale Schumacher's + * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991). + * In place of Schumacher's comparisons against a "threshold" value, we add a + * "dither" value to the input pixel and then round the result to the nearest + * output value. The dither value is equivalent to (0.5 - threshold) times + * the distance between output values. For ordered dithering, we assume that + * the output colors are equally spaced; if not, results will probably be + * worse, since the dither may be too much or too little at a given point. + * + * The normal calculation would be to form pixel value + dither, range-limit + * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual. + * We can skip the separate range-limiting step by extending the colorindex + * table in both directions. + */ + +#define ODITHER_SIZE 16 /* dimension of dither matrix */ +/* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */ +#define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */ +#define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */ + +typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE]; +typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE]; + +static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = { + /* Bayer's order-4 dither array. Generated by the code given in + * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I. + * The values in this array must range from 0 to ODITHER_CELLS-1. + */ + { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 }, + { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 }, + { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 }, + { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 }, + { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 }, + { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 }, + { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 }, + { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 }, + { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 }, + { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 }, + { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 }, + { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 }, + { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 }, + { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 }, + { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 }, + { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 } +}; + + +/* Declarations for Floyd-Steinberg dithering. + * + * Errors are accumulated into the array fserrors[], at a resolution of + * 1/16th of a pixel count. The error at a given pixel is propagated + * to its not-yet-processed neighbors using the standard F-S fractions, + * ... (here) 7/16 + * 3/16 5/16 1/16 + * We work left-to-right on even rows, right-to-left on odd rows. + * + * We can get away with a single array (holding one row's worth of errors) + * by using it to store the current row's errors at pixel columns not yet + * processed, but the next row's errors at columns already processed. We + * need only a few extra variables to hold the errors immediately around the + * current column. (If we are lucky, those variables are in registers, but + * even if not, they're probably cheaper to access than array elements are.) + * + * The fserrors[] array is indexed [component#][position]. + * We provide (#columns + 2) entries per component; the extra entry at each + * end saves us from special-casing the first and last pixels. + * + * Note: on a wide image, we might not have enough room in a PC's near data + * segment to hold the error array; so it is allocated with alloc_large. + */ + +#if BITS_IN_JSAMPLE == 8 +typedef INT16 FSERROR; /* 16 bits should be enough */ +typedef int LOCFSERROR; /* use 'int' for calculation temps */ +#else +typedef INT32 FSERROR; /* may need more than 16 bits */ +typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */ +#endif + +typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */ + + +/* Private subobject */ + +#define MAX_Q_COMPS 4 /* max components I can handle */ + +typedef struct { + struct jpeg_color_quantizer pub; /* public fields */ + + /* Initially allocated colormap is saved here */ + JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */ + int sv_actual; /* number of entries in use */ + + JSAMPARRAY colorindex; /* Precomputed mapping for speed */ + /* colorindex[i][j] = index of color closest to pixel value j in component i, + * premultiplied as described above. Since colormap indexes must fit into + * JSAMPLEs, the entries of this array will too. + */ + boolean is_padded; /* is the colorindex padded for odither? */ + + int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */ + + /* Variables for ordered dithering */ + int row_index; /* cur row's vertical index in dither matrix */ + ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */ + + /* Variables for Floyd-Steinberg dithering */ + FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */ + boolean on_odd_row; /* flag to remember which row we are on */ +} my_cquantizer; + +typedef my_cquantizer * my_cquantize_ptr; + + +/* + * Policy-making subroutines for create_colormap and create_colorindex. + * These routines determine the colormap to be used. The rest of the module + * only assumes that the colormap is orthogonal. + * + * * select_ncolors decides how to divvy up the available colors + * among the components. + * * output_value defines the set of representative values for a component. + * * largest_input_value defines the mapping from input values to + * representative values for a component. + * Note that the latter two routines may impose different policies for + * different components, though this is not currently done. + */ + + +LOCAL(int) +select_ncolors (j_decompress_ptr cinfo, int Ncolors[]) +/* Determine allocation of desired colors to components, */ +/* and fill in Ncolors[] array to indicate choice. */ +/* Return value is total number of colors (product of Ncolors[] values). */ +{ + int nc = cinfo->out_color_components; /* number of color components */ + int max_colors = cinfo->desired_number_of_colors; + int total_colors, iroot, i, j; + boolean changed; + long temp; + static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE }; + + /* We can allocate at least the nc'th root of max_colors per component. */ + /* Compute floor(nc'th root of max_colors). */ + iroot = 1; + do { + iroot++; + temp = iroot; /* set temp = iroot ** nc */ + for (i = 1; i < nc; i++) + temp *= iroot; + } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */ + iroot--; /* now iroot = floor(root) */ + + /* Must have at least 2 color values per component */ + if (iroot < 2) + ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp); + + /* Initialize to iroot color values for each component */ + total_colors = 1; + for (i = 0; i < nc; i++) { + Ncolors[i] = iroot; + total_colors *= iroot; + } + /* We may be able to increment the count for one or more components without + * exceeding max_colors, though we know not all can be incremented. + * Sometimes, the first component can be incremented more than once! + * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.) + * In RGB colorspace, try to increment G first, then R, then B. + */ + do { + changed = FALSE; + for (i = 0; i < nc; i++) { + j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i); + /* calculate new total_colors if Ncolors[j] is incremented */ + temp = total_colors / Ncolors[j]; + temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */ + if (temp > (long) max_colors) + break; /* won't fit, done with this pass */ + Ncolors[j]++; /* OK, apply the increment */ + total_colors = (int) temp; + changed = TRUE; + } + } while (changed); + + return total_colors; +} + + +LOCAL(int) +output_value (j_decompress_ptr cinfo, int ci, int j, int maxj) +/* Return j'th output value, where j will range from 0 to maxj */ +/* The output values must fall in 0..MAXJSAMPLE in increasing order */ +{ + /* We always provide values 0 and MAXJSAMPLE for each component; + * any additional values are equally spaced between these limits. + * (Forcing the upper and lower values to the limits ensures that + * dithering can't produce a color outside the selected gamut.) + */ + return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj); +} + + +LOCAL(int) +largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj) +/* Return largest input value that should map to j'th output value */ +/* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */ +{ + /* Breakpoints are halfway between values returned by output_value */ + return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj)); +} + + +/* + * Create the colormap. + */ + +LOCAL(void) +create_colormap (j_decompress_ptr cinfo) +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + JSAMPARRAY colormap; /* Created colormap */ + int total_colors; /* Number of distinct output colors */ + int i,j,k, nci, blksize, blkdist, ptr, val; + + /* Select number of colors for each component */ + total_colors = select_ncolors(cinfo, cquantize->Ncolors); + + /* Report selected color counts */ + if (cinfo->out_color_components == 3) + TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS, + total_colors, cquantize->Ncolors[0], + cquantize->Ncolors[1], cquantize->Ncolors[2]); + else + TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors); + + /* Allocate and fill in the colormap. */ + /* The colors are ordered in the map in standard row-major order, */ + /* i.e. rightmost (highest-indexed) color changes most rapidly. */ + + colormap = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components); + + /* blksize is number of adjacent repeated entries for a component */ + /* blkdist is distance between groups of identical entries for a component */ + blkdist = total_colors; + + for (i = 0; i < cinfo->out_color_components; i++) { + /* fill in colormap entries for i'th color component */ + nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ + blksize = blkdist / nci; + for (j = 0; j < nci; j++) { + /* Compute j'th output value (out of nci) for component */ + val = output_value(cinfo, i, j, nci-1); + /* Fill in all colormap entries that have this value of this component */ + for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) { + /* fill in blksize entries beginning at ptr */ + for (k = 0; k < blksize; k++) + colormap[i][ptr+k] = (JSAMPLE) val; + } + } + blkdist = blksize; /* blksize of this color is blkdist of next */ + } + + /* Save the colormap in private storage, + * where it will survive color quantization mode changes. + */ + cquantize->sv_colormap = colormap; + cquantize->sv_actual = total_colors; +} + + +/* + * Create the color index table. + */ + +LOCAL(void) +create_colorindex (j_decompress_ptr cinfo) +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + JSAMPROW indexptr; + int i,j,k, nci, blksize, val, pad; + + /* For ordered dither, we pad the color index tables by MAXJSAMPLE in + * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE). + * This is not necessary in the other dithering modes. However, we + * flag whether it was done in case user changes dithering mode. + */ + if (cinfo->dither_mode == JDITHER_ORDERED) { + pad = MAXJSAMPLE*2; + cquantize->is_padded = TRUE; + } else { + pad = 0; + cquantize->is_padded = FALSE; + } + + cquantize->colorindex = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + (JDIMENSION) (MAXJSAMPLE+1 + pad), + (JDIMENSION) cinfo->out_color_components); + + /* blksize is number of adjacent repeated entries for a component */ + blksize = cquantize->sv_actual; + + for (i = 0; i < cinfo->out_color_components; i++) { + /* fill in colorindex entries for i'th color component */ + nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ + blksize = blksize / nci; + + /* adjust colorindex pointers to provide padding at negative indexes. */ + if (pad) + cquantize->colorindex[i] += MAXJSAMPLE; + + /* in loop, val = index of current output value, */ + /* and k = largest j that maps to current val */ + indexptr = cquantize->colorindex[i]; + val = 0; + k = largest_input_value(cinfo, i, 0, nci-1); + for (j = 0; j <= MAXJSAMPLE; j++) { + while (j > k) /* advance val if past boundary */ + k = largest_input_value(cinfo, i, ++val, nci-1); + /* premultiply so that no multiplication needed in main processing */ + indexptr[j] = (JSAMPLE) (val * blksize); + } + /* Pad at both ends if necessary */ + if (pad) + for (j = 1; j <= MAXJSAMPLE; j++) { + indexptr[-j] = indexptr[0]; + indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE]; + } + } +} + + +/* + * Create an ordered-dither array for a component having ncolors + * distinct output values. + */ + +LOCAL(ODITHER_MATRIX_PTR) +make_odither_array (j_decompress_ptr cinfo, int ncolors) +{ + ODITHER_MATRIX_PTR odither; + int j,k; + INT32 num,den; + + odither = (ODITHER_MATRIX_PTR) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(ODITHER_MATRIX)); + /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1). + * Hence the dither value for the matrix cell with fill order f + * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1). + * On 16-bit-int machine, be careful to avoid overflow. + */ + den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1)); + for (j = 0; j < ODITHER_SIZE; j++) { + for (k = 0; k < ODITHER_SIZE; k++) { + num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k]))) + * MAXJSAMPLE; + /* Ensure round towards zero despite C's lack of consistency + * about rounding negative values in integer division... + */ + odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den); + } + } + return odither; +} + + +/* + * Create the ordered-dither tables. + * Components having the same number of representative colors may + * share a dither table. + */ + +LOCAL(void) +create_odither_tables (j_decompress_ptr cinfo) +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + ODITHER_MATRIX_PTR odither; + int i, j, nci; + + for (i = 0; i < cinfo->out_color_components; i++) { + nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ + odither = NULL; /* search for matching prior component */ + for (j = 0; j < i; j++) { + if (nci == cquantize->Ncolors[j]) { + odither = cquantize->odither[j]; + break; + } + } + if (odither == NULL) /* need a new table? */ + odither = make_odither_array(cinfo, nci); + cquantize->odither[i] = odither; + } +} + + +/* + * Map some rows of pixels to the output colormapped representation. + */ + +METHODDEF(void) +color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf, + JSAMPARRAY output_buf, int num_rows) +/* General case, no dithering */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + JSAMPARRAY colorindex = cquantize->colorindex; + register int pixcode, ci; + register JSAMPROW ptrin, ptrout; + int row; + JDIMENSION col; + JDIMENSION width = cinfo->output_width; + register int nc = cinfo->out_color_components; + + for (row = 0; row < num_rows; row++) { + ptrin = input_buf[row]; + ptrout = output_buf[row]; + for (col = width; col > 0; col--) { + pixcode = 0; + for (ci = 0; ci < nc; ci++) { + pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]); + } + *ptrout++ = (JSAMPLE) pixcode; + } + } +} + + +METHODDEF(void) +color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf, + JSAMPARRAY output_buf, int num_rows) +/* Fast path for out_color_components==3, no dithering */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + register int pixcode; + register JSAMPROW ptrin, ptrout; + JSAMPROW colorindex0 = cquantize->colorindex[0]; + JSAMPROW colorindex1 = cquantize->colorindex[1]; + JSAMPROW colorindex2 = cquantize->colorindex[2]; + int row; + JDIMENSION col; + JDIMENSION width = cinfo->output_width; + + for (row = 0; row < num_rows; row++) { + ptrin = input_buf[row]; + ptrout = output_buf[row]; + for (col = width; col > 0; col--) { + pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]); + pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]); + pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]); + *ptrout++ = (JSAMPLE) pixcode; + } + } +} + + +METHODDEF(void) +quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, + JSAMPARRAY output_buf, int num_rows) +/* General case, with ordered dithering */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + register JSAMPROW input_ptr; + register JSAMPROW output_ptr; + JSAMPROW colorindex_ci; + int * dither; /* points to active row of dither matrix */ + int row_index, col_index; /* current indexes into dither matrix */ + int nc = cinfo->out_color_components; + int ci; + int row; + JDIMENSION col; + JDIMENSION width = cinfo->output_width; + + for (row = 0; row < num_rows; row++) { + /* Initialize output values to 0 so can process components separately */ + jzero_far((void FAR *) output_buf[row], + (size_t) (width * SIZEOF(JSAMPLE))); + row_index = cquantize->row_index; + for (ci = 0; ci < nc; ci++) { + input_ptr = input_buf[row] + ci; + output_ptr = output_buf[row]; + colorindex_ci = cquantize->colorindex[ci]; + dither = cquantize->odither[ci][row_index]; + col_index = 0; + + for (col = width; col > 0; col--) { + /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE, + * select output value, accumulate into output code for this pixel. + * Range-limiting need not be done explicitly, as we have extended + * the colorindex table to produce the right answers for out-of-range + * inputs. The maximum dither is +- MAXJSAMPLE; this sets the + * required amount of padding. + */ + *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]]; + input_ptr += nc; + output_ptr++; + col_index = (col_index + 1) & ODITHER_MASK; + } + } + /* Advance row index for next row */ + row_index = (row_index + 1) & ODITHER_MASK; + cquantize->row_index = row_index; + } +} + + +METHODDEF(void) +quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, + JSAMPARRAY output_buf, int num_rows) +/* Fast path for out_color_components==3, with ordered dithering */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + register int pixcode; + register JSAMPROW input_ptr; + register JSAMPROW output_ptr; + JSAMPROW colorindex0 = cquantize->colorindex[0]; + JSAMPROW colorindex1 = cquantize->colorindex[1]; + JSAMPROW colorindex2 = cquantize->colorindex[2]; + int * dither0; /* points to active row of dither matrix */ + int * dither1; + int * dither2; + int row_index, col_index; /* current indexes into dither matrix */ + int row; + JDIMENSION col; + JDIMENSION width = cinfo->output_width; + + for (row = 0; row < num_rows; row++) { + row_index = cquantize->row_index; + input_ptr = input_buf[row]; + output_ptr = output_buf[row]; + dither0 = cquantize->odither[0][row_index]; + dither1 = cquantize->odither[1][row_index]; + dither2 = cquantize->odither[2][row_index]; + col_index = 0; + + for (col = width; col > 0; col--) { + pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) + + dither0[col_index]]); + pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) + + dither1[col_index]]); + pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) + + dither2[col_index]]); + *output_ptr++ = (JSAMPLE) pixcode; + col_index = (col_index + 1) & ODITHER_MASK; + } + row_index = (row_index + 1) & ODITHER_MASK; + cquantize->row_index = row_index; + } +} + + +METHODDEF(void) +quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, + JSAMPARRAY output_buf, int num_rows) +/* General case, with Floyd-Steinberg dithering */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + register LOCFSERROR cur; /* current error or pixel value */ + LOCFSERROR belowerr; /* error for pixel below cur */ + LOCFSERROR bpreverr; /* error for below/prev col */ + LOCFSERROR bnexterr; /* error for below/next col */ + LOCFSERROR delta; + register FSERRPTR errorptr; /* => fserrors[] at column before current */ + register JSAMPROW input_ptr; + register JSAMPROW output_ptr; + JSAMPROW colorindex_ci; + JSAMPROW colormap_ci; + int pixcode; + int nc = cinfo->out_color_components; + int dir; /* 1 for left-to-right, -1 for right-to-left */ + int dirnc; /* dir * nc */ + int ci; + int row; + JDIMENSION col; + JDIMENSION width = cinfo->output_width; + JSAMPLE *range_limit = cinfo->sample_range_limit; + SHIFT_TEMPS + + for (row = 0; row < num_rows; row++) { + /* Initialize output values to 0 so can process components separately */ + jzero_far((void FAR *) output_buf[row], + (size_t) (width * SIZEOF(JSAMPLE))); + for (ci = 0; ci < nc; ci++) { + input_ptr = input_buf[row] + ci; + output_ptr = output_buf[row]; + if (cquantize->on_odd_row) { + /* work right to left in this row */ + input_ptr += (width-1) * nc; /* so point to rightmost pixel */ + output_ptr += width-1; + dir = -1; + dirnc = -nc; + errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */ + } else { + /* work left to right in this row */ + dir = 1; + dirnc = nc; + errorptr = cquantize->fserrors[ci]; /* => entry before first column */ + } + colorindex_ci = cquantize->colorindex[ci]; + colormap_ci = cquantize->sv_colormap[ci]; + /* Preset error values: no error propagated to first pixel from left */ + cur = 0; + /* and no error propagated to row below yet */ + belowerr = bpreverr = 0; + + for (col = width; col > 0; col--) { + /* cur holds the error propagated from the previous pixel on the + * current line. Add the error propagated from the previous line + * to form the complete error correction term for this pixel, and + * round the error term (which is expressed * 16) to an integer. + * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct + * for either sign of the error value. + * Note: errorptr points to *previous* column's array entry. + */ + cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4); + /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE. + * The maximum error is +- MAXJSAMPLE; this sets the required size + * of the range_limit array. + */ + cur += GETJSAMPLE(*input_ptr); + cur = GETJSAMPLE(range_limit[cur]); + /* Select output value, accumulate into output code for this pixel */ + pixcode = GETJSAMPLE(colorindex_ci[cur]); + *output_ptr += (JSAMPLE) pixcode; + /* Compute actual representation error at this pixel */ + /* Note: we can do this even though we don't have the final */ + /* pixel code, because the colormap is orthogonal. */ + cur -= GETJSAMPLE(colormap_ci[pixcode]); + /* Compute error fractions to be propagated to adjacent pixels. + * Add these into the running sums, and simultaneously shift the + * next-line error sums left by 1 column. + */ + bnexterr = cur; + delta = cur * 2; + cur += delta; /* form error * 3 */ + errorptr[0] = (FSERROR) (bpreverr + cur); + cur += delta; /* form error * 5 */ + bpreverr = belowerr + cur; + belowerr = bnexterr; + cur += delta; /* form error * 7 */ + /* At this point cur contains the 7/16 error value to be propagated + * to the next pixel on the current line, and all the errors for the + * next line have been shifted over. We are therefore ready to move on. + */ + input_ptr += dirnc; /* advance input ptr to next column */ + output_ptr += dir; /* advance output ptr to next column */ + errorptr += dir; /* advance errorptr to current column */ + } + /* Post-loop cleanup: we must unload the final error value into the + * final fserrors[] entry. Note we need not unload belowerr because + * it is for the dummy column before or after the actual array. + */ + errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */ + } + cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE); + } +} + + +/* + * Allocate workspace for Floyd-Steinberg errors. + */ + +LOCAL(void) +alloc_fs_workspace (j_decompress_ptr cinfo) +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + size_t arraysize; + int i; + + arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR)); + for (i = 0; i < cinfo->out_color_components; i++) { + cquantize->fserrors[i] = (FSERRPTR) + (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize); + } +} + + +/* + * Initialize for one-pass color quantization. + */ + +METHODDEF(void) +start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan) +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + size_t arraysize; + int i; + + /* Install my colormap. */ + cinfo->colormap = cquantize->sv_colormap; + cinfo->actual_number_of_colors = cquantize->sv_actual; + + /* Initialize for desired dithering mode. */ + switch (cinfo->dither_mode) { + case JDITHER_NONE: + if (cinfo->out_color_components == 3) + cquantize->pub.color_quantize = color_quantize3; + else + cquantize->pub.color_quantize = color_quantize; + break; + case JDITHER_ORDERED: + if (cinfo->out_color_components == 3) + cquantize->pub.color_quantize = quantize3_ord_dither; + else + cquantize->pub.color_quantize = quantize_ord_dither; + cquantize->row_index = 0; /* initialize state for ordered dither */ + /* If user changed to ordered dither from another mode, + * we must recreate the color index table with padding. + * This will cost extra space, but probably isn't very likely. + */ + if (! cquantize->is_padded) + create_colorindex(cinfo); + /* Create ordered-dither tables if we didn't already. */ + if (cquantize->odither[0] == NULL) + create_odither_tables(cinfo); + break; + case JDITHER_FS: + cquantize->pub.color_quantize = quantize_fs_dither; + cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */ + /* Allocate Floyd-Steinberg workspace if didn't already. */ + if (cquantize->fserrors[0] == NULL) + alloc_fs_workspace(cinfo); + /* Initialize the propagated errors to zero. */ + arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR)); + for (i = 0; i < cinfo->out_color_components; i++) + jzero_far((void FAR *) cquantize->fserrors[i], arraysize); + break; + default: + ERREXIT(cinfo, JERR_NOT_COMPILED); + break; + } +} + + +/* + * Finish up at the end of the pass. + */ + +METHODDEF(void) +finish_pass_1_quant (j_decompress_ptr cinfo) +{ + /* no work in 1-pass case */ +} + + +/* + * Switch to a new external colormap between output passes. + * Shouldn't get to this module! + */ + +METHODDEF(void) +new_color_map_1_quant (j_decompress_ptr cinfo) +{ + ERREXIT(cinfo, JERR_MODE_CHANGE); +} + + +/* + * Module initialization routine for 1-pass color quantization. + */ + +GLOBAL(void) +jinit_1pass_quantizer (j_decompress_ptr cinfo) +{ + my_cquantize_ptr cquantize; + + cquantize = (my_cquantize_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_cquantizer)); + cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize; + cquantize->pub.start_pass = start_pass_1_quant; + cquantize->pub.finish_pass = finish_pass_1_quant; + cquantize->pub.new_color_map = new_color_map_1_quant; + cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */ + cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */ + + /* Make sure my internal arrays won't overflow */ + if (cinfo->out_color_components > MAX_Q_COMPS) + ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS); + /* Make sure colormap indexes can be represented by JSAMPLEs */ + if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1)) + ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1); + + /* Create the colormap and color index table. */ + create_colormap(cinfo); + create_colorindex(cinfo); + + /* Allocate Floyd-Steinberg workspace now if requested. + * We do this now since it is FAR storage and may affect the memory + * manager's space calculations. If the user changes to FS dither + * mode in a later pass, we will allocate the space then, and will + * possibly overrun the max_memory_to_use setting. + */ + if (cinfo->dither_mode == JDITHER_FS) + alloc_fs_workspace(cinfo); +} + +#endif /* QUANT_1PASS_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jquant2.c b/SlnkDWFImpl/CxImage/jpeg/jquant2.c new file mode 100644 index 0000000..87a3920 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jquant2.c @@ -0,0 +1,1310 @@ +/* + * jquant2.c + * + * Copyright (C) 1991-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains 2-pass color quantization (color mapping) routines. + * These routines provide selection of a custom color map for an image, + * followed by mapping of the image to that color map, with optional + * Floyd-Steinberg dithering. + * It is also possible to use just the second pass to map to an arbitrary + * externally-given color map. + * + * Note: ordered dithering is not supported, since there isn't any fast + * way to compute intercolor distances; it's unclear that ordered dither's + * fundamental assumptions even hold with an irregularly spaced color map. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + +#ifdef QUANT_2PASS_SUPPORTED + + +/* + * This module implements the well-known Heckbert paradigm for color + * quantization. Most of the ideas used here can be traced back to + * Heckbert's seminal paper + * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display", + * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304. + * + * In the first pass over the image, we accumulate a histogram showing the + * usage count of each possible color. To keep the histogram to a reasonable + * size, we reduce the precision of the input; typical practice is to retain + * 5 or 6 bits per color, so that 8 or 4 different input values are counted + * in the same histogram cell. + * + * Next, the color-selection step begins with a box representing the whole + * color space, and repeatedly splits the "largest" remaining box until we + * have as many boxes as desired colors. Then the mean color in each + * remaining box becomes one of the possible output colors. + * + * The second pass over the image maps each input pixel to the closest output + * color (optionally after applying a Floyd-Steinberg dithering correction). + * This mapping is logically trivial, but making it go fast enough requires + * considerable care. + * + * Heckbert-style quantizers vary a good deal in their policies for choosing + * the "largest" box and deciding where to cut it. The particular policies + * used here have proved out well in experimental comparisons, but better ones + * may yet be found. + * + * In earlier versions of the IJG code, this module quantized in YCbCr color + * space, processing the raw upsampled data without a color conversion step. + * This allowed the color conversion math to be done only once per colormap + * entry, not once per pixel. However, that optimization precluded other + * useful optimizations (such as merging color conversion with upsampling) + * and it also interfered with desired capabilities such as quantizing to an + * externally-supplied colormap. We have therefore abandoned that approach. + * The present code works in the post-conversion color space, typically RGB. + * + * To improve the visual quality of the results, we actually work in scaled + * RGB space, giving G distances more weight than R, and R in turn more than + * B. To do everything in integer math, we must use integer scale factors. + * The 2/3/1 scale factors used here correspond loosely to the relative + * weights of the colors in the NTSC grayscale equation. + * If you want to use this code to quantize a non-RGB color space, you'll + * probably need to change these scale factors. + */ + +#define R_SCALE 2 /* scale R distances by this much */ +#define G_SCALE 3 /* scale G distances by this much */ +#define B_SCALE 1 /* and B by this much */ + +/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined + * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B + * and B,G,R orders. If you define some other weird order in jmorecfg.h, + * you'll get compile errors until you extend this logic. In that case + * you'll probably want to tweak the histogram sizes too. + */ + +#if RGB_RED == 0 +#define C0_SCALE R_SCALE +#endif +#if RGB_BLUE == 0 +#define C0_SCALE B_SCALE +#endif +#if RGB_GREEN == 1 +#define C1_SCALE G_SCALE +#endif +#if RGB_RED == 2 +#define C2_SCALE R_SCALE +#endif +#if RGB_BLUE == 2 +#define C2_SCALE B_SCALE +#endif + + +/* + * First we have the histogram data structure and routines for creating it. + * + * The number of bits of precision can be adjusted by changing these symbols. + * We recommend keeping 6 bits for G and 5 each for R and B. + * If you have plenty of memory and cycles, 6 bits all around gives marginally + * better results; if you are short of memory, 5 bits all around will save + * some space but degrade the results. + * To maintain a fully accurate histogram, we'd need to allocate a "long" + * (preferably unsigned long) for each cell. In practice this is overkill; + * we can get by with 16 bits per cell. Few of the cell counts will overflow, + * and clamping those that do overflow to the maximum value will give close- + * enough results. This reduces the recommended histogram size from 256Kb + * to 128Kb, which is a useful savings on PC-class machines. + * (In the second pass the histogram space is re-used for pixel mapping data; + * in that capacity, each cell must be able to store zero to the number of + * desired colors. 16 bits/cell is plenty for that too.) + * Since the JPEG code is intended to run in small memory model on 80x86 + * machines, we can't just allocate the histogram in one chunk. Instead + * of a true 3-D array, we use a row of pointers to 2-D arrays. Each + * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and + * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that + * on 80x86 machines, the pointer row is in near memory but the actual + * arrays are in far memory (same arrangement as we use for image arrays). + */ + +#define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */ + +/* These will do the right thing for either R,G,B or B,G,R color order, + * but you may not like the results for other color orders. + */ +#define HIST_C0_BITS 5 /* bits of precision in R/B histogram */ +#define HIST_C1_BITS 6 /* bits of precision in G histogram */ +#define HIST_C2_BITS 5 /* bits of precision in B/R histogram */ + +/* Number of elements along histogram axes. */ +#define HIST_C0_ELEMS (1<cquantize; + register JSAMPROW ptr; + register histptr histp; + register hist3d histogram = cquantize->histogram; + int row; + JDIMENSION col; + JDIMENSION width = cinfo->output_width; + + for (row = 0; row < num_rows; row++) { + ptr = input_buf[row]; + for (col = width; col > 0; col--) { + /* get pixel value and index into the histogram */ + histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT] + [GETJSAMPLE(ptr[1]) >> C1_SHIFT] + [GETJSAMPLE(ptr[2]) >> C2_SHIFT]; + /* increment, check for overflow and undo increment if so. */ + if (++(*histp) <= 0) + (*histp)--; + ptr += 3; + } + } +} + + +/* + * Next we have the really interesting routines: selection of a colormap + * given the completed histogram. + * These routines work with a list of "boxes", each representing a rectangular + * subset of the input color space (to histogram precision). + */ + +typedef struct { + /* The bounds of the box (inclusive); expressed as histogram indexes */ + int c0min, c0max; + int c1min, c1max; + int c2min, c2max; + /* The volume (actually 2-norm) of the box */ + INT32 volume; + /* The number of nonzero histogram cells within this box */ + long colorcount; +} box; + +typedef box * boxptr; + + +LOCAL(boxptr) +find_biggest_color_pop (boxptr boxlist, int numboxes) +/* Find the splittable box with the largest color population */ +/* Returns NULL if no splittable boxes remain */ +{ + register boxptr boxp; + register int i; + register long maxc = 0; + boxptr which = NULL; + + for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) { + if (boxp->colorcount > maxc && boxp->volume > 0) { + which = boxp; + maxc = boxp->colorcount; + } + } + return which; +} + + +LOCAL(boxptr) +find_biggest_volume (boxptr boxlist, int numboxes) +/* Find the splittable box with the largest (scaled) volume */ +/* Returns NULL if no splittable boxes remain */ +{ + register boxptr boxp; + register int i; + register INT32 maxv = 0; + boxptr which = NULL; + + for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) { + if (boxp->volume > maxv) { + which = boxp; + maxv = boxp->volume; + } + } + return which; +} + + +LOCAL(void) +update_box (j_decompress_ptr cinfo, boxptr boxp) +/* Shrink the min/max bounds of a box to enclose only nonzero elements, */ +/* and recompute its volume and population */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + hist3d histogram = cquantize->histogram; + histptr histp; + int c0,c1,c2; + int c0min,c0max,c1min,c1max,c2min,c2max; + INT32 dist0,dist1,dist2; + long ccount; + + c0min = boxp->c0min; c0max = boxp->c0max; + c1min = boxp->c1min; c1max = boxp->c1max; + c2min = boxp->c2min; c2max = boxp->c2max; + + if (c0max > c0min) + for (c0 = c0min; c0 <= c0max; c0++) + for (c1 = c1min; c1 <= c1max; c1++) { + histp = & histogram[c0][c1][c2min]; + for (c2 = c2min; c2 <= c2max; c2++) + if (*histp++ != 0) { + boxp->c0min = c0min = c0; + goto have_c0min; + } + } + have_c0min: + if (c0max > c0min) + for (c0 = c0max; c0 >= c0min; c0--) + for (c1 = c1min; c1 <= c1max; c1++) { + histp = & histogram[c0][c1][c2min]; + for (c2 = c2min; c2 <= c2max; c2++) + if (*histp++ != 0) { + boxp->c0max = c0max = c0; + goto have_c0max; + } + } + have_c0max: + if (c1max > c1min) + for (c1 = c1min; c1 <= c1max; c1++) + for (c0 = c0min; c0 <= c0max; c0++) { + histp = & histogram[c0][c1][c2min]; + for (c2 = c2min; c2 <= c2max; c2++) + if (*histp++ != 0) { + boxp->c1min = c1min = c1; + goto have_c1min; + } + } + have_c1min: + if (c1max > c1min) + for (c1 = c1max; c1 >= c1min; c1--) + for (c0 = c0min; c0 <= c0max; c0++) { + histp = & histogram[c0][c1][c2min]; + for (c2 = c2min; c2 <= c2max; c2++) + if (*histp++ != 0) { + boxp->c1max = c1max = c1; + goto have_c1max; + } + } + have_c1max: + if (c2max > c2min) + for (c2 = c2min; c2 <= c2max; c2++) + for (c0 = c0min; c0 <= c0max; c0++) { + histp = & histogram[c0][c1min][c2]; + for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS) + if (*histp != 0) { + boxp->c2min = c2min = c2; + goto have_c2min; + } + } + have_c2min: + if (c2max > c2min) + for (c2 = c2max; c2 >= c2min; c2--) + for (c0 = c0min; c0 <= c0max; c0++) { + histp = & histogram[c0][c1min][c2]; + for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS) + if (*histp != 0) { + boxp->c2max = c2max = c2; + goto have_c2max; + } + } + have_c2max: + + /* Update box volume. + * We use 2-norm rather than real volume here; this biases the method + * against making long narrow boxes, and it has the side benefit that + * a box is splittable iff norm > 0. + * Since the differences are expressed in histogram-cell units, + * we have to shift back to JSAMPLE units to get consistent distances; + * after which, we scale according to the selected distance scale factors. + */ + dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE; + dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE; + dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE; + boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2; + + /* Now scan remaining volume of box and compute population */ + ccount = 0; + for (c0 = c0min; c0 <= c0max; c0++) + for (c1 = c1min; c1 <= c1max; c1++) { + histp = & histogram[c0][c1][c2min]; + for (c2 = c2min; c2 <= c2max; c2++, histp++) + if (*histp != 0) { + ccount++; + } + } + boxp->colorcount = ccount; +} + + +LOCAL(int) +median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes, + int desired_colors) +/* Repeatedly select and split the largest box until we have enough boxes */ +{ + int n,lb; + int c0,c1,c2,cmax; + register boxptr b1,b2; + + while (numboxes < desired_colors) { + /* Select box to split. + * Current algorithm: by population for first half, then by volume. + */ + if (numboxes*2 <= desired_colors) { + b1 = find_biggest_color_pop(boxlist, numboxes); + } else { + b1 = find_biggest_volume(boxlist, numboxes); + } + if (b1 == NULL) /* no splittable boxes left! */ + break; + b2 = &boxlist[numboxes]; /* where new box will go */ + /* Copy the color bounds to the new box. */ + b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max; + b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min; + /* Choose which axis to split the box on. + * Current algorithm: longest scaled axis. + * See notes in update_box about scaling distances. + */ + c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE; + c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE; + c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE; + /* We want to break any ties in favor of green, then red, blue last. + * This code does the right thing for R,G,B or B,G,R color orders only. + */ +#if RGB_RED == 0 + cmax = c1; n = 1; + if (c0 > cmax) { cmax = c0; n = 0; } + if (c2 > cmax) { n = 2; } +#else + cmax = c1; n = 1; + if (c2 > cmax) { cmax = c2; n = 2; } + if (c0 > cmax) { n = 0; } +#endif + /* Choose split point along selected axis, and update box bounds. + * Current algorithm: split at halfway point. + * (Since the box has been shrunk to minimum volume, + * any split will produce two nonempty subboxes.) + * Note that lb value is max for lower box, so must be < old max. + */ + switch (n) { + case 0: + lb = (b1->c0max + b1->c0min) / 2; + b1->c0max = lb; + b2->c0min = lb+1; + break; + case 1: + lb = (b1->c1max + b1->c1min) / 2; + b1->c1max = lb; + b2->c1min = lb+1; + break; + case 2: + lb = (b1->c2max + b1->c2min) / 2; + b1->c2max = lb; + b2->c2min = lb+1; + break; + } + /* Update stats for boxes */ + update_box(cinfo, b1); + update_box(cinfo, b2); + numboxes++; + } + return numboxes; +} + + +LOCAL(void) +compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor) +/* Compute representative color for a box, put it in colormap[icolor] */ +{ + /* Current algorithm: mean weighted by pixels (not colors) */ + /* Note it is important to get the rounding correct! */ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + hist3d histogram = cquantize->histogram; + histptr histp; + int c0,c1,c2; + int c0min,c0max,c1min,c1max,c2min,c2max; + long count; + long total = 0; + long c0total = 0; + long c1total = 0; + long c2total = 0; + + c0min = boxp->c0min; c0max = boxp->c0max; + c1min = boxp->c1min; c1max = boxp->c1max; + c2min = boxp->c2min; c2max = boxp->c2max; + + for (c0 = c0min; c0 <= c0max; c0++) + for (c1 = c1min; c1 <= c1max; c1++) { + histp = & histogram[c0][c1][c2min]; + for (c2 = c2min; c2 <= c2max; c2++) { + if ((count = *histp++) != 0) { + total += count; + c0total += ((c0 << C0_SHIFT) + ((1<>1)) * count; + c1total += ((c1 << C1_SHIFT) + ((1<>1)) * count; + c2total += ((c2 << C2_SHIFT) + ((1<>1)) * count; + } + } + } + + cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total); + cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total); + cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total); +} + + +LOCAL(void) +select_colors (j_decompress_ptr cinfo, int desired_colors) +/* Master routine for color selection */ +{ + boxptr boxlist; + int numboxes; + int i; + + /* Allocate workspace for box list */ + boxlist = (boxptr) (*cinfo->mem->alloc_small) + ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box)); + /* Initialize one box containing whole space */ + numboxes = 1; + boxlist[0].c0min = 0; + boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT; + boxlist[0].c1min = 0; + boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT; + boxlist[0].c2min = 0; + boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT; + /* Shrink it to actually-used volume and set its statistics */ + update_box(cinfo, & boxlist[0]); + /* Perform median-cut to produce final box list */ + numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors); + /* Compute the representative color for each box, fill colormap */ + for (i = 0; i < numboxes; i++) + compute_color(cinfo, & boxlist[i], i); + cinfo->actual_number_of_colors = numboxes; + TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes); +} + + +/* + * These routines are concerned with the time-critical task of mapping input + * colors to the nearest color in the selected colormap. + * + * We re-use the histogram space as an "inverse color map", essentially a + * cache for the results of nearest-color searches. All colors within a + * histogram cell will be mapped to the same colormap entry, namely the one + * closest to the cell's center. This may not be quite the closest entry to + * the actual input color, but it's almost as good. A zero in the cache + * indicates we haven't found the nearest color for that cell yet; the array + * is cleared to zeroes before starting the mapping pass. When we find the + * nearest color for a cell, its colormap index plus one is recorded in the + * cache for future use. The pass2 scanning routines call fill_inverse_cmap + * when they need to use an unfilled entry in the cache. + * + * Our method of efficiently finding nearest colors is based on the "locally + * sorted search" idea described by Heckbert and on the incremental distance + * calculation described by Spencer W. Thomas in chapter III.1 of Graphics + * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that + * the distances from a given colormap entry to each cell of the histogram can + * be computed quickly using an incremental method: the differences between + * distances to adjacent cells themselves differ by a constant. This allows a + * fairly fast implementation of the "brute force" approach of computing the + * distance from every colormap entry to every histogram cell. Unfortunately, + * it needs a work array to hold the best-distance-so-far for each histogram + * cell (because the inner loop has to be over cells, not colormap entries). + * The work array elements have to be INT32s, so the work array would need + * 256Kb at our recommended precision. This is not feasible in DOS machines. + * + * To get around these problems, we apply Thomas' method to compute the + * nearest colors for only the cells within a small subbox of the histogram. + * The work array need be only as big as the subbox, so the memory usage + * problem is solved. Furthermore, we need not fill subboxes that are never + * referenced in pass2; many images use only part of the color gamut, so a + * fair amount of work is saved. An additional advantage of this + * approach is that we can apply Heckbert's locality criterion to quickly + * eliminate colormap entries that are far away from the subbox; typically + * three-fourths of the colormap entries are rejected by Heckbert's criterion, + * and we need not compute their distances to individual cells in the subbox. + * The speed of this approach is heavily influenced by the subbox size: too + * small means too much overhead, too big loses because Heckbert's criterion + * can't eliminate as many colormap entries. Empirically the best subbox + * size seems to be about 1/512th of the histogram (1/8th in each direction). + * + * Thomas' article also describes a refined method which is asymptotically + * faster than the brute-force method, but it is also far more complex and + * cannot efficiently be applied to small subboxes. It is therefore not + * useful for programs intended to be portable to DOS machines. On machines + * with plenty of memory, filling the whole histogram in one shot with Thomas' + * refined method might be faster than the present code --- but then again, + * it might not be any faster, and it's certainly more complicated. + */ + + +/* log2(histogram cells in update box) for each axis; this can be adjusted */ +#define BOX_C0_LOG (HIST_C0_BITS-3) +#define BOX_C1_LOG (HIST_C1_BITS-3) +#define BOX_C2_LOG (HIST_C2_BITS-3) + +#define BOX_C0_ELEMS (1<actual_number_of_colors; + int maxc0, maxc1, maxc2; + int centerc0, centerc1, centerc2; + int i, x, ncolors; + INT32 minmaxdist, min_dist, max_dist, tdist; + INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */ + + /* Compute true coordinates of update box's upper corner and center. + * Actually we compute the coordinates of the center of the upper-corner + * histogram cell, which are the upper bounds of the volume we care about. + * Note that since ">>" rounds down, the "center" values may be closer to + * min than to max; hence comparisons to them must be "<=", not "<". + */ + maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT)); + centerc0 = (minc0 + maxc0) >> 1; + maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT)); + centerc1 = (minc1 + maxc1) >> 1; + maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT)); + centerc2 = (minc2 + maxc2) >> 1; + + /* For each color in colormap, find: + * 1. its minimum squared-distance to any point in the update box + * (zero if color is within update box); + * 2. its maximum squared-distance to any point in the update box. + * Both of these can be found by considering only the corners of the box. + * We save the minimum distance for each color in mindist[]; + * only the smallest maximum distance is of interest. + */ + minmaxdist = 0x7FFFFFFFL; + + for (i = 0; i < numcolors; i++) { + /* We compute the squared-c0-distance term, then add in the other two. */ + x = GETJSAMPLE(cinfo->colormap[0][i]); + if (x < minc0) { + tdist = (x - minc0) * C0_SCALE; + min_dist = tdist*tdist; + tdist = (x - maxc0) * C0_SCALE; + max_dist = tdist*tdist; + } else if (x > maxc0) { + tdist = (x - maxc0) * C0_SCALE; + min_dist = tdist*tdist; + tdist = (x - minc0) * C0_SCALE; + max_dist = tdist*tdist; + } else { + /* within cell range so no contribution to min_dist */ + min_dist = 0; + if (x <= centerc0) { + tdist = (x - maxc0) * C0_SCALE; + max_dist = tdist*tdist; + } else { + tdist = (x - minc0) * C0_SCALE; + max_dist = tdist*tdist; + } + } + + x = GETJSAMPLE(cinfo->colormap[1][i]); + if (x < minc1) { + tdist = (x - minc1) * C1_SCALE; + min_dist += tdist*tdist; + tdist = (x - maxc1) * C1_SCALE; + max_dist += tdist*tdist; + } else if (x > maxc1) { + tdist = (x - maxc1) * C1_SCALE; + min_dist += tdist*tdist; + tdist = (x - minc1) * C1_SCALE; + max_dist += tdist*tdist; + } else { + /* within cell range so no contribution to min_dist */ + if (x <= centerc1) { + tdist = (x - maxc1) * C1_SCALE; + max_dist += tdist*tdist; + } else { + tdist = (x - minc1) * C1_SCALE; + max_dist += tdist*tdist; + } + } + + x = GETJSAMPLE(cinfo->colormap[2][i]); + if (x < minc2) { + tdist = (x - minc2) * C2_SCALE; + min_dist += tdist*tdist; + tdist = (x - maxc2) * C2_SCALE; + max_dist += tdist*tdist; + } else if (x > maxc2) { + tdist = (x - maxc2) * C2_SCALE; + min_dist += tdist*tdist; + tdist = (x - minc2) * C2_SCALE; + max_dist += tdist*tdist; + } else { + /* within cell range so no contribution to min_dist */ + if (x <= centerc2) { + tdist = (x - maxc2) * C2_SCALE; + max_dist += tdist*tdist; + } else { + tdist = (x - minc2) * C2_SCALE; + max_dist += tdist*tdist; + } + } + + mindist[i] = min_dist; /* save away the results */ + if (max_dist < minmaxdist) + minmaxdist = max_dist; + } + + /* Now we know that no cell in the update box is more than minmaxdist + * away from some colormap entry. Therefore, only colors that are + * within minmaxdist of some part of the box need be considered. + */ + ncolors = 0; + for (i = 0; i < numcolors; i++) { + if (mindist[i] <= minmaxdist) + colorlist[ncolors++] = (JSAMPLE) i; + } + return ncolors; +} + + +LOCAL(void) +find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2, + int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[]) +/* Find the closest colormap entry for each cell in the update box, + * given the list of candidate colors prepared by find_nearby_colors. + * Return the indexes of the closest entries in the bestcolor[] array. + * This routine uses Thomas' incremental distance calculation method to + * find the distance from a colormap entry to successive cells in the box. + */ +{ + int ic0, ic1, ic2; + int i, icolor; + register INT32 * bptr; /* pointer into bestdist[] array */ + JSAMPLE * cptr; /* pointer into bestcolor[] array */ + INT32 dist0, dist1; /* initial distance values */ + register INT32 dist2; /* current distance in inner loop */ + INT32 xx0, xx1; /* distance increments */ + register INT32 xx2; + INT32 inc0, inc1, inc2; /* initial values for increments */ + /* This array holds the distance to the nearest-so-far color for each cell */ + INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS]; + + /* Initialize best-distance for each cell of the update box */ + bptr = bestdist; + for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--) + *bptr++ = 0x7FFFFFFFL; + + /* For each color selected by find_nearby_colors, + * compute its distance to the center of each cell in the box. + * If that's less than best-so-far, update best distance and color number. + */ + + /* Nominal steps between cell centers ("x" in Thomas article) */ +#define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE) +#define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE) +#define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE) + + for (i = 0; i < numcolors; i++) { + icolor = GETJSAMPLE(colorlist[i]); + /* Compute (square of) distance from minc0/c1/c2 to this color */ + inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE; + dist0 = inc0*inc0; + inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE; + dist0 += inc1*inc1; + inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE; + dist0 += inc2*inc2; + /* Form the initial difference increments */ + inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0; + inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1; + inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2; + /* Now loop over all cells in box, updating distance per Thomas method */ + bptr = bestdist; + cptr = bestcolor; + xx0 = inc0; + for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) { + dist1 = dist0; + xx1 = inc1; + for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) { + dist2 = dist1; + xx2 = inc2; + for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) { + if (dist2 < *bptr) { + *bptr = dist2; + *cptr = (JSAMPLE) icolor; + } + dist2 += xx2; + xx2 += 2 * STEP_C2 * STEP_C2; + bptr++; + cptr++; + } + dist1 += xx1; + xx1 += 2 * STEP_C1 * STEP_C1; + } + dist0 += xx0; + xx0 += 2 * STEP_C0 * STEP_C0; + } + } +} + + +LOCAL(void) +fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2) +/* Fill the inverse-colormap entries in the update box that contains */ +/* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */ +/* we can fill as many others as we wish.) */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + hist3d histogram = cquantize->histogram; + int minc0, minc1, minc2; /* lower left corner of update box */ + int ic0, ic1, ic2; + register JSAMPLE * cptr; /* pointer into bestcolor[] array */ + register histptr cachep; /* pointer into main cache array */ + /* This array lists the candidate colormap indexes. */ + JSAMPLE colorlist[MAXNUMCOLORS]; + int numcolors; /* number of candidate colors */ + /* This array holds the actually closest colormap index for each cell. */ + JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS]; + + /* Convert cell coordinates to update box ID */ + c0 >>= BOX_C0_LOG; + c1 >>= BOX_C1_LOG; + c2 >>= BOX_C2_LOG; + + /* Compute true coordinates of update box's origin corner. + * Actually we compute the coordinates of the center of the corner + * histogram cell, which are the lower bounds of the volume we care about. + */ + minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1); + minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1); + minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1); + + /* Determine which colormap entries are close enough to be candidates + * for the nearest entry to some cell in the update box. + */ + numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist); + + /* Determine the actually nearest colors. */ + find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist, + bestcolor); + + /* Save the best color numbers (plus 1) in the main cache array */ + c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */ + c1 <<= BOX_C1_LOG; + c2 <<= BOX_C2_LOG; + cptr = bestcolor; + for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) { + for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) { + cachep = & histogram[c0+ic0][c1+ic1][c2]; + for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) { + *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1); + } + } + } +} + + +/* + * Map some rows of pixels to the output colormapped representation. + */ + +METHODDEF(void) +pass2_no_dither (j_decompress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) +/* This version performs no dithering */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + hist3d histogram = cquantize->histogram; + register JSAMPROW inptr, outptr; + register histptr cachep; + register int c0, c1, c2; + int row; + JDIMENSION col; + JDIMENSION width = cinfo->output_width; + + for (row = 0; row < num_rows; row++) { + inptr = input_buf[row]; + outptr = output_buf[row]; + for (col = width; col > 0; col--) { + /* get pixel value and index into the cache */ + c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT; + c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT; + c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT; + cachep = & histogram[c0][c1][c2]; + /* If we have not seen this color before, find nearest colormap entry */ + /* and update the cache */ + if (*cachep == 0) + fill_inverse_cmap(cinfo, c0,c1,c2); + /* Now emit the colormap index for this cell */ + *outptr++ = (JSAMPLE) (*cachep - 1); + } + } +} + + +METHODDEF(void) +pass2_fs_dither (j_decompress_ptr cinfo, + JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) +/* This version performs Floyd-Steinberg dithering */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + hist3d histogram = cquantize->histogram; + register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */ + LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */ + LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */ + register FSERRPTR errorptr; /* => fserrors[] at column before current */ + JSAMPROW inptr; /* => current input pixel */ + JSAMPROW outptr; /* => current output pixel */ + histptr cachep; + int dir; /* +1 or -1 depending on direction */ + int dir3; /* 3*dir, for advancing inptr & errorptr */ + int row; + JDIMENSION col; + JDIMENSION width = cinfo->output_width; + JSAMPLE *range_limit = cinfo->sample_range_limit; + int *error_limit = cquantize->error_limiter; + JSAMPROW colormap0 = cinfo->colormap[0]; + JSAMPROW colormap1 = cinfo->colormap[1]; + JSAMPROW colormap2 = cinfo->colormap[2]; + SHIFT_TEMPS + + for (row = 0; row < num_rows; row++) { + inptr = input_buf[row]; + outptr = output_buf[row]; + if (cquantize->on_odd_row) { + /* work right to left in this row */ + inptr += (width-1) * 3; /* so point to rightmost pixel */ + outptr += width-1; + dir = -1; + dir3 = -3; + errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */ + cquantize->on_odd_row = FALSE; /* flip for next time */ + } else { + /* work left to right in this row */ + dir = 1; + dir3 = 3; + errorptr = cquantize->fserrors; /* => entry before first real column */ + cquantize->on_odd_row = TRUE; /* flip for next time */ + } + /* Preset error values: no error propagated to first pixel from left */ + cur0 = cur1 = cur2 = 0; + /* and no error propagated to row below yet */ + belowerr0 = belowerr1 = belowerr2 = 0; + bpreverr0 = bpreverr1 = bpreverr2 = 0; + + for (col = width; col > 0; col--) { + /* curN holds the error propagated from the previous pixel on the + * current line. Add the error propagated from the previous line + * to form the complete error correction term for this pixel, and + * round the error term (which is expressed * 16) to an integer. + * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct + * for either sign of the error value. + * Note: errorptr points to *previous* column's array entry. + */ + cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4); + cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4); + cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4); + /* Limit the error using transfer function set by init_error_limit. + * See comments with init_error_limit for rationale. + */ + cur0 = error_limit[cur0]; + cur1 = error_limit[cur1]; + cur2 = error_limit[cur2]; + /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE. + * The maximum error is +- MAXJSAMPLE (or less with error limiting); + * this sets the required size of the range_limit array. + */ + cur0 += GETJSAMPLE(inptr[0]); + cur1 += GETJSAMPLE(inptr[1]); + cur2 += GETJSAMPLE(inptr[2]); + cur0 = GETJSAMPLE(range_limit[cur0]); + cur1 = GETJSAMPLE(range_limit[cur1]); + cur2 = GETJSAMPLE(range_limit[cur2]); + /* Index into the cache with adjusted pixel value */ + cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT]; + /* If we have not seen this color before, find nearest colormap */ + /* entry and update the cache */ + if (*cachep == 0) + fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT); + /* Now emit the colormap index for this cell */ + { register int pixcode = *cachep - 1; + *outptr = (JSAMPLE) pixcode; + /* Compute representation error for this pixel */ + cur0 -= GETJSAMPLE(colormap0[pixcode]); + cur1 -= GETJSAMPLE(colormap1[pixcode]); + cur2 -= GETJSAMPLE(colormap2[pixcode]); + } + /* Compute error fractions to be propagated to adjacent pixels. + * Add these into the running sums, and simultaneously shift the + * next-line error sums left by 1 column. + */ + { register LOCFSERROR bnexterr, delta; + + bnexterr = cur0; /* Process component 0 */ + delta = cur0 * 2; + cur0 += delta; /* form error * 3 */ + errorptr[0] = (FSERROR) (bpreverr0 + cur0); + cur0 += delta; /* form error * 5 */ + bpreverr0 = belowerr0 + cur0; + belowerr0 = bnexterr; + cur0 += delta; /* form error * 7 */ + bnexterr = cur1; /* Process component 1 */ + delta = cur1 * 2; + cur1 += delta; /* form error * 3 */ + errorptr[1] = (FSERROR) (bpreverr1 + cur1); + cur1 += delta; /* form error * 5 */ + bpreverr1 = belowerr1 + cur1; + belowerr1 = bnexterr; + cur1 += delta; /* form error * 7 */ + bnexterr = cur2; /* Process component 2 */ + delta = cur2 * 2; + cur2 += delta; /* form error * 3 */ + errorptr[2] = (FSERROR) (bpreverr2 + cur2); + cur2 += delta; /* form error * 5 */ + bpreverr2 = belowerr2 + cur2; + belowerr2 = bnexterr; + cur2 += delta; /* form error * 7 */ + } + /* At this point curN contains the 7/16 error value to be propagated + * to the next pixel on the current line, and all the errors for the + * next line have been shifted over. We are therefore ready to move on. + */ + inptr += dir3; /* Advance pixel pointers to next column */ + outptr += dir; + errorptr += dir3; /* advance errorptr to current column */ + } + /* Post-loop cleanup: we must unload the final error values into the + * final fserrors[] entry. Note we need not unload belowerrN because + * it is for the dummy column before or after the actual array. + */ + errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */ + errorptr[1] = (FSERROR) bpreverr1; + errorptr[2] = (FSERROR) bpreverr2; + } +} + + +/* + * Initialize the error-limiting transfer function (lookup table). + * The raw F-S error computation can potentially compute error values of up to + * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be + * much less, otherwise obviously wrong pixels will be created. (Typical + * effects include weird fringes at color-area boundaries, isolated bright + * pixels in a dark area, etc.) The standard advice for avoiding this problem + * is to ensure that the "corners" of the color cube are allocated as output + * colors; then repeated errors in the same direction cannot cause cascading + * error buildup. However, that only prevents the error from getting + * completely out of hand; Aaron Giles reports that error limiting improves + * the results even with corner colors allocated. + * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty + * well, but the smoother transfer function used below is even better. Thanks + * to Aaron Giles for this idea. + */ + +LOCAL(void) +init_error_limit (j_decompress_ptr cinfo) +/* Allocate and fill in the error_limiter table */ +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + int * table; + int in, out; + + table = (int *) (*cinfo->mem->alloc_small) + ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int)); + table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */ + cquantize->error_limiter = table; + +#define STEPSIZE ((MAXJSAMPLE+1)/16) + /* Map errors 1:1 up to +- MAXJSAMPLE/16 */ + out = 0; + for (in = 0; in < STEPSIZE; in++, out++) { + table[in] = out; table[-in] = -out; + } + /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */ + for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) { + table[in] = out; table[-in] = -out; + } + /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */ + for (; in <= MAXJSAMPLE; in++) { + table[in] = out; table[-in] = -out; + } +#undef STEPSIZE +} + + +/* + * Finish up at the end of each pass. + */ + +METHODDEF(void) +finish_pass1 (j_decompress_ptr cinfo) +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + + /* Select the representative colors and fill in cinfo->colormap */ + cinfo->colormap = cquantize->sv_colormap; + select_colors(cinfo, cquantize->desired); + /* Force next pass to zero the color index table */ + cquantize->needs_zeroed = TRUE; +} + + +METHODDEF(void) +finish_pass2 (j_decompress_ptr cinfo) +{ + /* no work */ +} + + +/* + * Initialize for each processing pass. + */ + +METHODDEF(void) +start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan) +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + hist3d histogram = cquantize->histogram; + int i; + + /* Only F-S dithering or no dithering is supported. */ + /* If user asks for ordered dither, give him F-S. */ + if (cinfo->dither_mode != JDITHER_NONE) + cinfo->dither_mode = JDITHER_FS; + + if (is_pre_scan) { + /* Set up method pointers */ + cquantize->pub.color_quantize = prescan_quantize; + cquantize->pub.finish_pass = finish_pass1; + cquantize->needs_zeroed = TRUE; /* Always zero histogram */ + } else { + /* Set up method pointers */ + if (cinfo->dither_mode == JDITHER_FS) + cquantize->pub.color_quantize = pass2_fs_dither; + else + cquantize->pub.color_quantize = pass2_no_dither; + cquantize->pub.finish_pass = finish_pass2; + + /* Make sure color count is acceptable */ + i = cinfo->actual_number_of_colors; + if (i < 1) + ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1); + if (i > MAXNUMCOLORS) + ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS); + + if (cinfo->dither_mode == JDITHER_FS) { + size_t arraysize = (size_t) ((cinfo->output_width + 2) * + (3 * SIZEOF(FSERROR))); + /* Allocate Floyd-Steinberg workspace if we didn't already. */ + if (cquantize->fserrors == NULL) + cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large) + ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize); + /* Initialize the propagated errors to zero. */ + jzero_far((void FAR *) cquantize->fserrors, arraysize); + /* Make the error-limit table if we didn't already. */ + if (cquantize->error_limiter == NULL) + init_error_limit(cinfo); + cquantize->on_odd_row = FALSE; + } + + } + /* Zero the histogram or inverse color map, if necessary */ + if (cquantize->needs_zeroed) { + for (i = 0; i < HIST_C0_ELEMS; i++) { + jzero_far((void FAR *) histogram[i], + HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell)); + } + cquantize->needs_zeroed = FALSE; + } +} + + +/* + * Switch to a new external colormap between output passes. + */ + +METHODDEF(void) +new_color_map_2_quant (j_decompress_ptr cinfo) +{ + my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; + + /* Reset the inverse color map */ + cquantize->needs_zeroed = TRUE; +} + + +/* + * Module initialization routine for 2-pass color quantization. + */ + +GLOBAL(void) +jinit_2pass_quantizer (j_decompress_ptr cinfo) +{ + my_cquantize_ptr cquantize; + int i; + + cquantize = (my_cquantize_ptr) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + SIZEOF(my_cquantizer)); + cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize; + cquantize->pub.start_pass = start_pass_2_quant; + cquantize->pub.new_color_map = new_color_map_2_quant; + cquantize->fserrors = NULL; /* flag optional arrays not allocated */ + cquantize->error_limiter = NULL; + + /* Make sure jdmaster didn't give me a case I can't handle */ + if (cinfo->out_color_components != 3) + ERREXIT(cinfo, JERR_NOTIMPL); + + /* Allocate the histogram/inverse colormap storage */ + cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small) + ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d)); + for (i = 0; i < HIST_C0_ELEMS; i++) { + cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell)); + } + cquantize->needs_zeroed = TRUE; /* histogram is garbage now */ + + /* Allocate storage for the completed colormap, if required. + * We do this now since it is FAR storage and may affect + * the memory manager's space calculations. + */ + if (cinfo->enable_2pass_quant) { + /* Make sure color count is acceptable */ + int desired = cinfo->desired_number_of_colors; + /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */ + if (desired < 8) + ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8); + /* Make sure colormap indexes can be represented by JSAMPLEs */ + if (desired > MAXNUMCOLORS) + ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS); + cquantize->sv_colormap = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3); + cquantize->desired = desired; + } else + cquantize->sv_colormap = NULL; + + /* Only F-S dithering or no dithering is supported. */ + /* If user asks for ordered dither, give him F-S. */ + if (cinfo->dither_mode != JDITHER_NONE) + cinfo->dither_mode = JDITHER_FS; + + /* Allocate Floyd-Steinberg workspace if necessary. + * This isn't really needed until pass 2, but again it is FAR storage. + * Although we will cope with a later change in dither_mode, + * we do not promise to honor max_memory_to_use if dither_mode changes. + */ + if (cinfo->dither_mode == JDITHER_FS) { + cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large) + ((j_common_ptr) cinfo, JPOOL_IMAGE, + (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR)))); + /* Might as well create the error-limiting table too. */ + init_error_limit(cinfo); + } +} + +#endif /* QUANT_2PASS_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/jpeg/jutils.c b/SlnkDWFImpl/CxImage/jpeg/jutils.c new file mode 100644 index 0000000..286cda2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jutils.c @@ -0,0 +1,179 @@ +/* + * jutils.c + * + * Copyright (C) 1991-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains tables and miscellaneous utility routines needed + * for both compression and decompression. + * Note we prefix all global names with "j" to minimize conflicts with + * a surrounding application. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* + * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element + * of a DCT block read in natural order (left to right, top to bottom). + */ + +#if 0 /* This table is not actually needed in v6a */ + +const int jpeg_zigzag_order[DCTSIZE2] = { + 0, 1, 5, 6, 14, 15, 27, 28, + 2, 4, 7, 13, 16, 26, 29, 42, + 3, 8, 12, 17, 25, 30, 41, 43, + 9, 11, 18, 24, 31, 40, 44, 53, + 10, 19, 23, 32, 39, 45, 52, 54, + 20, 22, 33, 38, 46, 51, 55, 60, + 21, 34, 37, 47, 50, 56, 59, 61, + 35, 36, 48, 49, 57, 58, 62, 63 +}; + +#endif + +/* + * jpeg_natural_order[i] is the natural-order position of the i'th element + * of zigzag order. + * + * When reading corrupted data, the Huffman decoders could attempt + * to reference an entry beyond the end of this array (if the decoded + * zero run length reaches past the end of the block). To prevent + * wild stores without adding an inner-loop test, we put some extra + * "63"s after the real entries. This will cause the extra coefficient + * to be stored in location 63 of the block, not somewhere random. + * The worst case would be a run-length of 15, which means we need 16 + * fake entries. + */ + +const int jpeg_natural_order[DCTSIZE2+16] = { + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ + 63, 63, 63, 63, 63, 63, 63, 63 +}; + + +/* + * Arithmetic utilities + */ + +GLOBAL(long) +jdiv_round_up (long a, long b) +/* Compute a/b rounded up to next integer, ie, ceil(a/b) */ +/* Assumes a >= 0, b > 0 */ +{ + return (a + b - 1L) / b; +} + + +GLOBAL(long) +jround_up (long a, long b) +/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */ +/* Assumes a >= 0, b > 0 */ +{ + a += b - 1L; + return a - (a % b); +} + + +/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays + * and coefficient-block arrays. This won't work on 80x86 because the arrays + * are FAR and we're assuming a small-pointer memory model. However, some + * DOS compilers provide far-pointer versions of memcpy() and memset() even + * in the small-model libraries. These will be used if USE_FMEM is defined. + * Otherwise, the routines below do it the hard way. (The performance cost + * is not all that great, because these routines aren't very heavily used.) + */ + +#ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */ +#define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size) +#define FMEMZERO(target,size) MEMZERO(target,size) +#else /* 80x86 case, define if we can */ +#ifdef USE_FMEM +#define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size)) +#define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size)) +#endif +#endif + + +GLOBAL(void) +jcopy_sample_rows (JSAMPARRAY input_array, int source_row, + JSAMPARRAY output_array, int dest_row, + int num_rows, JDIMENSION num_cols) +/* Copy some rows of samples from one place to another. + * num_rows rows are copied from input_array[source_row++] + * to output_array[dest_row++]; these areas may overlap for duplication. + * The source and destination arrays must be at least as wide as num_cols. + */ +{ + register JSAMPROW inptr, outptr; +#ifdef FMEMCOPY + register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE)); +#else + register JDIMENSION count; +#endif + register int row; + + input_array += source_row; + output_array += dest_row; + + for (row = num_rows; row > 0; row--) { + inptr = *input_array++; + outptr = *output_array++; +#ifdef FMEMCOPY + FMEMCOPY(outptr, inptr, count); +#else + for (count = num_cols; count > 0; count--) + *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */ +#endif + } +} + + +GLOBAL(void) +jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row, + JDIMENSION num_blocks) +/* Copy a row of coefficient blocks from one place to another. */ +{ +#ifdef FMEMCOPY + FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF))); +#else + register JCOEFPTR inptr, outptr; + register long count; + + inptr = (JCOEFPTR) input_row; + outptr = (JCOEFPTR) output_row; + for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) { + *outptr++ = *inptr++; + } +#endif +} + + +GLOBAL(void) +jzero_far (void FAR * target, size_t bytestozero) +/* Zero out a chunk of FAR memory. */ +/* This might be sample-array data, block-array data, or alloc_large data. */ +{ +#ifdef FMEMZERO + FMEMZERO(target, bytestozero); +#else + register char FAR * ptr = (char FAR *) target; + register size_t count; + + for (count = bytestozero; count > 0; count--) { + *ptr++ = 0; + } +#endif +} diff --git a/SlnkDWFImpl/CxImage/jpeg/jversion.h b/SlnkDWFImpl/CxImage/jpeg/jversion.h new file mode 100644 index 0000000..dadd453 --- /dev/null +++ b/SlnkDWFImpl/CxImage/jpeg/jversion.h @@ -0,0 +1,14 @@ +/* + * jversion.h + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains software version identification. + */ + + +#define JVERSION "6b 27-Mar-1998" + +#define JCOPYRIGHT "Copyright (C) 1998, Thomas G. Lane" diff --git a/SlnkDWFImpl/CxImage/png/ANNOUNCE b/SlnkDWFImpl/CxImage/png/ANNOUNCE new file mode 100644 index 0000000..b45c2a5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/ANNOUNCE @@ -0,0 +1,28 @@ + +Libpng 1.2.7 - September 12, 2004 + +This is a public release of libpng, intended for use in production codes. + +Changes since the last public release (1.2.6): + + Revised pngtest so memory allocation testing is only done when PNG_DEBUG==1. + Removed unused pngasmrd.h file. + Removed references to uu.net for archived files. Added references to + PNG Spec (second edition) and the PNG ISO/IEC Standard. + Added "test-dd" target in 15 makefiles, to run pngtest in DESTDIR. + Fixed bug with "optimized window size" in the IDAT datastream, that + causes libpng to write PNG files with incorrect zlib header bytes. + Fixed bug with sCAL chunk and big-endian machines (David Munro). + Undid new code added in 1.2.6 to update the color_type in + png_set_filler(). + Added png_set_add_alpha() that updates color type. + Revised png_set_strip_filler() to not remove alpha if color_type has alpha. + Added makefile.hp64 + Changed projects/msvc/png32ms.def to scripts/png32ms.def in makefile.cygwin + +Send comments/corrections/commendations to +png-implement@ccrc.wustl.edu (subscription required; write to +majordomo@ccrc.wustl.edu with "subscribe png-implement" in the message) +or to glennrp@users.sourceforge.net + +Glenn R-P diff --git a/SlnkDWFImpl/CxImage/png/CHANGES b/SlnkDWFImpl/CxImage/png/CHANGES new file mode 100644 index 0000000..c3d217a --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/CHANGES @@ -0,0 +1,1373 @@ + +CHANGES - changes for libpng + +version 0.2 + added reader into png.h + fixed small problems in stub file + +version 0.3 + added pull reader + split up pngwrite.c to several files + added pnglib.txt + added example.c + cleaned up writer, adding a few new tranformations + fixed some bugs in writer + interfaced with zlib 0.5 + added K&R support + added check for 64 KB blocks for 16 bit machines + +version 0.4 + cleaned up code and commented code + simplified time handling into png_time + created png_color_16 and png_color_8 to handle color needs + cleaned up color type defines + fixed various bugs + made various names more consistant + interfaced with zlib 0.71 + cleaned up zTXt reader and writer (using zlib's Reset functions) + split transformations into pngrtran.c and pngwtran.c + +version 0.5 + interfaced with zlib 0.8 + fixed many reading and writing bugs + saved using 3 spaces instead of tabs + +version 0.6 + added png_large_malloc() and png_large_free() + added png_size_t + cleaned up some compiler warnings + added png_start_read_image() + +version 0.7 + cleaned up lots of bugs + finished dithering and other stuff + added test program + changed name from pnglib to libpng + +version 0.71 [June, 1995] + changed pngtest.png for zlib 0.93 + fixed error in libpng.txt and example.c + +version 0.8 + cleaned up some bugs + added png_set_filler() + split up pngstub.c into pngmem.c, pngio.c, and pngerror.c + added #define's to remove unwanted code + moved png_info_init() to png.c + added old_size into png_realloc() + added functions to manually set filtering and compression info + changed compression parameters based on image type + optimized filter selection code + added version info + changed external functions passing floats to doubles (k&r problems?) + put all the configurable stuff in pngconf.h + enabled png_set_shift to work with paletted images on read + added png_read_update_info() - updates info structure with + transformations + +version 0.81 [August, 1995] + incorporated Tim Wegner's medium model code (thanks, Tim) + +version 0.82 [September, 1995] + [unspecified changes] + +version 0.85 [December, 1995] + added more medium model code (almost everything's a far) + added i/o, error, and memory callback functions + fixed some bugs (16 bit, 4 bit interlaced, etc.) + added first run progressive reader (barely tested) + +version 0.86 [January, 1996] + fixed bugs + improved documentation + +version 0.87 [January, 1996] + fixed medium model bugs + fixed other bugs introduced in 0.85 and 0.86 + added some minor documentation + +version 0.88 [January, 1996] + fixed progressive bugs + replaced tabs with spaces + cleaned up documentation + added callbacks for read/write and warning/error functions + +version 0.89 [July, 1996] + added new initialization API to make libpng work better with shared libs + we now have png_create_read_struct(), png_create_write_struct(), + png_create_info_struct(), png_destroy_read_struct(), and + png_destroy_write_struct() instead of the separate calls to + malloc and png_read_init(), png_info_init(), and png_write_init() + changed warning/error callback functions to fix bug - this means you + should use the new initialization API if you were using the old + png_set_message_fn() calls, and that the old API no longer exists + so that people are aware that they need to change their code + changed filter selection API to allow selection of multiple filters + since it didn't work in previous versions of libpng anyways + optimized filter selection code + fixed png_set_background() to allow using an arbitrary RGB color for + paletted images + fixed gamma and background correction for paletted images, so + png_correct_palette is not needed unless you are correcting an + external palette (you will need to #define PNG_CORRECT_PALETTE_SUPPORTED + in pngconf.h) - if nobody uses this, it may disappear in the future. + fixed bug with Borland 64K memory allocation (Alexander Lehmann) + fixed bug in interlace handling (Smarasderagd, I think) + added more error checking for writing and image to reduce invalid files + separated read and write functions so that they won't both be linked + into a binary when only reading or writing functionality is used + new pngtest image also has interlacing and zTXt + updated documentation to reflect new API + +version 0.90 [January, 1997] + made CRC errors/warnings on critical and ancillary chunks configurable + libpng will use the zlib CRC routines by (compile-time) default + changed DOS small/medium model memory support - needs zlib 1.04 (Tim Wegner) + added external C++ wrapper statements to png.h (Gilles Dauphin) + allow PNG file to be read when some or all of file signature has already + been read from the beginning of the stream. ****This affects the size + of info_struct and invalidates all programs that use a shared libpng**** + fixed png_filler() declarations + fixed? background color conversions + fixed order of error function pointers to match documentation + current chunk name is now available in png_struct to reduce the number + of nearly identical error messages (will simplify multi-lingual + support when available) + try to get ready for unknown-chunk callback functions: + - previously read critical chunks are flagged, so the chunk handling + routines can determine if the chunk is in the right place + - all chunk handling routines have the same prototypes, so we will + be able to handle all chunks via a callback mechanism + try to fix Linux "setjmp" buffer size problems + removed png_large_malloc, png_large_free, and png_realloc functions. + +version 0.95 [March, 1997] + fixed bug in pngwutil.c allocating "up_row" twice and "avg_row" never + fixed bug in PNG file signature compares when start != 0 + changed parameter type of png_set_filler(...filler...) from png_byte + to png_uint_32 + added test for MACOS to ensure that both math.h and fp.h are not #included + added macros for libpng to be compiled as a Windows DLL (Andreas Kupries) + added "packswap" transformation, which changes the endianness of + packed-pixel bytes (Kevin Bracey) + added "strip_alpha" transformation, which removes the alpha channel of + input images without using it (not neccesarily a good idea) + added "swap_alpha" transformation, which puts the alpha channel in front + of the color bytes instead of after + removed all implicit variable tests which assume NULL == 0 (I think) + changed several variables to "png_size_t" to show 16/32-bit limitations + added new pCAL chunk read/write support + added experimental filter selection weighting (Greg Roelofs) + removed old png_set_rgbx() and png_set_xrgb() functions that have been + obsolete for about 2 years now (use png_set_filler() instead) + added macros to read 16- and 32-bit ints directly from buffer, to be + used only on those systems that support it (namely PowerPC and 680x0) + With some testing, this may become the default for MACOS/PPC systems. + only calculate CRC on data if we are going to use it + added macros for zTXt compression type PNG_zTXt_COMPRESSION_??? + added macros for simple libpng debugging output selectable at compile time + removed PNG_READ_END_MODE in progressive reader (Smarasderagd) + more description of info_struct in libpng.txt and png.h + more instructions in example.c + more chunk types tested in pngtest.c + renamed pngrcb.c to pngset.c, and all png_read_ functions to be + png_set_. We now have corresponding png_get_ + functions in pngget.c to get infomation in info_ptr. This isolates + the application from the internal organization of png_info_struct + (good for shared library implementations). + +version 0.96 [May, 1997] + fixed serious bug with < 8bpp images introduced in 0.95 + fixed 256-color transparency bug (Greg Roelofs) + fixed up documentation (Greg Roelofs, Laszlo Nyul) + fixed "error" in pngconf.h for Linux setjmp() behaviour + fixed DOS medium model support (Tim Wegner) + fixed png_check_keyword() for case with error in static string text + added read of CRC after IEND chunk for embedded PNGs (Laszlo Nyul) + added typecasts to quiet compiler errors + added more debugging info + +version 0.97 [January, 1998] + removed PNG_USE_OWN_CRC capability + relocated png_set_crc_action from pngrutil.c to pngrtran.c + fixed typecasts of "new_key", etc. (Andreas Dilger) + added RFC 1152 [sic] date support + fixed bug in gamma handling of 4-bit grayscale + added 2-bit grayscale gamma handling (Glenn R-P) + added more typecasts. 65536L becomes (png_uint_32)65536L, etc. (Glenn R-P) + minor corrections in libpng.txt + added simple sRGB support (Glenn R-P) + easier conditional compiling, e.g. define PNG_READ/WRITE_NOT_FULLY_SUPPORTED; + all configurable options can be selected from command-line instead + of having to edit pngconf.h (Glenn R-P) + fixed memory leak in pngwrite.c (free info_ptr->text) (Glenn R-P) + added more conditions for png_do_background, to avoid changing + black pixels to background when a background is supplied and + no pixels are transparent + repaired PNG_NO_STDIO behaviour + tested NODIV support and made it default behaviour (Greg Roelofs) + added "-m" option and PNGTEST_DEBUG_MEMORY to pngtest (John Bowler) + regularized version numbering scheme and bumped shared-library major + version number to 2 to avoid problems with libpng 0.89 apps (Greg Roelofs) + +version 0.98 [January, 1998] + cleaned up some typos in libpng.txt and in code documentation + fixed memory leaks in pCAL chunk processing (Glenn R-P and John Bowler) + cosmetic change "display_gamma" to "screen_gamma" in pngrtran.c + changed recommendation about file_gamma for PC images to .51 from .45, + in example.c and libpng.txt, added comments to distinguish between + screen_gamma, viewing_gamma, and display_gamma. + changed all references to RFC1152 to read RFC1123 and changed the + PNG_TIME_RFC1152_SUPPORTED macro to PNG_TIME_RFC1123_SUPPORTED + added png_invert_alpha capability (Glenn R-P -- suggestion by Jon Vincent) + changed srgb_intent from png_byte to int to avoid compiler bugs + +version 0.99 [January 30, 1998] + free info_ptr->text instead of end_info_ptr->text in pngread.c (John Bowler) + fixed a longstanding "packswap" bug in pngtrans.c + fixed some inconsistencies in pngconf.h that prevented compiling with + PNG_READ_GAMMA_SUPPORTED and PNG_READ_hIST_SUPPORTED undefined + fixed some typos and made other minor rearrangement of libpng.txt (Andreas) + changed recommendation about file_gamma for PC images to .50 from .51 in + example.c and libpng.txt, and changed file_gamma for sRGB images to .45 + added a number of functions to access information from the png structure + png_get_image_height(), etc. (Glenn R-P, suggestion by Brad Pettit) + added TARGET_MACOS similar to zlib-1.0.8 + define PNG_ALWAYS_EXTERN when __MWERKS__ && WIN32 are defined + added type casting to all png_malloc() function calls +version 0.99a [January 31, 1998] + Added type casts and parentheses to all returns that return a value.(Tim W.) +version 0.99b [February 4, 1998] + Added type cast png_uint_32 on malloc function calls where needed. + Changed type of num_hist from png_uint_32 to int (same as num_palette). + Added checks for rowbytes overflow, in case png_size_t is less than 32 bits. + Renamed makefile.elf to makefile.lnx. +version 0.99c [February 7, 1998] + More type casting. Removed erroneous overflow test in pngmem.c. + Added png_buffered_memcpy() and png_buffered_memset(), apply them to rowbytes. + Added UNIX manual pages libpng.3 (incorporating libpng.txt) and png.5. +version 0.99d [February 11, 1998] + Renamed "far_to_near()" "png_far_to_near()" + Revised libpng.3 + Version 99c "buffered" operations didn't work as intended. Replaced them + with png_memcpy_check() and png_memset_check(). + Added many "if (png_ptr == NULL) return" to quell compiler warnings about + unused png_ptr, mostly in pngget.c and pngset.c. + Check for overlength tRNS chunk present when indexed-color PLTE is read. + Cleaned up spelling errors in libpng.3/libpng.txt + Corrected a problem with png_get_tRNS() which returned undefined trans array +version 0.99e [February 28, 1998] + Corrected png_get_tRNS() again. + Add parentheses for easier reading of pngget.c, fixed "||" should be "&&". + Touched up example.c to make more of it compileable, although the entire + file still can't be compiled (Willem van Schaik) + Fixed a bug in png_do_shift() (Bryan Tsai) + Added a space in png.h prototype for png_write_chunk_start() + Replaced pngtest.png with one created with zlib 1.1.1 + Changed pngtest to report PASS even when file size is different (Jean-loup G.) + Corrected some logic errors in png_do_invert_alpha() (Chris Patterson) +version 0.99f [March 5, 1998] + Corrected a bug in pngpread() introduced in version 99c (Kevin Bracey) + Moved makefiles into a "scripts" directory, and added INSTALL instruction file + Added makefile.os2 and pngos2.def (A. Zabolotny) and makefile.s2x (W. Sebok) + Added pointers to "note on libpng versions" in makefile.lnx and README + Added row callback feature when reading and writing nonprogressive rows + and added a test of this feature in pngtest.c + Added user transform callbacks, with test of the feature in pngtest.c +version 0.99g [March 6, 1998, morning] + Minor changes to pngtest.c to suppress compiler warnings. + Removed "beta" language from documentation. +version 0.99h [March 6, 1998, evening] + Minor changes to previous minor changes to pngtest.c + Changed PNG_READ_NOT_FULLY_SUPPORTED to PNG_READ_TRANSFORMS_NOT_SUPPORTED + and added PNG_PROGRESSIVE_READ_NOT_SUPPORTED macro + Added user transform capability + +version 1.00 [March 7, 1998] + Changed several typedefs in pngrutil.c + Added makefile.wat (Pawel Mrochen), updated makefile.tc3 (Willem van Schaik) + replaced "while(1)" with "for(;;)" + added PNGARG() to prototypes in pngtest.c and removed some prototypes + updated some of the makefiles (Tom Lane) + changed some typedefs (s_start, etc.) in pngrutil.c + fixed dimensions of "short_months" array in pngwrite.c + Replaced ansi2knr.c with the one from jpeg-v6 + +version 1.0.0 [March 8, 1998] + Changed name from 1.00 to 1.0.0 (Adam Costello) + Added smakefile.ppc (with SCOPTIONS.ppc) for Amiga PPC (Andreas Kleinert) +version 1.0.0a [March 9, 1998] + Fixed three bugs in pngrtran.c to make gamma+background handling consistent + (Greg Roelofs) + Changed format of the PNG_LIBPNG_VER integer to xyyzz instead of xyz + for major, minor, and bugfix releases. This is 10001. (Adam Costello, + Tom Lane) + Make months range from 1-12 in png_convert_to_rfc1123 +version 1.0.0b [March 13, 1998] + Quieted compiler complaints about two empty "for" loops in pngrutil.c + Minor changes to makefile.s2x + Removed #ifdef/#endif around a png_free() in pngread.c + +version 1.0.1 [March 14, 1998] + Changed makefile.s2x to reduce security risk of using a relative pathname + Fixed some typos in the documentation (Greg). + Fixed a problem with value of "channels" returned by png_read_update_info() +version 1.0.1a [April 21, 1998] + Optimized Paeth calculations by replacing abs() function calls with intrinsics + plus other loop optimizations. Improves avg decoding speed by about 20%. + Commented out i386istic "align" compiler flags in makefile.lnx. + Reduced the default warning level in some makefiles, to make them consistent. + Removed references to IJG and JPEG in the ansi2knr.c copyright statement. + Fixed a bug in png_do_strip_filler with XXRRGGBB => RRGGBB transformation. + Added grayscale and 16-bit capability to png_do_read_filler(). + Fixed a bug in pngset.c, introduced in version 0.99c, that sets rowbytes + too large when writing an image with bit_depth < 8 (Bob Dellaca). + Corrected some bugs in the experimental weighted filtering heuristics. + Moved a misplaced pngrutil code block that truncates tRNS if it has more + than num_palette entries -- test was done before num_palette was defined. + Fixed a png_convert_to_rfc1123() bug that converts day 31 to 0 (Steve Eddins). + Changed compiler flags in makefile.wat for better optimization (Pawel Mrochen). +version 1.0.1b [May 2, 1998] + Relocated png_do_gray_to_rgb() within png_do_read_transformations() (Greg). + Relocated the png_composite macros from pngrtran.c to png.h (Greg). + Added makefile.sco (contributed by Mike Hopkirk). + Fixed two bugs (missing definitions of "istop") introduced in libpng-1.0.1a. + Fixed a bug in pngrtran.c that would set channels=5 under some circumstances. + More work on the Paeth-filtering, achieving imperceptible speedup (A Kleinert). + More work on loop optimization which may help when compiled with C++ compilers. + Added warnings when people try to use transforms they've defined out. + Collapsed 4 "i" and "c" loops into single "i" loops in pngrtran and pngwtran. + Revised paragraph about png_set_expand() in libpng.txt and libpng.3 (Greg) +version 1.0.1c [May 11, 1998] + Fixed a bug in pngrtran.c (introduced in libpng-1.0.1a) where the masks for + filler bytes should have been 0xff instead of 0xf. + Added max_pixel_depth=32 in pngrutil.c when using FILLER with palette images. + Moved PNG_WRITE_WEIGHTED_FILTER_SUPPORTED and PNG_WRITE_FLUSH_SUPPORTED + out of the PNG_WRITE_TRANSFORMS_NOT_SUPPORTED block of pngconf.h + Added "PNG_NO_WRITE_TRANSFORMS" etc., as alternatives for *_NOT_SUPPORTED, + for consistency, in pngconf.h + Added individual "ifndef PNG_NO_[CAPABILITY]" in pngconf.h to make it easier + to remove unwanted capabilities via the compile line + Made some corrections to grammar (which, it's) in documentation (Greg). + Corrected example.c, use of row_pointers in png_write_image(). +version 1.0.1d [May 24, 1998] + Corrected several statements that used side effects illegally in pngrutil.c + and pngtrans.c, that were introduced in version 1.0.1b + Revised png_read_rows() to avoid repeated if-testing for NULL (A Kleinert) + More corrections to example.c, use of row_pointers in png_write_image() + and png_read_rows(). + Added pngdll.mak and pngdef.pas to scripts directory, contributed by + Bob Dellaca, to make a png32bd.dll with Borland C++ 4.5 + Fixed error in example.c with png_set_text: num_text is 3, not 2 (Guido V.) + Changed several loops from count-down to count-up, for consistency. +version 1.0.1e [June 6, 1998] + Revised libpng.txt and libpng.3 description of png_set_read|write_fn(), and + added warnings when people try to set png_read_fn and png_write_fn in + the same structure. + Added a test such that png_do_gamma will be done when num_trans==0 + for truecolor images that have defined a background. This corrects an + error that was introduced in libpng-0.90 that can cause gamma processing + to be skipped. + Added tests in png.h to include "trans" and "trans_values" in structures + when PNG_READ_BACKGROUND_SUPPORTED or PNG_READ_EXPAND_SUPPORTED is defined. + Add png_free(png_ptr->time_buffer) in png_destroy_read_struct() + Moved png_convert_to_rfc_1123() from pngwrite.c to png.c + Added capability for user-provided malloc_fn() and free_fn() functions, + and revised pngtest.c to demonstrate their use, replacing the + PNGTEST_DEBUG_MEM feature. + Added makefile.w32, for Microsoft C++ 4.0 and later (Tim Wegner). + +version 1.0.2 [June 14, 1998] + Fixed two bugs in makefile.bor . +version 1.0.2a [December 30, 1998] + Replaced and extended code that was removed from png_set_filler() in 1.0.1a. + Fixed a bug in png_do_filler() that made it fail to write filler bytes in + the left-most pixel of each row (Kevin Bracey). + Changed "static pngcharp tIME_string" to "static char tIME_string[30]" + in pngtest.c (Duncan Simpson). + Fixed a bug in pngtest.c that caused pngtest to try to write a tIME chunk + even when no tIME chunk was present in the source file. + Fixed a problem in pngrutil.c: gray_to_rgb didn't always work with 16-bit. + Fixed a problem in png_read_push_finish_row(), which would not skip some + passes that it should skip, for images that are less than 3 pixels high. + Interchanged the order of calls to png_do_swap() and png_do_shift() + in pngwtran.c (John Cromer). + Added #ifdef PNG_DEBUG/#endif surrounding use of PNG_DEBUG in png.h . + Changed "bad adaptive filter type" from error to warning in pngrutil.c . + Fixed a documentation error about default filtering with 8-bit indexed-color. + Separated the PNG_NO_STDIO macro into PNG_NO_STDIO and PNG_NO_CONSOLE_IO + (L. Peter Deutsch). + Added png_set_rgb_to_gray() and png_get_rgb_to_gray_status() functions. + Added png_get_copyright() and png_get_header_version() functions. + Revised comments on png_set_progressive_read_fn() in libpng.txt and example.c + Added information about debugging in libpng.txt and libpng.3 . + Changed "ln -sf" to "ln -s -f" in makefile.s2x, makefile.lnx, and makefile.sco. + Removed lines after Dynamic Dependencies" in makefile.aco . + Revised makefile.dec to make a shared library (Jeremie Petit). + Removed trailing blanks from all files. +version 1.0.2a [January 6, 1999] + Removed misplaced #endif and #ifdef PNG_NO_EXTERN near the end of png.h + Added "if" tests to silence complaints about unused png_ptr in png.h and png.c + Changed "check_if_png" function in example.c to return true (nonzero) if PNG. + Changed libpng.txt to demonstrate png_sig_cmp() instead of png_check_sig() + which is obsolete. + +version 1.0.3 [January 14, 1999] + Added makefile.hux, for Hewlett Packard HPUX 10.20 and 11.00 (Jim Rice) + Added a statement of Y2K compliance in png.h, libpng.3, and Y2KINFO. +version 1.0.3a [August 12, 1999] + Added check for PNG_READ_INTERLACE_SUPPORTED in pngread.c; issue a warning + if an attempt is made to read an interlaced image when it's not supported. + Added check if png_ptr->trans is defined before freeing it in pngread.c + Modified the Y2K statement to include versions back to version 0.71 + Fixed a bug in the check for valid IHDR bit_depth/color_types in pngrutil.c + Modified makefile.wat (added -zp8 flag, ".symbolic", changed some comments) + Replaced leading blanks with tab characters in makefile.hux + Changed "dworkin.wustl.edu" to "ccrc.wustl.edu" in various documents. + Changed (float)red and (float)green to (double)red, (double)green + in png_set_rgb_to_gray() to avoid "promotion" problems in AIX. + Fixed a bug in pngconf.h that omitted when PNG_DEBUG==0 (K Bracey). + Reformatted libpng.3 and libpngpf.3 with proper fonts (script by J. vanZandt). + Updated documentation to refer to the PNG-1.2 specification. + Removed ansi2knr.c and left pointers to the latest source for ansi2knr.c + in makefile.knr, INSTALL, and README (L. Peter Deutsch) + Fixed bugs in calculation of the length of rowbytes when adding alpha + channels to 16-bit images, in pngrtran.c (Chris Nokleberg) + Added function png_set_user_transform_info() to store user_transform_ptr, + user_depth, and user_channels into the png_struct, and a function + png_get_user_transform_ptr() to retrieve the pointer (Chris Nokleberg) + Added function png_set_empty_plte_permitted() to make libpng useable + in MNG applications. + Corrected the typedef for png_free_ptr in png.h (Jesse Jones). + Correct gamma with srgb is 45455 instead of 45000 in pngrutil.c, to be + consistent with PNG-1.2, and allow variance of 500 before complaining. + Added assembler code contributed by Intel in file pngvcrd.c and modified + makefile.w32 to use it (Nirav Chhatrapati, INTEL Corporation, Gilles Vollant) + Changed "ln -s -f" to "ln -f -s" in the makefiles to make Solaris happy. + Added some aliases for png_set_expand() in pngrtran.c, namely + png_set_expand_PLTE(), png_set_expand_depth(), and png_set_expand_tRNS() + (Greg Roelofs, in "PNG: The Definitive Guide"). + Added makefile.beo for BEOS on X86, contributed by Sander Stok. +version 1.0.3b [August 26, 1999] + Replaced 2147483647L several places with PNG_MAX_UINT macro, defined in png.h + Changed leading blanks to tabs in all makefiles. + Define PNG_USE_PNGVCRD in makefile.w32, to get MMX assembler code. + Made alternate versions of png_set_expand() in pngrtran.c, namely + png_set_gray_1_2_4_to_8, png_set_palette_to_rgb, and png_set_tRNS_to_alpha + (Greg Roelofs, in "PNG: The Definitive Guide"). Deleted the 1.0.3a aliases. + Relocated start of 'extern "C"' block in png.h so it doesn't include pngconf.h + Revised calculation of num_blocks in pngmem.c to avoid a potentially + negative shift distance, whose results are undefined in the C language. + Added a check in pngset.c to prevent writing multiple tIME chunks. + Added a check in pngwrite.c to detect invalid small window_bits sizes. +version 1.0.3d [September 4, 1999] + Fixed type casting of igamma in pngrutil.c + Added new png_expand functions to scripts/pngdef.pas and pngos2.def + Added a demo read_user_transform_fn that examines the row filters in pngtest.c + +version 1.0.4 [September 24, 1999] + Define PNG_ALWAYS_EXTERN in pngconf.h if __STDC__ is defined + Delete #define PNG_INTERNAL and include "png.h" from pngasmrd.h + Made several minor corrections to pngtest.c + Renamed the makefiles with longer but more user friendly extensions. + Copied the PNG copyright and license to a separate LICENSE file. + Revised documentation, png.h, and example.c to remove reference to + "viewing_gamma" which no longer appears in the PNG specification. + Revised pngvcrd.c to use MMX code for interlacing only on the final pass. + Updated pngvcrd.c to use the faster C filter algorithms from libpng-1.0.1a + Split makefile.win32vc into two versions, makefile.vcawin32 (uses MMX + assembler code) and makefile.vcwin32 (doesn't). + Added a CPU timing report to pngtest.c (enabled by defining PNGTEST_TIMING) + Added a copy of pngnow.png to the distribution. +version 1.0.4a [September 25, 1999] + Increase max_pixel_depth in pngrutil.c if a user transform needs it. + Changed several division operations to right-shifts in pngvcrd.c +version 1.0.4b [September 30, 1999] + Added parentheses in line 3732 of pngvcrd.c + Added a comment in makefile.linux warning about buggy -O3 in pgcc 2.95.1 +version 1.0.4c [October 1, 1999] + Added a "png_check_version" function in png.c and pngtest.c that will generate + a helpful compiler error if an old png.h is found in the search path. + Changed type of png_user_transform_depth|channels from int to png_byte. +version 1.0.4d [October 6, 1999] + Changed 0.45 to 0.45455 in png_set_sRGB() + Removed unused PLTE entries from pngnow.png + Re-enabled some parts of pngvcrd.c (png_combine_row) that work properly. +version 1.0.4e [October 10, 1999] + Fixed sign error in pngvcrd.c (Greg Roelofs) + Replaced some instances of memcpy with simple assignments in pngvcrd (GR-P) +version 1.0.4f [October 15, 1999] + Surrounded example.c code with #if 0 .. #endif to prevent people from + inadvertently trying to compile it. + Changed png_get_header_version() from a function to a macro in png.h + Added type casting mostly in pngrtran.c and pngwtran.c + Removed some pointless "ptr = NULL" in pngmem.c + Added a "contrib" directory containing the source code from Greg's book. + +version 1.0.5 [October 15, 1999] + Minor editing of the INSTALL and README files. +version 1.0.5a [October 23, 1999] + Added contrib/pngsuite and contrib/pngminus (Willem van Schaik) + Fixed a typo in the png_set_sRGB() function call in example.c (Jan Nijtmans) + Further optimization and bugfix of pngvcrd.c + Revised pngset.c so that it does not allocate or free memory in the user's + text_ptr structure. Instead, it makes its own copy. + Created separate write_end_info_struct in pngtest.c for a more severe test. + Added code in pngwrite.c to free info_ptr->text[i].key to stop a memory leak. +version 1.0.5b [November 23, 1999] + Moved PNG_FLAG_HAVE_CHUNK_HEADER, PNG_FLAG_BACKGROUND_IS_GRAY and + PNG_FLAG_WROTE_tIME from flags to mode. + Added png_write_info_before_PLTE() function. + Fixed some typecasting in contrib/gregbook/*.c + Updated scripts/makevms.com and added makevms.com to contrib/gregbook + and contrib/pngminus (Martin Zinser) +version 1.0.5c [November 26, 1999] + Moved png_get_header_version from png.h to png.c, to accomodate ansi2knr. + Removed all global arrays (according to PNG_NO_GLOBAL_ARRAYS macro), to + accomodate making DLL's: Moved usr_png_ver from global variable to function + png_get_header_ver() in png.c. Moved png_sig to png_sig_bytes in png.c and + eliminated use of png_sig in pngwutil.c. Moved the various png_CHNK arrays + into pngtypes.h. Eliminated use of global png_pass arrays. Declared the + png_CHNK and png_pass arrays to be "const". Made the global arrays + available to applications (although none are used in libpng itself) when + PNG_NO_GLOBAL_ARRAYS is not defined or when PNG_GLOBAL_ARRAYS is defined. + Removed some extraneous "-I" from contrib/pngminus/makefile.std + Changed the PNG_sRGB_INTENT macros in png.h to be consistent with PNG-1.2. + Change PNG_SRGB_INTENT to PNG_sRGB_INTENT in libpng.txt and libpng.3 +version 1.0.5d [November 29, 1999] + Add type cast (png_const_charp) two places in png.c + Eliminated pngtypes.h; use macros instead to declare PNG_CHNK arrays. + Renamed "PNG_GLOBAL_ARRAYS" to "PNG_USE_GLOBAL_ARRAYS" and made available + to applications a macro "PNG_USE_LOCAL_ARRAYS". + #ifdef out all the new declarations when PNG_USE_GLOBAL_ARRAYS is defined. + Added PNG_EXPORT_VAR macro to accommodate making DLL's. +version 1.0.5e [November 30, 1999] + Added iCCP, iTXt, and sPLT support; added "lang" member to the png_text + structure; refactored the inflate/deflate support to make adding new chunks + with trailing compressed parts easier in the future, and added new functions + png_free_iCCP, png_free_pCAL, png_free_sPLT, png_free_text, png_get_iCCP, + png_get_spalettes, png_set_iCCP, png_set_spalettes (Eric S. Raymond). + NOTE: Applications that write text chunks MUST define png_text->lang + before calling png_set_text(). It must be set to NULL if you want to + write tEXt or zTXt chunks. If you want your application to be able to + run with older versions of libpng, use + + #ifdef PNG_iTXt_SUPPORTED + png_text[i].lang = NULL; + #endif + + Changed png_get_oFFs() and png_set_oFFs() to use signed rather than unsigned + offsets (Eric S. Raymond). + Combined PNG_READ_cHNK_SUPPORTED and PNG_WRITE_cHNK_SUPPORTED macros into + PNG_cHNK_SUPPORTED and combined the three types of PNG_text_SUPPORTED + macros, leaving the separate macros also available. + Removed comments on #endifs at the end of many short, non-nested #if-blocks. +version 1.0.5f [December 6, 1999] + Changed makefile.solaris to issue a warning about potential problems when + the ucb "ld" is in the path ahead of the ccs "ld". + Removed "- [date]" from the "synopsis" line in libpng.3 and libpngpf.3. + Added sCAL chunk support (Eric S. Raymond). +version 1.0.5g [December 7, 1999] + Fixed "png_free_spallettes" typo in png.h + Added code to handle new chunks in pngpread.c + Moved PNG_CHNK string macro definitions outside of PNG_NO_EXTERN block + Added "translated_key" to png_text structure and png_write_iTXt(). + Added code in pngwrite.c to work around a newly discovered zlib bug. +version 1.0.5h [December 10, 1999] + NOTE: regarding the note for version 1.0.5e, the following must also + be included in your code: + png_text[i].translated_key = NULL; + Unknown chunk handling is now supported. + Option to eliminate all floating point support was added. Some new + fixed-point functions such as png_set_gAMA_fixed() were added. + Expanded tabs and removed trailing blanks in source files. +version 1.0.5i [December 13, 1999] + Added some type casts to silence compiler warnings. + Renamed "png_free_spalette" to "png_free_spalettes" for consistency. + Removed leading blanks from a #define in pngvcrd.c + Added some parameters to the new png_set_keep_unknown_chunks() function. + Added a test for up->location != 0 in the first instance of writing + unknown chunks in pngwrite.c + Changed "num" to "i" in png_free_spalettes() and png_free_unknowns() to + prevent recursion. + Added png_free_hIST() function. + Various patches to fix bugs in the sCAL and integer cHRM processing, + and to add some convenience macros for use with sCAL. +version 1.0.5j [December 21, 1999] + Changed "unit" parameter of png_write_sCAL from png_byte to int, to work + around buggy compilers. + Added new type "png_fixed_point" for integers that hold float*100000 values + Restored backward compatibility of tEXt/zTXt chunk processing: + Restored the first four members of png_text to the same order as v.1.0.5d. + Added members "lang_key" and "itxt_length" to png_text struct. Set + text_length=0 when "text" contains iTXt data. Use the "compression" + member to distinguish among tEXt/zTXt/iTXt types. Added + PNG_ITXT_COMPRESSION_NONE (1) and PNG_ITXT_COMPRESSION_zTXt(2) macros. + The "Note" above, about backward incompatibility of libpng-1.0.5e, no + longer applies. + Fixed png_read|write_iTXt() to read|write parameters in the right order, + and to write the iTXt chunk after IDAT if it appears in the end_ptr. + Added pnggccrd.c, version of pngvcrd.c Intel assembler for gcc (Greg Roelofs) + Reversed the order of trying to write floating-point and fixed-point gAMA. +version 1.0.5k [December 27, 1999] + Added many parentheses, e.g., "if (a && b & c)" becomes "if (a && (b & c))" + Added png_handle_as_unknown() function (Glenn) + Added png_free_chunk_list() function and chunk_list and num_chunk_list members + of png_ptr. + Eliminated erroneous warnings about multiple sPLT chunks and sPLT-after-PLTE. + Fixed a libpng-1.0.5h bug in pngrutil.c that was issuing erroneous warnings + about ignoring incorrect gAMA with sRGB (gAMA was in fact not ignored) + Added png_free_tRNS(); png_set_tRNS() now malloc's its own trans array (ESR). + Define png_get_int_32 when oFFs chunk is supported as well as when pCAL is. + Changed type of proflen from png_int_32 to png_uint_32 in png_get_iCCP(). +version 1.0.5l [January 1, 2000] + Added functions png_set_read_user_chunk_fn() and png_get_user_chunk_ptr() + for setting a callback function to handle unknown chunks and for + retrieving the associated user pointer (Glenn). +version 1.0.5m [January 7, 2000] + Added high-level functions png_read_png(), png_write_png(), png_free_pixels(). +version 1.0.5n [January 9, 2000] + Added png_free_PLTE() function, and modified png_set_PLTE() to malloc its + own memory for info_ptr->palette. This makes it safe for the calling + application to free its copy of the palette any time after it calls + png_set_PLTE(). +version 1.0.5o [January 20, 2000] + Cosmetic changes only (removed some trailing blanks and TABs) +version 1.0.5p [January 31, 2000] + Renamed pngdll.mak to makefile.bd32 + Cosmetic changes in pngtest.c +version 1.0.5q [February 5, 2000] + Relocated the makefile.solaris warning about PATH problems. + Fixed pngvcrd.c bug by pushing/popping registers in mmxsupport (Bruce Oberg) + Revised makefile.gcmmx + Added PNG_SETJMP_SUPPORTED, PNG_SETJMP_NOT_SUPPORTED, and PNG_ABORT() macros +version 1.0.5r [February 7, 2000] + Removed superfluous prototype for png_get_itxt from png.h + Fixed a bug in pngrtran.c that improperly expanded the background color. + Return *num_text=0 from png_get_text() when appropriate, and fix documentation + of png_get_text() in libpng.txt/libpng.3. +version 1.0.5s [February 18, 2000] + Added "png_jmp_env()" macro to pngconf.h, to help people migrate to the + new error handler that's planned for the next libpng release, and changed + example.c, pngtest.c, and contrib programs to use this macro. + Revised some of the DLL-export macros in pngconf.h (Greg Roelofs) + Fixed a bug in png_read_png() that caused it to fail to expand some images + that it should have expanded. + Fixed some mistakes in the unused and undocumented INCH_CONVERSIONS functions + in pngget.c + Changed the allocation of palette, history, and trans arrays back to + the version 1.0.5 method (linking instead of copying) which restores + backward compatibility with version 1.0.5. Added some remarks about + that in example.c. Added "free_me" member to info_ptr and png_ptr + and added png_free_data() function. + Updated makefile.linux and makefile.gccmmx to make directories conditionally. + Made cosmetic changes to pngasmrd.h + Added png_set_rows() and png_get_rows(), for use with png_read|write_png(). + Modified png_read_png() to allocate info_ptr->row_pointers only if it + hasn't already been allocated. +version 1.0.5t [March 4, 2000] + Changed png_jmp_env() migration aiding macro to png_jmpbuf(). + Fixed "interlace" typo (should be "interlaced") in contrib/gregbook/read2-x.c + Fixed bug with use of PNG_BEFORE_IHDR bit in png_ptr->mode, introduced when + PNG_FLAG_HAVE_CHUNK_HEADER was moved into png_ptr->mode in version 1.0.5b + Files in contrib/gregbook were revised to use png_jmpbuf() and to select + a 24-bit visual if one is available, and to allow abbreviated options. + Files in contrib/pngminus were revised to use the png_jmpbuf() macro. + Removed spaces in makefile.linux and makefile.gcmmx, introduced in 1.0.5s +version 1.0.5u [March 5, 2000] + Simplified the code that detects old png.h in png.c and pngtest.c + Renamed png_spalette (_p, _pp) to png_sPLT_t (_tp, _tpp) + Increased precision of rgb_to_gray calculations from 8 to 15 bits and + added png_set_rgb_to_gray_fixed() function. + Added makefile.bc32 (32-bit Borland C++, C mode) +version 1.0.5v [March 11, 2000] + Added some parentheses to the png_jmpbuf macro definition. + Updated references to the zlib home page, which has moved to freesoftware.com. + Corrected bugs in documentation regarding png_read_row() and png_write_row(). + Updated documentation of png_rgb_to_gray calculations in libpng.3/libpng.txt. + Renamed makefile.borland,turboc3 back to makefile.bor,tc3 as in version 1.0.3, + revised borland makefiles; added makefile.ibmvac3 and makefile.gcc (Cosmin) + +version 1.0.6 [March 20, 2000] + Minor revisions of makefile.bor, libpng.txt, and gregbook/rpng2-win.c + Added makefile.sggcc (SGI IRIX with gcc) +version 1.0.6d [April 7, 2000] + Changed sprintf() to strcpy() in png_write_sCAL_s() to work without STDIO + Added data_length parameter to png_decompress_chunk() function + Revised documentation to remove reference to abandoned png_free_chnk functions + Fixed an error in png_rgb_to_gray_fixed() + Revised example.c, usage of png_destroy_write_struct(). + Renamed makefile.ibmvac3 to makefile.ibmc, added libpng.icc IBM project file + Added a check for info_ptr->free_me&PNG_FREE_TEXT when freeing text in png.c + Simplify png_sig_bytes() function to remove use of non-ISO-C strdup(). +version 1.0.6e [April 9, 2000] + Added png_data_freer() function. + In the code that checks for over-length tRNS chunks, added check of + info_ptr->num_trans as well as png_ptr->num_trans (Matthias Benckmann) + Minor revisions of libpng.txt/libpng.3. + Check for existing data and free it if the free_me flag is set, in png_set_*() + and png_handle_*(). + Only define PNG_WEIGHTED_FILTERS_SUPPORTED when PNG_FLOATING_POINT_SUPPORTED + is defined. + Changed several instances of PNG_NO_CONSOLE_ID to PNG_NO_STDIO in pngrutil.c + and mentioned the purposes of the two macros in libpng.txt/libpng.3. +version 1.0.6f [April 14, 2000] + Revised png_set_iCCP() and png_set_rows() to avoid prematurely freeing data. + Add checks in png_set_text() for NULL members of the input text structure. + Revised libpng.txt/libpng.3. + Removed superfluous prototype for png_set_itxt from png.h + Removed "else" from pngread.c, after png_error(), and changed "0" to "length". + Changed several png_errors about malformed ancillary chunks to png_warnings. +version 1.0.6g [April 24, 2000] + Added png_pass-* arrays to pnggccrd.c when PNG_USE_LOCAL_ARRAYS is defined. + Relocated paragraph about png_set_background() in libpng.3/libpng.txt + and other revisions (Matthias Benckmann) + Relocated info_ptr->free_me, png_ptr->free_me, and other info_ptr and + png_ptr members to restore binary compatibility with libpng-1.0.5 + (breaks compatibility with libpng-1.0.6). +version 1.0.6h [April 24, 2000] + Changed shared library so-number pattern from 2.x.y.z to xy.z (this builds + libpng.so.10 & libpng.so.10.6h instead of libpng.so.2 & libpng.so.2.1.0.6h) + This is a temporary change for test purposes. +version 1.0.6i [May 2, 2000] + Rearranged some members at the end of png_info and png_struct, to put + unknown_chunks_num and free_me within the original size of the png_structs + and free_me, png_read_user_fn, and png_free_fn within the original png_info, + because some old applications allocate the structs directly instead of + using png_create_*(). + Added documentation of user memory functions in libpng.txt/libpng.3 + Modified png_read_png so that it will use user_allocated row_pointers + if present, unless free_me directs that it be freed, and added description + of the use of png_set_rows() and png_get_rows() in libpng.txt/libpng.3. + Added PNG_LEGACY_SUPPORTED macro, and #ifdef out all new (since version + 1.00) members of png_struct and png_info, to regain binary compatibility + when you define this macro. Capabilities lost in this event + are user transforms (new in version 1.0.0),the user transform pointer + (new in version 1.0.2), rgb_to_gray (new in 1.0.5), iCCP, sCAL, sPLT, + the high-level interface, and unknown chunks support (all new in 1.0.6). + This was necessary because of old applications that allocate the structs + directly as authors were instructed to do in libpng-0.88 and earlier, + instead of using png_create_*(). + Added modes PNG_CREATED_READ_STRUCT and PNG_CREATED_WRITE_STRUCT which + can be used to detect codes that directly allocate the structs, and + code to check these modes in png_read_init() and png_write_init() and + generate a libpng error if the modes aren't set and PNG_LEGACY_SUPPORTED + was not defined. + Added makefile.intel and updated makefile.watcom (Pawel Mrochen) +version 1.0.6j [May 3, 2000] + Overloaded png_read_init() and png_write_init() with macros that convert + calls to png_read_init_2() or png_write_init_2() that check the version + and structure sizes. +version 1.0.7beta11 [May 7, 2000] + Removed the new PNG_CREATED_READ_STRUCT and PNG_CREATED_WRITE_STRUCT modes + which are no longer used. + Eliminated the three new members of png_text when PNG_LEGACY_SUPPORTED is + defined or when neither PNG_READ_iTXt_SUPPORTED nor PNG_WRITE_iTXT_SUPPORTED + is defined. + Made PNG_NO_READ|WRITE_iTXt the default setting, to avoid memory + overrun when old applications fill the info_ptr->text structure directly. + Added PNGAPI macro, and added it to the definitions of all exported functions. + Relocated version macro definitions ahead of the includes of zlib.h and + pngconf.h in png.h. +version 1.0.7beta12 [May 12, 2000] + Revised pngset.c to avoid a problem with expanding the png_debug macro. + Deleted some extraneous defines from pngconf.h + Made PNG_NO_CONSOLE_IO the default condition when PNG_BUILD_DLL is defined. + Use MSC _RPTn debugging instead of fprintf if _MSC_VER is defined. + Added png_access_version_number() function. + Check for mask&PNG_FREE_CHNK (for TEXT, SCAL, PCAL) in png_free_data(). + Expanded libpng.3/libpng.txt information about png_data_freer(). +version 1.0.7beta14 [May 17, 2000] (beta13 was not published) + Changed pnggccrd.c and pngvcrd.c to handle bad adaptive filter types as + warnings instead of errors, as pngrutil.c does. + Set the PNG_INFO_IDAT valid flag in png_set_rows() so png_write_png() + will actually write IDATs. + Made the default PNG_USE_LOCAL_ARRAYS depend on PNG_DLL instead of WIN32. + Make png_free_data() ignore its final parameter except when freeing data + that can have multiple instances (text, sPLT, unknowns). + Fixed a new bug in png_set_rows(). + Removed info_ptr->valid tests from png_free_data(), as in version 1.0.5. + Added png_set_invalid() function. + Fixed incorrect illustrations of png_destroy_write_struct() in example.c. +version 1.0.7beta15 [May 30, 2000] + Revised the deliberately erroneous Linux setjmp code in pngconf.h to produce + fewer error messages. + Rearranged checks for Z_OK to check the most likely path first in pngpread.c + and pngwutil.c. + Added checks in pngtest.c for png_create_*() returning NULL, and mentioned + in libpng.txt/libpng.3 the need for applications to check this. + Changed names of png_default_*() functions in pngtest to pngtest_*(). + Changed return type of png_get_x|y_offset_*() from png_uint_32 to png_int_32. + Fixed some bugs in the unused PNG_INCH_CONVERSIONS functions in pngget.c + Set each pointer to NULL after freeing it in png_free_data(). + Worked around a problem in pngconf.h; AIX's strings.h defines an "index" + macro that conflicts with libpng's png_color_16.index. (Dimitri Papadapoulos) + Added "msvc" directory with MSVC++ project files (Simon-Pierre Cadieux). +version 1.0.7beta16 [June 4, 2000] + Revised the workaround of AIX string.h "index" bug. + Added a check for overlength PLTE chunk in pngrutil.c. + Added PNG_NO_POINTER_INDEXING macro to use array-indexing instead of pointer + indexing in pngrutil.c and pngwutil.c to accommodate a buggy compiler. + Added a warning in png_decompress_chunk() when it runs out of data, e.g. + when it tries to read an erroneous PhotoShop iCCP chunk. + Added PNG_USE_DLL macro. + Revised the copyright/disclaimer/license notice. + Added contrib/msvctest directory +version 1.0.7rc1 [June 9, 2000] + Corrected the definition of PNG_TRANSFORM_INVERT_ALPHA (0x0400 not 0x0200) + Added contrib/visupng directory (Willem van Schaik) +version 1.0.7beta18 [June 23, 2000] + Revised PNGAPI definition, and pngvcrd.c to work with __GCC__ + and do not redefine PNGAPI if it is passed in via a compiler directive. + Revised visupng/PngFile.c to remove returns from within the Try block. + Removed leading underscores from "_PNG_H" and "_PNG_SAVE_BSD_SOURCE" macros. + Updated contrib/visupng/cexcept.h to version 1.0.0. + Fixed bugs in pngwrite.c and pngwutil.c that prevented writing iCCP chunks. +version 1.0.7rc2 [June 28, 2000] + Updated license to include disclaimers required by UCITA. + Fixed "DJBPP" typo in pnggccrd.c introduced in beta18. + +version 1.0.7 [July 1, 2000] + Revised the definition of "trans_values" in libpng.3/libpng.txt +version 1.0.8beta1 [July 8, 2000] + Added png_free(png_ptr, key) two places in pngpread.c to stop memory leaks. + Changed PNG_NO_STDIO to PNG_NO_CONSOLE_IO, several places in pngrutil.c and + pngwutil.c. + Changed PNG_EXPORT_VAR to use PNG_IMPEXP, in pngconf.h. + Removed unused "#include " from png.c + Added WindowsCE support. + Revised pnggccrd.c to work with gcc-2.95.2 and in the Cygwin environment. +version 1.0.8beta2 [July 10, 2000] + Added project files to the wince directory and made further revisions + of pngtest.c, pngrio.c, and pngwio.c in support of WindowsCE. +version 1.0.8beta3 [July 11, 2000] + Only set the PNG_FLAG_FREE_TRNS or PNG_FREE_TRNS flag in png_handle_tRNS() + for indexed-color input files to avoid potential double-freeing trans array + under some unusual conditions; problem was introduced in version 1.0.6f. + Further revisions to pngtest.c and files in the wince subdirectory. +version 1.0.8beta4 [July 14, 2000] + Added the files pngbar.png and pngbar.jpg to the distribution. + Added makefile.cygwin, and cygwin support in pngconf.h + Added PNG_NO_ZALLOC_ZERO macro (makes png_zalloc skip zeroing memory) +version 1.0.8rc1 [July 16, 2000] + Revised png_debug() macros and statements to eliminate compiler warnings. + +version 1.0.8 [July 24, 2000] + Added png_flush() in pngwrite.c, after png_write_IEND(). + Updated makefile.hpux to build a shared library. +version 1.0.9beta1 [November 10, 2000] + Fixed typo in scripts/makefile.hpux + Updated makevms.com in scripts and contrib/* and contrib/* (Martin Zinser) + Fixed seqence-point bug in contrib/pngminus/png2pnm (Martin Zinser) + Changed "cdrom.com" in documentation to "libpng.org" + Revised pnggccrd.c to get it all working, and updated makefile.gcmmx (Greg). + Changed type of "params" from voidp to png_voidp in png_read|write_png(). + Make sure PNGAPI and PNG_IMPEXP are defined in pngconf.h. + Revised the 3 instances of WRITEFILE in pngtest.c. + Relocated "msvc" and "wince" project subdirectories into "dll" subdirectory. + Updated png.rc in dll/msvc project + Revised makefile.dec to define and use LIBPATH and INCPATH + Increased size of global png_libpng_ver[] array from 12 to 18 chars. + Made global png_libpng_ver[], png_sig[] and png_pass_*[] arrays const. + Removed duplicate png_crc_finish() from png_handle_bKGD() function. + Added a warning when application calls png_read_update_info() multiple times. + Revised makefile.cygwin + Fixed bugs in iCCP support in pngrutil.c and pngwutil.c. + Replaced png_set_empty_plte_permitted() with png_permit_mng_features(). +version 1.0.9beta2 [November 19, 2000] + Renamed the "dll" subdirectory "projects". + Added borland project files to "projects" subdirectory. + Set VS_FF_PRERELEASE and VS_FF_PATCHED flags in msvc/png.rc when appropriate. + Add error message in png_set_compression_buffer_size() when malloc fails. +version 1.0.9beta3 [November 23, 2000] + Revised PNG_LIBPNG_BUILD_TYPE macro in png.h, used in the msvc project. + Removed the png_flush() in pngwrite.c that crashes some applications + that don't set png_output_flush_fn. + Added makefile.macosx and makefile.aix to scripts directory. +version 1.0.9beta4 [December 1, 2000] + Change png_chunk_warning to png_warning in png_check_keyword(). + Increased the first part of msg buffer from 16 to 18 in png_chunk_error(). +version 1.0.9beta5 [December 15, 2000] + Added support for filter method 64 (for PNG datastreams embedded in MNG). +version 1.0.9beta6 [December 18, 2000] + Revised png_set_filter() to accept filter method 64 when appropriate. + Added new PNG_HAVE_PNG_SIGNATURE bit to png_ptr->mode and use it to + help prevent applications from using MNG features in PNG datastreams. + Added png_permit_mng_features() function. + Revised libpng.3/libpng.txt. Changed "filter type" to "filter method". +version 1.0.9rc1 [December 23, 2000] + Revised test for PNG_HAVE_PNG_SIGNATURE in pngrutil.c + Fixed error handling of unknown compression type in png_decompress_chunk(). + In pngconf.h, define __cdecl when _MSC_VER is defined. +version 1.0.9beta7 [December 28, 2000] + Changed PNG_TEXT_COMPRESSION_zTXt to PNG_COMPRESSION_TYPE_BASE several places. + Revised memory management in png_set_hIST and png_handle_hIST in a backward + compatible manner. PLTE and tRNS were revised similarly. + Revised the iCCP chunk reader to ignore trailing garbage. +version 1.0.9beta8 [January 12, 2001] + Moved pngasmrd.h into pngconf.h. + Improved handling of out-of-spec garbage iCCP chunks generated by PhotoShop. +version 1.0.9beta9 [January 15, 2001] + Added png_set_invalid, png_permit_mng_features, and png_mmx_supported to + wince and msvc project module definition files. + Minor revision of makefile.cygwin. + Fixed bug with progressive reading of narrow interlaced images in pngpread.c +version 1.0.9beta10 [January 16, 2001] + Do not typedef png_FILE_p in pngconf.h when PNG_NO_STDIO is defined. + Fixed "png_mmx_supported" typo in project definition files. +version 1.0.9beta11 [January 19, 2001] + Updated makefile.sgi to make shared library. + Removed png_mmx_support() function and disabled PNG_MNG_FEATURES_SUPPORTED + by default, for the benefit of DLL forward compatibility. These will + be re-enabled in version 1.2.0. +version 1.0.9rc2 [January 22, 2001] + Revised cygwin support. + +version 1.0.9 [January 31, 2001] + Added check of cygwin's ALL_STATIC in pngconf.h + Added "-nommx" parameter to contrib/gregbook/rpng2-win and rpng2-x demos. +version 1.0.10beta1 [March 14, 2001] + Revised makefile.dec, makefile.sgi, and makefile.sggcc; added makefile.hpgcc. + Reformatted libpng.3 to eliminate bad line breaks. + Added checks for _mmx_supported in the read_filter_row function of pnggccrd.c + Added prototype for png_mmx_support() near the top of pnggccrd.c + Moved some error checking from png_handle_IHDR to png_set_IHDR. + Added PNG_NO_READ_SUPPORTED and PNG_NO_WRITE_SUPPORTED macros. + Revised png_mmx_support() function in pnggccrd.c + Restored version 1.0.8 PNG_WRITE_EMPTY_PLTE_SUPPORTED behavior in pngwutil.c + Fixed memory leak in contrib/visupng/PngFile.c + Fixed bugs in png_combine_row() in pnggccrd.c and pngvcrd.c (C version) + Added warnings when retrieving or setting gamma=0. + Increased the first part of msg buffer from 16 to 18 in png_chunk_warning(). +version 1.0.10rc1 [March 23, 2001] + Changed all instances of memcpy, strcpy, and strlen to png_memcpy, png_strcpy, + and png_strlen. + Revised png_mmx_supported() function in pnggccrd.c to return proper value. + Fixed bug in progressive reading (pngpread.c) with small images (height < 8). + +version 1.0.10 [March 30, 2001] + Deleted extraneous space (introduced in 1.0.9) from line 42 of makefile.cygwin + Added beos project files (Chris Herborth) +version 1.0.11beta1 [April 3, 2001] + Added type casts on several png_malloc() calls (Dimitri Papadapoulos). + Removed a no-longer needed AIX work-around from pngconf.h + Changed several "//" single-line comments to C-style in pnggccrd.c +version 1.0.11beta2 [April 11, 2001] + Removed PNGAPI from several functions whose prototypes did not have PNGAPI. + Updated scripts/pngos2.def +version 1.0.11beta3 [April 14, 2001] + Added checking the results of many instances of png_malloc() for NULL +version 1.0.11beta4 [April 20, 2001] + Undid the changes from version 1.0.11beta3. Added a check for NULL return + from user's malloc_fn(). + Removed some useless type casts of the NULL pointer. + Added makefile.netbsd + +version 1.0.11 [April 27, 2001] + Revised makefile.netbsd +version 1.0.12beta1 [May 14, 2001] + Test for Windows platform in pngconf.h when including malloc.h (Emmanuel Blot) + Updated makefile.cygwin and handling of Cygwin's ALL_STATIC in pngconf.h + Added some never-to-be-executed code in pnggccrd.c to quiet compiler warnings. + Eliminated the png_error about apps using png_read|write_init(). Instead, + libpng will reallocate the png_struct and info_struct if they are too small. + This retains future binary compatibility for old applications written for + libpng-0.88 and earlier. +version 1.2.0beta1 [May 6, 2001] + Bumped DLLNUM to 2. + Re-enabled PNG_MNG_FEATURES_SUPPORTED and enabled PNG_ASSEMBLER_CODE_SUPPORTED + by default. + Added runtime selection of MMX features. + Added png_set_strip_error_numbers function and related macros. +version 1.2.0beta2 [May 7, 2001] + Finished merging 1.2.0beta1 with version 1.0.11 + Added a check for attempts to read or write PLTE in grayscale PNG datastreams. +version 1.2.0beta3 [May 17, 2001] + Enabled user memory function by default. + Modified png_create_struct so it passes user mem_ptr to user memory allocator. + Increased png_mng_features flag from png_byte to png_uint_32. + Bumped shared-library (so-number) and dll-number to 3. +version 1.2.0beta4 [June 23, 2001] + Check for missing profile length field in iCCP chunk and free chunk_data + in case of truncated iCCP chunk. + Bumped shared-library number to 3 in makefile.sgi and makefile.sggcc + Bumped dll-number from 2 to 3 in makefile.cygwin + Revised contrib/gregbook/rpng*-x.c to avoid a memory leak and to exit cleanly + if user attempts to run it on an 8-bit display. + Updated contrib/gregbook + Use png_malloc instead of png_zalloc to allocate palette in pngset.c + Updated makefile.ibmc + Added some typecasts to eliminate gcc 3.0 warnings. Changed prototypes + of png_write_oFFS width and height from png_uint_32 to png_int_32. + Updated example.c + Revised prototypes for png_debug_malloc and png_debug_free in pngtest.c +version 1.2.0beta5 [August 8, 2001] + Revised contrib/gregbook + Revised makefile.gcmmx + Revised pnggccrd.c to conditionally compile some thread-unsafe code only + when PNG_THREAD_UNSAFE_OK is defined. + Added tests to prevent pngwutil.c from writing a bKGD or tRNS chunk with + value exceeding 2^bit_depth-1 + Revised makefile.sgi and makefile.sggcc + Replaced calls to fprintf(stderr,...) with png_warning() in pnggccrd.c + Removed restriction that do_invert_mono only operate on 1-bit opaque files + +version 1.2.0 [September 1, 2001] + Changed a png_warning() to png_debug() in pnggccrd.c + Fixed contrib/gregbook/rpng-x.c, rpng2-x.c to avoid crash with XFreeGC(). +version 1.2.1beta1 [October 19, 2001] + Revised makefile.std in contrib/pngminus + Include background_1 in png_struct regardless of gamma support. + Revised makefile.netbsd and makefile.macosx, added makefile.darwin. + Revised example.c to provide more details about using row_callback(). +version 1.2.1beta2 [October 25, 2001] + Added type cast to each NULL appearing in a function call, except for + WINCE functions. + Added makefile.so9. +version 1.2.1beta3 [October 27, 2001] + Removed type casts from all NULLs. + Simplified png_create_struct_2(). +version 1.2.1beta4 [November 7, 2001] + Revised png_create_info_struct() and png_creat_struct_2(). + Added error message if png_write_info() was omitted. + Type cast NULLs appearing in function calls when _NO_PROTO or + PNG_TYPECAST_NULL is defined. +version 1.2.1rc1 [November 24, 2001] + Type cast NULLs appearing in function calls except when PNG_NO_TYPECAST_NULL + is defined. + Changed typecast of "size" argument to png_size_t in pngmem.c calls to + the user malloc_fn, to agree with the prototype in png.h + Added a pop/push operation to pnggccrd.c, to preserve Eflag (Maxim Sobolev) + Updated makefile.sgi to recognize LIBPATH and INCPATH. + Updated various makefiles so "make clean" does not remove previous major + version of the shared library. +version 1.2.1rc2 [December 4, 2001] + Always allocate 256-entry internal palette, hist, and trans arrays, to + avoid out-of-bounds memory reference caused by invalid PNG datastreams. + Added a check for prefix_length > data_length in iCCP chunk handler. + +version 1.2.1 [December 7, 2001] + None. +version 1.2.2beta1 [February 22, 2002] + Fixed a bug with reading the length of iCCP profiles (Larry Reeves). + Revised makefile.linux, makefile.gcmmx, and makefile.sgi to generate + libpng.a, libpng12.so (not libpng.so.3), and libpng12/png.h + Revised makefile.darwin to remove "-undefined suppress" option. + Added checks for gamma and chromaticity values over 21474.83, which exceed + the limit for PNG unsigned 32-bit integers when encoded. + Revised calls to png_create_read_struct() and png_create_write_struct() + for simpler debugging. + Revised png_zalloc() so zlib handles errors (uses PNG_FLAG_MALLOC_NULL_MEM_OK) +version 1.2.2beta2 [February 23, 2002] + Check chunk_length and idat_size for invalid (over PNG_MAX_UINT) lengths. + Check for invalid image dimensions in png_get_IHDR. + Added missing "fi;" in the install target of the SGI makefiles. + Added install-static to all makefiles that make shared libraries. + Always do gamma compensation when image is partially transparent. +version 1.2.2beta3 [March 7, 2002] + Compute background.gray and background_1.gray even when color_type is RGB + in case image gets reduced to gray later. + Modified shared-library makefiles to install pkgconfig/libpngNN.pc. + Export (with PNGAPI) png_zalloc, png_zfree, and png_handle_as_unknown + Removed unused png_write_destroy_info prototype from png.h + Eliminated incorrect use of width_mmx from pnggccrd.c in pixel_bytes == 8 case + Added install-shared target to all makefiles that make shared libraries. + Stopped a double free of palette, hist, and trans when not using free_me. + Added makefile.32sunu for Sun Ultra 32 and makefile.64sunu for Sun Ultra 64. +version 1.2.2beta4 [March 8, 2002] + Compute background.gray and background_1.gray even when color_type is RGB + in case image gets reduced to gray later (Jason Summers). + Relocated a misplaced /bin/rm in the "install-shared" makefile targets + Added PNG_1_0_X macro which can be used to build a 1.0.x-compatible library. +version 1.2.2beta5 [March 26, 2002] + Added missing PNGAPI to several function definitions. + Check for invalid bit_depth or color_type in png_get_IHDR(), and + check for missing PLTE or IHDR in png_push_read_chunk() (Matthias Clasen). + Revised iTXt support to accept NULL for lang and lang_key. + Compute gamma for color components of background even when color_type is gray. + Changed "()" to "{}" in scripts/libpng.pc.in. + Revised makefiles to put png.h and pngconf.h only in $prefix/include/libpngNN + Revised makefiles to make symlink to libpng.so.NN in addition to libpngNN.so +version 1.2.2beta6 [March 31, 2002] +version 1.0.13beta1 [March 31, 2002] + Prevent png_zalloc() from trying to memset memory that it failed to acquire. + Add typecasts of PNG_MAX_UINT in pngset_cHRM_fixed() (Matt Holgate). + Ensure that the right function (user or default) is used to free the + png_struct after an error in png_create_read_struct_2(). +version 1.2.2rc1 [April 7, 2002] +version 1.0.13rc1 [April 7, 2002] + Save the ebx register in pnggccrd.c (Sami Farin) + Add "mem_ptr = png_ptr->mem_ptr" in png_destroy_write_struct() (Paul Gardner). + Updated makefiles to put headers in include/libpng and remove old include/*.h. + +version 1.2.2 [April 15, 2002] +version 1.0.13 [April 15, 2002] + Revised description of png_set_filter() in libpng.3/libpng.txt. + Revised makefile.netbsd and added makefile.neNNbsd and makefile.freebsd +version 1.0.13patch01 [April 17, 2002] +version 1.2.2patch01 [April 17, 2002] + Changed ${PNGMAJ}.${PNGVER} bug to ${PNGVER} in makefile.sgi and makefile.sggcc + Fixed VER -> PNGVER typo in makefile.macosx and added install-static to install + Added install: target to makefile.32sunu and makefile.64sunu +version 1.0.13patch03 [April 18, 2002] +version 1.2.2patch03 [April 18, 2002] + Revised 15 makefiles to link libpng.a to libpngNN.a and the include libpng + subdirectory to libpngNN subdirectory without the full pathname. + Moved generation of libpng.pc from "install" to "all" in 15 makefiles. +version 1.2.3rc1 [April 28, 2002] + Added install-man target to 15 makefiles (Dimitri Papadopolous-Orfanos). + Added $(DESTDIR) feature to 24 makefiles (Tim Mooney) + Fixed bug with $prefix, should be $(prefix) in makefile.hpux. + Updated cygwin-specific portion of pngconf.h and revised makefile.cygwin + Added a link from libpngNN.pc to libpng.pc in 15 makefiles. + Added links from include/libpngNN/*.h to include/*.h in 24 makefiles. + Revised makefile.darwin to make relative links without full pathname. + Added setjmp() at the end of png_create_*_struct_2() in case user forgets + to put one in their application. + Restored png_zalloc() and png_zfree() prototypes to version 1.2.1 and + removed them from module definition files. +version 1.2.3rc2 [May 1, 2002] + Fixed bug in reporting number of channels in pngget.c and pngset.c, + that was introduced in version 1.2.2beta5. + Exported png_zalloc(), png_zfree(), png_default_read(), png_default_write(), + png_default_flush(), and png_push_fill_buffer() and included them in + module definition files. + Added "libpng.pc" dependency to the "install-shared" target in 15 makefiles. +version 1.2.3rc3 [May 1, 2002] + Revised prototype for png_default_flush() + Remove old libpng.pc and libpngNN.pc before installing new ones. +version 1.2.3rc4 [May 2, 2002] + Typos in *.def files (png_default_read|write -> png_default_read|write_data) + In makefiles, changed rm libpng.NN.pc to rm libpngNN.pc + Added libpng-config and libpngNN-config and modified makefiles to install them. + Changed $(MANPATH) to $(DESTDIR)$(MANPATH) in makefiles + Added "Win32 DLL VB" configuration to projects/msvc/libpng.dsp +version 1.2.3rc5 [May 11, 2002] + Changed "error" and "message" in prototypes to "error_message" and + "warning_message" to avoid namespace conflict. + Revised 15 makefiles to build libpng-config from libpng-config-*.in + Once more restored png_zalloc and png_zfree to regular nonexported form. + Restored png_default_read|write_data, png_default_flush, png_read_fill_buffer + to nonexported form, but with PNGAPI, and removed them from module def files. +version 1.2.3rc6 [May 14, 2002] + Removed "PNGAPI" from png_zalloc() and png_zfree() in png.c + Changed "Gz" to "Gd" in projects/msvc/libpng.dsp and zlib.dsp. + Removed leftover libpng-config "sed" script from four makefiles. + Revised libpng-config creating script in 16 makefiles. + +version 1.2.3 [May 22, 2002] + Revised libpng-config target in makefile.cygwin. + Removed description of png_set_mem_fn() from documentation. + Revised makefile.freebsd. + Minor cosmetic changes to 15 makefiles, e.g., $(DI) = $(DESTDIR)/$(INCDIR). + Revised projects/msvc/README.txt + Changed -lpng to -lpngNN in LDFLAGS in several makefiles. +version 1.2.4beta1 [May 24, 2002] + Added libpng.pc and libpng-config to "all:" target in 16 makefiles. + Fixed bug in 16 makefiles: $(DESTDIR)/$(LIBPATH) to $(DESTDIR)$(LIBPATH) + Added missing "\" before closing double quote in makefile.gcmmx. + Plugged various memory leaks; added png_malloc_warn() and png_set_text_2() + functions. +version 1.2.4beta2 [June 25, 2002] + Plugged memory leak of png_ptr->current_text (Matt Holgate). + Check for buffer overflow before reading CRC in pngpread.c (Warwick Allison) + Added -soname to the loader flags in makefile.dec, makefile.sgi, and + makefile.sggcc. + Added "test-installed" target to makefile.linux, makefile.gcmmx, + makefile.sgi, and makefile.sggcc. +version 1.2.4beta3 [June 28, 2002] + Plugged memory leak of row_buf in pngtest.c when there is a png_error(). + Detect buffer overflow in pngpread.c when IDAT is corrupted with extra data. + Added "test-installed" target to makefile.32sunu, makefile.64sunu, + makefile.beos, makefile.darwin, makefile.dec, makefile.macosx, + makefile.solaris, makefile.hpux, makefile.hpgcc, and makefile.so9. +version 1.2.4rc1 and 1.0.14rc1 [July 2, 2002] + Added "test-installed" target to makefile.cygwin and makefile.sco. + Revised pnggccrd.c to be able to back out version 1.0.x via PNG_1_0_X macro. + +version 1.2.4 and 1.0.14 [July 8, 2002] + Changed png_warning() to png_error() when width is too large to process. +version 1.2.4patch01 [July 20, 2002] + Revised makefile.cygwin to use DLL number 12 instead of 13. +version 1.2.5beta1 [August 6, 2002] + Added code to contrib/gregbook/readpng2.c to ignore unused chunks. + Replaced toucan.png in contrib/gregbook (it has been corrupt since 1.0.11) + Removed some stray *.o files from contrib/gregbook. + Changed png_error() to png_warning() about "Too much data" in pngpread.c + and about "Extra compressed data" in pngrutil.c. + Prevent png_ptr->pass from exceeding 7 in png_push_finish_row(). + Updated makefile.hpgcc + Updated png.c and pnggccrd.c handling of return from png_mmx_support() +version 1.2.5beta2 [August 15, 2002] + Only issue png_warning() about "Too much data" in pngpread.c when avail_in + is nonzero. + Updated makefiles to install a separate libpng.so.3 with its own rpath. +version 1.2.5rc1 and 1.0.15rc1 [August 24, 2002] + Revised makefiles to not remove previous minor versions of shared libraries. +version 1.2.5rc2 and 1.0.15rc2 [September 16, 2002] + Revised 13 makefiles to remove "-lz" and "-L$(ZLIBLIB)", etc., from shared + library loader directive. + Added missing "$OBJSDLL" line to makefile.gcmmx. + Added missing "; fi" to makefile.32sunu. +version 1.2.5rc3 and 1.0.15rc3 [September 18, 2002] + Revised libpng-config script. + +version 1.2.5 and 1.0.15 [October 3, 2002] + Revised makefile.macosx, makefile.darwin, makefile.hpgcc, and makefile.hpux, + and makefile.aix. + Relocated two misplaced PNGAPI lines in pngtest.c +version 1.2.6beta1 [October 22, 2002] + Commented out warning about uninitialized mmx_support in pnggccrd.c. + Changed "IBMCPP__" flag to "__IBMCPP__" in pngconf.h. + Relocated two more misplaced PNGAPI lines in pngtest.c + Fixed memory overrun bug in png_do_read_filler() with 16-bit datastreams, + introduced in version 1.0.2. + Revised makefile.macosx, makefile.dec, makefile.aix, and makefile.32sunu. +version 1.2.6beta2 [November 1, 2002] + Added libpng-config "--ldopts" output. + Added "AR=ar" and "ARFLAGS=rc" and changed "ar rc" to "$(AR) $(ARFLAGS)" + in makefiles. +version 1.2.6beta3 [July 18, 2004] + Reverted makefile changes from version 1.2.6beta2 and some of the changes + from version 1.2.6beta1; these will be postponed until version 1.2.7. + Version 1.2.6 is going to be a simple bugfix release. + Changed the one instance of "ln -sf" to "ln -f -s" in each Sun makefile. + Fixed potential overrun in pngerror.c by using strncpy instead of memcpy. + Added "#!/bin/sh" at the top of configure, for recognition of the + 'x' flag under Cygwin (Cosmin). + Optimized vacuous tests that silence compiler warnings, in png.c (Cosmin). + Added support for PNG_USER_CONFIG, in pngconf.h (Cosmin). + Fixed the special memory handler for Borland C under DOS, in pngmem.c + (Cosmin). + Removed some spurious assignments in pngrutil.c (Cosmin). + Replaced 65536 with 65536L, and 0xffff with 0xffffL, to silence warnings + on 16-bit platforms (Cosmin). + Enclosed shift op expressions in parentheses, to silence warnings (Cosmin). + Used proper type png_fixed_point, to avoid problems on 16-bit platforms, + in png_handle_sRGB() (Cosmin). + Added compression_type to png_struct, and optimized the window size + inside the deflate stream (Cosmin). + Fixed definition of isnonalpha(), in pngerror.c and pngrutil.c (Cosmin). + Fixed handling of unknown chunks that come after IDAT (Cosmin). + Allowed png_error() and png_warning() to work even if png_ptr == NULL + (Cosmin). + Replaced row_info->rowbytes with row_bytes in png_write_find_filter() + (Cosmin). + Fixed definition of PNG_LIBPNG_VER_DLLNUM (Simon-Pierre). + Used PNG_LIBPNG_VER and PNG_LIBPNG_VER_STRING instead of the hardcoded + values in png.c (Simon-Pierre, Cosmin). + Initialized png_libpng_ver[] with PNG_LIBPNG_VER_STRING (Simon-Pierre). + Replaced PNG_LIBPNG_VER_MAJOR with PNG_LIBPNG_VER_DLLNUM in png.rc + (Simon-Pierre). + Moved the definition of PNG_HEADER_VERSION_STRING near the definitions + of the other PNG_LIBPNG_VER_... symbols in png.h (Cosmin). + Relocated #ifndef PNGAPI guards in pngconf.h (Simon-Pierre, Cosmin). + Updated scripts/makefile.vc(a)win32 (Cosmin). + Updated the MSVC project (Simon-Pierre, Cosmin). + Updated the Borland C++ Builder project (Cosmin). + Avoided access to asm_flags in pngvcrd.c, if PNG_1_0_X is defined (Cosmin). + Commented out warning about uninitialized mmx_support in pngvcrd.c (Cosmin). + Removed scripts/makefile.bd32 and scripts/pngdef.pas (Cosmin). + Added extra guard around inclusion of Turbo C memory headers, in pngconf.h + (Cosmin). + Renamed projects/msvc/ to projects/visualc6/, and projects/borland/ to + projects/cbuilder5/ (Cosmin). + Moved projects/visualc6/png32ms.def to scripts/pngw32.def, + and projects/visualc6/png.rc to scripts/pngw32.rc (Cosmin). + Added projects/visualc6/pngtest.dsp; removed contrib/msvctest/ (Cosmin). + Changed line endings to DOS style in cbuilder5 and visualc6 files, even + in the tar.* distributions (Cosmin). + Updated contrib/visupng/VisualPng.dsp (Cosmin). + Updated contrib/visupng/cexcept.h to version 2.0.0 (Cosmin). + Added a separate distribution with "configure" and supporting files (Junichi). +version 1.2.6beta4 [July 28, 2004] + Added user ability to change png_size_t via a PNG_SIZE_T macro. + Added png_sizeof() and png_convert_size() functions. + Added PNG_SIZE_MAX (maximum value of a png_size_t variable. + Added check in png_malloc_default() for (size_t)size != (png_uint_32)size + which would indicate an overflow. + Changed sPLT failure action from png_error to png_warning and abandon chunk. + Changed sCAL and iCCP failures from png_error to png_warning and abandon. + Added png_get_uint_31(png_ptr, buf) function. + Added PNG_UINT_32_MAX macro. + Renamed PNG_MAX_UINT to PNG_UINT_31_MAX. + Made png_zalloc() issue a png_warning and return NULL on potential + overflow. + Turn on PNG_NO_ZALLOC_ZERO by default in version 1.2.x + Revised "clobber list" in pnggccrd.c so it will compile under gcc-3.4. + Revised Borland portion of png_malloc() to return NULL or issue + png_error() according to setting of PNG_FLAG_MALLOC_NULL_MEM_OK. + Added PNG_NO_SEQUENTIAL_READ_SUPPORTED macro to conditionally remove + sequential read support. + Added some "#if PNG_WRITE_SUPPORTED" blocks. + #ifdef'ed out some redundancy in png_malloc_default(). + Use png_malloc instead of png_zalloc to allocate the pallete. +version 1.0.16rc1 and 1.2.6rc1 [August 4, 2004] + Fixed buffer overflow vulnerability in png_handle_tRNS() + Fixed integer arithmetic overflow vulnerability in png_read_png(). + Fixed some harmless bugs in png_handle_sBIT, etc, that would cause + duplicate chunk types to go undetected. + Fixed some timestamps in the -config version + Rearranged order of processing of color types in png_handle_tRNS(). + Added ROWBYTES macro to calculate rowbytes without integer overflow. + Updated makefile.darwin and removed makefile.macosx from scripts directory. + Imposed default one million column, one-million row limits on the image + dimensions, and added png_set_user_limits() function to override them. + Revised use of PNG_SET_USER_LIMITS_SUPPORTED macro. + Fixed wrong cast of returns from png_get_user_width|height_max(). + Changed some "keep the compiler happy" from empty statements to returns, + Revised libpng.txt to remove 1.2.x stuff from the 1.0.x distribution +version 1.0.16rc2 and 1.2.6rc2 [August 7, 2004] + Revised makefile.darwin and makefile.solaris. Removed makefile.macosx. + Revised pngtest's png_debug_malloc() to use png_malloc() instead of + png_malloc_default() which is not supposed to be exported. + Fixed off-by-one error in one of the conversions to PNG_ROWBYTES() in + pngpread.c. Bug was introduced in 1.2.6rc1. + Fixed bug in RGB to RGBX transformation introduced in 1.2.6rc1. + Fixed old bug in RGB to Gray transformation. + Fixed problem with 64-bit compilers by casting arguments to abs() + to png_int_32. + Changed "ln -sf" to "ln -f -s" in three makefiles (solaris, sco, so9). + Changed "HANDLE_CHUNK_*" to "PNG_HANDLE_CHUNK_*" (Cosmin) + Added "-@/bin/rm -f $(DL)/$(LIBNAME).so.$(PNGMAJ)" to 15 *NIX makefiles. + Added code to update the row_info->colortype in png_do_read_filler() (MSB). +version 1.0.16rc3 and 1.2.6rc3 [August 9, 2004] + Eliminated use of "abs()" in testing cHRM and gAMA values, to avoid + trouble with some 64-bit compilers. Created PNG_OUT_OF_RANGE() macro. + Revised documentation of png_set_keep_unknown_chunks(). + Check handle_as_unknown status in pngpread.c, as in pngread.c previously. + Moved "PNG_HANDLE_CHUNK_*" macros out of PNG_INTERNAL section of png.h + Added "rim" definitions for CONST4 and CONST6 in pnggccrd.c +version 1.0.16rc4 and 1.2.6rc4 [August 10, 2004] + Fixed mistake in pngtest.c introduced in 1.2.6rc2 (declaration of + "pinfo" was out of place). +version 1.0.16rc5 and 1.2.6rc5 [August 10, 2004] + Moved "PNG_HANDLE_CHUNK_*" macros out of PNG_ASSEMBLER_CODE_SUPPORTED + section of png.h where they were inadvertently placed in version rc3. + +version 1.0.16 and 1.2.6 [August 15, 2004] + Revised pngtest so memory allocation testing is only done when PNG_DEBUG==1. +version 1.2.7beta1 [August 26, 2004] + Removed unused pngasmrd.h file. + Removed references to uu.net for archived files. Added references to + PNG Spec (second edition) and the PNG ISO/IEC Standard. + Added "test-dd" target in 15 makefiles, to run pngtest in DESTDIR. + Fixed bug with "optimized window size" in the IDAT datastream, that + causes libpng to write PNG files with incorrect zlib header bytes. +version 1.2.7beta2 [August 28, 2004] + Fixed bug with sCAL chunk and big-endian machines (David Munro). + Undid new code added in 1.2.6rc2 to update the color_type in + png_set_filler(). + Added png_set_add_alpha() that updates color type. +version 1.0.17rc1 and 1.2.7rc1 [September 4, 2004] + Revised png_set_strip_filler() to not remove alpha if color_type has alpha. +version 1.0.17 and 1.2.7 [September 12, 2004] + Added makefile.hp64 + Changed projects/msvc/png32ms.def to scripts/png32ms.def in makefile.cygwin + +Send comments/corrections/commendations to +png-implement@ccrc.wustl.edu (subscription required; write to +majordomo@ccrc.wustl.edu with "subscribe png-implement" in the message) +or to glennrp@users.sourceforge.net + +Glenn R-P diff --git a/SlnkDWFImpl/CxImage/png/INSTALL b/SlnkDWFImpl/CxImage/png/INSTALL new file mode 100644 index 0000000..4892cd8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/INSTALL @@ -0,0 +1,167 @@ + +Installing libpng version 1.2.7 - September 12, 2004 + +Before installing libpng, you must first install zlib. zlib +can usually be found wherever you got libpng. zlib can be +placed in another directory, at the same level as libpng. +Note that your system might already have a preinstalled +zlib, but you will still need to have access to the +zlib.h and zconf.h include files that correspond to the +version of zlib that's installed. + +You can rename the directories that you downloaded (they +might be called "libpng-1.2.7" or "lpng109" and "zlib-1.2.1" +or "zlib121") so that you have directories called "zlib" and "libpng". + +Your directory structure should look like this: + + .. (the parent directory) + libpng (this directory) + INSTALL (this file) + README + *.h + *.c + contrib + gregbook + pngminus + pngsuite + visupng + projects + beos + c5builder (Borland) + visualc6 (msvc) + netware.txt + wince.txt + scripts + makefile.* + pngtest.png + etc. + zlib + README + *.h + *.c + contrib + etc. + +If the line endings in the files look funny, you may wish to get the other +distribution of libpng. It is available in both tar.gz (UNIX style line +endings) and zip (DOS style line endings) formats. + + +If you are building libpng with MSVC, you can enter the +libpng projects\visualc6 directory and follow the instructions in +projects\visualc6\README.txt. + +You can build libpng for WindowsCE by downloading and installing +the projects\wince directory as instructed in the projects\wince.txt file, and +then following the instructions in the README* files. Similarly, you can +build libpng for Netware or Beos as instructed in projects\netware.txt +or projects\beos. + +Else enter the zlib directory and follow the instructions in zlib/README, +then come back here and choose the appropriate makefile.sys in the scripts +directory. + +The files that are presently available in the scripts directory +include + + makefile.std => Generic UNIX makefile (cc, creates static libpng.a) + makefile.linux => Linux/ELF makefile + (gcc, creates libpng12.so.0.1.2.7) + makefile.gcmmx => Linux/ELF makefile + (gcc, creates libpng12.so.0.1.2.7, + uses assembler code tuned for Intel MMX platform) + makefile.gcc => Generic makefile (gcc, creates static libpng.a) + makefile.knr => Archaic UNIX Makefile that converts files with + ansi2knr (Requires ansi2knr.c from + ftp://ftp.cs.wisc.edu/ghost) + makefile.aix => AIX/gcc makefile + makefile.cygwin => Cygwin/gcc makefile + makefile.darwin => Darwin makefile, can use on MacosX + makefile.dec => DEC Alpha UNIX makefile + makefile.freebsd => FreeBSD makefile + makefile.hpgcc => HPUX makefile using gcc + makefile.hpux => HPUX (10.20 and 11.00) makefile + makefile.hp64 => HPUX (10.20 and 11.00) makefile, 64-bit + makefile.ibmc => IBM C/C++ version 3.x for Win32 and OS/2 (static) + makefile.intel => Intel C/C++ version 4.0 and later + libpng.icc => Project file for IBM VisualAge/C++ version 4.0 or later + makefile.netbsd => NetBSD/cc makefile, uses PNGGCCRD, makes libpng.so. + makefile.ne12bsd => NetBSD/cc makefile, uses PNGGCCRD, + makes libpng12.so + makefile.openbsd => OpenBSD makefile + makefile.sgi => Silicon Graphics IRIX makefile (cc, creates static lib) + makefile.sggcc => Silicon Graphics (gcc, + creates libpng12.so.0.1.2.7) + makefile.sunos => Sun makefile + makefile.solaris => Solaris 2.X makefile (gcc, + creates libpng12.so.0.1.2.7) + makefile.so9 => Solaris 9 makefile (gcc, + creates libpng12.so.0.1.2.7) + makefile.32sunu => Sun Ultra 32-bit makefile + makefile.64sunu => Sun Ultra 64-bit makefile + makefile.sco => For SCO OSr5 ELF and Unixware 7 with Native cc + makefile.mips => MIPS makefile + makefile.acorn => Acorn makefile + makefile.amiga => Amiga makefile + smakefile.ppc => AMIGA smakefile for SAS C V6.58/7.00 PPC compiler + (Requires SCOPTIONS, copied from scripts/SCOPTIONS.ppc) + makefile.atari => Atari makefile + makefile.beos => BEOS makefile for X86 + makefile.bor => Borland makefile (uses bcc) + makefile.bc32 => 32-bit Borland C++ (all modules compiled in C mode) + makefile.tc3 => Turbo C 3.0 makefile + makefile.dj2 => DJGPP 2 makefile + makefile.msc => Microsoft C makefile + makefile.vcawin32 => makefile for Microsoft Visual C++ 5.0 and later (uses + assembler code tuned for Intel MMX platform) + makefile.vcwin32 => makefile for Microsoft Visual C++ 4.0 and later (does + not use assembler code) + makefile.os2 => OS/2 Makefile (gcc and emx, requires pngos2.def) + pngos2.def => OS/2 module definition file used by makefile.os2 + makefile.watcom => Watcom 10a+ Makefile, 32-bit flat memory model + makevms.com => VMS build script + descrip.mms => VMS makefile for MMS or MMK + SCOPTIONS.ppc => Used with smakefile.ppc + +Copy the file (or files) that you need from the +scripts directory into this directory, for example + + MSDOS example: copy scripts\makefile.msc makefile + UNIX example: cp scripts/makefile.std makefile + +Read the makefile to see if you need to change any source or +target directories to match your preferences. + +Then read pngconf.h to see if you want to make any configuration +changes. + +Then just run "make" which will create the libpng library in +this directory and "make test" which will run a quick test that reads +the "pngtest.png" file and writes a "pngout.png" file that should be +identical to it. Look for "9782 zero samples" in the output of the +test. For more confidence, you can run another test by typing +"pngtest pngnow.png" and looking for "289 zero samples" in the output. +Also, you can run "pngtest -m contrib/pngsuite/*.png" and compare +your output with the result shown in contrib/pngsuite/README. + +Most of the makefiles will allow you to run "make install" to +put the library in its final resting place (if you want to +do that, run "make install" in the zlib directory first if necessary). +Some also allow you to run "make test-installed" after you have +run "make install". + +If you encounter a compiler error message complaining about the +lines + __png.h__ already includes setjmp.h; + __dont__ include it again.; +This means you have compiled another module that includes setjmp.h, +which is hazardous because the two modules might not include exactly +the same setjmp.h. If you are sure that you know what you are doing +and that they are exactly the same, then you can comment out or +delete the two lines. Better yet, use the cexcept interface +instead, as demonstrated in contrib/visupng of the libpng distribution. + +Further information can be found in the README and libpng.txt +files, in the individual makefiles, in png.h, and the manual pages +libpng.3 and png.5. diff --git a/SlnkDWFImpl/CxImage/png/KNOWNBUG b/SlnkDWFImpl/CxImage/png/KNOWNBUG new file mode 100644 index 0000000..0e874c7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/KNOWNBUG @@ -0,0 +1,11 @@ + +Known bugs in libpng version 1.2.7 + +1. April 22, 2001: pnggccrd.c has been reported to crash on NetBSD when + reading interlaced PNG files, when assembler code is enabled but running + on a non-MMX i386 platform. + + STATUS: Under investigation. The change to pnggccrd.c in libpng-1.2.1 + fixed a problem under FreeBSD but not the problem with NetBSD, which + still fails as of libpng-1.2.2rc1. + diff --git a/SlnkDWFImpl/CxImage/png/LICENSE b/SlnkDWFImpl/CxImage/png/LICENSE new file mode 100644 index 0000000..f0bf72c --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/LICENSE @@ -0,0 +1,109 @@ + +This copy of the libpng notices is provided for your convenience. In case of +any discrepancy between this copy and the notices in the file png.h that is +included in the libpng distribution, the latter shall prevail. + +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: + +If you modify libpng you may insert additional notices immediately following +this sentence. + +libpng version 1.2.6, September 12, 2004, is +Copyright (c) 2004 Glenn Randers-Pehrson, and is +distributed according to the same disclaimer and license as libpng-1.2.5 +with the following individual added to the list of Contributing Authors + + Cosmin Truta + +libpng versions 1.0.7, July 1, 2000, through 1.2.5 - October 3, 2002, are +Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are +distributed according to the same disclaimer and license as libpng-1.0.6 +with the following individuals added to the list of Contributing Authors + + Simon-Pierre Cadieux + Eric S. Raymond + Gilles Vollant + +and with the following additions to the disclaimer: + + There is no warranty against interference with your enjoyment of the + library or against infringement. There is no warranty that our + efforts or the library will fulfill any of your particular purposes + or needs. This library is provided with all faults, and the entire + risk of satisfactory quality, performance, accuracy, and effort is with + the user. + +libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are +Copyright (c) 1998, 1999 Glenn Randers-Pehrson, and are +distributed according to the same disclaimer and license as libpng-0.96, +with the following individuals added to the list of Contributing Authors: + + Tom Lane + Glenn Randers-Pehrson + Willem van Schaik + +libpng versions 0.89, June 1996, through 0.96, May 1997, are +Copyright (c) 1996, 1997 Andreas Dilger +Distributed according to the same disclaimer and license as libpng-0.88, +with the following individuals added to the list of Contributing Authors: + + John Bowler + Kevin Bracey + Sam Bushell + Magnus Holmgren + Greg Roelofs + Tom Tanner + +libpng versions 0.5, May 1995, through 0.88, January 1996, are +Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. + +For the purposes of this copyright and license, "Contributing Authors" +is defined as the following set of individuals: + + Andreas Dilger + Dave Martindale + Guy Eric Schalnat + Paul Schmidt + Tim Wegner + +The PNG Reference Library is supplied "AS IS". The Contributing Authors +and Group 42, Inc. disclaim all warranties, expressed or implied, +including, without limitation, the warranties of merchantability and of +fitness for any purpose. The Contributing Authors and Group 42, Inc. +assume no liability for direct, indirect, incidental, special, exemplary, +or consequential damages, which may result from the use of the PNG +Reference Library, even if advised of the possibility of such damage. + +Permission is hereby granted to use, copy, modify, and distribute this +source code, or portions hereof, for any purpose, without fee, subject +to the following restrictions: + +1. The origin of this source code must not be misrepresented. + +2. Altered versions must be plainly marked as such and must not + be misrepresented as being the original source. + +3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + +The Contributing Authors and Group 42, Inc. specifically permit, without +fee, and encourage the use of this source code as a component to +supporting the PNG file format in commercial products. If you use this +source code in a product, acknowledgment is not required but would be +appreciated. + + +A "png_get_copyright" function is available, for convenient use in "about" +boxes and the like: + + printf("%s",png_get_copyright(NULL)); + +Also, the PNG logo (in PNG format, of course) is supplied in the +files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31). + +Libpng is OSI Certified Open Source Software. OSI Certified Open Source is a +certification mark of the Open Source Initiative. + +Glenn Randers-Pehrson +glennrp@users.sourceforge.net +September 12, 2004 diff --git a/SlnkDWFImpl/CxImage/png/README b/SlnkDWFImpl/CxImage/png/README new file mode 100644 index 0000000..31fd2e7 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/README @@ -0,0 +1,260 @@ +README for libpng version 1.2.7 - September 12, 2004 (shared library 12.0) +See the note about version numbers near the top of png.h + +See INSTALL for instructions on how to install libpng. + +Libpng comes in several distribution formats. Get libpng-*.tar.gz +or libpng-*.tar.bz2 if you want UNIX-style line endings in the text +files, or lpng*.zip if you want DOS-style line endings. + +Version 0.89 was the first official release of libpng. Don't let the +fact that it's the first release fool you. The libpng library has been in +extensive use and testing since mid-1995. By late 1997 it had +finally gotten to the stage where there hadn't been significant +changes to the API in some time, and people have a bad feeling about +libraries with versions < 1.0. Version 1.0.0 was released in +March 1998. + +**** +Note that some of the changes to the png_info structure render this +version of the library binary incompatible with libpng-0.89 or +earlier versions if you are using a shared library. The type of the +"filler" parameter for png_set_filler() has changed from png_byte to +png_uint_32, which will affect shared-library applications that use +this function. + +To avoid problems with changes to the internals of png_info_struct, +new APIs have been made available in 0.95 to avoid direct application +access to info_ptr. These functions are the png_set_ and +png_get_ functions. These functions should be used when +accessing/storing the info_struct data, rather than manipulating it +directly, to avoid such problems in the future. + +It is important to note that the APIs do not make current programs +that access the info struct directly incompatible with the new +library. However, it is strongly suggested that new programs use +the new APIs (as shown in example.c and pngtest.c), and older programs +be converted to the new format, to facilitate upgrades in the future. +**** + +Additions since 0.90 include the ability to compile libpng as a +Windows DLL, and new APIs for accessing data in the info struct. +Experimental functions include the ability to set weighting and cost +factors for row filter selection, direct reads of integers from buffers +on big-endian processors that support misaligned data access, faster +methods of doing alpha composition, and more accurate 16->8 bit color +conversion. + +The additions since 0.89 include the ability to read from a PNG stream +which has had some (or all) of the signature bytes read by the calling +application. This also allows the reading of embedded PNG streams that +do not have the PNG file signature. As well, it is now possible to set +the library action on the detection of chunk CRC errors. It is possible +to set different actions based on whether the CRC error occurred in a +critical or an ancillary chunk. + +The changes made to the library, and bugs fixed are based on discussions +on the PNG-implement mailing list +and not on material submitted privately to Guy, Andreas, or Glenn. They will +forward any good suggestions to the list. + +For a detailed description on using libpng, read libpng.txt. For +examples of libpng in a program, see example.c and pngtest.c. For usage +information and restrictions (what little they are) on libpng, see +png.h. For a description on using zlib (the compression library used by +libpng) and zlib's restrictions, see zlib.h + +I have included a general makefile, as well as several machine and +compiler specific ones, but you may have to modify one for your own needs. + +You should use zlib 1.0.4 or later to run this, but it MAY work with +versions as old as zlib 0.95. Even so, there are bugs in older zlib +versions which can cause the output of invalid compression streams for +some images. You will definitely need zlib 1.0.4 or later if you are +taking advantage of the MS-DOS "far" structure allocation for the small +and medium memory models. You should also note that zlib is a +compression library that is useful for more things than just PNG files. +You can use zlib as a drop-in replacement for fread() and fwrite() if +you are so inclined. + +zlib should be available at the same place that libpng is, or at. +ftp://ftp.info-zip.org/pub/infozip/zlib + +You may also want a copy of the PNG specification. It is available +as an RFC, a W3C Recommendation, and an ISO/IEC Standard. You can find +these at http://www.libpng.org/pub/png/documents/ + +This code is currently being archived at libpng.sf.net in the +[DOWNLOAD] area, and on CompuServe, Lib 20 (PNG SUPPORT) +at GO GRAPHSUP. If you can't find it in any of those places, +e-mail me, and I'll help you find it. + +If you have any code changes, requests, problems, etc., please e-mail +them to me. Also, I'd appreciate any make files or project files, +and any modifications you needed to make to get libpng to compile, +along with a #define variable to tell what compiler/system you are on. +If you needed to add transformations to libpng, or wish libpng would +provide the image in a different way, drop me a note (and code, if +possible), so I can consider supporting the transformation. +Finally, if you get any warning messages when compiling libpng +(note: not zlib), and they are easy to fix, I'd appreciate the +fix. Please mention "libpng" somewhere in the subject line. Thanks. + +This release was created and will be supported by myself (of course +based in a large way on Guy's and Andreas' earlier work), and the PNG group. + +glennrp@users.sourceforge.net +png-implement@ccrc.wustl.edu (subscription required; write to +majordomo@ccrc.wustl.edu with "subscribe png-implement" in the message). + +You can't reach Guy, the original libpng author, at the addresses +given in previous versions of this document. He and Andreas will read mail +addressed to the png-implement list, however. + +Please do not send general questions about PNG. Send them to +the (png-list@ccrc.wustl.edu, subscription required, write to +majordomo@ccrc.wustl.edu with "subscribe png-list" in your message). +On the other hand, +please do not send libpng questions to that address, send them to me +or to the png-implement list. I'll +get them in the end anyway. If you have a question about something +in the PNG specification that is related to using libpng, send it +to me. Send me any questions that start with "I was using libpng, +and ...". If in doubt, send questions to me. I'll bounce them +to others, if necessary. + +Please do not send suggestions on how to change PNG. We have +been discussing PNG for nine years now, and it is official and +finished. If you have suggestions for libpng, however, I'll +gladly listen. Even if your suggestion is not used immediately, +it may be used later. + +Files in this distribution: + + ANNOUNCE => Announcement of this version, with recent changes + CHANGES => Description of changes between libpng versions + KNOWNBUG => List of known bugs and deficiencies + LICENSE => License to use and redistribute libpng + README => This file + TODO => Things not implemented in the current library + Y2KINFO => Statement of Y2K compliance + example.c => Example code for using libpng functions + libpng.3 => manual page for libpng (includes libpng.txt) + libpng.txt => Description of libpng and its functions + libpngpf.3 => manual page for libpng's private functions + png.5 => manual page for the PNG format + png.c => Basic interface functions common to library + png.h => Library function and interface declarations + pngconf.h => System specific library configuration + pngasmrd.h => Header file for assembler-coded functions + pngerror.c => Error/warning message I/O functions + pngget.c => Functions for retrieving info from struct + pngmem.c => Memory handling functions + pngbar.png => PNG logo, 88x31 + pngnow.png => PNG logo, 98x31 + pngpread.c => Progressive reading functions + pngread.c => Read data/helper high-level functions + pngrio.c => Lowest-level data read I/O functions + pngrtran.c => Read data transformation functions + pngrutil.c => Read data utility functions + pngset.c => Functions for storing data into the info_struct + pngtest.c => Library test program + pngtest.png => Library test sample image + pngtrans.c => Common data transformation functions + pngwio.c => Lowest-level write I/O functions + pngwrite.c => High-level write functions + pngwtran.c => Write data transformations + pngwutil.c => Write utility functions + contrib => Contributions + gregbook => source code for PNG reading and writing, from + Greg Roelofs' "PNG: The Definitive Guide", + O'Reilly, 1999 + msvctest => Builds and runs pngtest using a MSVC workspace + pngminus => Simple pnm2png and png2pnm programs + pngsuite => Test images + visupng => Contains a MSVC workspace for VisualPng + projects => Contains project files and workspaces for building DLL + beos => Contains a Beos workspace for building libpng + c5builder => Contains a Borland workspace for building libpng + and zlib + visualc6 => Contains a Microsoft Visual C++ (MSVC) workspace + for building libpng and zlib + netware.txt => Contains instructions for downloading a set of + project files for building libpng and zlib on + Netware. + wince.txt => Contains instructions for downloading a Microsoft + Visual C++ (Windows CD Toolkit) workspace for + building libpng and zlib on WindowsCE + scripts => Directory containing scripts for building libpng: + descrip.mms => VMS makefile for MMS or MMK + makefile.std => Generic UNIX makefile (cc, creates static libpng.a) + makefile.linux => Linux/ELF makefile + (gcc, creates libpng12.so.0.1.2.7) + makefile.gcmmx => Linux/ELF makefile + (gcc, creates libpng12.so.0.1.2.7, + uses assembler code tuned for Intel MMX platform) + makefile.gcc => Generic makefile (gcc, creates static libpng.a) + makefile.knr => Archaic UNIX Makefile that converts files with + ansi2knr (Requires ansi2knr.c from + ftp://ftp.cs.wisc.edu/ghost) + makefile.aix => AIX makefile + makefile.cygwin => Cygwin/gcc makefile + makefile.darwin => Darwin makefile + makefile.dec => DEC Alpha UNIX makefile + makefile.freebsd => FreeBSD makefile + makefile.hpgcc => HPUX makefile using gcc + makefile.hpux => HPUX (10.20 and 11.00) makefile + makefile.hp64 => HPUX (10.20 and 11.00) makefile, 64 bit + makefile.ibmc => IBM C/C++ version 3.x for Win32 and OS/2 (static) + makefile.intel => Intel C/C++ version 4.0 and later + libpng.icc => Project file, IBM VisualAge/C++ 4.0 or later + makefile.netbsd => NetBSD/cc makefile, PNGGCCRD, makes libpng.so. + makefile.ne12bsd => NetBSD/cc makefile, PNGGCCRD, makes libpng12.so + makefile.openbsd => OpenBSD makefile + makefile.sgi => Silicon Graphics IRIX (cc, creates static lib) + makefile.sggcc => Silicon Graphics + (gcc, creates libpng12.so.0.1.2.7) + makefile.sunos => Sun makefile + makefile.solaris => Solaris 2.X makefile + (gcc, creates libpng12.so.0.1.2.7) + makefile.so9 => Solaris 9 makefile + (gcc, creates libpng12.so.0.1.2.7) + makefile.32sunu => Sun Ultra 32-bit makefile + makefile.64sunu => Sun Ultra 64-bit makefile + makefile.sco => For SCO OSr5 ELF and Unixware 7 with Native cc + makefile.mips => MIPS makefile + makefile.acorn => Acorn makefile + makefile.amiga => Amiga makefile + smakefile.ppc => AMIGA smakefile for SAS C V6.58/7.00 PPC + compiler (Requires SCOPTIONS, copied from + scripts/SCOPTIONS.ppc) + makefile.atari => Atari makefile + makefile.beos => BEOS makefile for X86 + makefile.bor => Borland makefile (uses bcc) + makefile.bc32 => 32-bit Borland C++ (all modules compiled in C mode) + makefile.tc3 => Turbo C 3.0 makefile + makefile.dj2 => DJGPP 2 makefile + makefile.msc => Microsoft C makefile + makefile.vcawin32=> makefile for Microsoft Visual C++ 5.0 and + later (uses assembler code tuned for Intel MMX + platform) + makefile.vcwin32 => makefile for Microsoft Visual C++ 4.0 and + later (does not use assembler code) + makefile.os2 => OS/2 Makefile (gcc and emx, requires pngos2.def) + pngos2.def => OS/2 module definition file used by makefile.os2 + makefile.watcom => Watcom 10a+ Makefile, 32-bit flat memory model + makevms.com => VMS build script + SCOPTIONS.ppc => Used with smakefile.ppc + +Good luck, and happy coding. + +-Glenn Randers-Pehrson (current maintainer) + Internet: glennrp@users.sourceforge.net + +-Andreas Eric Dilger (former maintainer, 1996-1997) + Internet: adilger@enel.ucalgary.ca + Web: http://www-mddsp.enel.ucalgary.ca/People/adilger/ + +-Guy Eric Schalnat (original author and former maintainer, 1995-1996) + (formerly of Group 42, Inc) + Internet: gschal@infinet.com diff --git a/SlnkDWFImpl/CxImage/png/TODO b/SlnkDWFImpl/CxImage/png/TODO new file mode 100644 index 0000000..90f945c --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/TODO @@ -0,0 +1,24 @@ +TODO - list of things to do for libpng: + +Final bug fixes. +Improve API by hiding the png_struct and png_info structs. +Finish work on the no-floating-point version (including gamma compensation) +Better C++ wrapper/full C++ implementation? +Fix problem with C++ and EXTERN "C". +cHRM transformation. +Improve setjmp/longjmp usage or remove it in favor of returning error codes. +Add "grayscale->palette" transformation and "palette->grayscale" detection. +Improved dithering. +Multi-lingual error and warning message support. +Complete sRGB transformation (presently it simply uses gamma=0.45455). +Man pages for function calls. +Better documentation. +Better filter selection + (counting huffman bits/precompression? filter inertia? filter costs?). +Histogram creation. +Text conversion between different code pages (Latin-1 -> Mac and DOS). +Should we always malloc 2^bit_depth PLTE/tRNS/hIST entries for safety? +Build gamma tables using fixed point (and do away with floating point entirely). +Use greater precision when changing to linear gamma for compositing against + background and doing rgb-to-gray transformation. +Investigate pre-incremented loop counters and other loop constructions. diff --git a/SlnkDWFImpl/CxImage/png/Y2KINFO b/SlnkDWFImpl/CxImage/png/Y2KINFO new file mode 100644 index 0000000..c80a679 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/Y2KINFO @@ -0,0 +1,55 @@ + Y2K compliance in libpng: + ========================= + + September 12, 2004 + + Since the PNG Development group is an ad-hoc body, we can't make + an official declaration. + + This is your unofficial assurance that libpng from version 0.71 and + upward through 1.2.7 are Y2K compliant. It is my belief that earlier + versions were also Y2K compliant. + + Libpng only has three year fields. One is a 2-byte unsigned integer + that will hold years up to 65535. The other two hold the date in text + format, and will hold years up to 9999. + + The integer is + "png_uint_16 year" in png_time_struct. + + The strings are + "png_charp time_buffer" in png_struct and + "near_time_buffer", which is a local character string in png.c. + + There are seven time-related functions: + + png_convert_to_rfc_1123() in png.c + (formerly png_convert_to_rfc_1152() in error) + png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c + png_convert_from_time_t() in pngwrite.c + png_get_tIME() in pngget.c + png_handle_tIME() in pngrutil.c, called in pngread.c + png_set_tIME() in pngset.c + png_write_tIME() in pngwutil.c, called in pngwrite.c + + All appear to handle dates properly in a Y2K environment. The + png_convert_from_time_t() function calls gmtime() to convert from system + clock time, which returns (year - 1900), which we properly convert to + the full 4-digit year. There is a possibility that applications using + libpng are not passing 4-digit years into the png_convert_to_rfc_1123() + function, or that they are incorrectly passing only a 2-digit year + instead of "year - 1900" into the png_convert_from_struct_tm() function, + but this is not under our control. The libpng documentation has always + stated that it works with 4-digit years, and the APIs have been + documented as such. + + The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned + integer to hold the year, and can hold years as large as 65535. + + zlib, upon which libpng depends, is also Y2K compliant. It contains + no date-related code. + + + Glenn Randers-Pehrson + libpng maintainer + PNG Development Group diff --git a/SlnkDWFImpl/CxImage/png/configure b/SlnkDWFImpl/CxImage/png/configure new file mode 100644 index 0000000..59ab0e6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/configure @@ -0,0 +1,13 @@ +#!/bin/sh +echo " + There is no \"configure\" script in this distribution of + libpng-1.2.7. + + Instead, please copy the appropriate makefile for your system from the + \"scripts\" directory. Read the INSTALL file for more details. + + Update, July 2004: you can get a "configure" based distribution + from the libpng distribution sites. Download the file + libpng-1.2.7-config.tar.gz +" + diff --git a/SlnkDWFImpl/CxImage/png/libpng.txt b/SlnkDWFImpl/CxImage/png/libpng.txt new file mode 100644 index 0000000..c684d6a --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/libpng.txt @@ -0,0 +1,2958 @@ +libpng.txt - A description on how to use and modify libpng + + libpng version 1.2.7 - September 12, 2004 + Updated and distributed by Glenn Randers-Pehrson + + Copyright (c) 1998-2004 Glenn Randers-Pehrson + For conditions of distribution and use, see copyright + notice in png.h. + + based on: + + libpng 1.0 beta 6 version 0.96 May 28, 1997 + Updated and distributed by Andreas Dilger + Copyright (c) 1996, 1997 Andreas Dilger + + libpng 1.0 beta 2 - version 0.88 January 26, 1996 + For conditions of distribution and use, see copyright + notice in png.h. Copyright (c) 1995, 1996 Guy Eric + Schalnat, Group 42, Inc. + + Updated/rewritten per request in the libpng FAQ + Copyright (c) 1995, 1996 Frank J. T. Wojcik + December 18, 1995 & January 20, 1996 + +I. Introduction + +This file describes how to use and modify the PNG reference library +(known as libpng) for your own use. There are five sections to this +file: introduction, structures, reading, writing, and modification and +configuration notes for various special platforms. In addition to this +file, example.c is a good starting point for using the library, as +it is heavily commented and should include everything most people +will need. We assume that libpng is already installed; see the +INSTALL file for instructions on how to install libpng. + +Libpng was written as a companion to the PNG specification, as a way +of reducing the amount of time and effort it takes to support the PNG +file format in application programs. + +The PNG specification (second edition), November 2003, is available as +a W3C Recommendation and as an ISO Standard (ISO/IEC 15948:2003 (E)) at + + +The PNG-1.0 specification is available +as RFC 2083 and as a +W3C Recommendation . Some +additional chunks are described in the special-purpose public chunks +documents at . + +Other information +about PNG, and the latest version of libpng, can be found at the PNG home +page, . + +Most users will not have to modify the library significantly; advanced +users may want to modify it more. All attempts were made to make it as +complete as possible, while keeping the code easy to understand. +Currently, this library only supports C. Support for other languages +is being considered. + +Libpng has been designed to handle multiple sessions at one time, +to be easily modifiable, to be portable to the vast majority of +machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy +to use. The ultimate goal of libpng is to promote the acceptance of +the PNG file format in whatever way possible. While there is still +work to be done (see the TODO file), libpng should cover the +majority of the needs of its users. + +Libpng uses zlib for its compression and decompression of PNG files. +Further information about zlib, and the latest version of zlib, can +be found at the zlib home page, . +The zlib compression utility is a general purpose utility that is +useful for more than PNG files, and can be used without libpng. +See the documentation delivered with zlib for more details. +You can usually find the source files for the zlib utility wherever you +find the libpng source files. + +Libpng is thread safe, provided the threads are using different +instances of the structures. Each thread should have its own +png_struct and png_info instances, and thus its own image. +Libpng does not protect itself against two threads using the +same instance of a structure. Note: thread safety may be defeated +by use of some of the MMX assembler code in pnggccrd.c, which is only +compiled when the user defines PNG_THREAD_UNSAFE_OK. + +II. Structures + +There are two main structures that are important to libpng, png_struct +and png_info. The first, png_struct, is an internal structure that +will not, for the most part, be used by a user except as the first +variable passed to every libpng function call. + +The png_info structure is designed to provide information about the +PNG file. At one time, the fields of png_info were intended to be +directly accessible to the user. However, this tended to cause problems +with applications using dynamically loaded libraries, and as a result +a set of interface functions for png_info (the png_get_*() and png_set_*() +functions) was developed. The fields of png_info are still available for +older applications, but it is suggested that applications use the new +interfaces if at all possible. + +Applications that do make direct access to the members of png_struct (except +for png_ptr->jmpbuf) must be recompiled whenever the library is updated, +and applications that make direct access to the members of png_info must +be recompiled if they were compiled or loaded with libpng version 1.0.6, +in which the members were in a different order. In version 1.0.7, the +members of the png_info structure reverted to the old order, as they were +in versions 0.97c through 1.0.5. Starting with version 2.0.0, both +structures are going to be hidden, and the contents of the structures will +only be accessible through the png_get/png_set functions. + +The png.h header file is an invaluable reference for programming with libpng. +And while I'm on the topic, make sure you include the libpng header file: + +#include + +III. Reading + +We'll now walk you through the possible functions to call when reading +in a PNG file sequentially, briefly explaining the syntax and purpose +of each one. See example.c and png.h for more detail. While +progressive reading is covered in the next section, you will still +need some of the functions discussed in this section to read a PNG +file. + +Setup + +You will want to do the I/O initialization(*) before you get into libpng, +so if it doesn't work, you don't have much to undo. Of course, you +will also want to insure that you are, in fact, dealing with a PNG +file. Libpng provides a simple check to see if a file is a PNG file. +To use it, pass in the first 1 to 8 bytes of the file to the function +png_sig_cmp(), and it will return 0 if the bytes match the corresponding +bytes of the PNG signature, or nonzero otherwise. Of course, the more bytes +you pass in, the greater the accuracy of the prediction. + +If you are intending to keep the file pointer open for use in libpng, +you must ensure you don't read more than 8 bytes from the beginning +of the file, and you also have to make a call to png_set_sig_bytes_read() +with the number of bytes you read from the beginning. Libpng will +then only check the bytes (if any) that your program didn't read. + +(*): If you are not using the standard I/O functions, you will need +to replace them with custom functions. See the discussion under +Customizing libpng. + + + FILE *fp = fopen(file_name, "rb"); + if (!fp) + { + return (ERROR); + } + fread(header, 1, number, fp); + is_png = !png_sig_cmp(header, 0, number); + if (!is_png) + { + return (NOT_PNG); + } + + +Next, png_struct and png_info need to be allocated and initialized. In +order to ensure that the size of these structures is correct even with a +dynamically linked libpng, there are functions to initialize and +allocate the structures. We also pass the library version, optional +pointers to error handling functions, and a pointer to a data struct for +use by the error functions, if necessary (the pointer and functions can +be NULL if the default error handlers are to be used). See the section +on Changes to Libpng below regarding the old initialization functions. +The structure allocation functions quietly return NULL if they fail to +create the structure, so your application should check for that. + + png_structp png_ptr = png_create_read_struct + (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr, + user_error_fn, user_warning_fn); + if (!png_ptr) + return (ERROR); + + png_infop info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr) + { + png_destroy_read_struct(&png_ptr, + (png_infopp)NULL, (png_infopp)NULL); + return (ERROR); + } + + png_infop end_info = png_create_info_struct(png_ptr); + if (!end_info) + { + png_destroy_read_struct(&png_ptr, &info_ptr, + (png_infopp)NULL); + return (ERROR); + } + +If you want to use your own memory allocation routines, +define PNG_USER_MEM_SUPPORTED and use +png_create_read_struct_2() instead of png_create_read_struct(): + + png_structp png_ptr = png_create_read_struct_2 + (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr, + user_error_fn, user_warning_fn, (png_voidp) + user_mem_ptr, user_malloc_fn, user_free_fn); + +The error handling routines passed to png_create_read_struct() +and the memory alloc/free routines passed to png_create_struct_2() +are only necessary if you are not using the libpng supplied error +handling and memory alloc/free functions. + +When libpng encounters an error, it expects to longjmp back +to your routine. Therefore, you will need to call setjmp and pass +your png_jmpbuf(png_ptr). If you read the file from different +routines, you will need to update the jmpbuf field every time you enter +a new routine that will call a png_*() function. + +See your documentation of setjmp/longjmp for your compiler for more +information on setjmp/longjmp. See the discussion on libpng error +handling in the Customizing Libpng section below for more information +on the libpng error handling. If an error occurs, and libpng longjmp's +back to your setjmp, you will want to call png_destroy_read_struct() to +free any memory. + + if (setjmp(png_jmpbuf(png_ptr))) + { + png_destroy_read_struct(&png_ptr, &info_ptr, + &end_info); + fclose(fp); + return (ERROR); + } + +If you would rather avoid the complexity of setjmp/longjmp issues, +you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case +errors will result in a call to PNG_ABORT() which defaults to abort(). + +Now you need to set up the input code. The default for libpng is to +use the C function fread(). If you use this, you will need to pass a +valid FILE * in the function png_init_io(). Be sure that the file is +opened in binary mode. If you wish to handle reading data in another +way, you need not call the png_init_io() function, but you must then +implement the libpng I/O methods discussed in the Customizing Libpng +section below. + + png_init_io(png_ptr, fp); + +If you had previously opened the file and read any of the signature from +the beginning in order to see if this was a PNG file, you need to let +libpng know that there are some bytes missing from the start of the file. + + png_set_sig_bytes(png_ptr, number); + +Setting up callback code + +You can set up a callback function to handle any unknown chunks in the +input stream. You must supply the function + + read_chunk_callback(png_ptr ptr, + png_unknown_chunkp chunk); + { + /* The unknown chunk structure contains your + chunk data: */ + png_byte name[5]; + png_byte *data; + png_size_t size; + /* Note that libpng has already taken care of + the CRC handling */ + + /* put your code here. Return one of the + following: */ + + return (-n); /* chunk had an error */ + return (0); /* did not recognize */ + return (n); /* success */ + } + +(You can give your function another name that you like instead of +"read_chunk_callback") + +To inform libpng about your function, use + + png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr, + read_chunk_callback); + +This names not only the callback function, but also a user pointer that +you can retrieve with + + png_get_user_chunk_ptr(png_ptr); + +At this point, you can set up a callback function that will be +called after each row has been read, which you can use to control +a progress meter or the like. It's demonstrated in pngtest.c. +You must supply a function + + void read_row_callback(png_ptr ptr, png_uint_32 row, + int pass); + { + /* put your code here */ + } + +(You can give it another name that you like instead of "read_row_callback") + +To inform libpng about your function, use + + png_set_read_status_fn(png_ptr, read_row_callback); + +Width and height limits + +The PNG specification allows the width and height of an image to be as +large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns. +Since very few applications really need to process such large images, +we have imposed an arbitrary 1-million limit on rows and columns. +Larger images will be rejected immediately with a png_error() call. If +you wish to override this limit, you can use + + png_set_user_limits(png_ptr, width_max, height_max); + +to set your own limits, or use width_max = height_max = 0x7fffffffL +to allow all valid dimensions (libpng may reject some very large images +anyway because of potential buffer overflow conditions). + +You should put this statement after you create the PNG structure and +before calling png_read_info(), png_read_png(), or png_process_data(). +If you need to retrieve the limits that are being applied, use + + width_max = png_get_user_width_max(png_ptr); + height_max = png_get_user_height_max(png_ptr); + +Unknown-chunk handling + +Now you get to set the way the library processes unknown chunks in the +input PNG stream. Both known and unknown chunks will be read. Normal +behavior is that known chunks will be parsed into information in +various info_ptr members; unknown chunks will be discarded. To change +this, you can call: + + png_set_keep_unknown_chunks(png_ptr, keep, + chunk_list, num_chunks); + keep - 0: do not handle as unknown + 1: do not keep + 2: keep only if safe-to-copy + 3: keep even if unsafe-to-copy + You can use these definitions: + PNG_HANDLE_CHUNK_AS_DEFAULT 0 + PNG_HANDLE_CHUNK_NEVER 1 + PNG_HANDLE_CHUNK_IF_SAFE 2 + PNG_HANDLE_CHUNK_ALWAYS 3 + chunk_list - list of chunks affected (a byte string, + five bytes per chunk, NULL or '\0' if + num_chunks is 0) + num_chunks - number of chunks affected; if 0, all + unknown chunks are affected. If nonzero, + only the chunks in the list are affected + +Unknown chunks declared in this way will be saved as raw data onto a +list of png_unknown_chunk structures. If a chunk that is normally +known to libpng is named in the list, it will be handled as unknown, +according to the "keep" directive. If a chunk is named in successive +instances of png_set_keep_unknown_chunks(), the final instance will +take precedence. The IHDR and IEND chunks should not be named in +chunk_list; if they are, libpng will process them normally anyway. + +The high-level read interface + +At this point there are two ways to proceed; through the high-level +read interface, or through a sequence of low-level read operations. +You can use the high-level interface if (a) you are willing to read +the entire image into memory, and (b) the input transformations +you want to do are limited to the following set: + + PNG_TRANSFORM_IDENTITY No transformation + PNG_TRANSFORM_STRIP_16 Strip 16-bit samples to + 8 bits + PNG_TRANSFORM_STRIP_ALPHA Discard the alpha channel + PNG_TRANSFORM_PACKING Expand 1, 2 and 4-bit + samples to bytes + PNG_TRANSFORM_PACKSWAP Change order of packed + pixels to LSB first + PNG_TRANSFORM_EXPAND Perform set_expand() + PNG_TRANSFORM_INVERT_MONO Invert monochrome images + PNG_TRANSFORM_SHIFT Normalize pixels to the + sBIT depth + PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA + to BGRA + PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA + to AG + PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity + to transparency + PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples + +(This excludes setting a background color, doing gamma transformation, +dithering, and setting filler.) If this is the case, simply do this: + + png_read_png(png_ptr, info_ptr, png_transforms, NULL) + +where png_transforms is an integer containing the logical OR of +some set of transformation flags. This call is equivalent to png_read_info(), +followed the set of transformations indicated by the transform mask, +then png_read_image(), and finally png_read_end(). + +(The final parameter of this call is not yet used. Someday it might point +to transformation parameters required by some future input transform.) + +You must use png_transforms and not call any png_set_transform() functions +when you use png_read_png(). + +After you have called png_read_png(), you can retrieve the image data +with + + row_pointers = png_get_rows(png_ptr, info_ptr); + +where row_pointers is an array of pointers to the pixel data for each row: + + png_bytep row_pointers[height]; + +If you know your image size and pixel size ahead of time, you can allocate +row_pointers prior to calling png_read_png() with + + if (height > PNG_UINT_32_MAX/png_sizeof(png_byte)) + png_error (png_ptr, + "Image is too tall to process in memory"); + if (width > PNG_UINT_32_MAX/pixel_size) + png_error (png_ptr, + "Image is too wide to process in memory"); + row_pointers = png_malloc(png_ptr, + height*png_sizeof(png_bytep)); + for (int i=0; i) and +png_get_(png_ptr, info_ptr, ...) functions return non-zero if the +data has been read, or zero if it is missing. The parameters to the +png_get_ are set directly if they are simple data types, or a pointer +into the info_ptr is returned for any complex types. + + png_get_PLTE(png_ptr, info_ptr, &palette, + &num_palette); + palette - the palette for the file + (array of png_color) + num_palette - number of entries in the palette + + png_get_gAMA(png_ptr, info_ptr, &gamma); + gamma - the gamma the file is written + at (PNG_INFO_gAMA) + + png_get_sRGB(png_ptr, info_ptr, &srgb_intent); + srgb_intent - the rendering intent (PNG_INFO_sRGB) + The presence of the sRGB chunk + means that the pixel data is in the + sRGB color space. This chunk also + implies specific values of gAMA and + cHRM. + + png_get_iCCP(png_ptr, info_ptr, &name, + &compression_type, &profile, &proflen); + name - The profile name. + compression - The compression type; always + PNG_COMPRESSION_TYPE_BASE for PNG 1.0. + You may give NULL to this argument to + ignore it. + profile - International Color Consortium color + profile data. May contain NULs. + proflen - length of profile data in bytes. + + png_get_sBIT(png_ptr, info_ptr, &sig_bit); + sig_bit - the number of significant bits for + (PNG_INFO_sBIT) each of the gray, + red, green, and blue channels, + whichever are appropriate for the + given color type (png_color_16) + + png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, + &trans_values); + trans - array of transparent entries for + palette (PNG_INFO_tRNS) + trans_values - graylevel or color sample values of + the single transparent color for + non-paletted images (PNG_INFO_tRNS) + num_trans - number of transparent entries + (PNG_INFO_tRNS) + + png_get_hIST(png_ptr, info_ptr, &hist); + (PNG_INFO_hIST) + hist - histogram of palette (array of + png_uint_16) + + png_get_tIME(png_ptr, info_ptr, &mod_time); + mod_time - time image was last modified + (PNG_VALID_tIME) + + png_get_bKGD(png_ptr, info_ptr, &background); + background - background color (PNG_VALID_bKGD) + valid 16-bit red, green and blue + values, regardless of color_type + + num_comments = png_get_text(png_ptr, info_ptr, + &text_ptr, &num_text); + num_comments - number of comments + text_ptr - array of png_text holding image + comments + text_ptr[i].compression - type of compression used + on "text" PNG_TEXT_COMPRESSION_NONE + PNG_TEXT_COMPRESSION_zTXt + PNG_ITXT_COMPRESSION_NONE + PNG_ITXT_COMPRESSION_zTXt + text_ptr[i].key - keyword for comment. Must contain + 1-79 characters. + text_ptr[i].text - text comments for current + keyword. Can be empty. + text_ptr[i].text_length - length of text string, + after decompression, 0 for iTXt + text_ptr[i].itxt_length - length of itxt string, + after decompression, 0 for tEXt/zTXt + text_ptr[i].lang - language of comment (empty + string for unknown). + text_ptr[i].lang_key - keyword in UTF-8 + (empty string for unknown). + num_text - number of comments (same as + num_comments; you can put NULL here + to avoid the duplication) + Note while png_set_text() will accept text, language, + and translated keywords that can be NULL pointers, the + structure returned by png_get_text will always contain + regular zero-terminated C strings. They might be + empty strings but they will never be NULL pointers. + + num_spalettes = png_get_sPLT(png_ptr, info_ptr, + &palette_ptr); + palette_ptr - array of palette structures holding + contents of one or more sPLT chunks + read. + num_spalettes - number of sPLT chunks read. + + png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y, + &unit_type); + offset_x - positive offset from the left edge + of the screen + offset_y - positive offset from the top edge + of the screen + unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER + + png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y, + &unit_type); + res_x - pixels/unit physical resolution in + x direction + res_y - pixels/unit physical resolution in + x direction + unit_type - PNG_RESOLUTION_UNKNOWN, + PNG_RESOLUTION_METER + + png_get_sCAL(png_ptr, info_ptr, &unit, &width, + &height) + unit - physical scale units (an integer) + width - width of a pixel in physical scale units + height - height of a pixel in physical scale units + (width and height are doubles) + + png_get_sCAL_s(png_ptr, info_ptr, &unit, &width, + &height) + unit - physical scale units (an integer) + width - width of a pixel in physical scale units + height - height of a pixel in physical scale units + (width and height are strings like "2.54") + + num_unknown_chunks = png_get_unknown_chunks(png_ptr, + info_ptr, &unknowns) + unknowns - array of png_unknown_chunk + structures holding unknown chunks + unknowns[i].name - name of unknown chunk + unknowns[i].data - data of unknown chunk + unknowns[i].size - size of unknown chunk's data + unknowns[i].location - position of chunk in file + + The value of "i" corresponds to the order in which the + chunks were read from the PNG file or inserted with the + png_set_unknown_chunks() function. + +The data from the pHYs chunk can be retrieved in several convenient +forms: + + res_x = png_get_x_pixels_per_meter(png_ptr, + info_ptr) + res_y = png_get_y_pixels_per_meter(png_ptr, + info_ptr) + res_x_and_y = png_get_pixels_per_meter(png_ptr, + info_ptr) + res_x = png_get_x_pixels_per_inch(png_ptr, + info_ptr) + res_y = png_get_y_pixels_per_inch(png_ptr, + info_ptr) + res_x_and_y = png_get_pixels_per_inch(png_ptr, + info_ptr) + aspect_ratio = png_get_pixel_aspect_ratio(png_ptr, + info_ptr) + + (Each of these returns 0 [signifying "unknown"] if + the data is not present or if res_x is 0; + res_x_and_y is 0 if res_x != res_y) + +The data from the oFFs chunk can be retrieved in several convenient +forms: + + x_offset = png_get_x_offset_microns(png_ptr, info_ptr); + y_offset = png_get_y_offset_microns(png_ptr, info_ptr); + x_offset = png_get_x_offset_inches(png_ptr, info_ptr); + y_offset = png_get_y_offset_inches(png_ptr, info_ptr); + + (Each of these returns 0 [signifying "unknown" if both + x and y are 0] if the data is not present or if the + chunk is present but the unit is the pixel) + +For more information, see the png_info definition in png.h and the +PNG specification for chunk contents. Be careful with trusting +rowbytes, as some of the transformations could increase the space +needed to hold a row (expand, filler, gray_to_rgb, etc.). +See png_read_update_info(), below. + +A quick word about text_ptr and num_text. PNG stores comments in +keyword/text pairs, one pair per chunk, with no limit on the number +of text chunks, and a 2^31 byte limit on their size. While there are +suggested keywords, there is no requirement to restrict the use to these +strings. It is strongly suggested that keywords and text be sensible +to humans (that's the point), so don't use abbreviations. Non-printing +symbols are not allowed. See the PNG specification for more details. +There is also no requirement to have text after the keyword. + +Keywords should be limited to 79 Latin-1 characters without leading or +trailing spaces, but non-consecutive spaces are allowed within the +keyword. It is possible to have the same keyword any number of times. +The text_ptr is an array of png_text structures, each holding a +pointer to a language string, a pointer to a keyword and a pointer to +a text string. The text string, language code, and translated +keyword may be empty or NULL pointers. The keyword/text +pairs are put into the array in the order that they are received. +However, some or all of the text chunks may be after the image, so, to +make sure you have read all the text chunks, don't mess with these +until after you read the stuff after the image. This will be +mentioned again below in the discussion that goes with png_read_end(). + +Input transformations + +After you've read the header information, you can set up the library +to handle any special transformations of the image data. The various +ways to transform the data will be described in the order that they +should occur. This is important, as some of these change the color +type and/or bit depth of the data, and some others only work on +certain color types and bit depths. Even though each transformation +checks to see if it has data that it can do something with, you should +make sure to only enable a transformation if it will be valid for the +data. For example, don't swap red and blue on grayscale data. + +The colors used for the background and transparency values should be +supplied in the same format/depth as the current image data. They +are stored in the same format/depth as the image data in a bKGD or tRNS +chunk, so this is what libpng expects for this data. The colors are +transformed to keep in sync with the image data when an application +calls the png_read_update_info() routine (see below). + +Data will be decoded into the supplied row buffers packed into bytes +unless the library has been told to transform it into another format. +For example, 4 bit/pixel paletted or grayscale data will be returned +2 pixels/byte with the leftmost pixel in the high-order bits of the +byte, unless png_set_packing() is called. 8-bit RGB data will be stored +in RGB RGB RGB format unless png_set_filler() or png_set_add_alpha() +is called to insert filler bytes, either before or after each RGB triplet. +16-bit RGB data will be returned RRGGBB RRGGBB, with the most significant +byte of the color value first, unless png_set_strip_16() is called to +transform it to regular RGB RGB triplets, or png_set_filler|add alpha() +is called to insert filler bytes, either before or after each RRGGBB +triplet. Similarly, 8-bit or 16-bit grayscale data can be modified with +png_set_filler(), png_set_add_alpha(), or png_set_strip_16(). + +The following code transforms grayscale images of less than 8 to 8 bits, +changes paletted images to RGB, and adds a full alpha channel if there is +transparency information in a tRNS chunk. This is most useful on +grayscale images with bit depths of 2 or 4 or if there is a multiple-image +viewing application that wishes to treat all images in the same way. + + if (color_type == PNG_COLOR_TYPE_PALETTE) + png_set_palette_to_rgb(png_ptr); + + if (color_type == PNG_COLOR_TYPE_GRAY && + bit_depth < 8) png_set_gray_1_2_4_to_8(png_ptr); + + if (png_get_valid(png_ptr, info_ptr, + PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr); + +These three functions are actually aliases for png_set_expand(), added +in libpng version 1.0.4, with the function names expanded to improve code +readability. In some future version they may actually do different +things. + +PNG can have files with 16 bits per channel. If you only can handle +8 bits per channel, this will strip the pixels down to 8 bit. + + if (bit_depth == 16) + png_set_strip_16(png_ptr); + +If, for some reason, you don't need the alpha channel on an image, +and you want to remove it rather than combining it with the background +(but the image author certainly had in mind that you *would* combine +it with the background, so that's what you should probably do): + + if (color_type & PNG_COLOR_MASK_ALPHA) + png_set_strip_alpha(png_ptr); + +In PNG files, the alpha channel in an image +is the level of opacity. If you need the alpha channel in an image to +be the level of transparency instead of opacity, you can invert the +alpha channel (or the tRNS chunk data) after it's read, so that 0 is +fully opaque and 255 (in 8-bit or paletted images) or 65535 (in 16-bit +images) is fully transparent, with + + png_set_invert_alpha(png_ptr); + +PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as +they can, resulting in, for example, 8 pixels per byte for 1 bit +files. This code expands to 1 pixel per byte without changing the +values of the pixels: + + if (bit_depth < 8) + png_set_packing(png_ptr); + +PNG files have possible bit depths of 1, 2, 4, 8, and 16. All pixels +stored in a PNG image have been "scaled" or "shifted" up to the next +higher possible bit depth (e.g. from 5 bits/sample in the range [0,31] to +8 bits/sample in the range [0, 255]). However, it is also possible to +convert the PNG pixel data back to the original bit depth of the image. +This call reduces the pixels back down to the original bit depth: + + png_color_8p sig_bit; + + if (png_get_sBIT(png_ptr, info_ptr, &sig_bit)) + png_set_shift(png_ptr, sig_bit); + +PNG files store 3-color pixels in red, green, blue order. This code +changes the storage of the pixels to blue, green, red: + + if (color_type == PNG_COLOR_TYPE_RGB || + color_type == PNG_COLOR_TYPE_RGB_ALPHA) + png_set_bgr(png_ptr); + +PNG files store RGB pixels packed into 3 or 6 bytes. This code expands them +into 4 or 8 bytes for windowing systems that need them in this format: + + if (color_type == PNG_COLOR_TYPE_RGB) + png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE); + +where "filler" is the 8 or 16-bit number to fill with, and the location is +either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether +you want the filler before the RGB or after. This transformation +does not affect images that already have full alpha channels. To add an +opaque alpha channel, use filler=0xff or 0xffff and PNG_FILLER_AFTER which +will generate RGBA pixels. + +Note that png_set_filler() does not change the color type. If you want +to do that, you can add a true alpha channel with + + if (color_type == PNG_COLOR_TYPE_RGB || + color_type == PNG_COLOR_TYPE_GRAY) + png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER); + +where "filler" contains the alpha value to assign to each pixel. +This function became available in libpng-1.2.7. + +If you are reading an image with an alpha channel, and you need the +data as ARGB instead of the normal PNG format RGBA: + + if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) + png_set_swap_alpha(png_ptr); + +For some uses, you may want a grayscale image to be represented as +RGB. This code will do that conversion: + + if (color_type == PNG_COLOR_TYPE_GRAY || + color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + png_set_gray_to_rgb(png_ptr); + +Conversely, you can convert an RGB or RGBA image to grayscale or grayscale +with alpha. + + if (color_type == PNG_COLOR_TYPE_RGB || + color_type == PNG_COLOR_TYPE_RGB_ALPHA) + png_set_rgb_to_gray_fixed(png_ptr, error_action, + int red_weight, int green_weight); + + error_action = 1: silently do the conversion + error_action = 2: issue a warning if the original + image has any pixel where + red != green or red != blue + error_action = 3: issue an error and abort the + conversion if the original + image has any pixel where + red != green or red != blue + + red_weight: weight of red component times 100000 + green_weight: weight of green component times 100000 + If either weight is negative, default + weights (21268, 71514) are used. + +If you have set error_action = 1 or 2, you can +later check whether the image really was gray, after processing +the image rows, with the png_get_rgb_to_gray_status(png_ptr) function. +It will return a png_byte that is zero if the image was gray or +1 if there were any non-gray pixels. bKGD and sBIT data +will be silently converted to grayscale, using the green channel +data, regardless of the error_action setting. + +With red_weight+green_weight<=100000, +the normalized graylevel is computed: + + int rw = red_weight * 65536; + int gw = green_weight * 65536; + int bw = 65536 - (rw + gw); + gray = (rw*red + gw*green + bw*blue)/65536; + +The default values approximate those recommended in the Charles +Poynton's Color FAQ, +Copyright (c) 1998-01-04 Charles Poynton poynton@inforamp.net + + Y = 0.212671 * R + 0.715160 * G + 0.072169 * B + +Libpng approximates this with + + Y = 0.21268 * R + 0.7151 * G + 0.07217 * B + +which can be expressed with integers as + + Y = (6969 * R + 23434 * G + 2365 * B)/32768 + +The calculation is done in a linear colorspace, if the image gamma +is known. + +If you have a grayscale and you are using png_set_expand_depth(), +png_set_expand(), or png_set_gray_to_rgb to change to truecolor or to +a higher bit-depth, you must either supply the background color as a gray +value at the original file bit-depth (need_expand = 1) or else supply the +background color as an RGB triplet at the final, expanded bit depth +(need_expand = 0). Similarly, if you are reading a paletted image, you +must either supply the background color as a palette index (need_expand = 1) +or as an RGB triplet that may or may not be in the palette (need_expand = 0). + + png_color_16 my_background; + png_color_16p image_background; + + if (png_get_bKGD(png_ptr, info_ptr, &image_background)) + png_set_background(png_ptr, image_background, + PNG_BACKGROUND_GAMMA_FILE, 1, 1.0); + else + png_set_background(png_ptr, &my_background, + PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0); + +The png_set_background() function tells libpng to composite images +with alpha or simple transparency against the supplied background +color. If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid), +you may use this color, or supply another color more suitable for +the current display (e.g., the background color from a web page). You +need to tell libpng whether the color is in the gamma space of the +display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file +(PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one +that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't +know why anyone would use this, but it's here). + +To properly display PNG images on any kind of system, the application needs +to know what the display gamma is. Ideally, the user will know this, and +the application will allow them to set it. One method of allowing the user +to set the display gamma separately for each system is to check for a +SCREEN_GAMMA or DISPLAY_GAMMA environment variable, which will hopefully be +correctly set. + +Note that display_gamma is the overall gamma correction required to produce +pleasing results, which depends on the lighting conditions in the surrounding +environment. In a dim or brightly lit room, no compensation other than +the physical gamma exponent of the monitor is needed, while in a dark room +a slightly smaller exponent is better. + + double gamma, screen_gamma; + + if (/* We have a user-defined screen + gamma value */) + { + screen_gamma = user_defined_screen_gamma; + } + /* One way that applications can share the same + screen gamma value */ + else if ((gamma_str = getenv("SCREEN_GAMMA")) + != NULL) + { + screen_gamma = (double)atof(gamma_str); + } + /* If we don't have another value */ + else + { + screen_gamma = 2.2; /* A good guess for a + PC monitor in a bright office or a dim room */ + screen_gamma = 2.0; /* A good guess for a + PC monitor in a dark room */ + screen_gamma = 1.7 or 1.0; /* A good + guess for Mac systems */ + } + +The png_set_gamma() function handles gamma transformations of the data. +Pass both the file gamma and the current screen_gamma. If the file does +not have a gamma value, you can pass one anyway if you have an idea what +it is (usually 0.45455 is a good guess for GIF images on PCs). Note +that file gammas are inverted from screen gammas. See the discussions +on gamma in the PNG specification for an excellent description of what +gamma is, and why all applications should support it. It is strongly +recommended that PNG viewers support gamma correction. + + if (png_get_gAMA(png_ptr, info_ptr, &gamma)) + png_set_gamma(png_ptr, screen_gamma, gamma); + else + png_set_gamma(png_ptr, screen_gamma, 0.45455); + +If you need to reduce an RGB file to a paletted file, or if a paletted +file has more entries then will fit on your screen, png_set_dither() +will do that. Note that this is a simple match dither that merely +finds the closest color available. This should work fairly well with +optimized palettes, and fairly badly with linear color cubes. If you +pass a palette that is larger then maximum_colors, the file will +reduce the number of colors in the palette so it will fit into +maximum_colors. If there is a histogram, it will use it to make +more intelligent choices when reducing the palette. If there is no +histogram, it may not do as good a job. + + if (color_type & PNG_COLOR_MASK_COLOR) + { + if (png_get_valid(png_ptr, info_ptr, + PNG_INFO_PLTE)) + { + png_uint_16p histogram = NULL; + + png_get_hIST(png_ptr, info_ptr, + &histogram); + png_set_dither(png_ptr, palette, num_palette, + max_screen_colors, histogram, 1); + } + else + { + png_color std_color_cube[MAX_SCREEN_COLORS] = + { ... colors ... }; + + png_set_dither(png_ptr, std_color_cube, + MAX_SCREEN_COLORS, MAX_SCREEN_COLORS, + NULL,0); + } + } + +PNG files describe monochrome as black being zero and white being one. +The following code will reverse this (make black be one and white be +zero): + + if (bit_depth == 1 && color_type == PNG_COLOR_TYPE_GRAY) + png_set_invert_mono(png_ptr); + +This function can also be used to invert grayscale and gray-alpha images: + + if (color_type == PNG_COLOR_TYPE_GRAY || + color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + png_set_invert_mono(png_ptr); + +PNG files store 16 bit pixels in network byte order (big-endian, +ie. most significant bits first). This code changes the storage to the +other way (little-endian, i.e. least significant bits first, the +way PCs store them): + + if (bit_depth == 16) + png_set_swap(png_ptr); + +If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you +need to change the order the pixels are packed into bytes, you can use: + + if (bit_depth < 8) + png_set_packswap(png_ptr); + +Finally, you can write your own transformation function if none of +the existing ones meets your needs. This is done by setting a callback +with + + png_set_read_user_transform_fn(png_ptr, + read_transform_fn); + +You must supply the function + + void read_transform_fn(png_ptr ptr, row_info_ptr + row_info, png_bytep data) + +See pngtest.c for a working example. Your function will be called +after all of the other transformations have been processed. + +You can also set up a pointer to a user structure for use by your +callback function, and you can inform libpng that your transform +function will change the number of channels or bit depth with the +function + + png_set_user_transform_info(png_ptr, user_ptr, + user_depth, user_channels); + +The user's application, not libpng, is responsible for allocating and +freeing any memory required for the user structure. + +You can retrieve the pointer via the function +png_get_user_transform_ptr(). For example: + + voidp read_user_transform_ptr = + png_get_user_transform_ptr(png_ptr); + +The last thing to handle is interlacing; this is covered in detail below, +but you must call the function here if you want libpng to handle expansion +of the interlaced image. + + number_of_passes = png_set_interlace_handling(png_ptr); + +After setting the transformations, libpng can update your png_info +structure to reflect any transformations you've requested with this +call. This is most useful to update the info structure's rowbytes +field so you can use it to allocate your image memory. This function +will also update your palette with the correct screen_gamma and +background if these have been given with the calls above. + + png_read_update_info(png_ptr, info_ptr); + +After you call png_read_update_info(), you can allocate any +memory you need to hold the image. The row data is simply +raw byte data for all forms of images. As the actual allocation +varies among applications, no example will be given. If you +are allocating one large chunk, you will need to build an +array of pointers to each row, as it will be needed for some +of the functions below. + +Reading image data + +After you've allocated memory, you can read the image data. +The simplest way to do this is in one function call. If you are +allocating enough memory to hold the whole image, you can just +call png_read_image() and libpng will read in all the image data +and put it in the memory area supplied. You will need to pass in +an array of pointers to each row. + +This function automatically handles interlacing, so you don't need +to call png_set_interlace_handling() or call this function multiple +times, or any of that other stuff necessary with png_read_rows(). + + png_read_image(png_ptr, row_pointers); + +where row_pointers is: + + png_bytep row_pointers[height]; + +You can point to void or char or whatever you use for pixels. + +If you don't want to read in the whole image at once, you can +use png_read_rows() instead. If there is no interlacing (check +interlace_type == PNG_INTERLACE_NONE), this is simple: + + png_read_rows(png_ptr, row_pointers, NULL, + number_of_rows); + +where row_pointers is the same as in the png_read_image() call. + +If you are doing this just one row at a time, you can do this with +a single row_pointer instead of an array of row_pointers: + + png_bytep row_pointer = row; + png_read_row(png_ptr, row_pointer, NULL); + +If the file is interlaced (interlace_type != 0 in the IHDR chunk), things +get somewhat harder. The only current (PNG Specification version 1.2) +interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7) +is a somewhat complicated 2D interlace scheme, known as Adam7, that +breaks down an image into seven smaller images of varying size, based +on an 8x8 grid. + +libpng can fill out those images or it can give them to you "as is". +If you want them filled out, there are two ways to do that. The one +mentioned in the PNG specification is to expand each pixel to cover +those pixels that have not been read yet (the "rectangle" method). +This results in a blocky image for the first pass, which gradually +smooths out as more pixels are read. The other method is the "sparkle" +method, where pixels are drawn only in their final locations, with the +rest of the image remaining whatever colors they were initialized to +before the start of the read. The first method usually looks better, +but tends to be slower, as there are more pixels to put in the rows. + +If you don't want libpng to handle the interlacing details, just call +png_read_rows() seven times to read in all seven images. Each of the +images is a valid image by itself, or they can all be combined on an +8x8 grid to form a single image (although if you intend to combine them +you would be far better off using the libpng interlace handling). + +The first pass will return an image 1/8 as wide as the entire image +(every 8th column starting in column 0) and 1/8 as high as the original +(every 8th row starting in row 0), the second will be 1/8 as wide +(starting in column 4) and 1/8 as high (also starting in row 0). The +third pass will be 1/4 as wide (every 4th pixel starting in column 0) and +1/8 as high (every 8th row starting in row 4), and the fourth pass will +be 1/4 as wide and 1/4 as high (every 4th column starting in column 2, +and every 4th row starting in row 0). The fifth pass will return an +image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2), +while the sixth pass will be 1/2 as wide and 1/2 as high as the original +(starting in column 1 and row 0). The seventh and final pass will be as +wide as the original, and 1/2 as high, containing all of the odd +numbered scanlines. Phew! + +If you want libpng to expand the images, call this before calling +png_start_read_image() or png_read_update_info(): + + if (interlace_type == PNG_INTERLACE_ADAM7) + number_of_passes + = png_set_interlace_handling(png_ptr); + +This will return the number of passes needed. Currently, this +is seven, but may change if another interlace type is added. +This function can be called even if the file is not interlaced, +where it will return one pass. + +If you are not going to display the image after each pass, but are +going to wait until the entire image is read in, use the sparkle +effect. This effect is faster and the end result of either method +is exactly the same. If you are planning on displaying the image +after each pass, the "rectangle" effect is generally considered the +better looking one. + +If you only want the "sparkle" effect, just call png_read_rows() as +normal, with the third parameter NULL. Make sure you make pass over +the image number_of_passes times, and you don't change the data in the +rows between calls. You can change the locations of the data, just +not the data. Each pass only writes the pixels appropriate for that +pass, and assumes the data from previous passes is still valid. + + png_read_rows(png_ptr, row_pointers, NULL, + number_of_rows); + +If you only want the first effect (the rectangles), do the same as +before except pass the row buffer in the third parameter, and leave +the second parameter NULL. + + png_read_rows(png_ptr, NULL, row_pointers, + number_of_rows); + +Finishing a sequential read + +After you are finished reading the image through either the high- or +low-level interfaces, you can finish reading the file. If you are +interested in comments or time, which may be stored either before or +after the image data, you should pass the separate png_info struct if +you want to keep the comments from before and after the image +separate. If you are not interested, you can pass NULL. + + png_read_end(png_ptr, end_info); + +When you are done, you can free all memory allocated by libpng like this: + + png_destroy_read_struct(&png_ptr, &info_ptr, + &end_info); + +It is also possible to individually free the info_ptr members that +point to libpng-allocated storage with the following function: + + png_free_data(png_ptr, info_ptr, mask, seq) + mask - identifies data to be freed, a mask + containing the logical OR of one or + more of + PNG_FREE_PLTE, PNG_FREE_TRNS, + PNG_FREE_HIST, PNG_FREE_ICCP, + PNG_FREE_PCAL, PNG_FREE_ROWS, + PNG_FREE_SCAL, PNG_FREE_SPLT, + PNG_FREE_TEXT, PNG_FREE_UNKN, + or simply PNG_FREE_ALL + seq - sequence number of item to be freed + (-1 for all items) + +This function may be safely called when the relevant storage has +already been freed, or has not yet been allocated, or was allocated +by the user and not by libpng, and will in those +cases do nothing. The "seq" parameter is ignored if only one item +of the selected data type, such as PLTE, is allowed. If "seq" is not +-1, and multiple items are allowed for the data type identified in +the mask, such as text or sPLT, only the n'th item in the structure +is freed, where n is "seq". + +The default behavior is only to free data that was allocated internally +by libpng. This can be changed, so that libpng will not free the data, +or so that it will free data that was allocated by the user with png_malloc() +or png_zalloc() and passed in via a png_set_*() function, with + + png_data_freer(png_ptr, info_ptr, freer, mask) + mask - which data elements are affected + same choices as in png_free_data() + freer - one of + PNG_DESTROY_WILL_FREE_DATA + PNG_SET_WILL_FREE_DATA + PNG_USER_WILL_FREE_DATA + +This function only affects data that has already been allocated. +You can call this function after reading the PNG data but before calling +any png_set_*() functions, to control whether the user or the png_set_*() +function is responsible for freeing any existing data that might be present, +and again after the png_set_*() functions to control whether the user +or png_destroy_*() is supposed to free the data. When the user assumes +responsibility for libpng-allocated data, the application must use +png_free() to free it, and when the user transfers responsibility to libpng +for data that the user has allocated, the user must have used png_malloc() +or png_zalloc() to allocate it. + +If you allocated your row_pointers in a single block, as suggested above in +the description of the high level read interface, you must not transfer +responsibility for freeing it to the png_set_rows or png_read_destroy function, +because they would also try to free the individual row_pointers[i]. + +If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword +separately, do not transfer responsibility for freeing text_ptr to libpng, +because when libpng fills a png_text structure it combines these members with +the key member, and png_free_data() will free only text_ptr.key. Similarly, +if you transfer responsibility for free'ing text_ptr from libpng to your +application, your application must not separately free those members. + +The png_free_data() function will turn off the "valid" flag for anything +it frees. If you need to turn the flag off for a chunk that was freed by your +application instead of by libpng, you can use + + png_set_invalid(png_ptr, info_ptr, mask); + mask - identifies the chunks to be made invalid, + containing the logical OR of one or + more of + PNG_INFO_gAMA, PNG_INFO_sBIT, + PNG_INFO_cHRM, PNG_INFO_PLTE, + PNG_INFO_tRNS, PNG_INFO_bKGD, + PNG_INFO_hIST, PNG_INFO_pHYs, + PNG_INFO_oFFs, PNG_INFO_tIME, + PNG_INFO_pCAL, PNG_INFO_sRGB, + PNG_INFO_iCCP, PNG_INFO_sPLT, + PNG_INFO_sCAL, PNG_INFO_IDAT + +For a more compact example of reading a PNG image, see the file example.c. + +Reading PNG files progressively + +The progressive reader is slightly different then the non-progressive +reader. Instead of calling png_read_info(), png_read_rows(), and +png_read_end(), you make one call to png_process_data(), which calls +callbacks when it has the info, a row, or the end of the image. You +set up these callbacks with png_set_progressive_read_fn(). You don't +have to worry about the input/output functions of libpng, as you are +giving the library the data directly in png_process_data(). I will +assume that you have read the section on reading PNG files above, +so I will only highlight the differences (although I will show +all of the code). + +png_structp png_ptr; +png_infop info_ptr; + + /* An example code fragment of how you would + initialize the progressive reader in your + application. */ + int + initialize_png_reader() + { + png_ptr = png_create_read_struct + (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr, + user_error_fn, user_warning_fn); + if (!png_ptr) + return (ERROR); + info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr) + { + png_destroy_read_struct(&png_ptr, (png_infopp)NULL, + (png_infopp)NULL); + return (ERROR); + } + + if (setjmp(png_jmpbuf(png_ptr))) + { + png_destroy_read_struct(&png_ptr, &info_ptr, + (png_infopp)NULL); + return (ERROR); + } + + /* This one's new. You can provide functions + to be called when the header info is valid, + when each row is completed, and when the image + is finished. If you aren't using all functions, + you can specify NULL parameters. Even when all + three functions are NULL, you need to call + png_set_progressive_read_fn(). You can use + any struct as the user_ptr (cast to a void pointer + for the function call), and retrieve the pointer + from inside the callbacks using the function + + png_get_progressive_ptr(png_ptr); + + which will return a void pointer, which you have + to cast appropriately. + */ + png_set_progressive_read_fn(png_ptr, (void *)user_ptr, + info_callback, row_callback, end_callback); + + return 0; + } + + /* A code fragment that you call as you receive blocks + of data */ + int + process_data(png_bytep buffer, png_uint_32 length) + { + if (setjmp(png_jmpbuf(png_ptr))) + { + png_destroy_read_struct(&png_ptr, &info_ptr, + (png_infopp)NULL); + return (ERROR); + } + + /* This one's new also. Simply give it a chunk + of data from the file stream (in order, of + course). On machines with segmented memory + models machines, don't give it any more than + 64K. The library seems to run fine with sizes + of 4K. Although you can give it much less if + necessary (I assume you can give it chunks of + 1 byte, I haven't tried less then 256 bytes + yet). When this function returns, you may + want to display any rows that were generated + in the row callback if you don't already do + so there. + */ + png_process_data(png_ptr, info_ptr, buffer, length); + return 0; + } + + /* This function is called (as set by + png_set_progressive_read_fn() above) when enough data + has been supplied so all of the header has been + read. + */ + void + info_callback(png_structp png_ptr, png_infop info) + { + /* Do any setup here, including setting any of + the transformations mentioned in the Reading + PNG files section. For now, you _must_ call + either png_start_read_image() or + png_read_update_info() after all the + transformations are set (even if you don't set + any). You may start getting rows before + png_process_data() returns, so this is your + last chance to prepare for that. + */ + } + + /* This function is called when each row of image + data is complete */ + void + row_callback(png_structp png_ptr, png_bytep new_row, + png_uint_32 row_num, int pass) + { + /* If the image is interlaced, and you turned + on the interlace handler, this function will + be called for every row in every pass. Some + of these rows will not be changed from the + previous pass. When the row is not changed, + the new_row variable will be NULL. The rows + and passes are called in order, so you don't + really need the row_num and pass, but I'm + supplying them because it may make your life + easier. + + For the non-NULL rows of interlaced images, + you must call png_progressive_combine_row() + passing in the row and the old row. You can + call this function for NULL rows (it will just + return) and for non-interlaced images (it just + does the memcpy for you) if it will make the + code easier. Thus, you can just do this for + all cases: + */ + + png_progressive_combine_row(png_ptr, old_row, + new_row); + + /* where old_row is what was displayed for + previously for the row. Note that the first + pass (pass == 0, really) will completely cover + the old row, so the rows do not have to be + initialized. After the first pass (and only + for interlaced images), you will have to pass + the current row, and the function will combine + the old row and the new row. + */ + } + + void + end_callback(png_structp png_ptr, png_infop info) + { + /* This function is called after the whole image + has been read, including any chunks after the + image (up to and including the IEND). You + will usually have the same info chunk as you + had in the header, although some data may have + been added to the comments and time fields. + + Most people won't do much here, perhaps setting + a flag that marks the image as finished. + */ + } + + + +IV. Writing + +Much of this is very similar to reading. However, everything of +importance is repeated here, so you won't have to constantly look +back up in the reading section to understand writing. + +Setup + +You will want to do the I/O initialization before you get into libpng, +so if it doesn't work, you don't have anything to undo. If you are not +using the standard I/O functions, you will need to replace them with +custom writing functions. See the discussion under Customizing libpng. + + FILE *fp = fopen(file_name, "wb"); + if (!fp) + { + return (ERROR); + } + +Next, png_struct and png_info need to be allocated and initialized. +As these can be both relatively large, you may not want to store these +on the stack, unless you have stack space to spare. Of course, you +will want to check if they return NULL. If you are also reading, +you won't want to name your read structure and your write structure +both "png_ptr"; you can call them anything you like, such as +"read_ptr" and "write_ptr". Look at pngtest.c, for example. + + png_structp png_ptr = png_create_write_struct + (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr, + user_error_fn, user_warning_fn); + if (!png_ptr) + return (ERROR); + + png_infop info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr) + { + png_destroy_write_struct(&png_ptr, + (png_infopp)NULL); + return (ERROR); + } + +If you want to use your own memory allocation routines, +define PNG_USER_MEM_SUPPORTED and use +png_create_write_struct_2() instead of png_create_write_struct(): + + png_structp png_ptr = png_create_write_struct_2 + (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr, + user_error_fn, user_warning_fn, (png_voidp) + user_mem_ptr, user_malloc_fn, user_free_fn); + +After you have these structures, you will need to set up the +error handling. When libpng encounters an error, it expects to +longjmp() back to your routine. Therefore, you will need to call +setjmp() and pass the png_jmpbuf(png_ptr). If you +write the file from different routines, you will need to update +the png_jmpbuf(png_ptr) every time you enter a new routine that will +call a png_*() function. See your documentation of setjmp/longjmp +for your compiler for more information on setjmp/longjmp. See +the discussion on libpng error handling in the Customizing Libpng +section below for more information on the libpng error handling. + + if (setjmp(png_jmpbuf(png_ptr))) + { + png_destroy_write_struct(&png_ptr, &info_ptr); + fclose(fp); + return (ERROR); + } + ... + return; + +If you would rather avoid the complexity of setjmp/longjmp issues, +you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which case +errors will result in a call to PNG_ABORT() which defaults to abort(). + +Now you need to set up the output code. The default for libpng is to +use the C function fwrite(). If you use this, you will need to pass a +valid FILE * in the function png_init_io(). Be sure that the file is +opened in binary mode. Again, if you wish to handle writing data in +another way, see the discussion on libpng I/O handling in the Customizing +Libpng section below. + + png_init_io(png_ptr, fp); + +Write callbacks + +At this point, you can set up a callback function that will be +called after each row has been written, which you can use to control +a progress meter or the like. It's demonstrated in pngtest.c. +You must supply a function + + void write_row_callback(png_ptr, png_uint_32 row, + int pass); + { + /* put your code here */ + } + +(You can give it another name that you like instead of "write_row_callback") + +To inform libpng about your function, use + + png_set_write_status_fn(png_ptr, write_row_callback); + +You now have the option of modifying how the compression library will +run. The following functions are mainly for testing, but may be useful +in some cases, like if you need to write PNG files extremely fast and +are willing to give up some compression, or if you want to get the +maximum possible compression at the expense of slower writing. If you +have no special needs in this area, let the library do what it wants by +not calling this function at all, as it has been tuned to deliver a good +speed/compression ratio. The second parameter to png_set_filter() is +the filter method, for which the only valid values are 0 (as of the +July 1999 PNG specification, version 1.2) or 64 (if you are writing +a PNG datastream that is to be embedded in a MNG datastream). The third +parameter is a flag that indicates which filter type(s) are to be tested +for each scanline. See the PNG specification for details on the specific filter +types. + + + /* turn on or off filtering, and/or choose + specific filters. You can use either a single + PNG_FILTER_VALUE_NAME or the logical OR of one + or more PNG_FILTER_NAME masks. */ + png_set_filter(png_ptr, 0, + PNG_FILTER_NONE | PNG_FILTER_VALUE_NONE | + PNG_FILTER_SUB | PNG_FILTER_VALUE_SUB | + PNG_FILTER_UP | PNG_FILTER_VALUE_UP | + PNG_FILTER_AVE | PNG_FILTER_VALUE_AVE | + PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH| + PNG_ALL_FILTERS); + +If an application +wants to start and stop using particular filters during compression, +it should start out with all of the filters (to ensure that the previous +row of pixels will be stored in case it's needed later), and then add +and remove them after the start of compression. + +If you are writing a PNG datastream that is to be embedded in a MNG +datastream, the second parameter can be either 0 or 64. + +The png_set_compression_*() functions interface to the zlib compression +library, and should mostly be ignored unless you really know what you are +doing. The only generally useful call is png_set_compression_level() +which changes how much time zlib spends on trying to compress the image +data. See the Compression Library (zlib.h and algorithm.txt, distributed +with zlib) for details on the compression levels. + + /* set the zlib compression level */ + png_set_compression_level(png_ptr, + Z_BEST_COMPRESSION); + + /* set other zlib parameters */ + png_set_compression_mem_level(png_ptr, 8); + png_set_compression_strategy(png_ptr, + Z_DEFAULT_STRATEGY); + png_set_compression_window_bits(png_ptr, 15); + png_set_compression_method(png_ptr, 8); + png_set_compression_buffer_size(png_ptr, 8192) + +extern PNG_EXPORT(void,png_set_zbuf_size) + +Setting the contents of info for output + +You now need to fill in the png_info structure with all the data you +wish to write before the actual image. Note that the only thing you +are allowed to write after the image is the text chunks and the time +chunk (as of PNG Specification 1.2, anyway). See png_write_end() and +the latest PNG specification for more information on that. If you +wish to write them before the image, fill them in now, and flag that +data as being valid. If you want to wait until after the data, don't +fill them until png_write_end(). For all the fields in png_info and +their data types, see png.h. For explanations of what the fields +contain, see the PNG specification. + +Some of the more important parts of the png_info are: + + png_set_IHDR(png_ptr, info_ptr, width, height, + bit_depth, color_type, interlace_type, + compression_type, filter_method) + width - holds the width of the image + in pixels (up to 2^31). + height - holds the height of the image + in pixels (up to 2^31). + bit_depth - holds the bit depth of one of the + image channels. + (valid values are 1, 2, 4, 8, 16 + and depend also on the + color_type. See also significant + bits (sBIT) below). + color_type - describes which color/alpha + channels are present. + PNG_COLOR_TYPE_GRAY + (bit depths 1, 2, 4, 8, 16) + PNG_COLOR_TYPE_GRAY_ALPHA + (bit depths 8, 16) + PNG_COLOR_TYPE_PALETTE + (bit depths 1, 2, 4, 8) + PNG_COLOR_TYPE_RGB + (bit_depths 8, 16) + PNG_COLOR_TYPE_RGB_ALPHA + (bit_depths 8, 16) + + PNG_COLOR_MASK_PALETTE + PNG_COLOR_MASK_COLOR + PNG_COLOR_MASK_ALPHA + + interlace_type - PNG_INTERLACE_NONE or + PNG_INTERLACE_ADAM7 + compression_type - (must be + PNG_COMPRESSION_TYPE_DEFAULT) + filter_method - (must be PNG_FILTER_TYPE_DEFAULT + or, if you are writing a PNG to + be embedded in a MNG datastream, + can also be + PNG_INTRAPIXEL_DIFFERENCING) + + png_set_PLTE(png_ptr, info_ptr, palette, + num_palette); + palette - the palette for the file + (array of png_color) + num_palette - number of entries in the palette + + png_set_gAMA(png_ptr, info_ptr, gamma); + gamma - the gamma the image was created + at (PNG_INFO_gAMA) + + png_set_sRGB(png_ptr, info_ptr, srgb_intent); + srgb_intent - the rendering intent + (PNG_INFO_sRGB) The presence of + the sRGB chunk means that the pixel + data is in the sRGB color space. + This chunk also implies specific + values of gAMA and cHRM. Rendering + intent is the CSS-1 property that + has been defined by the International + Color Consortium + (http://www.color.org). + It can be one of + PNG_sRGB_INTENT_SATURATION, + PNG_sRGB_INTENT_PERCEPTUAL, + PNG_sRGB_INTENT_ABSOLUTE, or + PNG_sRGB_INTENT_RELATIVE. + + + png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, + srgb_intent); + srgb_intent - the rendering intent + (PNG_INFO_sRGB) The presence of the + sRGB chunk means that the pixel + data is in the sRGB color space. + This function also causes gAMA and + cHRM chunks with the specific values + that are consistent with sRGB to be + written. + + png_set_iCCP(png_ptr, info_ptr, name, compression_type, + profile, proflen); + name - The profile name. + compression - The compression type; always + PNG_COMPRESSION_TYPE_BASE for PNG 1.0. + You may give NULL to this argument to + ignore it. + profile - International Color Consortium color + profile data. May contain NULs. + proflen - length of profile data in bytes. + + png_set_sBIT(png_ptr, info_ptr, sig_bit); + sig_bit - the number of significant bits for + (PNG_INFO_sBIT) each of the gray, red, + green, and blue channels, whichever are + appropriate for the given color type + (png_color_16) + + png_set_tRNS(png_ptr, info_ptr, trans, num_trans, + trans_values); + trans - array of transparent entries for + palette (PNG_INFO_tRNS) + trans_values - graylevel or color sample values of + the single transparent color for + non-paletted images (PNG_INFO_tRNS) + num_trans - number of transparent entries + (PNG_INFO_tRNS) + + png_set_hIST(png_ptr, info_ptr, hist); + (PNG_INFO_hIST) + hist - histogram of palette (array of + png_uint_16) + + png_set_tIME(png_ptr, info_ptr, mod_time); + mod_time - time image was last modified + (PNG_VALID_tIME) + + png_set_bKGD(png_ptr, info_ptr, background); + background - background color (PNG_VALID_bKGD) + + png_set_text(png_ptr, info_ptr, text_ptr, num_text); + text_ptr - array of png_text holding image + comments + text_ptr[i].compression - type of compression used + on "text" PNG_TEXT_COMPRESSION_NONE + PNG_TEXT_COMPRESSION_zTXt + PNG_ITXT_COMPRESSION_NONE + PNG_ITXT_COMPRESSION_zTXt + text_ptr[i].key - keyword for comment. Must contain + 1-79 characters. + text_ptr[i].text - text comments for current + keyword. Can be NULL or empty. + text_ptr[i].text_length - length of text string, + after decompression, 0 for iTXt + text_ptr[i].itxt_length - length of itxt string, + after decompression, 0 for tEXt/zTXt + text_ptr[i].lang - language of comment (NULL or + empty for unknown). + text_ptr[i].translated_keyword - keyword in UTF-8 (NULL + or empty for unknown). + num_text - number of comments + + png_set_sPLT(png_ptr, info_ptr, &palette_ptr, + num_spalettes); + palette_ptr - array of png_sPLT_struct structures + to be added to the list of palettes + in the info structure. + num_spalettes - number of palette structures to be + added. + + png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, + unit_type); + offset_x - positive offset from the left + edge of the screen + offset_y - positive offset from the top + edge of the screen + unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER + + png_set_pHYs(png_ptr, info_ptr, res_x, res_y, + unit_type); + res_x - pixels/unit physical resolution + in x direction + res_y - pixels/unit physical resolution + in y direction + unit_type - PNG_RESOLUTION_UNKNOWN, + PNG_RESOLUTION_METER + + png_set_sCAL(png_ptr, info_ptr, unit, width, height) + unit - physical scale units (an integer) + width - width of a pixel in physical scale units + height - height of a pixel in physical scale units + (width and height are doubles) + + png_set_sCAL_s(png_ptr, info_ptr, unit, width, height) + unit - physical scale units (an integer) + width - width of a pixel in physical scale units + height - height of a pixel in physical scale units + (width and height are strings like "2.54") + + png_set_unknown_chunks(png_ptr, info_ptr, &unknowns, + num_unknowns) + unknowns - array of png_unknown_chunk + structures holding unknown chunks + unknowns[i].name - name of unknown chunk + unknowns[i].data - data of unknown chunk + unknowns[i].size - size of unknown chunk's data + unknowns[i].location - position to write chunk in file + 0: do not write chunk + PNG_HAVE_IHDR: before PLTE + PNG_HAVE_PLTE: before IDAT + PNG_AFTER_IDAT: after IDAT + +The "location" member is set automatically according to +what part of the output file has already been written. +You can change its value after calling png_set_unknown_chunks() +as demonstrated in pngtest.c. Within each of the "locations", +the chunks are sequenced according to their position in the +structure (that is, the value of "i", which is the order in which +the chunk was either read from the input file or defined with +png_set_unknown_chunks). + +A quick word about text and num_text. text is an array of png_text +structures. num_text is the number of valid structures in the array. +Each png_text structure holds a language code, a keyword, a text value, +and a compression type. + +The compression types have the same valid numbers as the compression +types of the image data. Currently, the only valid number is zero. +However, you can store text either compressed or uncompressed, unlike +images, which always have to be compressed. So if you don't want the +text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE. +Because tEXt and zTXt chunks don't have a language field, if you +specify PNG_TEXT_COMPRESSION_NONE or PNG_TEXT_COMPRESSION_zTXt +any language code or translated keyword will not be written out. + +Until text gets around 1000 bytes, it is not worth compressing it. +After the text has been written out to the file, the compression type +is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR, +so that it isn't written out again at the end (in case you are calling +png_write_end() with the same struct. + +The keywords that are given in the PNG Specification are: + + Title Short (one line) title or + caption for image + Author Name of image's creator + Description Description of image (possibly long) + Copyright Copyright notice + Creation Time Time of original image creation + (usually RFC 1123 format, see below) + Software Software used to create the image + Disclaimer Legal disclaimer + Warning Warning of nature of content + Source Device used to create the image + Comment Miscellaneous comment; conversion + from other image format + +The keyword-text pairs work like this. Keywords should be short +simple descriptions of what the comment is about. Some typical +keywords are found in the PNG specification, as is some recommendations +on keywords. You can repeat keywords in a file. You can even write +some text before the image and some after. For example, you may want +to put a description of the image before the image, but leave the +disclaimer until after, so viewers working over modem connections +don't have to wait for the disclaimer to go over the modem before +they start seeing the image. Finally, keywords should be full +words, not abbreviations. Keywords and text are in the ISO 8859-1 +(Latin-1) character set (a superset of regular ASCII) and can not +contain NUL characters, and should not contain control or other +unprintable characters. To make the comments widely readable, stick +with basic ASCII, and avoid machine specific character set extensions +like the IBM-PC character set. The keyword must be present, but +you can leave off the text string on non-compressed pairs. +Compressed pairs must have a text string, as only the text string +is compressed anyway, so the compression would be meaningless. + +PNG supports modification time via the png_time structure. Two +conversion routines are provided, png_convert_from_time_t() for +time_t and png_convert_from_struct_tm() for struct tm. The +time_t routine uses gmtime(). You don't have to use either of +these, but if you wish to fill in the png_time structure directly, +you should provide the time in universal time (GMT) if possible +instead of your local time. Note that the year number is the full +year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and +that months start with 1. + +If you want to store the time of the original image creation, you should +use a plain tEXt chunk with the "Creation Time" keyword. This is +necessary because the "creation time" of a PNG image is somewhat vague, +depending on whether you mean the PNG file, the time the image was +created in a non-PNG format, a still photo from which the image was +scanned, or possibly the subject matter itself. In order to facilitate +machine-readable dates, it is recommended that the "Creation Time" +tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"), +although this isn't a requirement. Unlike the tIME chunk, the +"Creation Time" tEXt chunk is not expected to be automatically changed +by the software. To facilitate the use of RFC 1123 dates, a function +png_convert_to_rfc1123(png_timep) is provided to convert from PNG +time to an RFC 1123 format string. + +Writing unknown chunks + +You can use the png_set_unknown_chunks function to queue up chunks +for writing. You give it a chunk name, raw data, and a size; that's +all there is to it. The chunks will be written by the next following +png_write_info_before_PLTE, png_write_info, or png_write_end function. +Any chunks previously read into the info structure's unknown-chunk +list will also be written out in a sequence that satisfies the PNG +specification's ordering rules. + +The high-level write interface + +At this point there are two ways to proceed; through the high-level +write interface, or through a sequence of low-level write operations. +You can use the high-level interface if your image data is present +in the info structure. All defined output +transformations are permitted, enabled by the following masks. + + PNG_TRANSFORM_IDENTITY No transformation + PNG_TRANSFORM_PACKING Pack 1, 2 and 4-bit samples + PNG_TRANSFORM_PACKSWAP Change order of packed + pixels to LSB first + PNG_TRANSFORM_INVERT_MONO Invert monochrome images + PNG_TRANSFORM_SHIFT Normalize pixels to the + sBIT depth + PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA + to BGRA + PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA + to AG + PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity + to transparency + PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples + PNG_TRANSFORM_STRIP_FILLER Strip out filler bytes. + +If you have valid image data in the info structure (you can use +png_set_rows() to put image data in the info structure), simply do this: + + png_write_png(png_ptr, info_ptr, png_transforms, NULL) + +where png_transforms is an integer containing the logical OR of some set of +transformation flags. This call is equivalent to png_write_info(), +followed the set of transformations indicated by the transform mask, +then png_write_image(), and finally png_write_end(). + +(The final parameter of this call is not yet used. Someday it might point +to transformation parameters required by some future output transform.) + +You must use png_transforms and not call any png_set_transform() functions +when you use png_write_png(). + +The low-level write interface + +If you are going the low-level route instead, you are now ready to +write all the file information up to the actual image data. You do +this with a call to png_write_info(). + + png_write_info(png_ptr, info_ptr); + +Note that there is one transformation you may need to do before +png_write_info(). In PNG files, the alpha channel in an image is the +level of opacity. If your data is supplied as a level of +transparency, you can invert the alpha channel before you write it, so +that 0 is fully transparent and 255 (in 8-bit or paletted images) or +65535 (in 16-bit images) is fully opaque, with + + png_set_invert_alpha(png_ptr); + +This must appear before png_write_info() instead of later with the +other transformations because in the case of paletted images the tRNS +chunk data has to be inverted before the tRNS chunk is written. If +your image is not a paletted image, the tRNS data (which in such cases +represents a single color to be rendered as transparent) won't need to +be changed, and you can safely do this transformation after your +png_write_info() call. + +If you need to write a private chunk that you want to appear before +the PLTE chunk when PLTE is present, you can write the PNG info in +two steps, and insert code to write your own chunk between them: + + png_write_info_before_PLTE(png_ptr, info_ptr); + png_set_unknown_chunks(png_ptr, info_ptr, ...); + png_write_info(png_ptr, info_ptr); + +After you've written the file information, you can set up the library +to handle any special transformations of the image data. The various +ways to transform the data will be described in the order that they +should occur. This is important, as some of these change the color +type and/or bit depth of the data, and some others only work on +certain color types and bit depths. Even though each transformation +checks to see if it has data that it can do something with, you should +make sure to only enable a transformation if it will be valid for the +data. For example, don't swap red and blue on grayscale data. + +PNG files store RGB pixels packed into 3 or 6 bytes. This code tells +the library to strip input data that has 4 or 8 bytes per pixel down +to 3 or 6 bytes (or strip 2 or 4-byte grayscale+filler data to 1 or 2 +bytes per pixel). + + png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE); + +where the 0 is unused, and the location is either PNG_FILLER_BEFORE or +PNG_FILLER_AFTER, depending upon whether the filler byte in the pixel +is stored XRGB or RGBX. + +PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as +they can, resulting in, for example, 8 pixels per byte for 1 bit files. +If the data is supplied at 1 pixel per byte, use this code, which will +correctly pack the pixels into a single byte: + + png_set_packing(png_ptr); + +PNG files reduce possible bit depths to 1, 2, 4, 8, and 16. If your +data is of another bit depth, you can write an sBIT chunk into the +file so that decoders can recover the original data if desired. + + /* Set the true bit depth of the image data */ + if (color_type & PNG_COLOR_MASK_COLOR) + { + sig_bit.red = true_bit_depth; + sig_bit.green = true_bit_depth; + sig_bit.blue = true_bit_depth; + } + else + { + sig_bit.gray = true_bit_depth; + } + if (color_type & PNG_COLOR_MASK_ALPHA) + { + sig_bit.alpha = true_bit_depth; + } + + png_set_sBIT(png_ptr, info_ptr, &sig_bit); + +If the data is stored in the row buffer in a bit depth other than +one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG), +this will scale the values to appear to be the correct bit depth as +is required by PNG. + + png_set_shift(png_ptr, &sig_bit); + +PNG files store 16 bit pixels in network byte order (big-endian, +ie. most significant bits first). This code would be used if they are +supplied the other way (little-endian, i.e. least significant bits +first, the way PCs store them): + + if (bit_depth > 8) + png_set_swap(png_ptr); + +If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you +need to change the order the pixels are packed into bytes, you can use: + + if (bit_depth < 8) + png_set_packswap(png_ptr); + +PNG files store 3 color pixels in red, green, blue order. This code +would be used if they are supplied as blue, green, red: + + png_set_bgr(png_ptr); + +PNG files describe monochrome as black being zero and white being +one. This code would be used if the pixels are supplied with this reversed +(black being one and white being zero): + + png_set_invert_mono(png_ptr); + +Finally, you can write your own transformation function if none of +the existing ones meets your needs. This is done by setting a callback +with + + png_set_write_user_transform_fn(png_ptr, + write_transform_fn); + +You must supply the function + + void write_transform_fn(png_ptr ptr, row_info_ptr + row_info, png_bytep data) + +See pngtest.c for a working example. Your function will be called +before any of the other transformations are processed. + +You can also set up a pointer to a user structure for use by your +callback function. + + png_set_user_transform_info(png_ptr, user_ptr, 0, 0); + +The user_channels and user_depth parameters of this function are ignored +when writing; you can set them to zero as shown. + +You can retrieve the pointer via the function png_get_user_transform_ptr(). +For example: + + voidp write_user_transform_ptr = + png_get_user_transform_ptr(png_ptr); + +It is possible to have libpng flush any pending output, either manually, +or automatically after a certain number of lines have been written. To +flush the output stream a single time call: + + png_write_flush(png_ptr); + +and to have libpng flush the output stream periodically after a certain +number of scanlines have been written, call: + + png_set_flush(png_ptr, nrows); + +Note that the distance between rows is from the last time png_write_flush() +was called, or the first row of the image if it has never been called. +So if you write 50 lines, and then png_set_flush 25, it will flush the +output on the next scanline, and every 25 lines thereafter, unless +png_write_flush() is called before 25 more lines have been written. +If nrows is too small (less than about 10 lines for a 640 pixel wide +RGB image) the image compression may decrease noticeably (although this +may be acceptable for real-time applications). Infrequent flushing will +only degrade the compression performance by a few percent over images +that do not use flushing. + +Writing the image data + +That's it for the transformations. Now you can write the image data. +The simplest way to do this is in one function call. If you have the +whole image in memory, you can just call png_write_image() and libpng +will write the image. You will need to pass in an array of pointers to +each row. This function automatically handles interlacing, so you don't +need to call png_set_interlace_handling() or call this function multiple +times, or any of that other stuff necessary with png_write_rows(). + + png_write_image(png_ptr, row_pointers); + +where row_pointers is: + + png_byte *row_pointers[height]; + +You can point to void or char or whatever you use for pixels. + +If you don't want to write the whole image at once, you can +use png_write_rows() instead. If the file is not interlaced, +this is simple: + + png_write_rows(png_ptr, row_pointers, + number_of_rows); + +row_pointers is the same as in the png_write_image() call. + +If you are just writing one row at a time, you can do this with +a single row_pointer instead of an array of row_pointers: + + png_bytep row_pointer = row; + + png_write_row(png_ptr, row_pointer); + +When the file is interlaced, things can get a good deal more +complicated. The only currently (as of the PNG Specification +version 1.2, dated July 1999) defined interlacing scheme for PNG files +is the "Adam7" interlace scheme, that breaks down an +image into seven smaller images of varying size. libpng will build +these images for you, or you can do them yourself. If you want to +build them yourself, see the PNG specification for details of which +pixels to write when. + +If you don't want libpng to handle the interlacing details, just +use png_set_interlace_handling() and call png_write_rows() the +correct number of times to write all seven sub-images. + +If you want libpng to build the sub-images, call this before you start +writing any rows: + + number_of_passes = + png_set_interlace_handling(png_ptr); + +This will return the number of passes needed. Currently, this +is seven, but may change if another interlace type is added. + +Then write the complete image number_of_passes times. + + png_write_rows(png_ptr, row_pointers, + number_of_rows); + +As some of these rows are not used, and thus return immediately, +you may want to read about interlacing in the PNG specification, +and only update the rows that are actually used. + +Finishing a sequential write + +After you are finished writing the image, you should finish writing +the file. If you are interested in writing comments or time, you should +pass an appropriately filled png_info pointer. If you are not interested, +you can pass NULL. + + png_write_end(png_ptr, info_ptr); + +When you are done, you can free all memory used by libpng like this: + + png_destroy_write_struct(&png_ptr, &info_ptr); + +It is also possible to individually free the info_ptr members that +point to libpng-allocated storage with the following function: + + png_free_data(png_ptr, info_ptr, mask, seq) + mask - identifies data to be freed, a mask + containing the logical OR of one or + more of + PNG_FREE_PLTE, PNG_FREE_TRNS, + PNG_FREE_HIST, PNG_FREE_ICCP, + PNG_FREE_PCAL, PNG_FREE_ROWS, + PNG_FREE_SCAL, PNG_FREE_SPLT, + PNG_FREE_TEXT, PNG_FREE_UNKN, + or simply PNG_FREE_ALL + seq - sequence number of item to be freed + (-1 for all items) + +This function may be safely called when the relevant storage has +already been freed, or has not yet been allocated, or was allocated +by the user and not by libpng, and will in those +cases do nothing. The "seq" parameter is ignored if only one item +of the selected data type, such as PLTE, is allowed. If "seq" is not +-1, and multiple items are allowed for the data type identified in +the mask, such as text or sPLT, only the n'th item in the structure +is freed, where n is "seq". + +If you allocated data such as a palette that you passed +in to libpng with png_set_*, you must not free it until just before the call to +png_destroy_write_struct(). + +The default behavior is only to free data that was allocated internally +by libpng. This can be changed, so that libpng will not free the data, +or so that it will free data that was allocated by the user with png_malloc() +or png_zalloc() and passed in via a png_set_*() function, with + + png_data_freer(png_ptr, info_ptr, freer, mask) + mask - which data elements are affected + same choices as in png_free_data() + freer - one of + PNG_DESTROY_WILL_FREE_DATA + PNG_SET_WILL_FREE_DATA + PNG_USER_WILL_FREE_DATA + +For example, to transfer responsibility for some data from a read structure +to a write structure, you could use + + png_data_freer(read_ptr, read_info_ptr, + PNG_USER_WILL_FREE_DATA, + PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST) + png_data_freer(write_ptr, write_info_ptr, + PNG_DESTROY_WILL_FREE_DATA, + PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST) + +thereby briefly reassigning responsibility for freeing to the user but +immediately afterwards reassigning it once more to the write_destroy +function. Having done this, it would then be safe to destroy the read +structure and continue to use the PLTE, tRNS, and hIST data in the write +structure. + +This function only affects data that has already been allocated. +You can call this function before calling after the png_set_*() functions +to control whether the user or png_destroy_*() is supposed to free the data. +When the user assumes responsibility for libpng-allocated data, the +application must use +png_free() to free it, and when the user transfers responsibility to libpng +for data that the user has allocated, the user must have used png_malloc() +or png_zalloc() to allocate it. + +If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword +separately, do not transfer responsibility for freeing text_ptr to libpng, +because when libpng fills a png_text structure it combines these members with +the key member, and png_free_data() will free only text_ptr.key. Similarly, +if you transfer responsibility for free'ing text_ptr from libpng to your +application, your application must not separately free those members. +For a more compact example of writing a PNG image, see the file example.c. + +V. Modifying/Customizing libpng: + +There are three issues here. The first is changing how libpng does +standard things like memory allocation, input/output, and error handling. +The second deals with more complicated things like adding new chunks, +adding new transformations, and generally changing how libpng works. +Both of those are compile-time issues; that is, they are generally +determined at the time the code is written, and there is rarely a need +to provide the user with a means of changing them. The third is a +run-time issue: choosing between and/or tuning one or more alternate +versions of computationally intensive routines; specifically, optimized +assembly-language (and therefore compiler- and platform-dependent) +versions. + +Memory allocation, input/output, and error handling + +All of the memory allocation, input/output, and error handling in libpng +goes through callbacks that are user-settable. The default routines are +in pngmem.c, pngrio.c, pngwio.c, and pngerror.c, respectively. To change +these functions, call the appropriate png_set_*_fn() function. + +Memory allocation is done through the functions png_malloc() +and png_free(). These currently just call the standard C functions. If +your pointers can't access more then 64K at a time, you will want to set +MAXSEG_64K in zlib.h. Since it is unlikely that the method of handling +memory allocation on a platform will change between applications, these +functions must be modified in the library at compile time. If you prefer +to use a different method of allocating and freeing data, you can use +png_create_read_struct_2() or png_create_write_struct_2() to register +your own functions as described above. +These functions also provide a void pointer that can be retrieved via + + mem_ptr=png_get_mem_ptr(png_ptr); + +Your replacement memory functions must have prototypes as follows: + + png_voidp malloc_fn(png_structp png_ptr, + png_size_t size); + void free_fn(png_structp png_ptr, png_voidp ptr); + +Your malloc_fn() must return NULL in case of failure. The png_malloc() +function will normally call png_error() if it receives a NULL from the +system memory allocator or from your replacement malloc_fn(). + +Input/Output in libpng is done through png_read() and png_write(), +which currently just call fread() and fwrite(). The FILE * is stored in +png_struct and is initialized via png_init_io(). If you wish to change +the method of I/O, the library supplies callbacks that you can set +through the function png_set_read_fn() and png_set_write_fn() at run +time, instead of calling the png_init_io() function. These functions +also provide a void pointer that can be retrieved via the function +png_get_io_ptr(). For example: + + png_set_read_fn(png_structp read_ptr, + voidp read_io_ptr, png_rw_ptr read_data_fn) + + png_set_write_fn(png_structp write_ptr, + voidp write_io_ptr, png_rw_ptr write_data_fn, + png_flush_ptr output_flush_fn); + + voidp read_io_ptr = png_get_io_ptr(read_ptr); + voidp write_io_ptr = png_get_io_ptr(write_ptr); + +The replacement I/O functions must have prototypes as follows: + + void user_read_data(png_structp png_ptr, + png_bytep data, png_size_t length); + void user_write_data(png_structp png_ptr, + png_bytep data, png_size_t length); + void user_flush_data(png_structp png_ptr); + +Supplying NULL for the read, write, or flush functions sets them back +to using the default C stream functions. It is an error to read from +a write stream, and vice versa. + +Error handling in libpng is done through png_error() and png_warning(). +Errors handled through png_error() are fatal, meaning that png_error() +should never return to its caller. Currently, this is handled via +setjmp() and longjmp() (unless you have compiled libpng with +PNG_SETJMP_NOT_SUPPORTED, in which case it is handled via PNG_ABORT()), +but you could change this to do things like exit() if you should wish. + +On non-fatal errors, png_warning() is called +to print a warning message, and then control returns to the calling code. +By default png_error() and png_warning() print a message on stderr via +fprintf() unless the library is compiled with PNG_NO_CONSOLE_IO defined +(because you don't want the messages) or PNG_NO_STDIO defined (because +fprintf() isn't available). If you wish to change the behavior of the error +functions, you will need to set up your own message callbacks. These +functions are normally supplied at the time that the png_struct is created. +It is also possible to redirect errors and warnings to your own replacement +functions after png_create_*_struct() has been called by calling: + + png_set_error_fn(png_structp png_ptr, + png_voidp error_ptr, png_error_ptr error_fn, + png_error_ptr warning_fn); + + png_voidp error_ptr = png_get_error_ptr(png_ptr); + +If NULL is supplied for either error_fn or warning_fn, then the libpng +default function will be used, calling fprintf() and/or longjmp() if a +problem is encountered. The replacement error functions should have +parameters as follows: + + void user_error_fn(png_structp png_ptr, + png_const_charp error_msg); + void user_warning_fn(png_structp png_ptr, + png_const_charp warning_msg); + +The motivation behind using setjmp() and longjmp() is the C++ throw and +catch exception handling methods. This makes the code much easier to write, +as there is no need to check every return code of every function call. +However, there are some uncertainties about the status of local variables +after a longjmp, so the user may want to be careful about doing anything after +setjmp returns non-zero besides returning itself. Consult your compiler +documentation for more details. For an alternative approach, you may wish +to use the "cexcept" facility (see http://cexcept.sourceforge.net). + +Custom chunks + +If you need to read or write custom chunks, you may need to get deeper +into the libpng code. The library now has mechanisms for storing +and writing chunks of unknown type; you can even declare callbacks +for custom chunks. Hoewver, this may not be good enough if the +library code itself needs to know about interactions between your +chunk and existing `intrinsic' chunks. + +If you need to write a new intrinsic chunk, first read the PNG +specification. Acquire a first level of +understanding of how it works. Pay particular attention to the +sections that describe chunk names, and look at how other chunks were +designed, so you can do things similarly. Second, check out the +sections of libpng that read and write chunks. Try to find a chunk +that is similar to yours and use it as a template. More details can +be found in the comments inside the code. It is best to handle unknown +chunks in a generic method, via callback functions, instead of by +modifying libpng functions. + +If you wish to write your own transformation for the data, look through +the part of the code that does the transformations, and check out some of +the simpler ones to get an idea of how they work. Try to find a similar +transformation to the one you want to add and copy off of it. More details +can be found in the comments inside the code itself. + +Configuring for 16 bit platforms + +You will want to look into zconf.h to tell zlib (and thus libpng) that +it cannot allocate more then 64K at a time. Even if you can, the memory +won't be accessible. So limit zlib and libpng to 64K by defining MAXSEG_64K. + +Configuring for DOS + +For DOS users who only have access to the lower 640K, you will +have to limit zlib's memory usage via a png_set_compression_mem_level() +call. See zlib.h or zconf.h in the zlib library for more information. + +Configuring for Medium Model + +Libpng's support for medium model has been tested on most of the popular +compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets +defined, and FAR gets defined to far in pngconf.h, and you should be +all set. Everything in the library (except for zlib's structure) is +expecting far data. You must use the typedefs with the p or pp on +the end for pointers (or at least look at them and be careful). Make +note that the rows of data are defined as png_bytepp, which is an +unsigned char far * far *. + +Configuring for gui/windowing platforms: + +You will need to write new error and warning functions that use the GUI +interface, as described previously, and set them to be the error and +warning functions at the time that png_create_*_struct() is called, +in order to have them available during the structure initialization. +They can be changed later via png_set_error_fn(). On some compilers, +you may also have to change the memory allocators (png_malloc, etc.). + +Configuring for compiler xxx: + +All includes for libpng are in pngconf.h. If you need to add/change/delete +an include, this is the place to do it. The includes that are not +needed outside libpng are protected by the PNG_INTERNAL definition, +which is only defined for those routines inside libpng itself. The +files in libpng proper only include png.h, which includes pngconf.h. + +Configuring zlib: + +There are special functions to configure the compression. Perhaps the +most useful one changes the compression level, which currently uses +input compression values in the range 0 - 9. The library normally +uses the default compression level (Z_DEFAULT_COMPRESSION = 6). Tests +have shown that for a large majority of images, compression values in +the range 3-6 compress nearly as well as higher levels, and do so much +faster. For online applications it may be desirable to have maximum speed +(Z_BEST_SPEED = 1). With versions of zlib after v0.99, you can also +specify no compression (Z_NO_COMPRESSION = 0), but this would create +files larger than just storing the raw bitmap. You can specify the +compression level by calling: + + png_set_compression_level(png_ptr, level); + +Another useful one is to reduce the memory level used by the library. +The memory level defaults to 8, but it can be lowered if you are +short on memory (running DOS, for example, where you only have 640K). +Note that the memory level does have an effect on compression; among +other things, lower levels will result in sections of incompressible +data being emitted in smaller stored blocks, with a correspondingly +larger relative overhead of up to 15% in the worst case. + + png_set_compression_mem_level(png_ptr, level); + +The other functions are for configuring zlib. They are not recommended +for normal use and may result in writing an invalid PNG file. See +zlib.h for more information on what these mean. + + png_set_compression_strategy(png_ptr, + strategy); + png_set_compression_window_bits(png_ptr, + window_bits); + png_set_compression_method(png_ptr, method); + png_set_compression_buffer_size(png_ptr, size); + +Controlling row filtering + +If you want to control whether libpng uses filtering or not, which +filters are used, and how it goes about picking row filters, you +can call one of these functions. The selection and configuration +of row filters can have a significant impact on the size and +encoding speed and a somewhat lesser impact on the decoding speed +of an image. Filtering is enabled by default for RGB and grayscale +images (with and without alpha), but not for paletted images nor +for any images with bit depths less than 8 bits/pixel. + +The 'method' parameter sets the main filtering method, which is +currently only '0' in the PNG 1.2 specification. The 'filters' +parameter sets which filter(s), if any, should be used for each +scanline. Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS +to turn filtering on and off, respectively. + +Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB, +PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise +ORed together with '|' to specify one or more filters to use. +These filters are described in more detail in the PNG specification. +If you intend to change the filter type during the course of writing +the image, you should start with flags set for all of the filters +you intend to use so that libpng can initialize its internal +structures appropriately for all of the filter types. (Note that this +means the first row must always be adaptively filtered, because libpng +currently does not allocate the filter buffers until png_write_row() +is called for the first time.) + + filters = PNG_FILTER_NONE | PNG_FILTER_SUB + PNG_FILTER_UP | PNG_FILTER_AVE | + PNG_FILTER_PAETH | PNG_ALL_FILTERS; + + png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, + filters); + The second parameter can also be + PNG_INTRAPIXEL_DIFFERENCING if you are + writing a PNG to be embedded in a MNG + datastream. This parameter must be the + same as the value of filter_method used + in png_set_IHDR(). + +It is also possible to influence how libpng chooses from among the +available filters. This is done in one or both of two ways - by +telling it how important it is to keep the same filter for successive +rows, and by telling it the relative computational costs of the filters. + + double weights[3] = {1.5, 1.3, 1.1}, + costs[PNG_FILTER_VALUE_LAST] = + {1.0, 1.3, 1.3, 1.5, 1.7}; + + png_set_filter_heuristics(png_ptr, + PNG_FILTER_HEURISTIC_WEIGHTED, 3, + weights, costs); + +The weights are multiplying factors that indicate to libpng that the +row filter should be the same for successive rows unless another row filter +is that many times better than the previous filter. In the above example, +if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a +"sum of absolute differences" 1.5 x 1.3 times higher than other filters +and still be chosen, while the NONE filter could have a sum 1.1 times +higher than other filters and still be chosen. Unspecified weights are +taken to be 1.0, and the specified weights should probably be declining +like those above in order to emphasize recent filters over older filters. + +The filter costs specify for each filter type a relative decoding cost +to be considered when selecting row filters. This means that filters +with higher costs are less likely to be chosen over filters with lower +costs, unless their "sum of absolute differences" is that much smaller. +The costs do not necessarily reflect the exact computational speeds of +the various filters, since this would unduly influence the final image +size. + +Note that the numbers above were invented purely for this example and +are given only to help explain the function usage. Little testing has +been done to find optimum values for either the costs or the weights. + +Removing unwanted object code + +There are a bunch of #define's in pngconf.h that control what parts of +libpng are compiled. All the defines end in _SUPPORTED. If you are +never going to use a capability, you can change the #define to #undef +before recompiling libpng and save yourself code and data space, or +you can turn off individual capabilities with defines that begin with +PNG_NO_. + +You can also turn all of the transforms and ancillary chunk capabilities +off en masse with compiler directives that define +PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS, +or all four, +along with directives to turn on any of the capabilities that you do +want. The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable +the extra transformations but still leave the library fully capable of reading +and writing PNG files with all known public chunks +Use of the PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive +produces a library that is incapable of reading or writing ancillary chunks. +If you are not using the progressive reading capability, you can +turn that off with PNG_NO_PROGRESSIVE_READ (don't confuse +this with the INTERLACING capability, which you'll still have). + +All the reading and writing specific code are in separate files, so the +linker should only grab the files it needs. However, if you want to +make sure, or if you are building a stand alone library, all the +reading files start with pngr and all the writing files start with +pngw. The files that don't match either (like png.c, pngtrans.c, etc.) +are used for both reading and writing, and always need to be included. +The progressive reader is in pngpread.c + +If you are creating or distributing a dynamically linked library (a .so +or DLL file), you should not remove or disable any parts of the library, +as this will cause applications linked with different versions of the +library to fail if they call functions not available in your library. +The size of the library itself should not be an issue, because only +those sections that are actually used will be loaded into memory. + +Requesting debug printout + +The macro definition PNG_DEBUG can be used to request debugging +printout. Set it to an integer value in the range 0 to 3. Higher +numbers result in increasing amounts of debugging information. The +information is printed to the "stderr" file, unless another file +name is specified in the PNG_DEBUG_FILE macro definition. + +When PNG_DEBUG > 0, the following functions (macros) become available: + + png_debug(level, message) + png_debug1(level, message, p1) + png_debug2(level, message, p1, p2) + +in which "level" is compared to PNG_DEBUG to decide whether to print +the message, "message" is the formatted string to be printed, +and p1 and p2 are parameters that are to be embedded in the string +according to printf-style formatting directives. For example, + + png_debug1(2, "foo=%d\n", foo); + +is expanded to + + if(PNG_DEBUG > 2) + fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo); + +When PNG_DEBUG is defined but is zero, the macros aren't defined, but you +can still use PNG_DEBUG to control your own debugging: + + #ifdef PNG_DEBUG + fprintf(stderr, ... + #endif + +When PNG_DEBUG = 1, the macros are defined, but only png_debug statements +having level = 0 will be printed. There aren't any such statements in +this version of libpng, but if you insert some they will be printed. + +VI. Runtime optimization + +A new feature in libpng 1.2.0 is the ability to dynamically switch between +standard and optimized versions of some routines. Currently these are +limited to three computationally intensive tasks when reading PNG files: +decoding row filters, expanding interlacing, and combining interlaced or +transparent row data with previous row data. Currently the optimized +versions are available only for x86 (Intel, AMD, etc.) platforms with +MMX support, though this may change in future versions. (For example, +the non-MMX assembler optimizations for zlib might become similarly +runtime-selectable in future releases, in which case libpng could be +extended to support them. Alternatively, the compile-time choice of +floating-point versus integer routines for gamma correction might become +runtime-selectable.) + +Because such optimizations tend to be very platform- and compiler-dependent, +both in how they are written and in how they perform, the new runtime code +in libpng has been written to allow programs to query, enable, and disable +either specific optimizations or all such optimizations. For example, to +enable all possible optimizations (bearing in mind that some "optimizations" +may actually run more slowly in rare cases): + + #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) + png_uint_32 mask, flags; + + flags = png_get_asm_flags(png_ptr); + mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE); + png_set_asm_flags(png_ptr, flags | mask); + #endif + +To enable only optimizations relevant to reading PNGs, use PNG_SELECT_READ +by itself when calling png_get_asm_flagmask(); similarly for optimizing +only writing. To disable all optimizations: + + #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) + flags = png_get_asm_flags(png_ptr); + mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE); + png_set_asm_flags(png_ptr, flags & ~mask); + #endif + +To enable or disable only MMX-related features, use png_get_mmx_flagmask() +in place of png_get_asm_flagmask(). The mmx version takes one additional +parameter: + + #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) + int selection = PNG_SELECT_READ | PNG_SELECT_WRITE; + int compilerID; + + mask = png_get_mmx_flagmask(selection, &compilerID); + #endif + +On return, compilerID will indicate which version of the MMX assembler +optimizations was compiled. Currently two flavors exist: Microsoft +Visual C++ (compilerID == 1) and GNU C (a.k.a. gcc/gas, compilerID == 2). +On non-x86 platforms or on systems compiled without MMX optimizations, a +value of -1 is used. + +Note that both png_get_asm_flagmask() and png_get_mmx_flagmask() return +all valid, settable optimization bits for the version of the library that's +currently in use. In the case of shared (dynamically linked) libraries, +this may include optimizations that did not exist at the time the code was +written and compiled. It is also possible, of course, to enable only known, +specific optimizations; for example: + + #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) + flags = PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ + | PNG_ASM_FLAG_MMX_READ_INTERLACE \ + | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ + | PNG_ASM_FLAG_MMX_READ_FILTER_UP \ + | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ + | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ; + png_set_asm_flags(png_ptr, flags); + #endif + +This method would enable only the MMX read-optimizations available at the +time of libpng 1.2.0's release, regardless of whether a later version of +the DLL were actually being used. (Also note that these functions did not +exist in versions older than 1.2.0, so any attempt to run a dynamically +linked app on such an older version would fail.) + +To determine whether the processor supports MMX instructions at all, use +the png_mmx_support() function: + + #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) + mmxsupport = png_mmx_support(); + #endif + +It returns -1 if MMX support is not compiled into libpng, 0 if MMX code +is compiled but MMX is not supported by the processor, or 1 if MMX support +is fully available. Note that png_mmx_support(), png_get_mmx_flagmask(), +and png_get_asm_flagmask() all may be called without allocating and ini- +tializing any PNG structures (for example, as part of a usage screen or +"about" box). + +The following code can be used to prevent an application from using the +thread_unsafe features, even if libpng was built with PNG_THREAD_UNSAFE_OK +defined: + +#if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) \ + && defined(PNG_THREAD_UNSAFE_OK) + /* Disable thread-unsafe features of pnggccrd */ + if (png_access_version() >= 10200) + { + png_uint_32 mmx_disable_mask = 0; + png_uint_32 asm_flags; + + mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ + | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ + | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ + | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); + asm_flags = png_get_asm_flags(png_ptr); + png_set_asm_flags(png_ptr, asm_flags & ~mmx_disable_mask); + } +#endif + +For more extensive examples of runtime querying, enabling and disabling +of optimized features, see contrib/gregbook/readpng2.c in the libpng +source-code distribution. + +VII. MNG support + +The MNG specification (available at http://www.libpng.org/pub/mng) allows +certain extensions to PNG for PNG images that are embedded in MNG datastreams. +Libpng can support some of these extensions. To enable them, use the +png_permit_mng_features() function: + + feature_set = png_permit_mng_features(png_ptr, mask) + mask is a png_uint_32 containing the logical OR of the + features you want to enable. These include + PNG_FLAG_MNG_EMPTY_PLTE + PNG_FLAG_MNG_FILTER_64 + PNG_ALL_MNG_FEATURES + feature_set is a png_uint_32 that is the logical AND of + your mask with the set of MNG features that is + supported by the version of libpng that you are using. + +It is an error to use this function when reading or writing a standalone +PNG file with the PNG 8-byte signature. The PNG datastream must be wrapped +in a MNG datastream. As a minimum, it must have the MNG 8-byte signature +and the MHDR and MEND chunks. Libpng does not provide support for these +or any other MNG chunks; your application must provide its own support for +them. You may wish to consider using libmng (available at +http://www.libmng.com) instead. + +VIII. Changes to Libpng from version 0.88 + +It should be noted that versions of libpng later than 0.96 are not +distributed by the original libpng author, Guy Schalnat, nor by +Andreas Dilger, who had taken over from Guy during 1996 and 1997, and +distributed versions 0.89 through 0.96, but rather by another member +of the original PNG Group, Glenn Randers-Pehrson. Guy and Andreas are +still alive and well, but they have moved on to other things. + +The old libpng functions png_read_init(), png_write_init(), +png_info_init(), png_read_destroy(), and png_write_destroy() have been +moved to PNG_INTERNAL in version 0.95 to discourage their use. These +functions will be removed from libpng version 2.0.0. + +The preferred method of creating and initializing the libpng structures is +via the png_create_read_struct(), png_create_write_struct(), and +png_create_info_struct() because they isolate the size of the structures +from the application, allow version error checking, and also allow the +use of custom error handling routines during the initialization, which +the old functions do not. The functions png_read_destroy() and +png_write_destroy() do not actually free the memory that libpng +allocated for these structs, but just reset the data structures, so they +can be used instead of png_destroy_read_struct() and +png_destroy_write_struct() if you feel there is too much system overhead +allocating and freeing the png_struct for each image read. + +Setting the error callbacks via png_set_message_fn() before +png_read_init() as was suggested in libpng-0.88 is no longer supported +because this caused applications that do not use custom error functions +to fail if the png_ptr was not initialized to zero. It is still possible +to set the error callbacks AFTER png_read_init(), or to change them with +png_set_error_fn(), which is essentially the same function, but with a new +name to force compilation errors with applications that try to use the old +method. + +Starting with version 1.0.7, you can find out which version of the library +you are using at run-time: + + png_uint_32 libpng_vn = png_access_version_number(); + +The number libpng_vn is constructed from the major version, minor +version with leading zero, and release number with leading zero, +(e.g., libpng_vn for version 1.0.7 is 10007). + +You can also check which version of png.h you used when compiling your +application: + + png_uint_32 application_vn = PNG_LIBPNG_VER; + +IX. Y2K Compliance in libpng + +September 12, 2004 + +Since the PNG Development group is an ad-hoc body, we can't make +an official declaration. + +This is your unofficial assurance that libpng from version 0.71 and +upward through 1.2.7 are Y2K compliant. It is my belief that earlier +versions were also Y2K compliant. + +Libpng only has three year fields. One is a 2-byte unsigned integer that +will hold years up to 65535. The other two hold the date in text +format, and will hold years up to 9999. + +The integer is + "png_uint_16 year" in png_time_struct. + +The strings are + "png_charp time_buffer" in png_struct and + "near_time_buffer", which is a local character string in png.c. + +There are seven time-related functions: + + png_convert_to_rfc_1123() in png.c + (formerly png_convert_to_rfc_1152() in error) + png_convert_from_struct_tm() in pngwrite.c, called + in pngwrite.c + png_convert_from_time_t() in pngwrite.c + png_get_tIME() in pngget.c + png_handle_tIME() in pngrutil.c, called in pngread.c + png_set_tIME() in pngset.c + png_write_tIME() in pngwutil.c, called in pngwrite.c + +All appear to handle dates properly in a Y2K environment. The +png_convert_from_time_t() function calls gmtime() to convert from system +clock time, which returns (year - 1900), which we properly convert to +the full 4-digit year. There is a possibility that applications using +libpng are not passing 4-digit years into the png_convert_to_rfc_1123() +function, or that they are incorrectly passing only a 2-digit year +instead of "year - 1900" into the png_convert_from_struct_tm() function, +but this is not under our control. The libpng documentation has always +stated that it works with 4-digit years, and the APIs have been +documented as such. + +The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned +integer to hold the year, and can hold years as large as 65535. + +zlib, upon which libpng depends, is also Y2K compliant. It contains +no date-related code. + + + Glenn Randers-Pehrson + libpng maintainer + PNG Development Group diff --git a/SlnkDWFImpl/CxImage/png/png.c b/SlnkDWFImpl/CxImage/png/png.c new file mode 100644 index 0000000..512b4f6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/png.c @@ -0,0 +1,826 @@ + +/* png.c - location for general purpose libpng functions + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + */ + +#define PNG_INTERNAL +#define PNG_NO_EXTERN +#include "png.h" + +/* Generate a compiler error if there is an old png.h in the search path. */ +typedef version_1_2_7 Your_png_h_is_not_version_1_2_7; + +/* Version information for C files. This had better match the version + * string defined in png.h. */ + +#ifdef PNG_USE_GLOBAL_ARRAYS +/* png_libpng_ver was changed to a function in version 1.0.5c */ +const char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING; + +/* png_sig was changed to a function in version 1.0.5c */ +/* Place to hold the signature string for a PNG file. */ +const png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; + +/* Invoke global declarations for constant strings for known chunk types */ +PNG_IHDR; +PNG_IDAT; +PNG_IEND; +PNG_PLTE; +PNG_bKGD; +PNG_cHRM; +PNG_gAMA; +PNG_hIST; +PNG_iCCP; +PNG_iTXt; +PNG_oFFs; +PNG_pCAL; +PNG_sCAL; +PNG_pHYs; +PNG_sBIT; +PNG_sPLT; +PNG_sRGB; +PNG_tEXt; +PNG_tIME; +PNG_tRNS; +PNG_zTXt; + +/* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ + +/* start of interlace block */ +const int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; + +/* offset to next interlace block */ +const int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; + +/* start of interlace block in the y direction */ +const int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1}; + +/* offset to next interlace block in the y direction */ +const int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2}; + +/* width of interlace block (used in assembler routines only) */ +#ifdef PNG_HAVE_ASSEMBLER_COMBINE_ROW +const int FARDATA png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; +#endif + +/* Height of interlace block. This is not currently used - if you need + * it, uncomment it here and in png.h +const int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1}; +*/ + +/* Mask to determine which pixels are valid in a pass */ +const int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff}; + +/* Mask to determine which pixels to overwrite while displaying */ +const int FARDATA png_pass_dsp_mask[] + = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff}; + +#endif + +/* Tells libpng that we have already handled the first "num_bytes" bytes + * of the PNG file signature. If the PNG data is embedded into another + * stream we can set num_bytes = 8 so that libpng will not attempt to read + * or write any of the magic bytes before it starts on the IHDR. + */ + +void PNGAPI +png_set_sig_bytes(png_structp png_ptr, int num_bytes) +{ + png_debug(1, "in png_set_sig_bytes\n"); + if (num_bytes > 8) + png_error(png_ptr, "Too many bytes for PNG signature."); + + png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes); +} + +/* Checks whether the supplied bytes match the PNG signature. We allow + * checking less than the full 8-byte signature so that those apps that + * already read the first few bytes of a file to determine the file type + * can simply check the remaining bytes for extra assurance. Returns + * an integer less than, equal to, or greater than zero if sig is found, + * respectively, to be less than, to match, or be greater than the correct + * PNG signature (this is the same behaviour as strcmp, memcmp, etc). + */ +int PNGAPI +png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check) +{ + png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10}; + if (num_to_check > 8) + num_to_check = 8; + else if (num_to_check < 1) + return (0); + + if (start > 7) + return (0); + + if (start + num_to_check > 8) + num_to_check = 8 - start; + + return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check))); +} + +/* (Obsolete) function to check signature bytes. It does not allow one + * to check a partial signature. This function might be removed in the + * future - use png_sig_cmp(). Returns true (nonzero) if the file is a PNG. + */ +int PNGAPI +png_check_sig(png_bytep sig, int num) +{ + return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num)); +} + +/* Function to allocate memory for zlib and clear it to 0. */ +#ifdef PNG_1_0_X +voidpf PNGAPI +#else +voidpf /* private */ +#endif +png_zalloc(voidpf png_ptr, uInt items, uInt size) +{ + png_voidp ptr; + png_structp p=png_ptr; + png_uint_32 save_flags=p->flags; + png_uint_32 num_bytes; + + if (items > PNG_UINT_32_MAX/size) + { + png_warning (png_ptr, "Potential overflow in png_zalloc()"); + return (NULL); + } + num_bytes = (png_uint_32)items * size; + + p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; + ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); + p->flags=save_flags; + +#if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO) + if (ptr == NULL) + return ((voidpf)ptr); + + if (num_bytes > (png_uint_32)0x8000L) + { + png_memset(ptr, 0, (png_size_t)0x8000L); + png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, + (png_size_t)(num_bytes - (png_uint_32)0x8000L)); + } + else + { + png_memset(ptr, 0, (png_size_t)num_bytes); + } +#endif + return ((voidpf)ptr); +} + +/* function to free memory for zlib */ +#ifdef PNG_1_0_X +void PNGAPI +#else +void /* private */ +#endif +png_zfree(voidpf png_ptr, voidpf ptr) +{ + png_free((png_structp)png_ptr, (png_voidp)ptr); +} + +/* Reset the CRC variable to 32 bits of 1's. Care must be taken + * in case CRC is > 32 bits to leave the top bits 0. + */ +void /* PRIVATE */ +png_reset_crc(png_structp png_ptr) +{ + png_ptr->crc = crc32(0, Z_NULL, 0); +} + +/* Calculate the CRC over a section of data. We can only pass as + * much data to this routine as the largest single buffer size. We + * also check that this data will actually be used before going to the + * trouble of calculating it. + */ +void /* PRIVATE */ +png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length) +{ + int need_crc = 1; + + if (png_ptr->chunk_name[0] & 0x20) /* ancillary */ + { + if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) == + (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN)) + need_crc = 0; + } + else /* critical */ + { + if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) + need_crc = 0; + } + + if (need_crc) + png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length); +} + +/* Allocate the memory for an info_struct for the application. We don't + * really need the png_ptr, but it could potentially be useful in the + * future. This should be used in favour of malloc(png_sizeof(png_info)) + * and png_info_init() so that applications that want to use a shared + * libpng don't have to be recompiled if png_info changes size. + */ +png_infop PNGAPI +png_create_info_struct(png_structp png_ptr) +{ + png_infop info_ptr; + + png_debug(1, "in png_create_info_struct\n"); + if(png_ptr == NULL) return (NULL); +#ifdef PNG_USER_MEM_SUPPORTED + info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO, + png_ptr->malloc_fn, png_ptr->mem_ptr); +#else + info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO); +#endif + if (info_ptr != NULL) + png_info_init_3(&info_ptr, png_sizeof(png_info)); + + return (info_ptr); +} + +/* This function frees the memory associated with a single info struct. + * Normally, one would use either png_destroy_read_struct() or + * png_destroy_write_struct() to free an info struct, but this may be + * useful for some applications. + */ +void PNGAPI +png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr) +{ + png_infop info_ptr = NULL; + + png_debug(1, "in png_destroy_info_struct\n"); + if (info_ptr_ptr != NULL) + info_ptr = *info_ptr_ptr; + + if (info_ptr != NULL) + { + png_info_destroy(png_ptr, info_ptr); + +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn, + png_ptr->mem_ptr); +#else + png_destroy_struct((png_voidp)info_ptr); +#endif + *info_ptr_ptr = NULL; + } +} + +/* Initialize the info structure. This is now an internal function (0.89) + * and applications using it are urged to use png_create_info_struct() + * instead. + */ +#undef png_info_init +void PNGAPI +png_info_init(png_infop info_ptr) +{ + /* We only come here via pre-1.0.12-compiled applications */ + png_info_init_3(&info_ptr, 0); +} + +void PNGAPI +png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size) +{ + png_infop info_ptr = *ptr_ptr; + + png_debug(1, "in png_info_init_3\n"); + + if(png_sizeof(png_info) > png_info_struct_size) + { + png_destroy_struct(info_ptr); + info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO); + *ptr_ptr = info_ptr; + } + + /* set everything to 0 */ + png_memset(info_ptr, 0, png_sizeof (png_info)); +} + +#ifdef PNG_FREE_ME_SUPPORTED +void PNGAPI +png_data_freer(png_structp png_ptr, png_infop info_ptr, + int freer, png_uint_32 mask) +{ + png_debug(1, "in png_data_freer\n"); + if (png_ptr == NULL || info_ptr == NULL) + return; + if(freer == PNG_DESTROY_WILL_FREE_DATA) + info_ptr->free_me |= mask; + else if(freer == PNG_USER_WILL_FREE_DATA) + info_ptr->free_me &= ~mask; + else + png_warning(png_ptr, + "Unknown freer parameter in png_data_freer."); +} +#endif + +void PNGAPI +png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask, + int num) +{ + png_debug(1, "in png_free_data\n"); + if (png_ptr == NULL || info_ptr == NULL) + return; + +#if defined(PNG_TEXT_SUPPORTED) +/* free text item num or (if num == -1) all text items */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_TEXT) & info_ptr->free_me) +#else +if (mask & PNG_FREE_TEXT) +#endif +{ + if (num != -1) + { + if (info_ptr->text && info_ptr->text[num].key) + { + png_free(png_ptr, info_ptr->text[num].key); + info_ptr->text[num].key = NULL; + } + } + else + { + int i; + for (i = 0; i < info_ptr->num_text; i++) + png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i); + png_free(png_ptr, info_ptr->text); + info_ptr->text = NULL; + info_ptr->num_text=0; + } +} +#endif + +#if defined(PNG_tRNS_SUPPORTED) +/* free any tRNS entry */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_TRNS) & info_ptr->free_me) +#else +if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS)) +#endif +{ + png_free(png_ptr, info_ptr->trans); + info_ptr->valid &= ~PNG_INFO_tRNS; +#ifndef PNG_FREE_ME_SUPPORTED + png_ptr->flags &= ~PNG_FLAG_FREE_TRNS; +#endif + info_ptr->trans = NULL; +} +#endif + +#if defined(PNG_sCAL_SUPPORTED) +/* free any sCAL entry */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_SCAL) & info_ptr->free_me) +#else +if (mask & PNG_FREE_SCAL) +#endif +{ +#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED) + png_free(png_ptr, info_ptr->scal_s_width); + png_free(png_ptr, info_ptr->scal_s_height); + info_ptr->scal_s_width = NULL; + info_ptr->scal_s_height = NULL; +#endif + info_ptr->valid &= ~PNG_INFO_sCAL; +} +#endif + +#if defined(PNG_pCAL_SUPPORTED) +/* free any pCAL entry */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_PCAL) & info_ptr->free_me) +#else +if (mask & PNG_FREE_PCAL) +#endif +{ + png_free(png_ptr, info_ptr->pcal_purpose); + png_free(png_ptr, info_ptr->pcal_units); + info_ptr->pcal_purpose = NULL; + info_ptr->pcal_units = NULL; + if (info_ptr->pcal_params != NULL) + { + int i; + for (i = 0; i < (int)info_ptr->pcal_nparams; i++) + { + png_free(png_ptr, info_ptr->pcal_params[i]); + info_ptr->pcal_params[i]=NULL; + } + png_free(png_ptr, info_ptr->pcal_params); + info_ptr->pcal_params = NULL; + } + info_ptr->valid &= ~PNG_INFO_pCAL; +} +#endif + +#if defined(PNG_iCCP_SUPPORTED) +/* free any iCCP entry */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_ICCP) & info_ptr->free_me) +#else +if (mask & PNG_FREE_ICCP) +#endif +{ + png_free(png_ptr, info_ptr->iccp_name); + png_free(png_ptr, info_ptr->iccp_profile); + info_ptr->iccp_name = NULL; + info_ptr->iccp_profile = NULL; + info_ptr->valid &= ~PNG_INFO_iCCP; +} +#endif + +#if defined(PNG_sPLT_SUPPORTED) +/* free a given sPLT entry, or (if num == -1) all sPLT entries */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_SPLT) & info_ptr->free_me) +#else +if (mask & PNG_FREE_SPLT) +#endif +{ + if (num != -1) + { + if(info_ptr->splt_palettes) + { + png_free(png_ptr, info_ptr->splt_palettes[num].name); + png_free(png_ptr, info_ptr->splt_palettes[num].entries); + info_ptr->splt_palettes[num].name = NULL; + info_ptr->splt_palettes[num].entries = NULL; + } + } + else + { + if(info_ptr->splt_palettes_num) + { + int i; + for (i = 0; i < (int)info_ptr->splt_palettes_num; i++) + png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i); + + png_free(png_ptr, info_ptr->splt_palettes); + info_ptr->splt_palettes = NULL; + info_ptr->splt_palettes_num = 0; + } + info_ptr->valid &= ~PNG_INFO_sPLT; + } +} +#endif + +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_UNKN) & info_ptr->free_me) +#else +if (mask & PNG_FREE_UNKN) +#endif +{ + if (num != -1) + { + if(info_ptr->unknown_chunks) + { + png_free(png_ptr, info_ptr->unknown_chunks[num].data); + info_ptr->unknown_chunks[num].data = NULL; + } + } + else + { + int i; + + if(info_ptr->unknown_chunks_num) + { + for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++) + png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i); + + png_free(png_ptr, info_ptr->unknown_chunks); + info_ptr->unknown_chunks = NULL; + info_ptr->unknown_chunks_num = 0; + } + } +} +#endif + +#if defined(PNG_hIST_SUPPORTED) +/* free any hIST entry */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_HIST) & info_ptr->free_me) +#else +if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST)) +#endif +{ + png_free(png_ptr, info_ptr->hist); + info_ptr->hist = NULL; + info_ptr->valid &= ~PNG_INFO_hIST; +#ifndef PNG_FREE_ME_SUPPORTED + png_ptr->flags &= ~PNG_FLAG_FREE_HIST; +#endif +} +#endif + +/* free any PLTE entry that was internally allocated */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_PLTE) & info_ptr->free_me) +#else +if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE)) +#endif +{ + png_zfree(png_ptr, info_ptr->palette); + info_ptr->palette = NULL; + info_ptr->valid &= ~PNG_INFO_PLTE; +#ifndef PNG_FREE_ME_SUPPORTED + png_ptr->flags &= ~PNG_FLAG_FREE_PLTE; +#endif + info_ptr->num_palette = 0; +} + +#if defined(PNG_INFO_IMAGE_SUPPORTED) +/* free any image bits attached to the info structure */ +#ifdef PNG_FREE_ME_SUPPORTED +if ((mask & PNG_FREE_ROWS) & info_ptr->free_me) +#else +if (mask & PNG_FREE_ROWS) +#endif +{ + if(info_ptr->row_pointers) + { + int row; + for (row = 0; row < (int)info_ptr->height; row++) + { + png_free(png_ptr, info_ptr->row_pointers[row]); + info_ptr->row_pointers[row]=NULL; + } + png_free(png_ptr, info_ptr->row_pointers); + info_ptr->row_pointers=NULL; + } + info_ptr->valid &= ~PNG_INFO_IDAT; +} +#endif + +#ifdef PNG_FREE_ME_SUPPORTED + if(num == -1) + info_ptr->free_me &= ~mask; + else + info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL); +#endif +} + +/* This is an internal routine to free any memory that the info struct is + * pointing to before re-using it or freeing the struct itself. Recall + * that png_free() checks for NULL pointers for us. + */ +void /* PRIVATE */ +png_info_destroy(png_structp png_ptr, png_infop info_ptr) +{ + png_debug(1, "in png_info_destroy\n"); + + png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1); + +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) + if (png_ptr->num_chunk_list) + { + png_free(png_ptr, png_ptr->chunk_list); + png_ptr->chunk_list=NULL; + png_ptr->num_chunk_list=0; + } +#endif + + png_info_init_3(&info_ptr, png_sizeof(png_info)); +} + +/* This function returns a pointer to the io_ptr associated with the user + * functions. The application should free any memory associated with this + * pointer before png_write_destroy() or png_read_destroy() are called. + */ +png_voidp PNGAPI +png_get_io_ptr(png_structp png_ptr) +{ + return (png_ptr->io_ptr); +} + +#if !defined(PNG_NO_STDIO) +/* Initialize the default input/output functions for the PNG file. If you + * use your own read or write routines, you can call either png_set_read_fn() + * or png_set_write_fn() instead of png_init_io(). If you have defined + * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't + * necessarily available. + */ +void PNGAPI +png_init_io(png_structp png_ptr, png_FILE_p fp) +{ + png_debug(1, "in png_init_io\n"); + png_ptr->io_ptr = (png_voidp)fp; +} +#endif + +#if defined(PNG_TIME_RFC1123_SUPPORTED) +/* Convert the supplied time into an RFC 1123 string suitable for use in + * a "Creation Time" or other text-based time string. + */ +png_charp PNGAPI +png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime) +{ + static PNG_CONST char short_months[12][4] = + {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + + if (png_ptr->time_buffer == NULL) + { + png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29* + png_sizeof(char))); + } + +#if defined(_WIN32_WCE) + { + wchar_t time_buf[29]; + wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"), + ptime->day % 32, short_months[(ptime->month - 1) % 12], + ptime->year, ptime->hour % 24, ptime->minute % 60, + ptime->second % 61); + WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29, + NULL, NULL); + } +#else +#ifdef USE_FAR_KEYWORD + { + char near_time_buf[29]; + sprintf(near_time_buf, "%d %s %d %02d:%02d:%02d +0000", + ptime->day % 32, short_months[(ptime->month - 1) % 12], + ptime->year, ptime->hour % 24, ptime->minute % 60, + ptime->second % 61); + png_memcpy(png_ptr->time_buffer, near_time_buf, + 29*png_sizeof(char)); + } +#else + sprintf(png_ptr->time_buffer, "%d %s %d %02d:%02d:%02d +0000", + ptime->day % 32, short_months[(ptime->month - 1) % 12], + ptime->year, ptime->hour % 24, ptime->minute % 60, + ptime->second % 61); +#endif +#endif /* _WIN32_WCE */ + return ((png_charp)png_ptr->time_buffer); +} +#endif /* PNG_TIME_RFC1123_SUPPORTED */ + +#if 0 +/* Signature string for a PNG file. */ +png_bytep PNGAPI +png_sig_bytes(void) +{ + return ((png_bytep)"\211\120\116\107\015\012\032\012"); +} +#endif + +png_charp PNGAPI +png_get_copyright(png_structp png_ptr) +{ + if (&png_ptr != NULL) /* silence compiler warning about unused png_ptr */ + return ((png_charp) "\n libpng version 1.2.7 - September 12, 2004\n\ + Copyright (c) 1998-2004 Glenn Randers-Pehrson\n\ + Copyright (c) 1996-1997 Andreas Dilger\n\ + Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n"); + return ((png_charp) ""); +} + +/* The following return the library version as a short string in the + * format 1.0.0 through 99.99.99zz. To get the version of *.h files + * used with your application, print out PNG_LIBPNG_VER_STRING, which + * is defined in png.h. + * Note: now there is no difference between png_get_libpng_ver() and + * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard, + * it is guaranteed that png.c uses the correct version of png.h. + */ +png_charp PNGAPI +png_get_libpng_ver(png_structp png_ptr) +{ + /* Version of *.c files used when building libpng */ + if (&png_ptr != NULL) /* silence compiler warning about unused png_ptr */ + return ((png_charp) PNG_LIBPNG_VER_STRING); + return ((png_charp) ""); +} + +png_charp PNGAPI +png_get_header_ver(png_structp png_ptr) +{ + /* Version of *.h files used when building libpng */ + if (&png_ptr != NULL) /* silence compiler warning about unused png_ptr */ + return ((png_charp) PNG_LIBPNG_VER_STRING); + return ((png_charp) ""); +} + +png_charp PNGAPI +png_get_header_version(png_structp png_ptr) +{ + /* Returns longer string containing both version and date */ + if (&png_ptr != NULL) /* silence compiler warning about unused png_ptr */ + return ((png_charp) PNG_HEADER_VERSION_STRING); + return ((png_charp) ""); +} + +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED +int PNGAPI +png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name) +{ + /* check chunk_name and return "keep" value if it's on the list, else 0 */ + int i; + png_bytep p; + if((png_ptr == NULL && chunk_name == NULL) || png_ptr->num_chunk_list<=0) + return 0; + p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5; + for (i = png_ptr->num_chunk_list; i; i--, p-=5) + if (!png_memcmp(chunk_name, p, 4)) + return ((int)*(p+4)); + return 0; +} +#endif + +/* This function, added to libpng-1.0.6g, is untested. */ +int PNGAPI +png_reset_zstream(png_structp png_ptr) +{ + return (inflateReset(&png_ptr->zstream)); +} + +/* This function was added to libpng-1.0.7 */ +png_uint_32 PNGAPI +png_access_version_number(void) +{ + /* Version of *.c files used when building libpng */ + return((png_uint_32) PNG_LIBPNG_VER); +} + + +#if !defined(PNG_1_0_X) +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) + /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */ +/* this INTERNAL function was added to libpng 1.2.0 */ +void /* PRIVATE */ +png_init_mmx_flags (png_structp png_ptr) +{ + png_ptr->mmx_rowbytes_threshold = 0; + png_ptr->mmx_bitdepth_threshold = 0; + +# if (defined(PNG_USE_PNGVCRD) || defined(PNG_USE_PNGGCCRD)) + + png_ptr->asm_flags |= PNG_ASM_FLAG_MMX_SUPPORT_COMPILED; + + if (png_mmx_support() > 0) { + png_ptr->asm_flags |= PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU +# ifdef PNG_HAVE_ASSEMBLER_COMBINE_ROW + | PNG_ASM_FLAG_MMX_READ_COMBINE_ROW +# endif +# ifdef PNG_HAVE_ASSEMBLER_READ_INTERLACE + | PNG_ASM_FLAG_MMX_READ_INTERLACE +# endif +# ifndef PNG_HAVE_ASSEMBLER_READ_FILTER_ROW + ; +# else + | PNG_ASM_FLAG_MMX_READ_FILTER_SUB + | PNG_ASM_FLAG_MMX_READ_FILTER_UP + | PNG_ASM_FLAG_MMX_READ_FILTER_AVG + | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ; + + png_ptr->mmx_rowbytes_threshold = PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT; + png_ptr->mmx_bitdepth_threshold = PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT; +# endif + } else { + png_ptr->asm_flags &= ~( PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU + | PNG_MMX_READ_FLAGS + | PNG_MMX_WRITE_FLAGS ); + } + +# else /* !((PNGVCRD || PNGGCCRD) && PNG_ASSEMBLER_CODE_SUPPORTED)) */ + + /* clear all MMX flags; no support is compiled in */ + png_ptr->asm_flags &= ~( PNG_MMX_FLAGS ); + +# endif /* ?(PNGVCRD || PNGGCCRD) */ +} + +#endif /* !(PNG_ASSEMBLER_CODE_SUPPORTED) */ + +/* this function was added to libpng 1.2.0 */ +#if !defined(PNG_USE_PNGGCCRD) && \ + !(defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_USE_PNGVCRD)) +int PNGAPI +png_mmx_support(void) +{ + return -1; +} +#endif +#endif /* PNG_1_0_X */ + +#ifdef PNG_SIZE_T +/* Added at libpng version 1.2.6 */ + PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size)); +png_size_t PNGAPI +png_convert_size(size_t size) +{ + if (size > (png_size_t)-1) + PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */ + return ((png_size_t)size); +} +#endif /* PNG_SIZE_T */ diff --git a/SlnkDWFImpl/CxImage/png/png.dsp b/SlnkDWFImpl/CxImage/png/png.dsp new file mode 100644 index 0000000..e9cac57 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/png.dsp @@ -0,0 +1,170 @@ +# Microsoft Developer Studio Project File - Name="png" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=png - Win32 Release +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "png.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "png.mak" CFG="png - Win32 Release" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "png - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "png - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "png - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir ".\Release" +# PROP BASE Intermediate_Dir ".\Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\zlib" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_AFXDLL" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x809 +# ADD RSC /l 0x809 /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "png - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir ".\Debug" +# PROP BASE Intermediate_Dir ".\Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c +# ADD CPP /nologo /MDd /W3 /GX /ZI /Od /I "..\zlib" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_AFXDLL" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x809 +# ADD RSC /l 0x809 /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "png - Win32 Release" +# Name "png - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90" +# Begin Source File + +SOURCE=.\png.c +# End Source File +# Begin Source File + +SOURCE=.\pngerror.c +# End Source File +# Begin Source File + +SOURCE=.\pngget.c +# End Source File +# Begin Source File + +SOURCE=.\pngmem.c +# End Source File +# Begin Source File + +SOURCE=.\pngpread.c +# End Source File +# Begin Source File + +SOURCE=.\pngread.c +# End Source File +# Begin Source File + +SOURCE=.\pngrio.c +# End Source File +# Begin Source File + +SOURCE=.\pngrtran.c +# End Source File +# Begin Source File + +SOURCE=.\pngrutil.c +# End Source File +# Begin Source File + +SOURCE=.\pngset.c +# End Source File +# Begin Source File + +SOURCE=.\pngtrans.c +# End Source File +# Begin Source File + +SOURCE=.\pngvcrd.c +# End Source File +# Begin Source File + +SOURCE=.\pngwio.c +# End Source File +# Begin Source File + +SOURCE=.\pngwrite.c +# End Source File +# Begin Source File + +SOURCE=.\pngwtran.c +# End Source File +# Begin Source File + +SOURCE=.\pngwutil.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" +# Begin Source File + +SOURCE=.\png.h +# End Source File +# Begin Source File + +SOURCE=.\pngconf.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/png/png.dsw b/SlnkDWFImpl/CxImage/png/png.dsw new file mode 100644 index 0000000..030fb06 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/png.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "png"=.\png.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/png/png.h b/SlnkDWFImpl/CxImage/png/png.h new file mode 100644 index 0000000..1d85d8d --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/png.h @@ -0,0 +1,3361 @@ +/* png.h - header file for PNG reference library + * + * libpng version 1.2.7 - September 12, 2004 + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * Authors and maintainers: + * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat + * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger + * libpng versions 0.97, January 1998, through 1.2.7 - September 12, 2004: Glenn + * See also "Contributing Authors", below. + * + * Note about libpng version numbers: + * + * Due to various miscommunications, unforeseen code incompatibilities + * and occasional factors outside the authors' control, version numbering + * on the library has not always been consistent and straightforward. + * The following table summarizes matters since version 0.89c, which was + * the first widely used release: + * + * source png.h png.h shared-lib + * version string int version + * ------- ------ ----- ---------- + * 0.89c "1.0 beta 3" 0.89 89 1.0.89 + * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90] + * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95] + * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96] + * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97] + * 0.97c 0.97 97 2.0.97 + * 0.98 0.98 98 2.0.98 + * 0.99 0.99 98 2.0.99 + * 0.99a-m 0.99 99 2.0.99 + * 1.00 1.00 100 2.1.0 [100 should be 10000] + * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000] + * 1.0.1 png.h string is 10001 2.1.0 + * 1.0.1a-e identical to the 10002 from here on, the shared library + * 1.0.2 source version) 10002 is 2.V where V is the source code + * 1.0.2a-b 10003 version, except as noted. + * 1.0.3 10003 + * 1.0.3a-d 10004 + * 1.0.4 10004 + * 1.0.4a-f 10005 + * 1.0.5 (+ 2 patches) 10005 + * 1.0.5a-d 10006 + * 1.0.5e-r 10100 (not source compatible) + * 1.0.5s-v 10006 (not binary compatible) + * 1.0.6 (+ 3 patches) 10006 (still binary incompatible) + * 1.0.6d-f 10007 (still binary incompatible) + * 1.0.6g 10007 + * 1.0.6h 10007 10.6h (testing xy.z so-numbering) + * 1.0.6i 10007 10.6i + * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0) + * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible) + * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible) + * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible) + * 1.0.7 1 10007 (still compatible) + * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4 + * 1.0.8rc1 1 10008 2.1.0.8rc1 + * 1.0.8 1 10008 2.1.0.8 + * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6 + * 1.0.9rc1 1 10009 2.1.0.9rc1 + * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10 + * 1.0.9rc2 1 10009 2.1.0.9rc2 + * 1.0.9 1 10009 2.1.0.9 + * 1.0.10beta1 1 10010 2.1.0.10beta1 + * 1.0.10rc1 1 10010 2.1.0.10rc1 + * 1.0.10 1 10010 2.1.0.10 + * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3 + * 1.0.11rc1 1 10011 2.1.0.11rc1 + * 1.0.11 1 10011 2.1.0.11 + * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2 + * 1.0.12rc1 2 10012 2.1.0.12rc1 + * 1.0.12 2 10012 2.1.0.12 + * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned) + * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2 + * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5 + * 1.2.0rc1 3 10200 3.1.2.0rc1 + * 1.2.0 3 10200 3.1.2.0 + * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4 + * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2 + * 1.2.1 3 10201 3.1.2.1 + * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6 + * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1 + * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1 + * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1 + * 1.0.13 10 10013 10.so.0.1.0.13 + * 1.2.2 12 10202 12.so.0.1.2.2 + * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6 + * 1.2.3 12 10203 12.so.0.1.2.3 + * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3 + * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1 + * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1 + * 1.0.14 10 10014 10.so.0.1.0.14 + * 1.2.4 13 10204 12.so.0.1.2.4 + * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2 + * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3 + * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3 + * 1.0.15 10 10015 10.so.0.1.0.15 + * 1.2.5 13 10205 12.so.0.1.2.5 + * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4 + * 1.0.16 10 10016 10.so.0.1.0.16 + * 1.2.6 13 10206 12.so.0.1.2.6 + * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2 + * 1.0.17rc1 10 10017 12.so.0.1.0.17rc1 + * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1 + * 1.0.17 10 10017 12.so.0.1.0.17 + * 1.2.7 13 10207 12.so.0.1.2.7 + * + * Henceforth the source version will match the shared-library major + * and minor numbers; the shared-library major version number will be + * used for changes in backward compatibility, as it is intended. The + * PNG_LIBPNG_VER macro, which is not used within libpng but is available + * for applications, is an unsigned integer of the form xyyzz corresponding + * to the source version x.y.z (leading zeros in y and z). Beta versions + * were given the previous public release number plus a letter, until + * version 1.0.6j; from then on they were given the upcoming public + * release number plus "betaNN" or "rcN". + * + * Binary incompatibility exists only when applications make direct access + * to the info_ptr or png_ptr members through png.h, and the compiled + * application is loaded with a different version of the library. + * + * DLLNUM will change each time there are forward or backward changes + * in binary compatibility (e.g., when a new feature is added). + * + * See libpng.txt or libpng.3 for more information. The PNG specification + * is available as a W3C Recommendation and as an ISO Specification, + * defines should NOT be changed. + */ +#define PNG_INFO_gAMA 0x0001 +#define PNG_INFO_sBIT 0x0002 +#define PNG_INFO_cHRM 0x0004 +#define PNG_INFO_PLTE 0x0008 +#define PNG_INFO_tRNS 0x0010 +#define PNG_INFO_bKGD 0x0020 +#define PNG_INFO_hIST 0x0040 +#define PNG_INFO_pHYs 0x0080 +#define PNG_INFO_oFFs 0x0100 +#define PNG_INFO_tIME 0x0200 +#define PNG_INFO_pCAL 0x0400 +#define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */ +#define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */ +#define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */ +#define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */ +#define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */ + +/* This is used for the transformation routines, as some of them + * change these values for the row. It also should enable using + * the routines for other purposes. + */ +typedef struct png_row_info_struct +{ + png_uint_32 width; /* width of row */ + png_uint_32 rowbytes; /* number of bytes in row */ + png_byte color_type; /* color type of row */ + png_byte bit_depth; /* bit depth of row */ + png_byte channels; /* number of channels (1, 2, 3, or 4) */ + png_byte pixel_depth; /* bits per pixel (depth * channels) */ +} png_row_info; + +typedef png_row_info FAR * png_row_infop; +typedef png_row_info FAR * FAR * png_row_infopp; + +/* These are the function types for the I/O functions and for the functions + * that allow the user to override the default I/O functions with his or her + * own. The png_error_ptr type should match that of user-supplied warning + * and error functions, while the png_rw_ptr type should match that of the + * user read/write data functions. + */ +typedef struct png_struct_def png_struct; +typedef png_struct FAR * png_structp; + +typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp)); +typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t)); +typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp)); +typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32, + int)); +typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32, + int)); + +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED +typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop)); +typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop)); +typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep, + png_uint_32, int)); +#endif + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_LEGACY_SUPPORTED) +typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp, + png_row_infop, png_bytep)); +#endif + +#if defined(PNG_USER_CHUNKS_SUPPORTED) +typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp)); +#endif +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) +typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp)); +#endif + +/* Transform masks for the high-level interface */ +#define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */ +#define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */ +#define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */ +#define PNG_TRANSFORM_PACKING 0x0004 /* read and write */ +#define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */ +#define PNG_TRANSFORM_EXPAND 0x0010 /* read only */ +#define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */ +#define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */ +#define PNG_TRANSFORM_BGR 0x0080 /* read and write */ +#define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */ +#define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */ +#define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */ +#define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */ + +/* Flags for MNG supported features */ +#define PNG_FLAG_MNG_EMPTY_PLTE 0x01 +#define PNG_FLAG_MNG_FILTER_64 0x04 +#define PNG_ALL_MNG_FEATURES 0x05 + +typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t)); +typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp)); + +/* The structure that holds the information to read and write PNG files. + * The only people who need to care about what is inside of this are the + * people who will be modifying the library for their own special needs. + * It should NOT be accessed directly by an application, except to store + * the jmp_buf. + */ + +struct png_struct_def +{ +#ifdef PNG_SETJMP_SUPPORTED + jmp_buf jmpbuf; /* used in png_error */ +#endif + png_error_ptr error_fn; /* function for printing errors and aborting */ + png_error_ptr warning_fn; /* function for printing warnings */ + png_voidp error_ptr; /* user supplied struct for error functions */ + png_rw_ptr write_data_fn; /* function for writing output data */ + png_rw_ptr read_data_fn; /* function for reading input data */ + png_voidp io_ptr; /* ptr to application struct for I/O functions */ + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) + png_user_transform_ptr read_user_transform_fn; /* user read transform */ +#endif + +#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) + png_user_transform_ptr write_user_transform_fn; /* user write transform */ +#endif + +/* These were added in libpng-1.0.2 */ +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) + png_voidp user_transform_ptr; /* user supplied struct for user transform */ + png_byte user_transform_depth; /* bit depth of user transformed pixels */ + png_byte user_transform_channels; /* channels in user transformed pixels */ +#endif +#endif + + png_uint_32 mode; /* tells us where we are in the PNG file */ + png_uint_32 flags; /* flags indicating various things to libpng */ + png_uint_32 transformations; /* which transformations to perform */ + + z_stream zstream; /* pointer to decompression structure (below) */ + png_bytep zbuf; /* buffer for zlib */ + png_size_t zbuf_size; /* size of zbuf */ + int zlib_level; /* holds zlib compression level */ + int zlib_method; /* holds zlib compression method */ + int zlib_window_bits; /* holds zlib compression window bits */ + int zlib_mem_level; /* holds zlib compression memory level */ + int zlib_strategy; /* holds zlib compression strategy */ + + png_uint_32 width; /* width of image in pixels */ + png_uint_32 height; /* height of image in pixels */ + png_uint_32 num_rows; /* number of rows in current pass */ + png_uint_32 usr_width; /* width of row at start of write */ + png_uint_32 rowbytes; /* size of row in bytes */ + png_uint_32 irowbytes; /* size of current interlaced row in bytes */ + png_uint_32 iwidth; /* width of current interlaced row in pixels */ + png_uint_32 row_number; /* current row in interlace pass */ + png_bytep prev_row; /* buffer to save previous (unfiltered) row */ + png_bytep row_buf; /* buffer to save current (unfiltered) row */ + png_bytep sub_row; /* buffer to save "sub" row when filtering */ + png_bytep up_row; /* buffer to save "up" row when filtering */ + png_bytep avg_row; /* buffer to save "avg" row when filtering */ + png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */ + png_row_info row_info; /* used for transformation routines */ + + png_uint_32 idat_size; /* current IDAT size for read */ + png_uint_32 crc; /* current chunk CRC value */ + png_colorp palette; /* palette from the input file */ + png_uint_16 num_palette; /* number of color entries in palette */ + png_uint_16 num_trans; /* number of transparency values */ + png_byte chunk_name[5]; /* null-terminated name of current chunk */ + png_byte compression; /* file compression type (always 0) */ + png_byte filter; /* file filter type (always 0) */ + png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */ + png_byte pass; /* current interlace pass (0 - 6) */ + png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */ + png_byte color_type; /* color type of file */ + png_byte bit_depth; /* bit depth of file */ + png_byte usr_bit_depth; /* bit depth of users row */ + png_byte pixel_depth; /* number of bits per pixel */ + png_byte channels; /* number of channels in file */ + png_byte usr_channels; /* channels at start of write */ + png_byte sig_bytes; /* magic bytes read/written from start of file */ + +#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED) +#ifdef PNG_LEGACY_SUPPORTED + png_byte filler; /* filler byte for pixel expansion */ +#else + png_uint_16 filler; /* filler bytes for pixel expansion */ +#endif +#endif + +#if defined(PNG_bKGD_SUPPORTED) + png_byte background_gamma_type; +# ifdef PNG_FLOATING_POINT_SUPPORTED + float background_gamma; +# endif + png_color_16 background; /* background color in screen gamma space */ +#if defined(PNG_READ_GAMMA_SUPPORTED) + png_color_16 background_1; /* background normalized to gamma 1.0 */ +#endif +#endif /* PNG_bKGD_SUPPORTED */ + +#if defined(PNG_WRITE_FLUSH_SUPPORTED) + png_flush_ptr output_flush_fn;/* Function for flushing output */ + png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */ + png_uint_32 flush_rows; /* number of rows written since last flush */ +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) + int gamma_shift; /* number of "insignificant" bits 16-bit gamma */ +#ifdef PNG_FLOATING_POINT_SUPPORTED + float gamma; /* file gamma value */ + float screen_gamma; /* screen gamma value (display_exponent) */ +#endif +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) + png_bytep gamma_table; /* gamma table for 8-bit depth files */ + png_bytep gamma_from_1; /* converts from 1.0 to screen */ + png_bytep gamma_to_1; /* converts from file to 1.0 */ + png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */ + png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */ + png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */ +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED) + png_color_8 sig_bit; /* significant bits in each available channel */ +#endif + +#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED) + png_color_8 shift; /* shift for significant bit tranformation */ +#endif + +#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \ + || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) + png_bytep trans; /* transparency values for paletted files */ + png_color_16 trans_values; /* transparency values for non-paletted files */ +#endif + + png_read_status_ptr read_row_fn; /* called after each row is decoded */ + png_write_status_ptr write_row_fn; /* called after each row is encoded */ +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED + png_progressive_info_ptr info_fn; /* called after header data fully read */ + png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */ + png_progressive_end_ptr end_fn; /* called after image is complete */ + png_bytep save_buffer_ptr; /* current location in save_buffer */ + png_bytep save_buffer; /* buffer for previously read data */ + png_bytep current_buffer_ptr; /* current location in current_buffer */ + png_bytep current_buffer; /* buffer for recently used data */ + png_uint_32 push_length; /* size of current input chunk */ + png_uint_32 skip_length; /* bytes to skip in input data */ + png_size_t save_buffer_size; /* amount of data now in save_buffer */ + png_size_t save_buffer_max; /* total size of save_buffer */ + png_size_t buffer_size; /* total amount of available input data */ + png_size_t current_buffer_size; /* amount of data now in current_buffer */ + int process_mode; /* what push library is currently doing */ + int cur_palette; /* current push library palette index */ + +# if defined(PNG_TEXT_SUPPORTED) + png_size_t current_text_size; /* current size of text input data */ + png_size_t current_text_left; /* how much text left to read in input */ + png_charp current_text; /* current text chunk buffer */ + png_charp current_text_ptr; /* current location in current_text */ +# endif /* PNG_PROGRESSIVE_READ_SUPPORTED && PNG_TEXT_SUPPORTED */ + +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */ + +#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__) +/* for the Borland special 64K segment handler */ + png_bytepp offset_table_ptr; + png_bytep offset_table; + png_uint_16 offset_table_number; + png_uint_16 offset_table_count; + png_uint_16 offset_table_count_free; +#endif + +#if defined(PNG_READ_DITHER_SUPPORTED) + png_bytep palette_lookup; /* lookup table for dithering */ + png_bytep dither_index; /* index translation for palette files */ +#endif + +#if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED) + png_uint_16p hist; /* histogram */ +#endif + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + png_byte heuristic_method; /* heuristic for row filter selection */ + png_byte num_prev_filters; /* number of weights for previous rows */ + png_bytep prev_filters; /* filter type(s) of previous row(s) */ + png_uint_16p filter_weights; /* weight(s) for previous line(s) */ + png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */ + png_uint_16p filter_costs; /* relative filter calculation cost */ + png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */ +#endif + +#if defined(PNG_TIME_RFC1123_SUPPORTED) + png_charp time_buffer; /* String to hold RFC 1123 time text */ +#endif + +/* New members added in libpng-1.0.6 */ + +#ifdef PNG_FREE_ME_SUPPORTED + png_uint_32 free_me; /* flags items libpng is responsible for freeing */ +#endif + +#if defined(PNG_USER_CHUNKS_SUPPORTED) + png_voidp user_chunk_ptr; + png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */ +#endif + +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) + int num_chunk_list; + png_bytep chunk_list; +#endif + +/* New members added in libpng-1.0.3 */ +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) + png_byte rgb_to_gray_status; + /* These were changed from png_byte in libpng-1.0.6 */ + png_uint_16 rgb_to_gray_red_coeff; + png_uint_16 rgb_to_gray_green_coeff; + png_uint_16 rgb_to_gray_blue_coeff; +#endif + +/* New member added in libpng-1.0.4 (renamed in 1.0.9) */ +#if defined(PNG_MNG_FEATURES_SUPPORTED) || \ + defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) +/* changed from png_byte to png_uint_32 at version 1.2.0 */ +#ifdef PNG_1_0_X + png_byte mng_features_permitted; +#else + png_uint_32 mng_features_permitted; +#endif /* PNG_1_0_X */ +#endif + +/* New member added in libpng-1.0.7 */ +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) + png_fixed_point int_gamma; +#endif + +/* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */ +#if defined(PNG_MNG_FEATURES_SUPPORTED) + png_byte filter_type; +#endif + +#if defined(PNG_1_0_X) || (defined(PNG_DEBUG) && defined(PNG_USE_PNGGCCRD)) +/* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */ + png_uint_32 row_buf_size; +#endif + +/* New members added in libpng-1.2.0 */ +#if !defined(PNG_1_0_X) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) + png_byte mmx_bitdepth_threshold; + png_uint_32 mmx_rowbytes_threshold; + png_uint_32 asm_flags; +#endif + +/* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */ +#ifdef PNG_USER_MEM_SUPPORTED + png_voidp mem_ptr; /* user supplied struct for mem functions */ + png_malloc_ptr malloc_fn; /* function for allocating memory */ + png_free_ptr free_fn; /* function for freeing memory */ +#endif + +/* New member added in libpng-1.0.13 and 1.2.0 */ + png_bytep big_row_buf; /* buffer to save current (unfiltered) row */ + +#if defined(PNG_READ_DITHER_SUPPORTED) +/* The following three members were added at version 1.0.14 and 1.2.4 */ + png_bytep dither_sort; /* working sort array */ + png_bytep index_to_palette; /* where the original index currently is */ + /* in the palette */ + png_bytep palette_to_index; /* which original index points to this */ + /* palette color */ +#endif + +/* New members added in libpng-1.0.16 and 1.2.6 */ + png_byte compression_type; + +#ifdef PNG_SET_USER_LIMITS_SUPPORTED + png_uint_32 user_width_max; + png_uint_32 user_height_max; +#endif + +}; + + +/* This triggers a compiler error in png.c, if png.c and png.h + * do not agree upon the version number. + */ +typedef png_structp version_1_2_7; + +typedef png_struct FAR * FAR * png_structpp; + +/* Here are the function definitions most commonly used. This is not + * the place to find out how to use libpng. See libpng.txt for the + * full explanation, see example.c for the summary. This just provides + * a simple one line description of the use of each function. + */ + +/* Returns the version number of the library */ +extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void)); + +/* Tell lib we have already handled the first magic bytes. + * Handling more than 8 bytes from the beginning of the file is an error. + */ +extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr, + int num_bytes)); + +/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a + * PNG file. Returns zero if the supplied bytes match the 8-byte PNG + * signature, and non-zero otherwise. Having num_to_check == 0 or + * start > 7 will always fail (ie return non-zero). + */ +extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start, + png_size_t num_to_check)); + +/* Simple signature checking function. This is the same as calling + * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n). + */ +extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num)); + +/* Allocate and initialize png_ptr struct for reading, and any other memory. */ +extern PNG_EXPORT(png_structp,png_create_read_struct) + PNGARG((png_const_charp user_png_ver, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warn_fn)); + +/* Allocate and initialize png_ptr struct for writing, and any other memory */ +extern PNG_EXPORT(png_structp,png_create_write_struct) + PNGARG((png_const_charp user_png_ver, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warn_fn)); + +#ifdef PNG_WRITE_SUPPORTED +extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size) + PNGARG((png_structp png_ptr)); +#endif + +#ifdef PNG_WRITE_SUPPORTED +extern PNG_EXPORT(void,png_set_compression_buffer_size) + PNGARG((png_structp png_ptr, png_uint_32 size)); +#endif + +/* Reset the compression stream */ +extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr)); + +/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */ +#ifdef PNG_USER_MEM_SUPPORTED +extern PNG_EXPORT(png_structp,png_create_read_struct_2) + PNGARG((png_const_charp user_png_ver, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, + png_malloc_ptr malloc_fn, png_free_ptr free_fn)); +extern PNG_EXPORT(png_structp,png_create_write_struct_2) + PNGARG((png_const_charp user_png_ver, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, + png_malloc_ptr malloc_fn, png_free_ptr free_fn)); +#endif + +/* Write a PNG chunk - size, type, (optional) data, CRC. */ +extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr, + png_bytep chunk_name, png_bytep data, png_size_t length)); + +/* Write the start of a PNG chunk - length and chunk name. */ +extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr, + png_bytep chunk_name, png_uint_32 length)); + +/* Write the data of a PNG chunk started with png_write_chunk_start(). */ +extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr, + png_bytep data, png_size_t length)); + +/* Finish a chunk started with png_write_chunk_start() (includes CRC). */ +extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr)); + +/* Allocate and initialize the info structure */ +extern PNG_EXPORT(png_infop,png_create_info_struct) + PNGARG((png_structp png_ptr)); + +/* Initialize the info structure (old interface - DEPRECATED) */ +extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr)); +#undef png_info_init +#define png_info_init(info_ptr) png_info_init_3(&info_ptr,\ + png_sizeof(png_info)); +extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr, + png_size_t png_info_struct_size)); + +/* Writes all the PNG information before the image. */ +extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr, + png_infop info_ptr)); +extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr, + png_infop info_ptr)); + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* read the information before the actual image data. */ +extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr, + png_infop info_ptr)); +#endif + +#if defined(PNG_TIME_RFC1123_SUPPORTED) +extern PNG_EXPORT(png_charp,png_convert_to_rfc1123) + PNGARG((png_structp png_ptr, png_timep ptime)); +#endif + +#if !defined(_WIN32_WCE) +/* "time.h" functions are not supported on WindowsCE */ +#if defined(PNG_WRITE_tIME_SUPPORTED) +/* convert from a struct tm to png_time */ +extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime, + struct tm FAR * ttime)); + +/* convert from time_t to png_time. Uses gmtime() */ +extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime, + time_t ttime)); +#endif /* PNG_WRITE_tIME_SUPPORTED */ +#endif /* _WIN32_WCE */ + +#if defined(PNG_READ_EXPAND_SUPPORTED) +/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */ +extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr)); +extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr)); +extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr)); +extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) +/* Use blue, green, red order for pixels. */ +extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) +/* Expand the grayscale to 24-bit RGB if necessary. */ +extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) +/* Reduce RGB to grayscale. */ +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr, + int error_action, double red, double green )); +#endif +extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr, + int error_action, png_fixed_point red, png_fixed_point green )); +extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp + png_ptr)); +#endif + +extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth, + png_colorp palette)); + +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED) +extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \ + defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) +extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \ + defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) +extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED) +/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */ +extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr, + png_uint_32 filler, int flags)); +/* The values of the PNG_FILLER_ defines should NOT be changed */ +#define PNG_FILLER_BEFORE 0 +#define PNG_FILLER_AFTER 1 +/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */ +#if !defined(PNG_1_0_X) +extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr, + png_uint_32 filler, int flags)); +#endif +#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */ + +#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) +/* Swap bytes in 16-bit depth files. */ +extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) +/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */ +extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED) +/* Swap packing order of pixels in bytes. */ +extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED) +/* Converts files to legal bit depths. */ +extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr, + png_color_8p true_bits)); +#endif + +#if defined(PNG_READ_INTERLACING_SUPPORTED) || \ + defined(PNG_WRITE_INTERLACING_SUPPORTED) +/* Have the code handle the interlacing. Returns the number of passes. */ +extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED) +/* Invert monochrome files */ +extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) +/* Handle alpha and tRNS by replacing with a background color. */ +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr, + png_color_16p background_color, int background_gamma_code, + int need_expand, double background_gamma)); +#endif +#define PNG_BACKGROUND_GAMMA_UNKNOWN 0 +#define PNG_BACKGROUND_GAMMA_SCREEN 1 +#define PNG_BACKGROUND_GAMMA_FILE 2 +#define PNG_BACKGROUND_GAMMA_UNIQUE 3 +#endif + +#if defined(PNG_READ_16_TO_8_SUPPORTED) +/* strip the second byte of information from a 16-bit depth file. */ +extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_DITHER_SUPPORTED) +/* Turn on dithering, and reduce the palette to the number of colors available. */ +extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr, + png_colorp palette, int num_palette, int maximum_colors, + png_uint_16p histogram, int full_dither)); +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) +/* Handle gamma correction. Screen_gamma=(display_exponent) */ +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr, + double screen_gamma, double default_file_gamma)); +#endif +#endif + +#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) +/* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */ +/* Deprecated and will be removed. Use png_permit_mng_features() instead. */ +extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr, + int empty_plte_permitted)); +#endif + +#if defined(PNG_WRITE_FLUSH_SUPPORTED) +/* Set how many lines between output flushes - 0 for no flushing */ +extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows)); +/* Flush the current PNG output buffer */ +extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr)); +#endif + +/* optional update palette with requested transformations */ +extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr)); + +/* optional call to update the users info structure */ +extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr, + png_infop info_ptr)); + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* read one or more rows of image data. */ +extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr, + png_bytepp row, png_bytepp display_row, png_uint_32 num_rows)); +#endif + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* read a row of data. */ +extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr, + png_bytep row, + png_bytep display_row)); +#endif + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* read the whole image into memory at once. */ +extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr, + png_bytepp image)); +#endif + +/* write a row of image data */ +extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr, + png_bytep row)); + +/* write a few rows of image data */ +extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr, + png_bytepp row, png_uint_32 num_rows)); + +/* write the image data */ +extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr, + png_bytepp image)); + +/* writes the end of the PNG file. */ +extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr, + png_infop info_ptr)); + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* read the end of the PNG file. */ +extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr, + png_infop info_ptr)); +#endif + +/* free any memory associated with the png_info_struct */ +extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr, + png_infopp info_ptr_ptr)); + +/* free any memory associated with the png_struct and the png_info_structs */ +extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp + png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr)); + +/* free all memory used by the read (old method - NOT DLL EXPORTED) */ +extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr, + png_infop end_info_ptr)); + +/* free any memory associated with the png_struct and the png_info_structs */ +extern PNG_EXPORT(void,png_destroy_write_struct) + PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)); + +/* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */ +extern void png_write_destroy PNGARG((png_structp png_ptr)); + +/* set the libpng method of handling chunk CRC errors */ +extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr, + int crit_action, int ancil_action)); + +/* Values for png_set_crc_action() to say how to handle CRC errors in + * ancillary and critical chunks, and whether to use the data contained + * therein. Note that it is impossible to "discard" data in a critical + * chunk. For versions prior to 0.90, the action was always error/quit, + * whereas in version 0.90 and later, the action for CRC errors in ancillary + * chunks is warn/discard. These values should NOT be changed. + * + * value action:critical action:ancillary + */ +#define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */ +#define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */ +#define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */ +#define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */ +#define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */ +#define PNG_CRC_NO_CHANGE 5 /* use current value use current value */ + +/* These functions give the user control over the scan-line filtering in + * libpng and the compression methods used by zlib. These functions are + * mainly useful for testing, as the defaults should work with most users. + * Those users who are tight on memory or want faster performance at the + * expense of compression can modify them. See the compression library + * header file (zlib.h) for an explination of the compression functions. + */ + +/* set the filtering method(s) used by libpng. Currently, the only valid + * value for "method" is 0. + */ +extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method, + int filters)); + +/* Flags for png_set_filter() to say which filters to use. The flags + * are chosen so that they don't conflict with real filter types + * below, in case they are supplied instead of the #defined constants. + * These values should NOT be changed. + */ +#define PNG_NO_FILTERS 0x00 +#define PNG_FILTER_NONE 0x08 +#define PNG_FILTER_SUB 0x10 +#define PNG_FILTER_UP 0x20 +#define PNG_FILTER_AVG 0x40 +#define PNG_FILTER_PAETH 0x80 +#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \ + PNG_FILTER_AVG | PNG_FILTER_PAETH) + +/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now. + * These defines should NOT be changed. + */ +#define PNG_FILTER_VALUE_NONE 0 +#define PNG_FILTER_VALUE_SUB 1 +#define PNG_FILTER_VALUE_UP 2 +#define PNG_FILTER_VALUE_AVG 3 +#define PNG_FILTER_VALUE_PAETH 4 +#define PNG_FILTER_VALUE_LAST 5 + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */ +/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_ + * defines, either the default (minimum-sum-of-absolute-differences), or + * the experimental method (weighted-minimum-sum-of-absolute-differences). + * + * Weights are factors >= 1.0, indicating how important it is to keep the + * filter type consistent between rows. Larger numbers mean the current + * filter is that many times as likely to be the same as the "num_weights" + * previous filters. This is cumulative for each previous row with a weight. + * There needs to be "num_weights" values in "filter_weights", or it can be + * NULL if the weights aren't being specified. Weights have no influence on + * the selection of the first row filter. Well chosen weights can (in theory) + * improve the compression for a given image. + * + * Costs are factors >= 1.0 indicating the relative decoding costs of a + * filter type. Higher costs indicate more decoding expense, and are + * therefore less likely to be selected over a filter with lower computational + * costs. There needs to be a value in "filter_costs" for each valid filter + * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't + * setting the costs. Costs try to improve the speed of decompression without + * unduly increasing the compressed image size. + * + * A negative weight or cost indicates the default value is to be used, and + * values in the range [0.0, 1.0) indicate the value is to remain unchanged. + * The default values for both weights and costs are currently 1.0, but may + * change if good general weighting/cost heuristics can be found. If both + * the weights and costs are set to 1.0, this degenerates the WEIGHTED method + * to the UNWEIGHTED method, but with added encoding time/computation. + */ +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr, + int heuristic_method, int num_weights, png_doublep filter_weights, + png_doublep filter_costs)); +#endif +#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */ + +/* Heuristic used for row filter selection. These defines should NOT be + * changed. + */ +#define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */ +#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */ +#define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */ +#define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */ + +/* Set the library compression level. Currently, valid values range from + * 0 - 9, corresponding directly to the zlib compression levels 0 - 9 + * (0 - no compression, 9 - "maximal" compression). Note that tests have + * shown that zlib compression levels 3-6 usually perform as well as level 9 + * for PNG images, and do considerably fewer caclulations. In the future, + * these values may not correspond directly to the zlib compression levels. + */ +extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr, + int level)); + +extern PNG_EXPORT(void,png_set_compression_mem_level) + PNGARG((png_structp png_ptr, int mem_level)); + +extern PNG_EXPORT(void,png_set_compression_strategy) + PNGARG((png_structp png_ptr, int strategy)); + +extern PNG_EXPORT(void,png_set_compression_window_bits) + PNGARG((png_structp png_ptr, int window_bits)); + +extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr, + int method)); + +/* These next functions are called for input/output, memory, and error + * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c, + * and call standard C I/O routines such as fread(), fwrite(), and + * fprintf(). These functions can be made to use other I/O routines + * at run time for those applications that need to handle I/O in a + * different manner by calling png_set_???_fn(). See libpng.txt for + * more information. + */ + +#if !defined(PNG_NO_STDIO) +/* Initialize the input/output for the PNG file to the default functions. */ +extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp)); +#endif + +/* Replace the (error and abort), and warning functions with user + * supplied functions. If no messages are to be printed you must still + * write and use replacement functions. The replacement error_fn should + * still do a longjmp to the last setjmp location if you are using this + * method of error handling. If error_fn or warning_fn is NULL, the + * default function will be used. + */ + +extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr, + png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn)); + +/* Return the user pointer associated with the error functions */ +extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr)); + +/* Replace the default data output functions with a user supplied one(s). + * If buffered output is not used, then output_flush_fn can be set to NULL. + * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time + * output_flush_fn will be ignored (and thus can be NULL). + */ +extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr, + png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)); + +/* Replace the default data input function with a user supplied one. */ +extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr, + png_voidp io_ptr, png_rw_ptr read_data_fn)); + +/* Return the user pointer associated with the I/O functions */ +extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr)); + +extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr, + png_read_status_ptr read_row_fn)); + +extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr, + png_write_status_ptr write_row_fn)); + +#ifdef PNG_USER_MEM_SUPPORTED +/* Replace the default memory allocation functions with user supplied one(s). */ +extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr, + png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn)); +/* Return the user pointer associated with the memory functions */ +extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr)); +#endif + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_LEGACY_SUPPORTED) +extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp + png_ptr, png_user_transform_ptr read_user_transform_fn)); +#endif + +#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_LEGACY_SUPPORTED) +extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp + png_ptr, png_user_transform_ptr write_user_transform_fn)); +#endif + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_LEGACY_SUPPORTED) +extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp + png_ptr, png_voidp user_transform_ptr, int user_transform_depth, + int user_transform_channels)); +/* Return the user pointer associated with the user transform functions */ +extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr) + PNGARG((png_structp png_ptr)); +#endif + +#ifdef PNG_USER_CHUNKS_SUPPORTED +extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr, + png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn)); +extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp + png_ptr)); +#endif + +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED +/* Sets the function callbacks for the push reader, and a pointer to a + * user-defined structure available to the callback functions. + */ +extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr, + png_voidp progressive_ptr, + png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn, + png_progressive_end_ptr end_fn)); + +/* returns the user pointer associated with the push read functions */ +extern PNG_EXPORT(png_voidp,png_get_progressive_ptr) + PNGARG((png_structp png_ptr)); + +/* function to be called when data becomes available */ +extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_bytep buffer, png_size_t buffer_size)); + +/* function that combines rows. Not very much different than the + * png_combine_row() call. Is this even used????? + */ +extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr, + png_bytep old_row, png_bytep new_row)); +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */ + +extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr, + png_uint_32 size)); + +#if defined(PNG_1_0_X) +# define png_malloc_warn png_malloc +#else +/* Added at libpng version 1.2.4 */ +extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr, + png_uint_32 size)); +#endif + +/* frees a pointer allocated by png_malloc() */ +extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr)); + +#if defined(PNG_1_0_X) +/* Function to allocate memory for zlib. */ +extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items, + uInt size)); + +/* Function to free memory for zlib */ +extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr)); +#endif + +/* Free data that was allocated internally */ +extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 free_me, int num)); +#ifdef PNG_FREE_ME_SUPPORTED +/* Reassign responsibility for freeing existing data, whether allocated + * by libpng or by the application */ +extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr, + png_infop info_ptr, int freer, png_uint_32 mask)); +#endif +/* assignments for png_data_freer */ +#define PNG_DESTROY_WILL_FREE_DATA 1 +#define PNG_SET_WILL_FREE_DATA 1 +#define PNG_USER_WILL_FREE_DATA 2 +/* Flags for png_ptr->free_me and info_ptr->free_me */ +#define PNG_FREE_HIST 0x0008 +#define PNG_FREE_ICCP 0x0010 +#define PNG_FREE_SPLT 0x0020 +#define PNG_FREE_ROWS 0x0040 +#define PNG_FREE_PCAL 0x0080 +#define PNG_FREE_SCAL 0x0100 +#define PNG_FREE_UNKN 0x0200 +#define PNG_FREE_LIST 0x0400 +#define PNG_FREE_PLTE 0x1000 +#define PNG_FREE_TRNS 0x2000 +#define PNG_FREE_TEXT 0x4000 +#define PNG_FREE_ALL 0x7fff +#define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */ + +#ifdef PNG_USER_MEM_SUPPORTED +extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr, + png_uint_32 size)); +extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr, + png_voidp ptr)); +#endif + +extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr, + png_voidp s1, png_voidp s2, png_uint_32 size)); + +extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr, + png_voidp s1, int value, png_uint_32 size)); + +#if defined(USE_FAR_KEYWORD) /* memory model conversion function */ +extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr, + int check)); +#endif /* USE_FAR_KEYWORD */ + +/* Fatal error in PNG image of libpng - can't continue */ +extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr, + png_const_charp error_message)); + +/* The same, but the chunk name is prepended to the error string. */ +extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr, + png_const_charp error_message)); + +/* Non-fatal error in libpng. Can continue, but may have a problem. */ +extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr, + png_const_charp warning_message)); + +/* Non-fatal error in libpng, chunk name is prepended to message. */ +extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr, + png_const_charp warning_message)); + +/* The png_set_ functions are for storing values in the png_info_struct. + * Similarly, the png_get_ calls are used to read values from the + * png_info_struct, either storing the parameters in the passed variables, or + * setting pointers into the png_info_struct where the data is stored. The + * png_get_ functions return a non-zero value if the data was available + * in info_ptr, or return zero and do not change any of the parameters if the + * data was not available. + * + * These functions should be used instead of directly accessing png_info + * to avoid problems with future changes in the size and internal layout of + * png_info_struct. + */ +/* Returns "flag" if chunk data is valid in info_ptr. */ +extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr, +png_infop info_ptr, png_uint_32 flag)); + +/* Returns number of bytes needed to hold a transformed row. */ +extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr, +png_infop info_ptr)); + +#if defined(PNG_INFO_IMAGE_SUPPORTED) +/* Returns row_pointers, which is an array of pointers to scanlines that was +returned from png_read_png(). */ +extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr, +png_infop info_ptr)); +/* Set row_pointers, which is an array of pointers to scanlines for use +by png_write_png(). */ +extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_bytepp row_pointers)); +#endif + +/* Returns number of color channels in image. */ +extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr, +png_infop info_ptr)); + +#ifdef PNG_EASY_ACCESS_SUPPORTED +/* Returns image width in pixels. */ +extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +/* Returns image height in pixels. */ +extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +/* Returns image bit_depth. */ +extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +/* Returns image color_type. */ +extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +/* Returns image filter_type. */ +extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +/* Returns image interlace_type. */ +extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +/* Returns image compression_type. */ +extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +/* Returns image resolution in pixels per meter, from pHYs chunk data. */ +extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp +png_ptr, png_infop info_ptr)); +extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp +png_ptr, png_infop info_ptr)); +extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +/* Returns pixel aspect ratio, computed from pHYs chunk data. */ +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp +png_ptr, png_infop info_ptr)); +#endif + +/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */ +extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp +png_ptr, png_infop info_ptr)); +extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp +png_ptr, png_infop info_ptr)); +extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp +png_ptr, png_infop info_ptr)); +extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp +png_ptr, png_infop info_ptr)); + +#endif /* PNG_EASY_ACCESS_SUPPORTED */ + +/* Returns pointer to signature string read from PNG header */ +extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr, +png_infop info_ptr)); + +#if defined(PNG_bKGD_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_color_16p *background)); +#endif + +#if defined(PNG_bKGD_SUPPORTED) +extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_color_16p background)); +#endif + +#if defined(PNG_cHRM_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr, + png_infop info_ptr, double *white_x, double *white_y, double *red_x, + double *red_y, double *green_x, double *green_y, double *blue_x, + double *blue_y)); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point + *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y, + png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point + *int_blue_x, png_fixed_point *int_blue_y)); +#endif +#endif + +#if defined(PNG_cHRM_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr, + png_infop info_ptr, double white_x, double white_y, double red_x, + double red_y, double green_x, double green_y, double blue_x, double blue_y)); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y, + png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point + int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x, + png_fixed_point int_blue_y)); +#endif +#endif + +#if defined(PNG_gAMA_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr, + png_infop info_ptr, double *file_gamma)); +#endif +extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_fixed_point *int_file_gamma)); +#endif + +#if defined(PNG_gAMA_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr, + png_infop info_ptr, double file_gamma)); +#endif +extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_fixed_point int_file_gamma)); +#endif + +#if defined(PNG_hIST_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_16p *hist)); +#endif + +#if defined(PNG_hIST_SUPPORTED) +extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_16p hist)); +#endif + +extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 *width, png_uint_32 *height, + int *bit_depth, int *color_type, int *interlace_method, + int *compression_method, int *filter_method)); + +extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, + int color_type, int interlace_method, int compression_method, + int filter_method)); + +#if defined(PNG_oFFs_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y, + int *unit_type)); +#endif + +#if defined(PNG_oFFs_SUPPORTED) +extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y, + int unit_type)); +#endif + +#if defined(PNG_pCAL_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1, + int *type, int *nparams, png_charp *units, png_charpp *params)); +#endif + +#if defined(PNG_pCAL_SUPPORTED) +extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1, + int type, int nparams, png_charp units, png_charpp params)); +#endif + +#if defined(PNG_pHYs_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)); +#endif + +#if defined(PNG_pHYs_SUPPORTED) +extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type)); +#endif + +extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_colorp *palette, int *num_palette)); + +extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_colorp palette, int num_palette)); + +#if defined(PNG_sBIT_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_color_8p *sig_bit)); +#endif + +#if defined(PNG_sBIT_SUPPORTED) +extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_color_8p sig_bit)); +#endif + +#if defined(PNG_sRGB_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr, + png_infop info_ptr, int *intent)); +#endif + +#if defined(PNG_sRGB_SUPPORTED) +extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr, + png_infop info_ptr, int intent)); +extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr, + png_infop info_ptr, int intent)); +#endif + +#if defined(PNG_iCCP_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_charpp name, int *compression_type, + png_charpp profile, png_uint_32 *proflen)); + /* Note to maintainer: profile should be png_bytepp */ +#endif + +#if defined(PNG_iCCP_SUPPORTED) +extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_charp name, int compression_type, + png_charp profile, png_uint_32 proflen)); + /* Note to maintainer: profile should be png_bytep */ +#endif + +#if defined(PNG_sPLT_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_sPLT_tpp entries)); +#endif + +#if defined(PNG_sPLT_SUPPORTED) +extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_sPLT_tp entries, int nentries)); +#endif + +#if defined(PNG_TEXT_SUPPORTED) +/* png_get_text also returns the number of text chunks in *num_text */ +extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_textp *text_ptr, int *num_text)); +#endif + +/* + * Note while png_set_text() will accept a structure whose text, + * language, and translated keywords are NULL pointers, the structure + * returned by png_get_text will always contain regular + * zero-terminated C strings. They might be empty strings but + * they will never be NULL pointers. + */ + +#if defined(PNG_TEXT_SUPPORTED) +extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_textp text_ptr, int num_text)); +#endif + +#if defined(PNG_tIME_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_timep *mod_time)); +#endif + +#if defined(PNG_tIME_SUPPORTED) +extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_timep mod_time)); +#endif + +#if defined(PNG_tRNS_SUPPORTED) +extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_bytep *trans, int *num_trans, + png_color_16p *trans_values)); +#endif + +#if defined(PNG_tRNS_SUPPORTED) +extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_bytep trans, int num_trans, + png_color_16p trans_values)); +#endif + +#if defined(PNG_tRNS_SUPPORTED) +#endif + +#if defined(PNG_sCAL_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr, + png_infop info_ptr, int *unit, double *width, double *height)); +#else +#ifdef PNG_FIXED_POINT_SUPPORTED +extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr, + png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight)); +#endif +#endif +#endif /* PNG_sCAL_SUPPORTED */ + +#if defined(PNG_sCAL_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr, + png_infop info_ptr, int unit, double width, double height)); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr, + png_infop info_ptr, int unit, png_charp swidth, png_charp sheight)); +#endif +#endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */ + +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) +/* provide a list of chunks and how they are to be handled, if the built-in + handling or default unknown chunk handling is not desired. Any chunks not + listed will be handled in the default manner. The IHDR and IEND chunks + must not be listed. + keep = 0: follow default behavour + = 1: do not keep + = 2: keep only if safe-to-copy + = 3: keep even if unsafe-to-copy +*/ +extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp + png_ptr, int keep, png_bytep chunk_list, int num_chunks)); +extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr, + png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)); +extern PNG_EXPORT(void, png_set_unknown_chunk_location) + PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location)); +extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp + png_ptr, png_infop info_ptr, png_unknown_chunkpp entries)); +#endif +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED +PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep + chunk_name)); +#endif + +/* Png_free_data() will turn off the "valid" flag for anything it frees. + If you need to turn it off for a chunk that your application has freed, + you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */ +extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr, + png_infop info_ptr, int mask)); + +#if defined(PNG_INFO_IMAGE_SUPPORTED) +/* The "params" pointer is currently not used and is for future expansion. */ +extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr, + png_infop info_ptr, + int transforms, + png_voidp params)); +extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr, + png_infop info_ptr, + int transforms, + png_voidp params)); +#endif + +/* Define PNG_DEBUG at compile time for debugging information. Higher + * numbers for PNG_DEBUG mean more debugging information. This has + * only been added since version 0.95 so it is not implemented throughout + * libpng yet, but more support will be added as needed. + */ +#ifdef PNG_DEBUG +#if (PNG_DEBUG > 0) +#if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER) +#include +#if (PNG_DEBUG > 1) +#define png_debug(l,m) _RPT0(_CRT_WARN,m) +#define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1) +#define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2) +#endif +#else /* PNG_DEBUG_FILE || !_MSC_VER */ +#ifndef PNG_DEBUG_FILE +#define PNG_DEBUG_FILE stderr +#endif /* PNG_DEBUG_FILE */ +#if (PNG_DEBUG > 1) +#define png_debug(l,m) \ +{ \ + int num_tabs=l; \ + fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \ + (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \ +} +#define png_debug1(l,m,p1) \ +{ \ + int num_tabs=l; \ + fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \ + (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \ +} +#define png_debug2(l,m,p1,p2) \ +{ \ + int num_tabs=l; \ + fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \ + (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \ +} +#endif /* (PNG_DEBUG > 1) */ +#endif /* _MSC_VER */ +#endif /* (PNG_DEBUG > 0) */ +#endif /* PNG_DEBUG */ +#ifndef png_debug +#define png_debug(l, m) +#endif +#ifndef png_debug1 +#define png_debug1(l, m, p1) +#endif +#ifndef png_debug2 +#define png_debug2(l, m, p1, p2) +#endif + +extern PNG_EXPORT(png_bytep,png_sig_bytes) PNGARG((void)); + +extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr)); +extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr)); +extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr)); +extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr)); + +#ifdef PNG_MNG_FEATURES_SUPPORTED +extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp + png_ptr, png_uint_32 mng_features_permitted)); +#endif + +/* For use in png_set_keep_unknown, added to version 1.2.6 */ +#define PNG_HANDLE_CHUNK_AS_DEFAULT 0 +#define PNG_HANDLE_CHUNK_NEVER 1 +#define PNG_HANDLE_CHUNK_IF_SAFE 2 +#define PNG_HANDLE_CHUNK_ALWAYS 3 + +/* Added to version 1.2.0 */ +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) +#define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */ +#define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */ +#define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04 +#define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08 +#define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10 +#define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20 +#define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40 +#define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80 +#define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */ + +#define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ + | PNG_ASM_FLAG_MMX_READ_INTERLACE \ + | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ + | PNG_ASM_FLAG_MMX_READ_FILTER_UP \ + | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ + | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ) +#define PNG_MMX_WRITE_FLAGS ( 0 ) + +#define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \ + | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \ + | PNG_MMX_READ_FLAGS \ + | PNG_MMX_WRITE_FLAGS ) + +#define PNG_SELECT_READ 1 +#define PNG_SELECT_WRITE 2 + +#if !defined(PNG_1_0_X) +/* pngget.c */ +extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask) + PNGARG((int flag_select, int *compilerID)); + +/* pngget.c */ +extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask) + PNGARG((int flag_select)); + +/* pngget.c */ +extern PNG_EXPORT(png_uint_32,png_get_asm_flags) + PNGARG((png_structp png_ptr)); + +/* pngget.c */ +extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold) + PNGARG((png_structp png_ptr)); + +/* pngget.c */ +extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold) + PNGARG((png_structp png_ptr)); + +/* pngset.c */ +extern PNG_EXPORT(void,png_set_asm_flags) + PNGARG((png_structp png_ptr, png_uint_32 asm_flags)); + +/* pngset.c */ +extern PNG_EXPORT(void,png_set_mmx_thresholds) + PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold, + png_uint_32 mmx_rowbytes_threshold)); + +#endif /* PNG_1_0_X */ +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + +#if !defined(PNG_1_0_X) +/* png.c, pnggccrd.c, or pngvcrd.c */ +extern PNG_EXPORT(int,png_mmx_support) PNGARG((void)); + +/* Strip the prepended error numbers ("#nnn ") from error and warning + * messages before passing them to the error or warning handler. */ +#ifdef PNG_ERROR_NUMBERS_SUPPORTED +extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp + png_ptr, png_uint_32 strip_mode)); +#endif + +#endif /* PNG_1_0_X */ + +/* Added at libpng-1.2.6 */ +#ifdef PNG_SET_USER_LIMITS_SUPPORTED +extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp + png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max)); +extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp + png_ptr)); +extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp + png_ptr)); +#endif + +/* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */ + +#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED +/* With these routines we avoid an integer divide, which will be slower on + * most machines. However, it does take more operations than the corresponding + * divide method, so it may be slower on a few RISC systems. There are two + * shifts (by 8 or 16 bits) and an addition, versus a single integer divide. + * + * Note that the rounding factors are NOT supposed to be the same! 128 and + * 32768 are correct for the NODIV code; 127 and 32767 are correct for the + * standard method. + * + * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ] + */ + + /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */ + +# define png_composite(composite, fg, alpha, bg) \ + { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \ + + (png_uint_16)(bg)*(png_uint_16)(255 - \ + (png_uint_16)(alpha)) + (png_uint_16)128); \ + (composite) = (png_byte)((temp + (temp >> 8)) >> 8); } + +# define png_composite_16(composite, fg, alpha, bg) \ + { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \ + + (png_uint_32)(bg)*(png_uint_32)(65535L - \ + (png_uint_32)(alpha)) + (png_uint_32)32768L); \ + (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); } + +#else /* standard method using integer division */ + +# define png_composite(composite, fg, alpha, bg) \ + (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \ + (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \ + (png_uint_16)127) / 255) + +# define png_composite_16(composite, fg, alpha, bg) \ + (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \ + (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \ + (png_uint_32)32767) / (png_uint_32)65535L) + +#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */ + +/* These next functions are used internally in the code. They generally + * shouldn't be used unless you are writing code to add or replace some + * functionality in libpng. More information about most functions can + * be found in the files where the functions are located. + */ + +#if defined(PNG_INTERNAL) + +/* Various modes of operation. Note that after an init, mode is set to + * zero automatically when the structure is created. + */ +#define PNG_HAVE_IHDR 0x01 +#define PNG_HAVE_PLTE 0x02 +#define PNG_HAVE_IDAT 0x04 +#define PNG_AFTER_IDAT 0x08 +#define PNG_HAVE_IEND 0x10 +#define PNG_HAVE_gAMA 0x20 +#define PNG_HAVE_cHRM 0x40 +#define PNG_HAVE_sRGB 0x80 +#define PNG_HAVE_CHUNK_HEADER 0x100 +#define PNG_WROTE_tIME 0x200 +#define PNG_WROTE_INFO_BEFORE_PLTE 0x400 +#define PNG_BACKGROUND_IS_GRAY 0x800 +#define PNG_HAVE_PNG_SIGNATURE 0x1000 + +/* flags for the transformations the PNG library does on the image data */ +#define PNG_BGR 0x0001 +#define PNG_INTERLACE 0x0002 +#define PNG_PACK 0x0004 +#define PNG_SHIFT 0x0008 +#define PNG_SWAP_BYTES 0x0010 +#define PNG_INVERT_MONO 0x0020 +#define PNG_DITHER 0x0040 +#define PNG_BACKGROUND 0x0080 +#define PNG_BACKGROUND_EXPAND 0x0100 + /* 0x0200 unused */ +#define PNG_16_TO_8 0x0400 +#define PNG_RGBA 0x0800 +#define PNG_EXPAND 0x1000 +#define PNG_GAMMA 0x2000 +#define PNG_GRAY_TO_RGB 0x4000 +#define PNG_FILLER 0x8000L +#define PNG_PACKSWAP 0x10000L +#define PNG_SWAP_ALPHA 0x20000L +#define PNG_STRIP_ALPHA 0x40000L +#define PNG_INVERT_ALPHA 0x80000L +#define PNG_USER_TRANSFORM 0x100000L +#define PNG_RGB_TO_GRAY_ERR 0x200000L +#define PNG_RGB_TO_GRAY_WARN 0x400000L +#define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */ +#define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */ + +/* flags for png_create_struct */ +#define PNG_STRUCT_PNG 0x0001 +#define PNG_STRUCT_INFO 0x0002 + +/* Scaling factor for filter heuristic weighting calculations */ +#define PNG_WEIGHT_SHIFT 8 +#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT)) +#define PNG_COST_SHIFT 3 +#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT)) + +/* flags for the png_ptr->flags rather than declaring a byte for each one */ +#define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001 +#define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002 +#define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004 +#define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008 +#define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010 +#define PNG_FLAG_ZLIB_FINISHED 0x0020 +#define PNG_FLAG_ROW_INIT 0x0040 +#define PNG_FLAG_FILLER_AFTER 0x0080 +#define PNG_FLAG_CRC_ANCILLARY_USE 0x0100 +#define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200 +#define PNG_FLAG_CRC_CRITICAL_USE 0x0400 +#define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800 +#define PNG_FLAG_FREE_PLTE 0x1000 +#define PNG_FLAG_FREE_TRNS 0x2000 +#define PNG_FLAG_FREE_HIST 0x4000 +#define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L +#define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L +#define PNG_FLAG_LIBRARY_MISMATCH 0x20000L +#define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L +#define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L +#define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L + +#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \ + PNG_FLAG_CRC_ANCILLARY_NOWARN) + +#define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \ + PNG_FLAG_CRC_CRITICAL_IGNORE) + +#define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \ + PNG_FLAG_CRC_CRITICAL_MASK) + +/* save typing and make code easier to understand */ + +#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \ + abs((int)((c1).green) - (int)((c2).green)) + \ + abs((int)((c1).blue) - (int)((c2).blue))) + +/* Added to libpng-1.2.6 JB */ +#define PNG_ROWBYTES(pixel_bits, width) \ + ((pixel_bits) >= 8 ? \ + ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \ + (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) ) + +/* PNG_OUT_OF_RANGE returns true if value is outside the range + ideal-delta..ideal+delta. Each argument is evaluated twice. + "ideal" and "delta" should be constants, normally simple + integers, "value" a variable. Added to libpng-1.2.6 JB */ +#define PNG_OUT_OF_RANGE(value, ideal, delta) \ + ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) ) + +/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */ +#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN) +/* place to hold the signature string for a PNG file. */ +#ifdef PNG_USE_GLOBAL_ARRAYS + PNG_EXPORT_VAR (const png_byte FARDATA) png_sig[8]; +#else +#define png_sig png_sig_bytes(NULL) +#endif +#endif /* PNG_NO_EXTERN */ + +/* Constant strings for known chunk types. If you need to add a chunk, + * define the name here, and add an invocation of the macro in png.c and + * wherever it's needed. + */ +#define PNG_IHDR const png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'} +#define PNG_IDAT const png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'} +#define PNG_IEND const png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'} +#define PNG_PLTE const png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'} +#define PNG_bKGD const png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'} +#define PNG_cHRM const png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'} +#define PNG_gAMA const png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'} +#define PNG_hIST const png_byte png_hIST[5] = {104, 73, 83, 84, '\0'} +#define PNG_iCCP const png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'} +#define PNG_iTXt const png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'} +#define PNG_oFFs const png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'} +#define PNG_pCAL const png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'} +#define PNG_sCAL const png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'} +#define PNG_pHYs const png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'} +#define PNG_sBIT const png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'} +#define PNG_sPLT const png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'} +#define PNG_sRGB const png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'} +#define PNG_tEXt const png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'} +#define PNG_tIME const png_byte png_tIME[5] = {116, 73, 77, 69, '\0'} +#define PNG_tRNS const png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'} +#define PNG_zTXt const png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'} + +#ifdef PNG_USE_GLOBAL_ARRAYS +PNG_EXPORT_VAR (const png_byte FARDATA) png_IHDR[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_IDAT[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_IEND[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_PLTE[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_bKGD[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_cHRM[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_gAMA[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_hIST[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_iCCP[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_iTXt[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_oFFs[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_pCAL[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_sCAL[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_pHYs[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_sBIT[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_sPLT[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_sRGB[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_tEXt[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_tIME[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_tRNS[5]; +PNG_EXPORT_VAR (const png_byte FARDATA) png_zTXt[5]; +#endif /* PNG_USE_GLOBAL_ARRAYS */ + + +/* Inline macros to do direct reads of bytes from the input buffer. These + * require that you are using an architecture that uses PNG byte ordering + * (MSB first) and supports unaligned data storage. I think that PowerPC + * in big-endian mode and 680x0 are the only ones that will support this. + * The x86 line of processors definitely do not. The png_get_int_32() + * routine also assumes we are using two's complement format for negative + * values, which is almost certainly true. + */ +#if defined(PNG_READ_BIG_ENDIAN_SUPPORTED) +# if defined(PNG_pCAL_SUPPORTED) || defined(PNG_oFFs_SUPPORTED) +# define png_get_int_32(buf) ( *((png_int_32p) (buf))) +# endif +# define png_get_uint_32(buf) ( *((png_uint_32p) (buf))) +# define png_get_uint_16(buf) ( *((png_uint_16p) (buf))) +#else +# if defined(PNG_pCAL_SUPPORTED) || defined(PNG_oFFs_SUPPORTED) +PNG_EXTERN png_int_32 png_get_int_32 PNGARG((png_bytep buf)); +# endif +PNG_EXTERN png_uint_32 png_get_uint_32 PNGARG((png_bytep buf)); +PNG_EXTERN png_uint_16 png_get_uint_16 PNGARG((png_bytep buf)); +#endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */ +PNG_EXTERN png_uint_32 png_get_uint_31 PNGARG((png_structp png_ptr, + png_bytep buf)); + +/* Initialize png_ptr struct for reading, and allocate any other memory. + * (old interface - DEPRECATED - use png_create_read_struct instead). + */ +extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr)); +#undef png_read_init +#define png_read_init(png_ptr) png_read_init_3(&png_ptr, \ + PNG_LIBPNG_VER_STRING, png_sizeof(png_struct)); +extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr, + png_const_charp user_png_ver, png_size_t png_struct_size)); +extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr, + png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t + png_info_size)); + +/* Initialize png_ptr struct for writing, and allocate any other memory. + * (old interface - DEPRECATED - use png_create_write_struct instead). + */ +extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr)); +#undef png_write_init +#define png_write_init(png_ptr) png_write_init_3(&png_ptr, \ + PNG_LIBPNG_VER_STRING, png_sizeof(png_struct)); +extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr, + png_const_charp user_png_ver, png_size_t png_struct_size)); +extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr, + png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t + png_info_size)); + +/* Allocate memory for an internal libpng struct */ +PNG_EXTERN png_voidp png_create_struct PNGARG((int type)); + +/* Free memory from internal libpng struct */ +PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr)); + +PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr + malloc_fn, png_voidp mem_ptr)); +PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr, + png_free_ptr free_fn, png_voidp mem_ptr)); + +/* Free any memory that info_ptr points to and reset struct. */ +PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr, + png_infop info_ptr)); + +#ifndef PNG_1_0_X +/* Function to allocate memory for zlib. */ +PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size)); + +/* Function to free memory for zlib */ +PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr)); + +#ifdef PNG_SIZE_T +/* Function to convert a sizeof an item to png_sizeof item */ + PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size)); +#endif + +/* Next four functions are used internally as callbacks. PNGAPI is required + * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */ + +PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr, + png_bytep data, png_size_t length)); + +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED +PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr, + png_bytep buffer, png_size_t length)); +#endif + +PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr, + png_bytep data, png_size_t length)); + +#if defined(PNG_WRITE_FLUSH_SUPPORTED) +#if !defined(PNG_NO_STDIO) +PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr)); +#endif +#endif +#else /* PNG_1_0_X */ +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED +PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr, + png_bytep buffer, png_size_t length)); +#endif +#endif /* PNG_1_0_X */ + +/* Reset the CRC variable */ +PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr)); + +/* Write the "data" buffer to whatever output you are using. */ +PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data, + png_size_t length)); + +/* Read data from whatever input you are using into the "data" buffer */ +PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data, + png_size_t length)); + +/* Read bytes into buf, and update png_ptr->crc */ +PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf, + png_size_t length)); + +/* Decompress data in a chunk that uses compression */ +#if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \ + defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED) +PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr, + int comp_type, png_charp chunkdata, png_size_t chunklength, + png_size_t prefix_length, png_size_t *data_length)); +#endif + +/* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */ +PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip)); + +/* Read the CRC from the file and compare it to the libpng calculated CRC */ +PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr)); + +/* Calculate the CRC over a section of data. Note that we are only + * passing a maximum of 64K on systems that have this as a memory limit, + * since this is the maximum buffer size we can specify. + */ +PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr, + png_size_t length)); + +#if defined(PNG_WRITE_FLUSH_SUPPORTED) +PNG_EXTERN void png_flush PNGARG((png_structp png_ptr)); +#endif + + +/* Place a 32-bit number into a buffer in PNG byte order (big-endian). + * The only currently known PNG chunks that use signed numbers are + * the ancillary extension chunks, oFFs and pCAL. + */ +PNG_EXTERN void png_save_uint_32 PNGARG((png_bytep buf, png_uint_32 i)); + +#if defined(PNG_WRITE_pCAL_SUPPORTED) || defined(PNG_WRITE_oFFs_SUPPORTED) +PNG_EXTERN void png_save_int_32 PNGARG((png_bytep buf, png_int_32 i)); +#endif + +/* Place a 16-bit number into a buffer in PNG byte order. + * The parameter is declared unsigned int, not png_uint_16, + * just to avoid potential problems on pre-ANSI C compilers. + */ +PNG_EXTERN void png_save_uint_16 PNGARG((png_bytep buf, unsigned int i)); + +/* simple function to write the signature */ +PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr)); + +/* write various chunks */ + +/* Write the IHDR chunk, and update the png_struct with the necessary + * information. + */ +PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width, + png_uint_32 height, + int bit_depth, int color_type, int compression_method, int filter_method, + int interlace_method)); + +PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette, + png_uint_32 num_pal)); + +PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data, + png_size_t length)); + +PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr)); + +#if defined(PNG_WRITE_gAMA_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma)); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point + file_gamma)); +#endif +#endif + +#if defined(PNG_WRITE_sBIT_SUPPORTED) +PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit, + int color_type)); +#endif + +#if defined(PNG_WRITE_cHRM_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr, + double white_x, double white_y, + double red_x, double red_y, double green_x, double green_y, + double blue_x, double blue_y)); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr, + png_fixed_point int_white_x, png_fixed_point int_white_y, + png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point + int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x, + png_fixed_point int_blue_y)); +#endif +#endif + +#if defined(PNG_WRITE_sRGB_SUPPORTED) +PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr, + int intent)); +#endif + +#if defined(PNG_WRITE_iCCP_SUPPORTED) +PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr, + png_charp name, int compression_type, + png_charp profile, int proflen)); + /* Note to maintainer: profile should be png_bytep */ +#endif + +#if defined(PNG_WRITE_sPLT_SUPPORTED) +PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr, + png_sPLT_tp palette)); +#endif + +#if defined(PNG_WRITE_tRNS_SUPPORTED) +PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans, + png_color_16p values, int number, int color_type)); +#endif + +#if defined(PNG_WRITE_bKGD_SUPPORTED) +PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr, + png_color_16p values, int color_type)); +#endif + +#if defined(PNG_WRITE_hIST_SUPPORTED) +PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist, + int num_hist)); +#endif + +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \ + defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED) +PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr, + png_charp key, png_charpp new_key)); +#endif + +#if defined(PNG_WRITE_tEXt_SUPPORTED) +PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key, + png_charp text, png_size_t text_len)); +#endif + +#if defined(PNG_WRITE_zTXt_SUPPORTED) +PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key, + png_charp text, png_size_t text_len, int compression)); +#endif + +#if defined(PNG_WRITE_iTXt_SUPPORTED) +PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr, + int compression, png_charp key, png_charp lang, png_charp lang_key, + png_charp text)); +#endif + +#if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */ +PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr, + png_infop info_ptr, png_textp text_ptr, int num_text)); +#endif + +#if defined(PNG_WRITE_oFFs_SUPPORTED) +PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr, + png_int_32 x_offset, png_int_32 y_offset, int unit_type)); +#endif + +#if defined(PNG_WRITE_pCAL_SUPPORTED) +PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose, + png_int_32 X0, png_int_32 X1, int type, int nparams, + png_charp units, png_charpp params)); +#endif + +#if defined(PNG_WRITE_pHYs_SUPPORTED) +PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr, + png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit, + int unit_type)); +#endif + +#if defined(PNG_WRITE_tIME_SUPPORTED) +PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr, + png_timep mod_time)); +#endif + +#if defined(PNG_WRITE_sCAL_SUPPORTED) +#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO) +PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr, + int unit, double width, double height)); +#else +#ifdef PNG_FIXED_POINT_SUPPORTED +PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr, + int unit, png_charp width, png_charp height)); +#endif +#endif +#endif + +/* Called when finished processing a row of data */ +PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr)); + +/* Internal use only. Called before first row of data */ +PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr)); + +#if defined(PNG_READ_GAMMA_SUPPORTED) +PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr)); +#endif + +/* combine a row of data, dealing with alpha, etc. if requested */ +PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row, + int mask)); + +#if defined(PNG_READ_INTERLACING_SUPPORTED) +/* expand an interlaced row */ +/* OLD pre-1.0.9 interface: +PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info, + png_bytep row, int pass, png_uint_32 transformations)); + */ +PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr)); +#endif + +/* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */ + +#if defined(PNG_WRITE_INTERLACING_SUPPORTED) +/* grab pixels out of a row for an interlaced pass */ +PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info, + png_bytep row, int pass)); +#endif + +/* unfilter a row */ +PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr, + png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter)); + +/* Choose the best filter to use and filter the row data */ +PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr, + png_row_infop row_info)); + +/* Write out the filtered row. */ +PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr, + png_bytep filtered_row)); +/* finish a row while reading, dealing with interlacing passes, etc. */ +PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr)); + +/* initialize the row buffers, etc. */ +PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr)); +/* optional call to update the users info structure */ +PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr, + png_infop info_ptr)); + +/* these are the functions that do the transformations */ +#if defined(PNG_READ_FILLER_SUPPORTED) +PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info, + png_bytep row, png_uint_32 filler, png_uint_32 flags)); +#endif + +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) +PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info, + png_bytep row)); +#endif + +#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) +PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info, + png_bytep row)); +#endif + +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) +PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info, + png_bytep row)); +#endif + +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) +PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info, + png_bytep row)); +#endif + +#if defined(PNG_WRITE_FILLER_SUPPORTED) || \ + defined(PNG_READ_STRIP_ALPHA_SUPPORTED) +PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info, + png_bytep row, png_uint_32 flags)); +#endif + +#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) +PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row)); +#endif + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED) +PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row)); +#endif + +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) +PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop + row_info, png_bytep row)); +#endif + +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) +PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info, + png_bytep row)); +#endif + +#if defined(PNG_READ_PACK_SUPPORTED) +PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row)); +#endif + +#if defined(PNG_READ_SHIFT_SUPPORTED) +PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row, + png_color_8p sig_bits)); +#endif + +#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED) +PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row)); +#endif + +#if defined(PNG_READ_16_TO_8_SUPPORTED) +PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row)); +#endif + +#if defined(PNG_READ_DITHER_SUPPORTED) +PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info, + png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup)); + +# if defined(PNG_CORRECT_PALETTE_SUPPORTED) +PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr, + png_colorp palette, int num_palette)); +# endif +#endif + +#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) +PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row)); +#endif + +#if defined(PNG_WRITE_PACK_SUPPORTED) +PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info, + png_bytep row, png_uint_32 bit_depth)); +#endif + +#if defined(PNG_WRITE_SHIFT_SUPPORTED) +PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row, + png_color_8p bit_depth)); +#endif + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) +#if defined(PNG_READ_GAMMA_SUPPORTED) +PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row, + png_color_16p trans_values, png_color_16p background, + png_color_16p background_1, + png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1, + png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1, + png_uint_16pp gamma_16_to_1, int gamma_shift)); +#else +PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row, + png_color_16p trans_values, png_color_16p background)); +#endif +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) +PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row, + png_bytep gamma_table, png_uint_16pp gamma_16_table, + int gamma_shift)); +#endif + +#if defined(PNG_READ_EXPAND_SUPPORTED) +PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info, + png_bytep row, png_colorp palette, png_bytep trans, int num_trans)); +PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info, + png_bytep row, png_color_16p trans_value)); +#endif + +/* The following decodes the appropriate chunks, and does error correction, + * then calls the appropriate callback for the chunk if it is valid. + */ + +/* decode the IHDR chunk */ +PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); + +#if defined(PNG_READ_bKGD_SUPPORTED) +PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_cHRM_SUPPORTED) +PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_gAMA_SUPPORTED) +PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_hIST_SUPPORTED) +PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_iCCP_SUPPORTED) +extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif /* PNG_READ_iCCP_SUPPORTED */ + +#if defined(PNG_READ_iTXt_SUPPORTED) +PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_oFFs_SUPPORTED) +PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_pCAL_SUPPORTED) +PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_pHYs_SUPPORTED) +PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_sBIT_SUPPORTED) +PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_sCAL_SUPPORTED) +PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_sPLT_SUPPORTED) +extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif /* PNG_READ_sPLT_SUPPORTED */ + +#if defined(PNG_READ_sRGB_SUPPORTED) +PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_tEXt_SUPPORTED) +PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_tIME_SUPPORTED) +PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_tRNS_SUPPORTED) +PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +#if defined(PNG_READ_zTXt_SUPPORTED) +PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr, + png_uint_32 length)); +#endif + +PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 length)); + +PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr, + png_bytep chunk_name)); + +/* handle the transformations for reading and writing */ +PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr)); +PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr)); + +PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr)); + +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED +PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr, + png_infop info_ptr)); +PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr, + png_infop info_ptr)); +PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr)); +PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr, + png_uint_32 length)); +PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr)); +PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr)); +PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr, + png_bytep buffer, png_size_t buffer_length)); +PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr)); +PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr, + png_bytep buffer, png_size_t buffer_length)); +PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr)); +PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 length)); +PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr, + png_infop info_ptr)); +PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr, + png_infop info_ptr)); +PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row)); +PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr, + png_infop info_ptr)); +PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr, + png_infop info_ptr)); +PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr)); +#if defined(PNG_READ_tEXt_SUPPORTED) +PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 length)); +PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr, + png_infop info_ptr)); +#endif +#if defined(PNG_READ_zTXt_SUPPORTED) +PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 length)); +PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr, + png_infop info_ptr)); +#endif +#if defined(PNG_READ_iTXt_SUPPORTED) +PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr, + png_infop info_ptr, png_uint_32 length)); +PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr, + png_infop info_ptr)); +#endif + +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */ + +#ifdef PNG_MNG_FEATURES_SUPPORTED +PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info, + png_bytep row)); +PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info, + png_bytep row)); +#endif + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) +/* png.c */ /* PRIVATE */ +PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr)); +#endif +/* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */ + +#endif /* PNG_INTERNAL */ + +#ifdef __cplusplus +} +#endif + +#endif /* PNG_VERSION_INFO_ONLY */ +/* do not put anything past this line */ +#endif /* PNG_H */ diff --git a/SlnkDWFImpl/CxImage/png/png.vcproj b/SlnkDWFImpl/CxImage/png/png.vcproj new file mode 100644 index 0000000..f62767e --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/png.vcproj @@ -0,0 +1,545 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/png/png.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/png/png.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..f57b253 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/png.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/png/pngconf.h b/SlnkDWFImpl/CxImage/png/pngconf.h new file mode 100644 index 0000000..71bfde5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngconf.h @@ -0,0 +1,1376 @@ + +/* pngconf.h - machine configurable file for libpng + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + */ + +/* Any machine specific code is near the front of this file, so if you + * are configuring libpng for a machine, you may want to read the section + * starting here down to where it starts to typedef png_color, png_text, + * and png_info. + */ + +#ifndef PNGCONF_H +#define PNGCONF_H + +#ifdef PNG_USER_CONFIG +#include "pngusr.h" +#endif + +/* This is the size of the compression buffer, and thus the size of + * an IDAT chunk. Make this whatever size you feel is best for your + * machine. One of these will be allocated per png_struct. When this + * is full, it writes the data to the disk, and does some other + * calculations. Making this an extremely small size will slow + * the library down, but you may want to experiment to determine + * where it becomes significant, if you are concerned with memory + * usage. Note that zlib allocates at least 32Kb also. For readers, + * this describes the size of the buffer available to read the data in. + * Unless this gets smaller than the size of a row (compressed), + * it should not make much difference how big this is. + */ + +#ifndef PNG_ZBUF_SIZE +# define PNG_ZBUF_SIZE 8192 +#endif + +/* Enable if you want a write-only libpng */ + +#ifndef PNG_NO_READ_SUPPORTED +# define PNG_READ_SUPPORTED +#endif + +/* Enable if you want a read-only libpng */ + +#ifndef PNG_NO_WRITE_SUPPORTED +# define PNG_WRITE_SUPPORTED +#endif + +/* Enabled by default in 1.2.0. You can disable this if you don't need to + support PNGs that are embedded in MNG datastreams */ +#if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES) +# ifndef PNG_MNG_FEATURES_SUPPORTED +# define PNG_MNG_FEATURES_SUPPORTED +# endif +#endif + +#ifndef PNG_NO_FLOATING_POINT_SUPPORTED +# ifndef PNG_FLOATING_POINT_SUPPORTED +# define PNG_FLOATING_POINT_SUPPORTED +# endif +#endif + +/* If you are running on a machine where you cannot allocate more + * than 64K of memory at once, uncomment this. While libpng will not + * normally need that much memory in a chunk (unless you load up a very + * large file), zlib needs to know how big of a chunk it can use, and + * libpng thus makes sure to check any memory allocation to verify it + * will fit into memory. +#define PNG_MAX_MALLOC_64K + */ +#if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K) +# define PNG_MAX_MALLOC_64K +#endif + +/* Special munging to support doing things the 'cygwin' way: + * 'Normal' png-on-win32 defines/defaults: + * PNG_BUILD_DLL -- building dll + * PNG_USE_DLL -- building an application, linking to dll + * (no define) -- building static library, or building an + * application and linking to the static lib + * 'Cygwin' defines/defaults: + * PNG_BUILD_DLL -- (ignored) building the dll + * (no define) -- (ignored) building an application, linking to the dll + * PNG_STATIC -- (ignored) building the static lib, or building an + * application that links to the static lib. + * ALL_STATIC -- (ignored) building various static libs, or building an + * application that links to the static libs. + * Thus, + * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and + * this bit of #ifdefs will define the 'correct' config variables based on + * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but + * unnecessary. + * + * Also, the precedence order is: + * ALL_STATIC (since we can't #undef something outside our namespace) + * PNG_BUILD_DLL + * PNG_STATIC + * (nothing) == PNG_USE_DLL + * + * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent + * of auto-import in binutils, we no longer need to worry about + * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore, + * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes + * to __declspec() stuff. However, we DO need to worry about + * PNG_BUILD_DLL and PNG_STATIC because those change some defaults + * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed. + */ +#if defined(__CYGWIN__) +# if defined(ALL_STATIC) +# if defined(PNG_BUILD_DLL) +# undef PNG_BUILD_DLL +# endif +# if defined(PNG_USE_DLL) +# undef PNG_USE_DLL +# endif +# if defined(PNG_DLL) +# undef PNG_DLL +# endif +# if !defined(PNG_STATIC) +# define PNG_STATIC +# endif +# else +# if defined (PNG_BUILD_DLL) +# if defined(PNG_STATIC) +# undef PNG_STATIC +# endif +# if defined(PNG_USE_DLL) +# undef PNG_USE_DLL +# endif +# if !defined(PNG_DLL) +# define PNG_DLL +# endif +# else +# if defined(PNG_STATIC) +# if defined(PNG_USE_DLL) +# undef PNG_USE_DLL +# endif +# if defined(PNG_DLL) +# undef PNG_DLL +# endif +# else +# if !defined(PNG_USE_DLL) +# define PNG_USE_DLL +# endif +# if !defined(PNG_DLL) +# define PNG_DLL +# endif +# endif +# endif +# endif +#endif + +/* This protects us against compilers that run on a windowing system + * and thus don't have or would rather us not use the stdio types: + * stdin, stdout, and stderr. The only one currently used is stderr + * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will + * prevent these from being compiled and used. #defining PNG_NO_STDIO + * will also prevent these, plus will prevent the entire set of stdio + * macros and functions (FILE *, printf, etc.) from being compiled and used, + * unless (PNG_DEBUG > 0) has been #defined. + * + * #define PNG_NO_CONSOLE_IO + * #define PNG_NO_STDIO + */ + +#if defined(_WIN32_WCE) +# include + /* Console I/O functions are not supported on WindowsCE */ +# define PNG_NO_CONSOLE_IO +# ifdef PNG_DEBUG +# undef PNG_DEBUG +# endif +#endif + +#ifdef PNG_BUILD_DLL +# ifndef PNG_CONSOLE_IO_SUPPORTED +# ifndef PNG_NO_CONSOLE_IO +# define PNG_NO_CONSOLE_IO +# endif +# endif +#endif + +# ifdef PNG_NO_STDIO +# ifndef PNG_NO_CONSOLE_IO +# define PNG_NO_CONSOLE_IO +# endif +# ifdef PNG_DEBUG +# if (PNG_DEBUG > 0) +# include +# endif +# endif +# else +# if !defined(_WIN32_WCE) +/* "stdio.h" functions are not supported on WindowsCE */ +# include +# endif +# endif + +/* This macro protects us against machines that don't have function + * prototypes (ie K&R style headers). If your compiler does not handle + * function prototypes, define this macro and use the included ansi2knr. + * I've always been able to use _NO_PROTO as the indicator, but you may + * need to drag the empty declaration out in front of here, or change the + * ifdef to suit your own needs. + */ +#ifndef PNGARG + +#ifdef OF /* zlib prototype munger */ +# define PNGARG(arglist) OF(arglist) +#else + +#ifdef _NO_PROTO +# define PNGARG(arglist) () +# ifndef PNG_TYPECAST_NULL +# define PNG_TYPECAST_NULL +# endif +#else +# define PNGARG(arglist) arglist +#endif /* _NO_PROTO */ + +#endif /* OF */ + +#endif /* PNGARG */ + +/* Try to determine if we are compiling on a Mac. Note that testing for + * just __MWERKS__ is not good enough, because the Codewarrior is now used + * on non-Mac platforms. + */ +#ifndef MACOS +# if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \ + defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC) +# define MACOS +# endif +#endif + +/* enough people need this for various reasons to include it here */ +#if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE) +# include +#endif + +#if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED) +# define PNG_SETJMP_SUPPORTED +#endif + +#ifdef PNG_SETJMP_SUPPORTED +/* This is an attempt to force a single setjmp behaviour on Linux. If + * the X config stuff didn't define _BSD_SOURCE we wouldn't need this. + */ + +# ifdef __linux__ +# ifdef _BSD_SOURCE +# define PNG_SAVE_BSD_SOURCE +# undef _BSD_SOURCE +# endif +# ifdef _SETJMP_H + /* If you encounter a compiler error here, see the explanation + * near the end of INSTALL. + */ + __png.h__ already includes setjmp.h; + __dont__ include it again.; +# endif +# endif /* __linux__ */ + + /* include setjmp.h for error handling */ +# include + +# ifdef __linux__ +# ifdef PNG_SAVE_BSD_SOURCE +# define _BSD_SOURCE +# undef PNG_SAVE_BSD_SOURCE +# endif +# endif /* __linux__ */ +#endif /* PNG_SETJMP_SUPPORTED */ + +#ifdef BSD +# include +#else +# include +#endif + +/* Other defines for things like memory and the like can go here. */ +#ifdef PNG_INTERNAL + +#include + +/* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which + * aren't usually used outside the library (as far as I know), so it is + * debatable if they should be exported at all. In the future, when it is + * possible to have run-time registry of chunk-handling functions, some of + * these will be made available again. +#define PNG_EXTERN extern + */ +#define PNG_EXTERN + +/* Other defines specific to compilers can go here. Try to keep + * them inside an appropriate ifdef/endif pair for portability. + */ + +#if defined(PNG_FLOATING_POINT_SUPPORTED) +# if defined(MACOS) + /* We need to check that hasn't already been included earlier + * as it seems it doesn't agree with , yet we should really use + * if possible. + */ +# if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__) +# include +# endif +# else +# include +# endif +# if defined(_AMIGA) && defined(__SASC) && defined(_M68881) + /* Amiga SAS/C: We must include builtin FPU functions when compiling using + * MATH=68881 + */ +# include +# endif +#endif + +/* Codewarrior on NT has linking problems without this. */ +#if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__) +# define PNG_ALWAYS_EXTERN +#endif + +/* This provides the non-ANSI (far) memory allocation routines. */ +#if defined(__TURBOC__) && defined(__MSDOS__) +# include +# include +#endif + +/* I have no idea why is this necessary... */ +#if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \ + defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__)) +# include +#endif + +/* This controls how fine the dithering gets. As this allocates + * a largish chunk of memory (32K), those who are not as concerned + * with dithering quality can decrease some or all of these. + */ +#ifndef PNG_DITHER_RED_BITS +# define PNG_DITHER_RED_BITS 5 +#endif +#ifndef PNG_DITHER_GREEN_BITS +# define PNG_DITHER_GREEN_BITS 5 +#endif +#ifndef PNG_DITHER_BLUE_BITS +# define PNG_DITHER_BLUE_BITS 5 +#endif + +/* This controls how fine the gamma correction becomes when you + * are only interested in 8 bits anyway. Increasing this value + * results in more memory being used, and more pow() functions + * being called to fill in the gamma tables. Don't set this value + * less then 8, and even that may not work (I haven't tested it). + */ + +#ifndef PNG_MAX_GAMMA_8 +# define PNG_MAX_GAMMA_8 11 +#endif + +/* This controls how much a difference in gamma we can tolerate before + * we actually start doing gamma conversion. + */ +#ifndef PNG_GAMMA_THRESHOLD +# define PNG_GAMMA_THRESHOLD 0.05 +#endif + +#endif /* PNG_INTERNAL */ + +/* The following uses const char * instead of char * for error + * and warning message functions, so some compilers won't complain. + * If you do not want to use const, define PNG_NO_CONST here. + */ + +#ifndef PNG_NO_CONST +# define PNG_CONST const +#else +# define PNG_CONST +#endif + +/* The following defines give you the ability to remove code from the + * library that you will not be using. I wish I could figure out how to + * automate this, but I can't do that without making it seriously hard + * on the users. So if you are not using an ability, change the #define + * to and #undef, and that part of the library will not be compiled. If + * your linker can't find a function, you may want to make sure the + * ability is defined here. Some of these depend upon some others being + * defined. I haven't figured out all the interactions here, so you may + * have to experiment awhile to get everything to compile. If you are + * creating or using a shared library, you probably shouldn't touch this, + * as it will affect the size of the structures, and this will cause bad + * things to happen if the library and/or application ever change. + */ + +/* Any features you will not be using can be undef'ed here */ + +/* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user + * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS + * on the compile line, then pick and choose which ones to define without + * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED + * if you only want to have a png-compliant reader/writer but don't need + * any of the extra transformations. This saves about 80 kbytes in a + * typical installation of the library. (PNG_NO_* form added in version + * 1.0.1c, for consistency) + */ + +/* The size of the png_text structure changed in libpng-1.0.6 when + * iTXt is supported. It is turned off by default, to support old apps + * that malloc the png_text structure instead of calling png_set_text() + * and letting libpng malloc it. It will be turned on by default in + * libpng-1.3.0. + */ + +#ifndef PNG_iTXt_SUPPORTED +# if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt) +# define PNG_NO_READ_iTXt +# endif +# if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt) +# define PNG_NO_WRITE_iTXt +# endif +#endif + +/* The following support, added after version 1.0.0, can be turned off here en + * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility + * with old applications that require the length of png_struct and png_info + * to remain unchanged. + */ + +#ifdef PNG_LEGACY_SUPPORTED +# define PNG_NO_FREE_ME +# define PNG_NO_READ_UNKNOWN_CHUNKS +# define PNG_NO_WRITE_UNKNOWN_CHUNKS +# define PNG_NO_READ_USER_CHUNKS +# define PNG_NO_READ_iCCP +# define PNG_NO_WRITE_iCCP +# define PNG_NO_READ_iTXt +# define PNG_NO_WRITE_iTXt +# define PNG_NO_READ_sCAL +# define PNG_NO_WRITE_sCAL +# define PNG_NO_READ_sPLT +# define PNG_NO_WRITE_sPLT +# define PNG_NO_INFO_IMAGE +# define PNG_NO_READ_RGB_TO_GRAY +# define PNG_NO_READ_USER_TRANSFORM +# define PNG_NO_WRITE_USER_TRANSFORM +# define PNG_NO_USER_MEM +# define PNG_NO_READ_EMPTY_PLTE +# define PNG_NO_MNG_FEATURES +# define PNG_NO_FIXED_POINT_SUPPORTED +#endif + +/* Ignore attempt to turn off both floating and fixed point support */ +#if !defined(PNG_FLOATING_POINT_SUPPORTED) || \ + !defined(PNG_NO_FIXED_POINT_SUPPORTED) +# define PNG_FIXED_POINT_SUPPORTED +#endif + +#ifndef PNG_NO_FREE_ME +# define PNG_FREE_ME_SUPPORTED +#endif + +#if defined(PNG_READ_SUPPORTED) + +#if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \ + !defined(PNG_NO_READ_TRANSFORMS) +# define PNG_READ_TRANSFORMS_SUPPORTED +#endif + +#ifdef PNG_READ_TRANSFORMS_SUPPORTED +# ifndef PNG_NO_READ_EXPAND +# define PNG_READ_EXPAND_SUPPORTED +# endif +# ifndef PNG_NO_READ_SHIFT +# define PNG_READ_SHIFT_SUPPORTED +# endif +# ifndef PNG_NO_READ_PACK +# define PNG_READ_PACK_SUPPORTED +# endif +# ifndef PNG_NO_READ_BGR +# define PNG_READ_BGR_SUPPORTED +# endif +# ifndef PNG_NO_READ_SWAP +# define PNG_READ_SWAP_SUPPORTED +# endif +# ifndef PNG_NO_READ_PACKSWAP +# define PNG_READ_PACKSWAP_SUPPORTED +# endif +# ifndef PNG_NO_READ_INVERT +# define PNG_READ_INVERT_SUPPORTED +# endif +# ifndef PNG_NO_READ_DITHER +# define PNG_READ_DITHER_SUPPORTED +# endif +# ifndef PNG_NO_READ_BACKGROUND +# define PNG_READ_BACKGROUND_SUPPORTED +# endif +# ifndef PNG_NO_READ_16_TO_8 +# define PNG_READ_16_TO_8_SUPPORTED +# endif +# ifndef PNG_NO_READ_FILLER +# define PNG_READ_FILLER_SUPPORTED +# endif +# ifndef PNG_NO_READ_GAMMA +# define PNG_READ_GAMMA_SUPPORTED +# endif +# ifndef PNG_NO_READ_GRAY_TO_RGB +# define PNG_READ_GRAY_TO_RGB_SUPPORTED +# endif +# ifndef PNG_NO_READ_SWAP_ALPHA +# define PNG_READ_SWAP_ALPHA_SUPPORTED +# endif +# ifndef PNG_NO_READ_INVERT_ALPHA +# define PNG_READ_INVERT_ALPHA_SUPPORTED +# endif +# ifndef PNG_NO_READ_STRIP_ALPHA +# define PNG_READ_STRIP_ALPHA_SUPPORTED +# endif +# ifndef PNG_NO_READ_USER_TRANSFORM +# define PNG_READ_USER_TRANSFORM_SUPPORTED +# endif +# ifndef PNG_NO_READ_RGB_TO_GRAY +# define PNG_READ_RGB_TO_GRAY_SUPPORTED +# endif +#endif /* PNG_READ_TRANSFORMS_SUPPORTED */ + +#if !defined(PNG_NO_PROGRESSIVE_READ) && \ + !defined(PNG_PROGRESSIVE_READ_NOT_SUPPORTED) /* if you don't do progressive */ +# define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */ +#endif /* about interlacing capability! You'll */ + /* still have interlacing unless you change the following line: */ + +#define PNG_READ_INTERLACING_SUPPORTED /* required for PNG-compliant decoders */ + +#ifndef PNG_NO_READ_COMPOSITE_NODIV +# ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */ +# define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */ +# endif +#endif + +/* Deprecated, will be removed from version 2.0.0. + Use PNG_MNG_FEATURES_SUPPORTED instead. */ +#ifndef PNG_NO_READ_EMPTY_PLTE +# define PNG_READ_EMPTY_PLTE_SUPPORTED +#endif + +#endif /* PNG_READ_SUPPORTED */ + +#if defined(PNG_WRITE_SUPPORTED) + +# if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \ + !defined(PNG_NO_WRITE_TRANSFORMS) +# define PNG_WRITE_TRANSFORMS_SUPPORTED +#endif + +#ifdef PNG_WRITE_TRANSFORMS_SUPPORTED +# ifndef PNG_NO_WRITE_SHIFT +# define PNG_WRITE_SHIFT_SUPPORTED +# endif +# ifndef PNG_NO_WRITE_PACK +# define PNG_WRITE_PACK_SUPPORTED +# endif +# ifndef PNG_NO_WRITE_BGR +# define PNG_WRITE_BGR_SUPPORTED +# endif +# ifndef PNG_NO_WRITE_SWAP +# define PNG_WRITE_SWAP_SUPPORTED +# endif +# ifndef PNG_NO_WRITE_PACKSWAP +# define PNG_WRITE_PACKSWAP_SUPPORTED +# endif +# ifndef PNG_NO_WRITE_INVERT +# define PNG_WRITE_INVERT_SUPPORTED +# endif +# ifndef PNG_NO_WRITE_FILLER +# define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */ +# endif +# ifndef PNG_NO_WRITE_SWAP_ALPHA +# define PNG_WRITE_SWAP_ALPHA_SUPPORTED +# endif +# ifndef PNG_NO_WRITE_INVERT_ALPHA +# define PNG_WRITE_INVERT_ALPHA_SUPPORTED +# endif +# ifndef PNG_NO_WRITE_USER_TRANSFORM +# define PNG_WRITE_USER_TRANSFORM_SUPPORTED +# endif +#endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */ + +#define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant + encoders, but can cause trouble + if left undefined */ + +#if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \ + defined(PNG_FLOATING_POINT_SUPPORTED) +# define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED +#endif + +#ifndef PNG_NO_WRITE_FLUSH +# define PNG_WRITE_FLUSH_SUPPORTED +#endif + +/* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */ +#ifndef PNG_NO_WRITE_EMPTY_PLTE +# define PNG_WRITE_EMPTY_PLTE_SUPPORTED +#endif + +#endif /* PNG_WRITE_SUPPORTED */ + +#ifndef PNG_1_0_X +# ifndef PNG_NO_ERROR_NUMBERS +# define PNG_ERROR_NUMBERS_SUPPORTED +# endif +#endif /* PNG_1_0_X */ + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) +# ifndef PNG_NO_USER_TRANSFORM_PTR +# define PNG_USER_TRANSFORM_PTR_SUPPORTED +# endif +#endif + +#ifndef PNG_NO_STDIO +# define PNG_TIME_RFC1123_SUPPORTED +#endif + +/* This adds extra functions in pngget.c for accessing data from the + * info pointer (added in version 0.99) + * png_get_image_width() + * png_get_image_height() + * png_get_bit_depth() + * png_get_color_type() + * png_get_compression_type() + * png_get_filter_type() + * png_get_interlace_type() + * png_get_pixel_aspect_ratio() + * png_get_pixels_per_meter() + * png_get_x_offset_pixels() + * png_get_y_offset_pixels() + * png_get_x_offset_microns() + * png_get_y_offset_microns() + */ +#if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED) +# define PNG_EASY_ACCESS_SUPPORTED +#endif + +/* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0 + even when PNG_USE_PNGVCRD or PNG_USE_PNGGCCRD is not defined */ +#if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE) +# ifndef PNG_ASSEMBLER_CODE_SUPPORTED +# define PNG_ASSEMBLER_CODE_SUPPORTED +# endif +# if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE) +# define PNG_MMX_CODE_SUPPORTED +# endif +#endif + +/* If you are sure that you don't need thread safety and you are compiling + with PNG_USE_PNGCCRD for an MMX application, you can define this for + faster execution. See pnggccrd.c. +#define PNG_THREAD_UNSAFE_OK +*/ + +#if !defined(PNG_1_0_X) +#if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED) +# define PNG_USER_MEM_SUPPORTED +#endif +#endif /* PNG_1_0_X */ + +/* Added at libpng-1.2.6 */ +#if !defined(PNG_1_0_X) +#ifndef PNG_SET_USER_LIMITS_SUPPORTED +#if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED) +# define PNG_SET_USER_LIMITS_SUPPORTED +#endif +#endif +#endif /* PNG_1_0_X */ + +/* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter + * how large, set these limits to 0x7fffffffL + */ +#ifndef PNG_USER_WIDTH_MAX +# define PNG_USER_WIDTH_MAX 1000000L +#endif +#ifndef PNG_USER_HEIGHT_MAX +# define PNG_USER_HEIGHT_MAX 1000000L +#endif + +/* These are currently experimental features, define them if you want */ + +/* very little testing */ +/* +#ifdef PNG_READ_SUPPORTED +# ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED +# define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED +# endif +#endif +*/ + +/* This is only for PowerPC big-endian and 680x0 systems */ +/* some testing */ +/* +#ifndef PNG_READ_BIG_ENDIAN_SUPPORTED +# define PNG_READ_BIG_ENDIAN_SUPPORTED +#endif +*/ + +/* Buggy compilers (e.g., gcc 2.7.2.2) need this */ +/* +#define PNG_NO_POINTER_INDEXING +*/ + +/* These functions are turned off by default, as they will be phased out. */ +/* +#define PNG_USELESS_TESTS_SUPPORTED +#define PNG_CORRECT_PALETTE_SUPPORTED +*/ + +/* Any chunks you are not interested in, you can undef here. The + * ones that allocate memory may be expecially important (hIST, + * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info + * a bit smaller. + */ + +#if defined(PNG_READ_SUPPORTED) && \ + !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \ + !defined(PNG_NO_READ_ANCILLARY_CHUNKS) +# define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED +#endif + +#if defined(PNG_WRITE_SUPPORTED) && \ + !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \ + !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS) +# define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED +#endif + +#ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED + +#ifdef PNG_NO_READ_TEXT +# define PNG_NO_READ_iTXt +# define PNG_NO_READ_tEXt +# define PNG_NO_READ_zTXt +#endif +#ifndef PNG_NO_READ_bKGD +# define PNG_READ_bKGD_SUPPORTED +# define PNG_bKGD_SUPPORTED +#endif +#ifndef PNG_NO_READ_cHRM +# define PNG_READ_cHRM_SUPPORTED +# define PNG_cHRM_SUPPORTED +#endif +#ifndef PNG_NO_READ_gAMA +# define PNG_READ_gAMA_SUPPORTED +# define PNG_gAMA_SUPPORTED +#endif +#ifndef PNG_NO_READ_hIST +# define PNG_READ_hIST_SUPPORTED +# define PNG_hIST_SUPPORTED +#endif +#ifndef PNG_NO_READ_iCCP +# define PNG_READ_iCCP_SUPPORTED +# define PNG_iCCP_SUPPORTED +#endif +#ifndef PNG_NO_READ_iTXt +# ifndef PNG_READ_iTXt_SUPPORTED +# define PNG_READ_iTXt_SUPPORTED +# endif +# ifndef PNG_iTXt_SUPPORTED +# define PNG_iTXt_SUPPORTED +# endif +#endif +#ifndef PNG_NO_READ_oFFs +# define PNG_READ_oFFs_SUPPORTED +# define PNG_oFFs_SUPPORTED +#endif +#ifndef PNG_NO_READ_pCAL +# define PNG_READ_pCAL_SUPPORTED +# define PNG_pCAL_SUPPORTED +#endif +#ifndef PNG_NO_READ_sCAL +# define PNG_READ_sCAL_SUPPORTED +# define PNG_sCAL_SUPPORTED +#endif +#ifndef PNG_NO_READ_pHYs +# define PNG_READ_pHYs_SUPPORTED +# define PNG_pHYs_SUPPORTED +#endif +#ifndef PNG_NO_READ_sBIT +# define PNG_READ_sBIT_SUPPORTED +# define PNG_sBIT_SUPPORTED +#endif +#ifndef PNG_NO_READ_sPLT +# define PNG_READ_sPLT_SUPPORTED +# define PNG_sPLT_SUPPORTED +#endif +#ifndef PNG_NO_READ_sRGB +# define PNG_READ_sRGB_SUPPORTED +# define PNG_sRGB_SUPPORTED +#endif +#ifndef PNG_NO_READ_tEXt +# define PNG_READ_tEXt_SUPPORTED +# define PNG_tEXt_SUPPORTED +#endif +#ifndef PNG_NO_READ_tIME +# define PNG_READ_tIME_SUPPORTED +# define PNG_tIME_SUPPORTED +#endif +#ifndef PNG_NO_READ_tRNS +# define PNG_READ_tRNS_SUPPORTED +# define PNG_tRNS_SUPPORTED +#endif +#ifndef PNG_NO_READ_zTXt +# define PNG_READ_zTXt_SUPPORTED +# define PNG_zTXt_SUPPORTED +#endif +#ifndef PNG_NO_READ_UNKNOWN_CHUNKS +# define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED +# ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED +# define PNG_UNKNOWN_CHUNKS_SUPPORTED +# endif +# ifndef PNG_NO_HANDLE_AS_UNKNOWN +# define PNG_HANDLE_AS_UNKNOWN_SUPPORTED +# endif +#endif +#if !defined(PNG_NO_READ_USER_CHUNKS) && \ + defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) +# define PNG_READ_USER_CHUNKS_SUPPORTED +# define PNG_USER_CHUNKS_SUPPORTED +# ifdef PNG_NO_READ_UNKNOWN_CHUNKS +# undef PNG_NO_READ_UNKNOWN_CHUNKS +# endif +# ifdef PNG_NO_HANDLE_AS_UNKNOWN +# undef PNG_NO_HANDLE_AS_UNKNOWN +# endif +#endif +#ifndef PNG_NO_READ_OPT_PLTE +# define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */ +#endif /* optional PLTE chunk in RGB and RGBA images */ +#if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \ + defined(PNG_READ_zTXt_SUPPORTED) +# define PNG_READ_TEXT_SUPPORTED +# define PNG_TEXT_SUPPORTED +#endif + +#endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */ + +#ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED + +#ifdef PNG_NO_WRITE_TEXT +# define PNG_NO_WRITE_iTXt +# define PNG_NO_WRITE_tEXt +# define PNG_NO_WRITE_zTXt +#endif +#ifndef PNG_NO_WRITE_bKGD +# define PNG_WRITE_bKGD_SUPPORTED +# ifndef PNG_bKGD_SUPPORTED +# define PNG_bKGD_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_cHRM +# define PNG_WRITE_cHRM_SUPPORTED +# ifndef PNG_cHRM_SUPPORTED +# define PNG_cHRM_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_gAMA +# define PNG_WRITE_gAMA_SUPPORTED +# ifndef PNG_gAMA_SUPPORTED +# define PNG_gAMA_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_hIST +# define PNG_WRITE_hIST_SUPPORTED +# ifndef PNG_hIST_SUPPORTED +# define PNG_hIST_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_iCCP +# define PNG_WRITE_iCCP_SUPPORTED +# ifndef PNG_iCCP_SUPPORTED +# define PNG_iCCP_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_iTXt +# ifndef PNG_WRITE_iTXt_SUPPORTED +# define PNG_WRITE_iTXt_SUPPORTED +# endif +# ifndef PNG_iTXt_SUPPORTED +# define PNG_iTXt_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_oFFs +# define PNG_WRITE_oFFs_SUPPORTED +# ifndef PNG_oFFs_SUPPORTED +# define PNG_oFFs_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_pCAL +# define PNG_WRITE_pCAL_SUPPORTED +# ifndef PNG_pCAL_SUPPORTED +# define PNG_pCAL_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_sCAL +# define PNG_WRITE_sCAL_SUPPORTED +# ifndef PNG_sCAL_SUPPORTED +# define PNG_sCAL_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_pHYs +# define PNG_WRITE_pHYs_SUPPORTED +# ifndef PNG_pHYs_SUPPORTED +# define PNG_pHYs_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_sBIT +# define PNG_WRITE_sBIT_SUPPORTED +# ifndef PNG_sBIT_SUPPORTED +# define PNG_sBIT_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_sPLT +# define PNG_WRITE_sPLT_SUPPORTED +# ifndef PNG_sPLT_SUPPORTED +# define PNG_sPLT_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_sRGB +# define PNG_WRITE_sRGB_SUPPORTED +# ifndef PNG_sRGB_SUPPORTED +# define PNG_sRGB_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_tEXt +# define PNG_WRITE_tEXt_SUPPORTED +# ifndef PNG_tEXt_SUPPORTED +# define PNG_tEXt_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_tIME +# define PNG_WRITE_tIME_SUPPORTED +# ifndef PNG_tIME_SUPPORTED +# define PNG_tIME_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_tRNS +# define PNG_WRITE_tRNS_SUPPORTED +# ifndef PNG_tRNS_SUPPORTED +# define PNG_tRNS_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_zTXt +# define PNG_WRITE_zTXt_SUPPORTED +# ifndef PNG_zTXt_SUPPORTED +# define PNG_zTXt_SUPPORTED +# endif +#endif +#ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS +# define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED +# ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED +# define PNG_UNKNOWN_CHUNKS_SUPPORTED +# endif +# ifndef PNG_NO_HANDLE_AS_UNKNOWN +# ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED +# define PNG_HANDLE_AS_UNKNOWN_SUPPORTED +# endif +# endif +#endif +#if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \ + defined(PNG_WRITE_zTXt_SUPPORTED) +# define PNG_WRITE_TEXT_SUPPORTED +# ifndef PNG_TEXT_SUPPORTED +# define PNG_TEXT_SUPPORTED +# endif +#endif + +#endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */ + +/* Turn this off to disable png_read_png() and + * png_write_png() and leave the row_pointers member + * out of the info structure. + */ +#ifndef PNG_NO_INFO_IMAGE +# define PNG_INFO_IMAGE_SUPPORTED +#endif + +/* need the time information for reading tIME chunks */ +#if defined(PNG_tIME_SUPPORTED) +# if !defined(_WIN32_WCE) + /* "time.h" functions are not supported on WindowsCE */ +# include +# endif +#endif + +/* Some typedefs to get us started. These should be safe on most of the + * common platforms. The typedefs should be at least as large as the + * numbers suggest (a png_uint_32 must be at least 32 bits long), but they + * don't have to be exactly that size. Some compilers dislike passing + * unsigned shorts as function parameters, so you may be better off using + * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may + * want to have unsigned int for png_uint_32 instead of unsigned long. + */ + +typedef unsigned long png_uint_32; +typedef long png_int_32; +typedef unsigned short png_uint_16; +typedef short png_int_16; +typedef unsigned char png_byte; + +/* This is usually size_t. It is typedef'ed just in case you need it to + change (I'm not sure if you will or not, so I thought I'd be safe) */ +#ifdef PNG_SIZE_T + typedef PNG_SIZE_T png_size_t; +# define png_sizeof(x) png_convert_size(sizeof (x)) +#else + typedef size_t png_size_t; +# define png_sizeof(x) sizeof (x) +#endif + +/* The following is needed for medium model support. It cannot be in the + * PNG_INTERNAL section. Needs modification for other compilers besides + * MSC. Model independent support declares all arrays and pointers to be + * large using the far keyword. The zlib version used must also support + * model independent data. As of version zlib 1.0.4, the necessary changes + * have been made in zlib. The USE_FAR_KEYWORD define triggers other + * changes that are needed. (Tim Wegner) + */ + +/* Separate compiler dependencies (problem here is that zlib.h always + defines FAR. (SJT) */ +#ifdef __BORLANDC__ +# if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__) +# define LDATA 1 +# else +# define LDATA 0 +# endif + /* GRR: why is Cygwin in here? Cygwin is not Borland C... */ +# if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__) +# define PNG_MAX_MALLOC_64K +# if (LDATA != 1) +# ifndef FAR +# define FAR __far +# endif +# define USE_FAR_KEYWORD +# endif /* LDATA != 1 */ + /* Possibly useful for moving data out of default segment. + * Uncomment it if you want. Could also define FARDATA as + * const if your compiler supports it. (SJT) +# define FARDATA FAR + */ +# endif /* __WIN32__, __FLAT__, __CYGWIN__ */ +#endif /* __BORLANDC__ */ + + +/* Suggest testing for specific compiler first before testing for + * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM, + * making reliance oncertain keywords suspect. (SJT) + */ + +/* MSC Medium model */ +#if defined(FAR) +# if defined(M_I86MM) +# define USE_FAR_KEYWORD +# define FARDATA FAR +# include +# endif +#endif + +/* SJT: default case */ +#ifndef FAR +# define FAR +#endif + +/* At this point FAR is always defined */ +#ifndef FARDATA +# define FARDATA +#endif + +/* Typedef for floating-point numbers that are converted + to fixed-point with a multiple of 100,000, e.g., int_gamma */ +typedef png_int_32 png_fixed_point; + +/* Add typedefs for pointers */ +typedef void FAR * png_voidp; +typedef png_byte FAR * png_bytep; +typedef png_uint_32 FAR * png_uint_32p; +typedef png_int_32 FAR * png_int_32p; +typedef png_uint_16 FAR * png_uint_16p; +typedef png_int_16 FAR * png_int_16p; +typedef PNG_CONST char FAR * png_const_charp; +typedef char FAR * png_charp; +typedef png_fixed_point FAR * png_fixed_point_p; + +#ifndef PNG_NO_STDIO +#if defined(_WIN32_WCE) +typedef HANDLE png_FILE_p; +#else +typedef FILE * png_FILE_p; +#endif +#endif + +#ifdef PNG_FLOATING_POINT_SUPPORTED +typedef double FAR * png_doublep; +#endif + +/* Pointers to pointers; i.e. arrays */ +typedef png_byte FAR * FAR * png_bytepp; +typedef png_uint_32 FAR * FAR * png_uint_32pp; +typedef png_int_32 FAR * FAR * png_int_32pp; +typedef png_uint_16 FAR * FAR * png_uint_16pp; +typedef png_int_16 FAR * FAR * png_int_16pp; +typedef PNG_CONST char FAR * FAR * png_const_charpp; +typedef char FAR * FAR * png_charpp; +typedef png_fixed_point FAR * FAR * png_fixed_point_pp; +#ifdef PNG_FLOATING_POINT_SUPPORTED +typedef double FAR * FAR * png_doublepp; +#endif + +/* Pointers to pointers to pointers; i.e., pointer to array */ +typedef char FAR * FAR * FAR * png_charppp; + +/* libpng typedefs for types in zlib. If zlib changes + * or another compression library is used, then change these. + * Eliminates need to change all the source files. + */ +typedef charf * png_zcharp; +typedef charf * FAR * png_zcharpp; +typedef z_stream FAR * png_zstreamp; + +/* + * Define PNG_BUILD_DLL if the module being built is a Windows + * LIBPNG DLL. + * + * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL. + * It is equivalent to Microsoft predefined macro _DLL that is + * automatically defined when you compile using the share + * version of the CRT (C Run-Time library) + * + * The cygwin mods make this behavior a little different: + * Define PNG_BUILD_DLL if you are building a dll for use with cygwin + * Define PNG_STATIC if you are building a static library for use with cygwin, + * -or- if you are building an application that you want to link to the + * static library. + * PNG_USE_DLL is defined by default (no user action needed) unless one of + * the other flags is defined. + */ + +#if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL)) +# define PNG_DLL +#endif +/* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib. + * When building a static lib, default to no GLOBAL ARRAYS, but allow + * command-line override + */ +#if defined(__CYGWIN__) +# if !defined(PNG_STATIC) +# if defined(PNG_USE_GLOBAL_ARRAYS) +# undef PNG_USE_GLOBAL_ARRAYS +# endif +# if !defined(PNG_USE_LOCAL_ARRAYS) +# define PNG_USE_LOCAL_ARRAYS +# endif +# else +# if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS) +# if defined(PNG_USE_GLOBAL_ARRAYS) +# undef PNG_USE_GLOBAL_ARRAYS +# endif +# endif +# endif +# if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS) +# define PNG_USE_LOCAL_ARRAYS +# endif +#endif + +/* Do not use global arrays (helps with building DLL's) + * They are no longer used in libpng itself, since version 1.0.5c, + * but might be required for some pre-1.0.5c applications. + */ +#if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS) +# if defined(PNG_NO_GLOBAL_ARRAYS) || (defined(__GNUC__) && defined(PNG_DLL)) +# define PNG_USE_LOCAL_ARRAYS +# else +# define PNG_USE_GLOBAL_ARRAYS +# endif +#endif + +#if defined(__CYGWIN__) +# undef PNGAPI +# define PNGAPI __cdecl +# undef PNG_IMPEXP +# define PNG_IMPEXP +#endif + +/* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall", + * you may get warnings regarding the linkage of png_zalloc and png_zfree. + * Don't ignore those warnings; you must also reset the default calling + * convention in your compiler to match your PNGAPI, and you must build + * zlib and your applications the same way you build libpng. + */ + +#if defined(__MINGW32__) && !defined(PNG_MODULEDEF) +# ifndef PNG_NO_MODULEDEF +# define PNG_NO_MODULEDEF +# endif +#endif + +#if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF) +# define PNG_IMPEXP +#endif + +#if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \ + (( defined(_Windows) || defined(_WINDOWS) || \ + defined(WIN32) || defined(_WIN32) || defined(__WIN32__) )) + +# ifndef PNGAPI +# if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800)) +# define PNGAPI __cdecl +# else +# define PNGAPI _cdecl +# endif +# endif + +# if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \ + 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */) +# define PNG_IMPEXP +# endif + +# if !defined(PNG_IMPEXP) + +# define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol +# define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol + + /* Borland/Microsoft */ +# if defined(_MSC_VER) || defined(__BORLANDC__) +# if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500) +# define PNG_EXPORT PNG_EXPORT_TYPE1 +# else +# define PNG_EXPORT PNG_EXPORT_TYPE2 +# if defined(PNG_BUILD_DLL) +# define PNG_IMPEXP __export +# else +# define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in + VC++ */ +# endif /* Exists in Borland C++ for + C++ classes (== huge) */ +# endif +# endif + +# if !defined(PNG_IMPEXP) +# if defined(PNG_BUILD_DLL) +# define PNG_IMPEXP __declspec(dllexport) +# else +# define PNG_IMPEXP __declspec(dllimport) +# endif +# endif +# endif /* PNG_IMPEXP */ +#else /* !(DLL || non-cygwin WINDOWS) */ +# if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__) +# ifndef PNGAPI +# define PNGAPI _System +# endif +# else +# if 0 /* ... other platforms, with other meanings */ +# endif +# endif +#endif + +#ifndef PNGAPI +# define PNGAPI +#endif +#ifndef PNG_IMPEXP +# define PNG_IMPEXP +#endif + +#ifndef PNG_EXPORT +# define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol +#endif + +#ifdef PNG_USE_GLOBAL_ARRAYS +# ifndef PNG_EXPORT_VAR +# define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type +# endif +#endif + +/* User may want to use these so they are not in PNG_INTERNAL. Any library + * functions that are passed far data must be model independent. + */ + +#ifndef PNG_ABORT +# define PNG_ABORT() abort() +#endif + +#ifdef PNG_SETJMP_SUPPORTED +# define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf) +#else +# define png_jmpbuf(png_ptr) \ + (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED) +#endif + +#if defined(USE_FAR_KEYWORD) /* memory model independent fns */ +/* use this to make far-to-near assignments */ +# define CHECK 1 +# define NOCHECK 0 +# define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK)) +# define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK)) +# define png_strcpy _fstrcpy +# define png_strncpy _fstrncpy /* Added to v 1.2.6 */ +# define png_strlen _fstrlen +# define png_memcmp _fmemcmp /* SJT: added */ +# define png_memcpy _fmemcpy +# define png_memset _fmemset +#else /* use the usual functions */ +# define CVT_PTR(ptr) (ptr) +# define CVT_PTR_NOCHECK(ptr) (ptr) +# define png_strcpy strcpy +# define png_strncpy strncpy /* Added to v 1.2.6 */ +# define png_strlen strlen +# define png_memcmp memcmp /* SJT: added */ +# define png_memcpy memcpy +# define png_memset memset +#endif +/* End of memory model independent support */ + +/* Just a little check that someone hasn't tried to define something + * contradictory. + */ +#if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K) +# undef PNG_ZBUF_SIZE +# define PNG_ZBUF_SIZE 65536L +#endif + +#ifdef PNG_READ_SUPPORTED +/* Prior to libpng-1.0.9, this block was in pngasmrd.h */ +#if defined(PNG_INTERNAL) + +/* These are the default thresholds before the MMX code kicks in; if either + * rowbytes or bitdepth is below the threshold, plain C code is used. These + * can be overridden at runtime via the png_set_mmx_thresholds() call in + * libpng 1.2.0 and later. The values below were chosen by Intel. + */ + +#ifndef PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT +# define PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT 128 /* >= */ +#endif +#ifndef PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT +# define PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT 9 /* >= */ +#endif + +/* Set this in the makefile for VC++ on Pentium, not here. */ +/* Platform must be Pentium. Makefile must assemble and load pngvcrd.c . + * MMX will be detected at run time and used if present. + */ +#ifdef PNG_USE_PNGVCRD +# define PNG_HAVE_ASSEMBLER_COMBINE_ROW +# define PNG_HAVE_ASSEMBLER_READ_INTERLACE +# define PNG_HAVE_ASSEMBLER_READ_FILTER_ROW +#endif + +/* Set this in the makefile for gcc/as on Pentium, not here. */ +/* Platform must be Pentium. Makefile must assemble and load pnggccrd.c . + * MMX will be detected at run time and used if present. + */ +#ifdef PNG_USE_PNGGCCRD +# define PNG_HAVE_ASSEMBLER_COMBINE_ROW +# define PNG_HAVE_ASSEMBLER_READ_INTERLACE +# define PNG_HAVE_ASSEMBLER_READ_FILTER_ROW +#endif +/* - see pnggccrd.c for info about what is currently enabled */ + +#endif /* PNG_INTERNAL */ +#endif /* PNG_READ_SUPPORTED */ + +#endif /* PNGCONF_H */ + diff --git a/SlnkDWFImpl/CxImage/png/pngerror.c b/SlnkDWFImpl/CxImage/png/pngerror.c new file mode 100644 index 0000000..18ab837 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngerror.c @@ -0,0 +1,295 @@ + +/* pngerror.c - stub functions for i/o and memory allocation + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * This file provides a location for all error handling. Users who + * need special error handling are expected to write replacement functions + * and use png_set_error_fn() to use those functions. See the instructions + * at each function. + */ + +#define PNG_INTERNAL +#include "png.h" + +static void /* PRIVATE */ +png_default_error PNGARG((png_structp png_ptr, + png_const_charp error_message)); +static void /* PRIVATE */ +png_default_warning PNGARG((png_structp png_ptr, + png_const_charp warning_message)); + +/* This function is called whenever there is a fatal error. This function + * should not be changed. If there is a need to handle errors differently, + * you should supply a replacement error function and use png_set_error_fn() + * to replace the error function at run-time. + */ +void PNGAPI +png_error(png_structp png_ptr, png_const_charp error_message) +{ +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + char msg[16]; + if (png_ptr->flags&(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT)) + { + if (*error_message == '#') + { + int offset; + for (offset=1; offset<15; offset++) + if (*(error_message+offset) == ' ') + break; + if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT) + { + int i; + for (i=0; iflags&PNG_FLAG_STRIP_ERROR_TEXT) + { + msg[0]='0'; + msg[1]='\0'; + error_message=msg; + } + } + } +#endif + if (png_ptr != NULL && png_ptr->error_fn != NULL) + (*(png_ptr->error_fn))(png_ptr, error_message); + + /* If the custom handler doesn't exist, or if it returns, + use the default handler, which will not return. */ + png_default_error(png_ptr, error_message); +} + +/* This function is called whenever there is a non-fatal error. This function + * should not be changed. If there is a need to handle warnings differently, + * you should supply a replacement warning function and use + * png_set_error_fn() to replace the warning function at run-time. + */ +void PNGAPI +png_warning(png_structp png_ptr, png_const_charp warning_message) +{ + int offset = 0; +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + if (png_ptr->flags&(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT)) +#endif + { + if (*warning_message == '#') + { + for (offset=1; offset<15; offset++) + if (*(warning_message+offset) == ' ') + break; + } + } + if (png_ptr != NULL && png_ptr->warning_fn != NULL) + (*(png_ptr->warning_fn))(png_ptr, warning_message+offset); + else + png_default_warning(png_ptr, warning_message+offset); +} + +/* These utilities are used internally to build an error message that relates + * to the current chunk. The chunk name comes from png_ptr->chunk_name, + * this is used to prefix the message. The message is limited in length + * to 63 bytes, the name characters are output as hex digits wrapped in [] + * if the character is invalid. + */ +#define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97)) +static PNG_CONST char png_digit[16] = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F' +}; + +static void /* PRIVATE */ +png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp + error_message) +{ + int iout = 0, iin = 0; + + while (iin < 4) + { + int c = png_ptr->chunk_name[iin++]; + if (isnonalpha(c)) + { + buffer[iout++] = '['; + buffer[iout++] = png_digit[(c & 0xf0) >> 4]; + buffer[iout++] = png_digit[c & 0x0f]; + buffer[iout++] = ']'; + } + else + { + buffer[iout++] = (png_byte)c; + } + } + + if (error_message == NULL) + buffer[iout] = 0; + else + { + buffer[iout++] = ':'; + buffer[iout++] = ' '; + png_strncpy(buffer+iout, error_message, 63); + buffer[iout+63] = 0; + } +} + +void PNGAPI +png_chunk_error(png_structp png_ptr, png_const_charp error_message) +{ + char msg[18+64]; + png_format_buffer(png_ptr, msg, error_message); + png_error(png_ptr, msg); +} + +void PNGAPI +png_chunk_warning(png_structp png_ptr, png_const_charp warning_message) +{ + char msg[18+64]; + png_format_buffer(png_ptr, msg, warning_message); + png_warning(png_ptr, msg); +} + +/* This is the default error handling function. Note that replacements for + * this function MUST NOT RETURN, or the program will likely crash. This + * function is used by default, or if the program supplies NULL for the + * error function pointer in png_set_error_fn(). + */ +static void /* PRIVATE */ +png_default_error(png_structp png_ptr, png_const_charp error_message) +{ +#ifndef PNG_NO_CONSOLE_IO +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + if (*error_message == '#') + { + int offset; + char error_number[16]; + for (offset=0; offset<15; offset++) + { + error_number[offset] = *(error_message+offset+1); + if (*(error_message+offset) == ' ') + break; + } + if((offset > 1) && (offset < 15)) + { + error_number[offset-1]='\0'; + fprintf(stderr, "libpng error no. %s: %s\n", error_number, + error_message+offset); + } + else + fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset); + } + else +#endif + fprintf(stderr, "libpng error: %s\n", error_message); +#endif + +#ifdef PNG_SETJMP_SUPPORTED +# ifdef USE_FAR_KEYWORD + { + jmp_buf jmpbuf; + png_memcpy(jmpbuf,png_ptr->jmpbuf,png_sizeof(jmp_buf)); + longjmp(jmpbuf, 1); + } +# else + longjmp(png_ptr->jmpbuf, 1); +# endif +#else + /* make compiler happy */ ; + if (png_ptr) + PNG_ABORT(); +#endif +#ifdef PNG_NO_CONSOLE_IO + /* make compiler happy */ ; + if (&error_message != NULL) + return; +#endif +} + +/* This function is called when there is a warning, but the library thinks + * it can continue anyway. Replacement functions don't have to do anything + * here if you don't want them to. In the default configuration, png_ptr is + * not used, but it is passed in case it may be useful. + */ +static void /* PRIVATE */ +png_default_warning(png_structp png_ptr, png_const_charp warning_message) +{ +#ifndef PNG_NO_CONSOLE_IO +# ifdef PNG_ERROR_NUMBERS_SUPPORTED + if (*warning_message == '#') + { + int offset; + char warning_number[16]; + for (offset=0; offset<15; offset++) + { + warning_number[offset]=*(warning_message+offset+1); + if (*(warning_message+offset) == ' ') + break; + } + if((offset > 1) && (offset < 15)) + { + warning_number[offset-1]='\0'; + fprintf(stderr, "libpng warning no. %s: %s\n", warning_number, + warning_message+offset); + } + else + fprintf(stderr, "libpng warning: %s\n", warning_message); + } + else +# endif + fprintf(stderr, "libpng warning: %s\n", warning_message); +#else + /* make compiler happy */ ; + if (warning_message) + return; +#endif + /* make compiler happy */ ; + if (png_ptr) + return; +} + +/* This function is called when the application wants to use another method + * of handling errors and warnings. Note that the error function MUST NOT + * return to the calling routine or serious problems will occur. The return + * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1) + */ +void PNGAPI +png_set_error_fn(png_structp png_ptr, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warning_fn) +{ + png_ptr->error_ptr = error_ptr; + png_ptr->error_fn = error_fn; + png_ptr->warning_fn = warning_fn; +} + + +/* This function returns a pointer to the error_ptr associated with the user + * functions. The application should free any memory associated with this + * pointer before png_write_destroy and png_read_destroy are called. + */ +png_voidp PNGAPI +png_get_error_ptr(png_structp png_ptr) +{ + return ((png_voidp)png_ptr->error_ptr); +} + + +#ifdef PNG_ERROR_NUMBERS_SUPPORTED +void PNGAPI +png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode) +{ + if(png_ptr != NULL) + { + png_ptr->flags &= + ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode); + } +} +#endif diff --git a/SlnkDWFImpl/CxImage/png/pnggccrd.c b/SlnkDWFImpl/CxImage/png/pnggccrd.c new file mode 100644 index 0000000..db1091d --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pnggccrd.c @@ -0,0 +1,5408 @@ +/* pnggccrd.c - mixed C/assembler version of utilities to read a PNG file + * + * For Intel x86 CPU (Pentium-MMX or later) and GNU C compiler. + * + * See http://www.intel.com/drg/pentiumII/appnotes/916/916.htm + * and http://www.intel.com/drg/pentiumII/appnotes/923/923.htm + * for Intel's performance analysis of the MMX vs. non-MMX code. + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * Copyright (c) 1998, Intel Corporation + * + * Based on MSVC code contributed by Nirav Chhatrapati, Intel Corp., 1998. + * Interface to libpng contributed by Gilles Vollant, 1999. + * GNU C port by Greg Roelofs, 1999-2001. + * + * Lines 2350-4300 converted in place with intel2gas 1.3.1: + * + * intel2gas -mdI pnggccrd.c.partially-msvc -o pnggccrd.c + * + * and then cleaned up by hand. See http://hermes.terminal.at/intel2gas/ . + * + * NOTE: A sufficiently recent version of GNU as (or as.exe under DOS/Windows) + * is required to assemble the newer MMX instructions such as movq. + * For djgpp, see + * + * ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/bnu281b.zip + * + * (or a later version in the same directory). For Linux, check your + * distribution's web site(s) or try these links: + * + * http://rufus.w3.org/linux/RPM/binutils.html + * http://www.debian.org/Packages/stable/devel/binutils.html + * ftp://ftp.slackware.com/pub/linux/slackware/slackware/slakware/d1/ + * binutils.tgz + * + * For other platforms, see the main GNU site: + * + * ftp://ftp.gnu.org/pub/gnu/binutils/ + * + * Version 2.5.2l.15 is definitely too old... + */ + +/* + * TEMPORARY PORTING NOTES AND CHANGELOG (mostly by Greg Roelofs) + * ===================================== + * + * 19991006: + * - fixed sign error in post-MMX cleanup code (16- & 32-bit cases) + * + * 19991007: + * - additional optimizations (possible or definite): + * x [DONE] write MMX code for 64-bit case (pixel_bytes == 8) [not tested] + * - write MMX code for 48-bit case (pixel_bytes == 6) + * - figure out what's up with 24-bit case (pixel_bytes == 3): + * why subtract 8 from width_mmx in the pass 4/5 case? + * (only width_mmx case) (near line 1606) + * x [DONE] replace pixel_bytes within each block with the true + * constant value (or are compilers smart enough to do that?) + * - rewrite all MMX interlacing code so it's aligned with + * the *beginning* of the row buffer, not the end. This + * would not only allow one to eliminate half of the memory + * writes for odd passes (that is, pass == odd), it may also + * eliminate some unaligned-data-access exceptions (assuming + * there's a penalty for not aligning 64-bit accesses on + * 64-bit boundaries). The only catch is that the "leftover" + * pixel(s) at the end of the row would have to be saved, + * but there are enough unused MMX registers in every case, + * so this is not a problem. A further benefit is that the + * post-MMX cleanup code (C code) in at least some of the + * cases could be done within the assembler block. + * x [DONE] the "v3 v2 v1 v0 v7 v6 v5 v4" comments are confusing, + * inconsistent, and don't match the MMX Programmer's Reference + * Manual conventions anyway. They should be changed to + * "b7 b6 b5 b4 b3 b2 b1 b0," where b0 indicates the byte that + * was lowest in memory (e.g., corresponding to a left pixel) + * and b7 is the byte that was highest (e.g., a right pixel). + * + * 19991016: + * - Brennan's Guide notwithstanding, gcc under Linux does *not* + * want globals prefixed by underscores when referencing them-- + * i.e., if the variable is const4, then refer to it as const4, + * not _const4. This seems to be a djgpp-specific requirement. + * Also, such variables apparently *must* be declared outside + * of functions; neither static nor automatic variables work if + * defined within the scope of a single function, but both + * static and truly global (multi-module) variables work fine. + * + * 19991023: + * - fixed png_combine_row() non-MMX replication bug (odd passes only?) + * - switched from string-concatenation-with-macros to cleaner method of + * renaming global variables for djgpp--i.e., always use prefixes in + * inlined assembler code (== strings) and conditionally rename the + * variables, not the other way around. Hence _const4, _mask8_0, etc. + * + * 19991024: + * - fixed mmxsupport()/png_do_read_interlace() first-row bug + * This one was severely weird: even though mmxsupport() doesn't touch + * ebx (where "row" pointer was stored), it nevertheless managed to zero + * the register (even in static/non-fPIC code--see below), which in turn + * caused png_do_read_interlace() to return prematurely on the first row of + * interlaced images (i.e., without expanding the interlaced pixels). + * Inspection of the generated assembly code didn't turn up any clues, + * although it did point at a minor optimization (i.e., get rid of + * mmx_supported_local variable and just use eax). Possibly the CPUID + * instruction is more destructive than it looks? (Not yet checked.) + * - "info gcc" was next to useless, so compared fPIC and non-fPIC assembly + * listings... Apparently register spillage has to do with ebx, since + * it's used to index the global offset table. Commenting it out of the + * input-reg lists in png_combine_row() eliminated compiler barfage, so + * ifdef'd with __PIC__ macro: if defined, use a global for unmask + * + * 19991107: + * - verified CPUID clobberage: 12-char string constant ("GenuineIntel", + * "AuthenticAMD", etc.) placed in ebx:ecx:edx. Still need to polish. + * + * 19991120: + * - made "diff" variable (now "_dif") global to simplify conversion of + * filtering routines (running out of regs, sigh). "diff" is still used + * in interlacing routines, however. + * - fixed up both versions of mmxsupport() (ORIG_THAT_USED_TO_CLOBBER_EBX + * macro determines which is used); original not yet tested. + * + * 20000213: + * - when compiling with gcc, be sure to use -fomit-frame-pointer + * + * 20000319: + * - fixed a register-name typo in png_do_read_interlace(), default (MMX) case, + * pass == 4 or 5, that caused visible corruption of interlaced images + * + * 20000623: + * - Various problems were reported with gcc 2.95.2 in the Cygwin environment, + * many of the form "forbidden register 0 (ax) was spilled for class AREG." + * This is explained at http://gcc.gnu.org/fom_serv/cache/23.html, and + * Chuck Wilson supplied a patch involving dummy output registers. See + * http://sourceforge.net/bugs/?func=detailbug&bug_id=108741&group_id=5624 + * for the original (anonymous) SourceForge bug report. + * + * 20000706: + * - Chuck Wilson passed along these remaining gcc 2.95.2 errors: + * pnggccrd.c: In function `png_combine_row': + * pnggccrd.c:525: more than 10 operands in `asm' + * pnggccrd.c:669: more than 10 operands in `asm' + * pnggccrd.c:828: more than 10 operands in `asm' + * pnggccrd.c:994: more than 10 operands in `asm' + * pnggccrd.c:1177: more than 10 operands in `asm' + * They are all the same problem and can be worked around by using the + * global _unmask variable unconditionally, not just in the -fPIC case. + * Reportedly earlier versions of gcc also have the problem with more than + * 10 operands; they just don't report it. Much strangeness ensues, etc. + * + * 20000729: + * - enabled png_read_filter_row_mmx_up() (shortest remaining unconverted + * MMX routine); began converting png_read_filter_row_mmx_sub() + * - to finish remaining sections: + * - clean up indentation and comments + * - preload local variables + * - add output and input regs (order of former determines numerical + * mapping of latter) + * - avoid all usage of ebx (including bx, bh, bl) register [20000823] + * - remove "$" from addressing of Shift and Mask variables [20000823] + * + * 20000731: + * - global union vars causing segfaults in png_read_filter_row_mmx_sub()? + * + * 20000822: + * - ARGH, stupid png_read_filter_row_mmx_sub() segfault only happens with + * shared-library (-fPIC) version! Code works just fine as part of static + * library. Damn damn damn damn damn, should have tested that sooner. + * ebx is getting clobbered again (explicitly this time); need to save it + * on stack or rewrite asm code to avoid using it altogether. Blargh! + * + * 20000823: + * - first section was trickiest; all remaining sections have ebx -> edx now. + * (-fPIC works again.) Also added missing underscores to various Shift* + * and *Mask* globals and got rid of leading "$" signs. + * + * 20000826: + * - added visual separators to help navigate microscopic printed copies + * (http://pobox.com/~newt/code/gpr-latest.zip, mode 10); started working + * on png_read_filter_row_mmx_avg() + * + * 20000828: + * - finished png_read_filter_row_mmx_avg(): only Paeth left! (930 lines...) + * What the hell, did png_read_filter_row_mmx_paeth(), too. Comments not + * cleaned up/shortened in either routine, but functionality is complete + * and seems to be working fine. + * + * 20000829: + * - ahhh, figured out last(?) bit of gcc/gas asm-fu: if register is listed + * as an input reg (with dummy output variables, etc.), then it *cannot* + * also appear in the clobber list or gcc 2.95.2 will barf. The solution + * is simple enough... + * + * 20000914: + * - bug in png_read_filter_row_mmx_avg(): 16-bit grayscale not handled + * correctly (but 48-bit RGB just fine) + * + * 20000916: + * - fixed bug in png_read_filter_row_mmx_avg(), bpp == 2 case; three errors: + * - "_ShiftBpp.use = 24;" should have been "_ShiftBpp.use = 16;" + * - "_ShiftRem.use = 40;" should have been "_ShiftRem.use = 48;" + * - "psllq _ShiftRem, %%mm2" should have been "psrlq _ShiftRem, %%mm2" + * + * 20010101: + * - added new png_init_mmx_flags() function (here only because it needs to + * call mmxsupport(), which should probably become global png_mmxsupport()); + * modified other MMX routines to run conditionally (png_ptr->asm_flags) + * + * 20010103: + * - renamed mmxsupport() to png_mmx_support(), with auto-set of mmx_supported, + * and made it public; moved png_init_mmx_flags() to png.c as internal func + * + * 20010104: + * - removed dependency on png_read_filter_row_c() (C code already duplicated + * within MMX version of png_read_filter_row()) so no longer necessary to + * compile it into pngrutil.o + * + * 20010310: + * - fixed buffer-overrun bug in png_combine_row() C code (non-MMX) + * + * 20020304: + * - eliminated incorrect use of width_mmx in pixel_bytes == 8 case + * + * 20040724: + * - more tinkering with clobber list at lines 4529 and 5033, to get + * it to compile on gcc-3.4. + * + * STILL TO DO: + * - test png_do_read_interlace() 64-bit case (pixel_bytes == 8) + * - write MMX code for 48-bit case (pixel_bytes == 6) + * - figure out what's up with 24-bit case (pixel_bytes == 3): + * why subtract 8 from width_mmx in the pass 4/5 case? + * (only width_mmx case) (near line 1606) + * - rewrite all MMX interlacing code so it's aligned with beginning + * of the row buffer, not the end (see 19991007 for details) + * x pick one version of mmxsupport() and get rid of the other + * - add error messages to any remaining bogus default cases + * - enable pixel_depth == 8 cases in png_read_filter_row()? (test speed) + * x add support for runtime enable/disable/query of various MMX routines + */ + +#define PNG_INTERNAL +#include "png.h" + +#if defined(PNG_USE_PNGGCCRD) + +int PNGAPI png_mmx_support(void); + +#ifdef PNG_USE_LOCAL_ARRAYS +static const int FARDATA png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; +static const int FARDATA png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; +static const int FARDATA png_pass_width[7] = {8, 4, 4, 2, 2, 1, 1}; +#endif + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) +/* djgpp, Win32, and Cygwin add their own underscores to global variables, + * so define them without: */ +#if defined(__DJGPP__) || defined(WIN32) || defined(__CYGWIN__) +# define _mmx_supported mmx_supported +# define _const4 const4 +# define _const6 const6 +# define _mask8_0 mask8_0 +# define _mask16_1 mask16_1 +# define _mask16_0 mask16_0 +# define _mask24_2 mask24_2 +# define _mask24_1 mask24_1 +# define _mask24_0 mask24_0 +# define _mask32_3 mask32_3 +# define _mask32_2 mask32_2 +# define _mask32_1 mask32_1 +# define _mask32_0 mask32_0 +# define _mask48_5 mask48_5 +# define _mask48_4 mask48_4 +# define _mask48_3 mask48_3 +# define _mask48_2 mask48_2 +# define _mask48_1 mask48_1 +# define _mask48_0 mask48_0 +# define _LBCarryMask LBCarryMask +# define _HBClearMask HBClearMask +# define _ActiveMask ActiveMask +# define _ActiveMask2 ActiveMask2 +# define _ActiveMaskEnd ActiveMaskEnd +# define _ShiftBpp ShiftBpp +# define _ShiftRem ShiftRem +#ifdef PNG_THREAD_UNSAFE_OK +# define _unmask unmask +# define _FullLength FullLength +# define _MMXLength MMXLength +# define _dif dif +# define _patemp patemp +# define _pbtemp pbtemp +# define _pctemp pctemp +#endif +#endif + + +/* These constants are used in the inlined MMX assembly code. + Ignore gcc's "At top level: defined but not used" warnings. */ + +/* GRR 20000706: originally _unmask was needed only when compiling with -fPIC, + * since that case uses the %ebx register for indexing the Global Offset Table + * and there were no other registers available. But gcc 2.95 and later emit + * "more than 10 operands in `asm'" errors when %ebx is used to preload unmask + * in the non-PIC case, so we'll just use the global unconditionally now. + */ +#ifdef PNG_THREAD_UNSAFE_OK +static int _unmask; +#endif + +static unsigned long long _mask8_0 = 0x0102040810204080LL; + +static unsigned long long _mask16_1 = 0x0101020204040808LL; +static unsigned long long _mask16_0 = 0x1010202040408080LL; + +static unsigned long long _mask24_2 = 0x0101010202020404LL; +static unsigned long long _mask24_1 = 0x0408080810101020LL; +static unsigned long long _mask24_0 = 0x2020404040808080LL; + +static unsigned long long _mask32_3 = 0x0101010102020202LL; +static unsigned long long _mask32_2 = 0x0404040408080808LL; +static unsigned long long _mask32_1 = 0x1010101020202020LL; +static unsigned long long _mask32_0 = 0x4040404080808080LL; + +static unsigned long long _mask48_5 = 0x0101010101010202LL; +static unsigned long long _mask48_4 = 0x0202020204040404LL; +static unsigned long long _mask48_3 = 0x0404080808080808LL; +static unsigned long long _mask48_2 = 0x1010101010102020LL; +static unsigned long long _mask48_1 = 0x2020202040404040LL; +static unsigned long long _mask48_0 = 0x4040808080808080LL; + +static unsigned long long _const4 = 0x0000000000FFFFFFLL; +//static unsigned long long _const5 = 0x000000FFFFFF0000LL; // NOT USED +static unsigned long long _const6 = 0x00000000000000FFLL; + +// These are used in the row-filter routines and should/would be local +// variables if not for gcc addressing limitations. +// WARNING: Their presence probably defeats the thread safety of libpng. + +#ifdef PNG_THREAD_UNSAFE_OK +static png_uint_32 _FullLength; +static png_uint_32 _MMXLength; +static int _dif; +static int _patemp; // temp variables for Paeth routine +static int _pbtemp; +static int _pctemp; +#endif + +void /* PRIVATE */ +png_squelch_warnings(void) +{ +#ifdef PNG_THREAD_UNSAFE_OK + _dif = _dif; + _patemp = _patemp; + _pbtemp = _pbtemp; + _pctemp = _pctemp; + _MMXLength = _MMXLength; +#endif + _const4 = _const4; + _const6 = _const6; + _mask8_0 = _mask8_0; + _mask16_1 = _mask16_1; + _mask16_0 = _mask16_0; + _mask24_2 = _mask24_2; + _mask24_1 = _mask24_1; + _mask24_0 = _mask24_0; + _mask32_3 = _mask32_3; + _mask32_2 = _mask32_2; + _mask32_1 = _mask32_1; + _mask32_0 = _mask32_0; + _mask48_5 = _mask48_5; + _mask48_4 = _mask48_4; + _mask48_3 = _mask48_3; + _mask48_2 = _mask48_2; + _mask48_1 = _mask48_1; + _mask48_0 = _mask48_0; +} +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + + +static int _mmx_supported = 2; + +/*===========================================================================*/ +/* */ +/* P N G _ C O M B I N E _ R O W */ +/* */ +/*===========================================================================*/ + +#if defined(PNG_HAVE_ASSEMBLER_COMBINE_ROW) + +#define BPP2 2 +#define BPP3 3 /* bytes per pixel (a.k.a. pixel_bytes) */ +#define BPP4 4 +#define BPP6 6 /* (defined only to help avoid cut-and-paste errors) */ +#define BPP8 8 + +/* Combines the row recently read in with the previous row. + This routine takes care of alpha and transparency if requested. + This routine also handles the two methods of progressive display + of interlaced images, depending on the mask value. + The mask value describes which pixels are to be combined with + the row. The pattern always repeats every 8 pixels, so just 8 + bits are needed. A one indicates the pixel is to be combined; a + zero indicates the pixel is to be skipped. This is in addition + to any alpha or transparency value associated with the pixel. + If you want all pixels to be combined, pass 0xff (255) in mask. */ + +/* Use this routine for the x86 platform - it uses a faster MMX routine + if the machine supports MMX. */ + +void /* PRIVATE */ +png_combine_row(png_structp png_ptr, png_bytep row, int mask) +{ + png_debug(1, "in png_combine_row (pnggccrd.c)\n"); + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) + if (_mmx_supported == 2) { +#if !defined(PNG_1_0_X) + /* this should have happened in png_init_mmx_flags() already */ + png_warning(png_ptr, "asm_flags may not have been initialized"); +#endif + png_mmx_support(); + } +#endif + + if (mask == 0xff) + { + png_debug(2,"mask == 0xff: doing single png_memcpy()\n"); + png_memcpy(row, png_ptr->row_buf + 1, + (png_size_t)PNG_ROWBYTES(png_ptr->row_info.pixel_depth,png_ptr->width)); + } + else /* (png_combine_row() is never called with mask == 0) */ + { + switch (png_ptr->row_info.pixel_depth) + { + case 1: /* png_ptr->row_info.pixel_depth */ + { + png_bytep sp; + png_bytep dp; + int s_inc, s_start, s_end; + int m; + int shift; + png_uint_32 i; + + sp = png_ptr->row_buf + 1; + dp = row; + m = 0x80; +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 7; + s_inc = 1; + } + else +#endif + { + s_start = 7; + s_end = 0; + s_inc = -1; + } + + shift = s_start; + + for (i = 0; i < png_ptr->width; i++) + { + if (m & mask) + { + int value; + + value = (*sp >> shift) & 0x1; + *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + + case 2: /* png_ptr->row_info.pixel_depth */ + { + png_bytep sp; + png_bytep dp; + int s_start, s_end, s_inc; + int m; + int shift; + png_uint_32 i; + int value; + + sp = png_ptr->row_buf + 1; + dp = row; + m = 0x80; +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 6; + s_inc = 2; + } + else +#endif + { + s_start = 6; + s_end = 0; + s_inc = -2; + } + + shift = s_start; + + for (i = 0; i < png_ptr->width; i++) + { + if (m & mask) + { + value = (*sp >> shift) & 0x3; + *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + + case 4: /* png_ptr->row_info.pixel_depth */ + { + png_bytep sp; + png_bytep dp; + int s_start, s_end, s_inc; + int m; + int shift; + png_uint_32 i; + int value; + + sp = png_ptr->row_buf + 1; + dp = row; + m = 0x80; +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 4; + s_inc = 4; + } + else +#endif + { + s_start = 4; + s_end = 0; + s_inc = -4; + } + shift = s_start; + + for (i = 0; i < png_ptr->width; i++) + { + if (m & mask) + { + value = (*sp >> shift) & 0xf; + *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + + case 8: /* png_ptr->row_info.pixel_depth */ + { + png_bytep srcptr; + png_bytep dstptr; + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && _mmx_supported */ ) +#else + if (_mmx_supported) +#endif + { + png_uint_32 len; + int diff; + int dummy_value_a; // fix 'forbidden register spilled' error + int dummy_value_d; + int dummy_value_c; + int dummy_value_S; + int dummy_value_D; + _unmask = ~mask; // global variable for -fPIC version + srcptr = png_ptr->row_buf + 1; + dstptr = row; + len = png_ptr->width &~7; // reduce to multiple of 8 + diff = (int) (png_ptr->width & 7); // amount lost + + __asm__ __volatile__ ( + "movd _unmask, %%mm7 \n\t" // load bit pattern + "psubb %%mm6, %%mm6 \n\t" // zero mm6 + "punpcklbw %%mm7, %%mm7 \n\t" + "punpcklwd %%mm7, %%mm7 \n\t" + "punpckldq %%mm7, %%mm7 \n\t" // fill reg with 8 masks + + "movq _mask8_0, %%mm0 \n\t" + "pand %%mm7, %%mm0 \n\t" // nonzero if keep byte + "pcmpeqb %%mm6, %%mm0 \n\t" // zeros->1s, v versa + +// preload "movl len, %%ecx \n\t" // load length of line +// preload "movl srcptr, %%esi \n\t" // load source +// preload "movl dstptr, %%edi \n\t" // load dest + + "cmpl $0, %%ecx \n\t" // len == 0 ? + "je mainloop8end \n\t" + + "mainloop8: \n\t" + "movq (%%esi), %%mm4 \n\t" // *srcptr + "pand %%mm0, %%mm4 \n\t" + "movq %%mm0, %%mm6 \n\t" + "pandn (%%edi), %%mm6 \n\t" // *dstptr + "por %%mm6, %%mm4 \n\t" + "movq %%mm4, (%%edi) \n\t" + "addl $8, %%esi \n\t" // inc by 8 bytes processed + "addl $8, %%edi \n\t" + "subl $8, %%ecx \n\t" // dec by 8 pixels processed + "ja mainloop8 \n\t" + + "mainloop8end: \n\t" +// preload "movl diff, %%ecx \n\t" // (diff is in eax) + "movl %%eax, %%ecx \n\t" + "cmpl $0, %%ecx \n\t" + "jz end8 \n\t" +// preload "movl mask, %%edx \n\t" + "sall $24, %%edx \n\t" // make low byte, high byte + + "secondloop8: \n\t" + "sall %%edx \n\t" // move high bit to CF + "jnc skip8 \n\t" // if CF = 0 + "movb (%%esi), %%al \n\t" + "movb %%al, (%%edi) \n\t" + + "skip8: \n\t" + "incl %%esi \n\t" + "incl %%edi \n\t" + "decl %%ecx \n\t" + "jnz secondloop8 \n\t" + + "end8: \n\t" + "EMMS \n\t" // DONE + + : "=a" (dummy_value_a), // output regs (dummy) + "=d" (dummy_value_d), + "=c" (dummy_value_c), + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "3" (srcptr), // esi // input regs + "4" (dstptr), // edi + "0" (diff), // eax +// was (unmask) "b" RESERVED // ebx // Global Offset Table idx + "2" (len), // ecx + "1" (mask) // edx + +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm4", "%mm6", "%mm7" // clobber list +#endif + ); + } + else /* mmx _not supported - Use modified C routine */ +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + register png_uint_32 i; + png_uint_32 initial_val = png_pass_start[png_ptr->pass]; + /* png.c: png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; */ + register int stride = png_pass_inc[png_ptr->pass]; + /* png.c: png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; */ + register int rep_bytes = png_pass_width[png_ptr->pass]; + /* png.c: png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; */ + png_uint_32 len = png_ptr->width &~7; /* reduce to mult. of 8 */ + int diff = (int) (png_ptr->width & 7); /* amount lost */ + register png_uint_32 final_val = len; /* GRR bugfix */ + + srcptr = png_ptr->row_buf + 1 + initial_val; + dstptr = row + initial_val; + + for (i = initial_val; i < final_val; i += stride) + { + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + if (diff) /* number of leftover pixels: 3 for pngtest */ + { + final_val+=diff /* *BPP1 */ ; + for (; i < final_val; i += stride) + { + if (rep_bytes > (int)(final_val-i)) + rep_bytes = (int)(final_val-i); + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + } + + } /* end of else (_mmx_supported) */ + + break; + } /* end 8 bpp */ + + case 16: /* png_ptr->row_info.pixel_depth */ + { + png_bytep srcptr; + png_bytep dstptr; + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && _mmx_supported */ ) +#else + if (_mmx_supported) +#endif + { + png_uint_32 len; + int diff; + int dummy_value_a; // fix 'forbidden register spilled' error + int dummy_value_d; + int dummy_value_c; + int dummy_value_S; + int dummy_value_D; + _unmask = ~mask; // global variable for -fPIC version + srcptr = png_ptr->row_buf + 1; + dstptr = row; + len = png_ptr->width &~7; // reduce to multiple of 8 + diff = (int) (png_ptr->width & 7); // amount lost // + + __asm__ __volatile__ ( + "movd _unmask, %%mm7 \n\t" // load bit pattern + "psubb %%mm6, %%mm6 \n\t" // zero mm6 + "punpcklbw %%mm7, %%mm7 \n\t" + "punpcklwd %%mm7, %%mm7 \n\t" + "punpckldq %%mm7, %%mm7 \n\t" // fill reg with 8 masks + + "movq _mask16_0, %%mm0 \n\t" + "movq _mask16_1, %%mm1 \n\t" + + "pand %%mm7, %%mm0 \n\t" + "pand %%mm7, %%mm1 \n\t" + + "pcmpeqb %%mm6, %%mm0 \n\t" + "pcmpeqb %%mm6, %%mm1 \n\t" + +// preload "movl len, %%ecx \n\t" // load length of line +// preload "movl srcptr, %%esi \n\t" // load source +// preload "movl dstptr, %%edi \n\t" // load dest + + "cmpl $0, %%ecx \n\t" + "jz mainloop16end \n\t" + + "mainloop16: \n\t" + "movq (%%esi), %%mm4 \n\t" + "pand %%mm0, %%mm4 \n\t" + "movq %%mm0, %%mm6 \n\t" + "movq (%%edi), %%mm7 \n\t" + "pandn %%mm7, %%mm6 \n\t" + "por %%mm6, %%mm4 \n\t" + "movq %%mm4, (%%edi) \n\t" + + "movq 8(%%esi), %%mm5 \n\t" + "pand %%mm1, %%mm5 \n\t" + "movq %%mm1, %%mm7 \n\t" + "movq 8(%%edi), %%mm6 \n\t" + "pandn %%mm6, %%mm7 \n\t" + "por %%mm7, %%mm5 \n\t" + "movq %%mm5, 8(%%edi) \n\t" + + "addl $16, %%esi \n\t" // inc by 16 bytes processed + "addl $16, %%edi \n\t" + "subl $8, %%ecx \n\t" // dec by 8 pixels processed + "ja mainloop16 \n\t" + + "mainloop16end: \n\t" +// preload "movl diff, %%ecx \n\t" // (diff is in eax) + "movl %%eax, %%ecx \n\t" + "cmpl $0, %%ecx \n\t" + "jz end16 \n\t" +// preload "movl mask, %%edx \n\t" + "sall $24, %%edx \n\t" // make low byte, high byte + + "secondloop16: \n\t" + "sall %%edx \n\t" // move high bit to CF + "jnc skip16 \n\t" // if CF = 0 + "movw (%%esi), %%ax \n\t" + "movw %%ax, (%%edi) \n\t" + + "skip16: \n\t" + "addl $2, %%esi \n\t" + "addl $2, %%edi \n\t" + "decl %%ecx \n\t" + "jnz secondloop16 \n\t" + + "end16: \n\t" + "EMMS \n\t" // DONE + + : "=a" (dummy_value_a), // output regs (dummy) + "=c" (dummy_value_c), + "=d" (dummy_value_d), + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "0" (diff), // eax // input regs +// was (unmask) " " RESERVED // ebx // Global Offset Table idx + "1" (len), // ecx + "2" (mask), // edx + "3" (srcptr), // esi + "4" (dstptr) // edi + +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1", "%mm4" // clobber list + , "%mm5", "%mm6", "%mm7" +#endif + ); + } + else /* mmx _not supported - Use modified C routine */ +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + register png_uint_32 i; + png_uint_32 initial_val = BPP2 * png_pass_start[png_ptr->pass]; + /* png.c: png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; */ + register int stride = BPP2 * png_pass_inc[png_ptr->pass]; + /* png.c: png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; */ + register int rep_bytes = BPP2 * png_pass_width[png_ptr->pass]; + /* png.c: png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; */ + png_uint_32 len = png_ptr->width &~7; /* reduce to mult. of 8 */ + int diff = (int) (png_ptr->width & 7); /* amount lost */ + register png_uint_32 final_val = BPP2 * len; /* GRR bugfix */ + + srcptr = png_ptr->row_buf + 1 + initial_val; + dstptr = row + initial_val; + + for (i = initial_val; i < final_val; i += stride) + { + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + if (diff) /* number of leftover pixels: 3 for pngtest */ + { + final_val+=diff*BPP2; + for (; i < final_val; i += stride) + { + if (rep_bytes > (int)(final_val-i)) + rep_bytes = (int)(final_val-i); + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + } + } /* end of else (_mmx_supported) */ + + break; + } /* end 16 bpp */ + + case 24: /* png_ptr->row_info.pixel_depth */ + { + png_bytep srcptr; + png_bytep dstptr; + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && _mmx_supported */ ) +#else + if (_mmx_supported) +#endif + { + png_uint_32 len; + int diff; + int dummy_value_a; // fix 'forbidden register spilled' error + int dummy_value_d; + int dummy_value_c; + int dummy_value_S; + int dummy_value_D; + _unmask = ~mask; // global variable for -fPIC version + srcptr = png_ptr->row_buf + 1; + dstptr = row; + len = png_ptr->width &~7; // reduce to multiple of 8 + diff = (int) (png_ptr->width & 7); // amount lost // + + __asm__ __volatile__ ( + "movd _unmask, %%mm7 \n\t" // load bit pattern + "psubb %%mm6, %%mm6 \n\t" // zero mm6 + "punpcklbw %%mm7, %%mm7 \n\t" + "punpcklwd %%mm7, %%mm7 \n\t" + "punpckldq %%mm7, %%mm7 \n\t" // fill reg with 8 masks + + "movq _mask24_0, %%mm0 \n\t" + "movq _mask24_1, %%mm1 \n\t" + "movq _mask24_2, %%mm2 \n\t" + + "pand %%mm7, %%mm0 \n\t" + "pand %%mm7, %%mm1 \n\t" + "pand %%mm7, %%mm2 \n\t" + + "pcmpeqb %%mm6, %%mm0 \n\t" + "pcmpeqb %%mm6, %%mm1 \n\t" + "pcmpeqb %%mm6, %%mm2 \n\t" + +// preload "movl len, %%ecx \n\t" // load length of line +// preload "movl srcptr, %%esi \n\t" // load source +// preload "movl dstptr, %%edi \n\t" // load dest + + "cmpl $0, %%ecx \n\t" + "jz mainloop24end \n\t" + + "mainloop24: \n\t" + "movq (%%esi), %%mm4 \n\t" + "pand %%mm0, %%mm4 \n\t" + "movq %%mm0, %%mm6 \n\t" + "movq (%%edi), %%mm7 \n\t" + "pandn %%mm7, %%mm6 \n\t" + "por %%mm6, %%mm4 \n\t" + "movq %%mm4, (%%edi) \n\t" + + "movq 8(%%esi), %%mm5 \n\t" + "pand %%mm1, %%mm5 \n\t" + "movq %%mm1, %%mm7 \n\t" + "movq 8(%%edi), %%mm6 \n\t" + "pandn %%mm6, %%mm7 \n\t" + "por %%mm7, %%mm5 \n\t" + "movq %%mm5, 8(%%edi) \n\t" + + "movq 16(%%esi), %%mm6 \n\t" + "pand %%mm2, %%mm6 \n\t" + "movq %%mm2, %%mm4 \n\t" + "movq 16(%%edi), %%mm7 \n\t" + "pandn %%mm7, %%mm4 \n\t" + "por %%mm4, %%mm6 \n\t" + "movq %%mm6, 16(%%edi) \n\t" + + "addl $24, %%esi \n\t" // inc by 24 bytes processed + "addl $24, %%edi \n\t" + "subl $8, %%ecx \n\t" // dec by 8 pixels processed + + "ja mainloop24 \n\t" + + "mainloop24end: \n\t" +// preload "movl diff, %%ecx \n\t" // (diff is in eax) + "movl %%eax, %%ecx \n\t" + "cmpl $0, %%ecx \n\t" + "jz end24 \n\t" +// preload "movl mask, %%edx \n\t" + "sall $24, %%edx \n\t" // make low byte, high byte + + "secondloop24: \n\t" + "sall %%edx \n\t" // move high bit to CF + "jnc skip24 \n\t" // if CF = 0 + "movw (%%esi), %%ax \n\t" + "movw %%ax, (%%edi) \n\t" + "xorl %%eax, %%eax \n\t" + "movb 2(%%esi), %%al \n\t" + "movb %%al, 2(%%edi) \n\t" + + "skip24: \n\t" + "addl $3, %%esi \n\t" + "addl $3, %%edi \n\t" + "decl %%ecx \n\t" + "jnz secondloop24 \n\t" + + "end24: \n\t" + "EMMS \n\t" // DONE + + : "=a" (dummy_value_a), // output regs (dummy) + "=d" (dummy_value_d), + "=c" (dummy_value_c), + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "3" (srcptr), // esi // input regs + "4" (dstptr), // edi + "0" (diff), // eax +// was (unmask) "b" RESERVED // ebx // Global Offset Table idx + "2" (len), // ecx + "1" (mask) // edx + +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1", "%mm2" // clobber list + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + else /* mmx _not supported - Use modified C routine */ +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + register png_uint_32 i; + png_uint_32 initial_val = BPP3 * png_pass_start[png_ptr->pass]; + /* png.c: png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; */ + register int stride = BPP3 * png_pass_inc[png_ptr->pass]; + /* png.c: png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; */ + register int rep_bytes = BPP3 * png_pass_width[png_ptr->pass]; + /* png.c: png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; */ + png_uint_32 len = png_ptr->width &~7; /* reduce to mult. of 8 */ + int diff = (int) (png_ptr->width & 7); /* amount lost */ + register png_uint_32 final_val = BPP3 * len; /* GRR bugfix */ + + srcptr = png_ptr->row_buf + 1 + initial_val; + dstptr = row + initial_val; + + for (i = initial_val; i < final_val; i += stride) + { + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + if (diff) /* number of leftover pixels: 3 for pngtest */ + { + final_val+=diff*BPP3; + for (; i < final_val; i += stride) + { + if (rep_bytes > (int)(final_val-i)) + rep_bytes = (int)(final_val-i); + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + } + } /* end of else (_mmx_supported) */ + + break; + } /* end 24 bpp */ + + case 32: /* png_ptr->row_info.pixel_depth */ + { + png_bytep srcptr; + png_bytep dstptr; + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && _mmx_supported */ ) +#else + if (_mmx_supported) +#endif + { + png_uint_32 len; + int diff; + int dummy_value_a; // fix 'forbidden register spilled' error + int dummy_value_d; + int dummy_value_c; + int dummy_value_S; + int dummy_value_D; + _unmask = ~mask; // global variable for -fPIC version + srcptr = png_ptr->row_buf + 1; + dstptr = row; + len = png_ptr->width &~7; // reduce to multiple of 8 + diff = (int) (png_ptr->width & 7); // amount lost // + + __asm__ __volatile__ ( + "movd _unmask, %%mm7 \n\t" // load bit pattern + "psubb %%mm6, %%mm6 \n\t" // zero mm6 + "punpcklbw %%mm7, %%mm7 \n\t" + "punpcklwd %%mm7, %%mm7 \n\t" + "punpckldq %%mm7, %%mm7 \n\t" // fill reg with 8 masks + + "movq _mask32_0, %%mm0 \n\t" + "movq _mask32_1, %%mm1 \n\t" + "movq _mask32_2, %%mm2 \n\t" + "movq _mask32_3, %%mm3 \n\t" + + "pand %%mm7, %%mm0 \n\t" + "pand %%mm7, %%mm1 \n\t" + "pand %%mm7, %%mm2 \n\t" + "pand %%mm7, %%mm3 \n\t" + + "pcmpeqb %%mm6, %%mm0 \n\t" + "pcmpeqb %%mm6, %%mm1 \n\t" + "pcmpeqb %%mm6, %%mm2 \n\t" + "pcmpeqb %%mm6, %%mm3 \n\t" + +// preload "movl len, %%ecx \n\t" // load length of line +// preload "movl srcptr, %%esi \n\t" // load source +// preload "movl dstptr, %%edi \n\t" // load dest + + "cmpl $0, %%ecx \n\t" // lcr + "jz mainloop32end \n\t" + + "mainloop32: \n\t" + "movq (%%esi), %%mm4 \n\t" + "pand %%mm0, %%mm4 \n\t" + "movq %%mm0, %%mm6 \n\t" + "movq (%%edi), %%mm7 \n\t" + "pandn %%mm7, %%mm6 \n\t" + "por %%mm6, %%mm4 \n\t" + "movq %%mm4, (%%edi) \n\t" + + "movq 8(%%esi), %%mm5 \n\t" + "pand %%mm1, %%mm5 \n\t" + "movq %%mm1, %%mm7 \n\t" + "movq 8(%%edi), %%mm6 \n\t" + "pandn %%mm6, %%mm7 \n\t" + "por %%mm7, %%mm5 \n\t" + "movq %%mm5, 8(%%edi) \n\t" + + "movq 16(%%esi), %%mm6 \n\t" + "pand %%mm2, %%mm6 \n\t" + "movq %%mm2, %%mm4 \n\t" + "movq 16(%%edi), %%mm7 \n\t" + "pandn %%mm7, %%mm4 \n\t" + "por %%mm4, %%mm6 \n\t" + "movq %%mm6, 16(%%edi) \n\t" + + "movq 24(%%esi), %%mm7 \n\t" + "pand %%mm3, %%mm7 \n\t" + "movq %%mm3, %%mm5 \n\t" + "movq 24(%%edi), %%mm4 \n\t" + "pandn %%mm4, %%mm5 \n\t" + "por %%mm5, %%mm7 \n\t" + "movq %%mm7, 24(%%edi) \n\t" + + "addl $32, %%esi \n\t" // inc by 32 bytes processed + "addl $32, %%edi \n\t" + "subl $8, %%ecx \n\t" // dec by 8 pixels processed + "ja mainloop32 \n\t" + + "mainloop32end: \n\t" +// preload "movl diff, %%ecx \n\t" // (diff is in eax) + "movl %%eax, %%ecx \n\t" + "cmpl $0, %%ecx \n\t" + "jz end32 \n\t" +// preload "movl mask, %%edx \n\t" + "sall $24, %%edx \n\t" // low byte => high byte + + "secondloop32: \n\t" + "sall %%edx \n\t" // move high bit to CF + "jnc skip32 \n\t" // if CF = 0 + "movl (%%esi), %%eax \n\t" + "movl %%eax, (%%edi) \n\t" + + "skip32: \n\t" + "addl $4, %%esi \n\t" + "addl $4, %%edi \n\t" + "decl %%ecx \n\t" + "jnz secondloop32 \n\t" + + "end32: \n\t" + "EMMS \n\t" // DONE + + : "=a" (dummy_value_a), // output regs (dummy) + "=d" (dummy_value_d), + "=c" (dummy_value_c), + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "3" (srcptr), // esi // input regs + "4" (dstptr), // edi + "0" (diff), // eax +// was (unmask) "b" RESERVED // ebx // Global Offset Table idx + "2" (len), // ecx + "1" (mask) // edx + +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1", "%mm2", "%mm3" // clobber list + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + else /* mmx _not supported - Use modified C routine */ +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + register png_uint_32 i; + png_uint_32 initial_val = BPP4 * png_pass_start[png_ptr->pass]; + /* png.c: png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; */ + register int stride = BPP4 * png_pass_inc[png_ptr->pass]; + /* png.c: png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; */ + register int rep_bytes = BPP4 * png_pass_width[png_ptr->pass]; + /* png.c: png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; */ + png_uint_32 len = png_ptr->width &~7; /* reduce to mult. of 8 */ + int diff = (int) (png_ptr->width & 7); /* amount lost */ + register png_uint_32 final_val = BPP4 * len; /* GRR bugfix */ + + srcptr = png_ptr->row_buf + 1 + initial_val; + dstptr = row + initial_val; + + for (i = initial_val; i < final_val; i += stride) + { + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + if (diff) /* number of leftover pixels: 3 for pngtest */ + { + final_val+=diff*BPP4; + for (; i < final_val; i += stride) + { + if (rep_bytes > (int)(final_val-i)) + rep_bytes = (int)(final_val-i); + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + } + } /* end of else (_mmx_supported) */ + + break; + } /* end 32 bpp */ + + case 48: /* png_ptr->row_info.pixel_depth */ + { + png_bytep srcptr; + png_bytep dstptr; + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && _mmx_supported */ ) +#else + if (_mmx_supported) +#endif + { + png_uint_32 len; + int diff; + int dummy_value_a; // fix 'forbidden register spilled' error + int dummy_value_d; + int dummy_value_c; + int dummy_value_S; + int dummy_value_D; + _unmask = ~mask; // global variable for -fPIC version + srcptr = png_ptr->row_buf + 1; + dstptr = row; + len = png_ptr->width &~7; // reduce to multiple of 8 + diff = (int) (png_ptr->width & 7); // amount lost // + + __asm__ __volatile__ ( + "movd _unmask, %%mm7 \n\t" // load bit pattern + "psubb %%mm6, %%mm6 \n\t" // zero mm6 + "punpcklbw %%mm7, %%mm7 \n\t" + "punpcklwd %%mm7, %%mm7 \n\t" + "punpckldq %%mm7, %%mm7 \n\t" // fill reg with 8 masks + + "movq _mask48_0, %%mm0 \n\t" + "movq _mask48_1, %%mm1 \n\t" + "movq _mask48_2, %%mm2 \n\t" + "movq _mask48_3, %%mm3 \n\t" + "movq _mask48_4, %%mm4 \n\t" + "movq _mask48_5, %%mm5 \n\t" + + "pand %%mm7, %%mm0 \n\t" + "pand %%mm7, %%mm1 \n\t" + "pand %%mm7, %%mm2 \n\t" + "pand %%mm7, %%mm3 \n\t" + "pand %%mm7, %%mm4 \n\t" + "pand %%mm7, %%mm5 \n\t" + + "pcmpeqb %%mm6, %%mm0 \n\t" + "pcmpeqb %%mm6, %%mm1 \n\t" + "pcmpeqb %%mm6, %%mm2 \n\t" + "pcmpeqb %%mm6, %%mm3 \n\t" + "pcmpeqb %%mm6, %%mm4 \n\t" + "pcmpeqb %%mm6, %%mm5 \n\t" + +// preload "movl len, %%ecx \n\t" // load length of line +// preload "movl srcptr, %%esi \n\t" // load source +// preload "movl dstptr, %%edi \n\t" // load dest + + "cmpl $0, %%ecx \n\t" + "jz mainloop48end \n\t" + + "mainloop48: \n\t" + "movq (%%esi), %%mm7 \n\t" + "pand %%mm0, %%mm7 \n\t" + "movq %%mm0, %%mm6 \n\t" + "pandn (%%edi), %%mm6 \n\t" + "por %%mm6, %%mm7 \n\t" + "movq %%mm7, (%%edi) \n\t" + + "movq 8(%%esi), %%mm6 \n\t" + "pand %%mm1, %%mm6 \n\t" + "movq %%mm1, %%mm7 \n\t" + "pandn 8(%%edi), %%mm7 \n\t" + "por %%mm7, %%mm6 \n\t" + "movq %%mm6, 8(%%edi) \n\t" + + "movq 16(%%esi), %%mm6 \n\t" + "pand %%mm2, %%mm6 \n\t" + "movq %%mm2, %%mm7 \n\t" + "pandn 16(%%edi), %%mm7 \n\t" + "por %%mm7, %%mm6 \n\t" + "movq %%mm6, 16(%%edi) \n\t" + + "movq 24(%%esi), %%mm7 \n\t" + "pand %%mm3, %%mm7 \n\t" + "movq %%mm3, %%mm6 \n\t" + "pandn 24(%%edi), %%mm6 \n\t" + "por %%mm6, %%mm7 \n\t" + "movq %%mm7, 24(%%edi) \n\t" + + "movq 32(%%esi), %%mm6 \n\t" + "pand %%mm4, %%mm6 \n\t" + "movq %%mm4, %%mm7 \n\t" + "pandn 32(%%edi), %%mm7 \n\t" + "por %%mm7, %%mm6 \n\t" + "movq %%mm6, 32(%%edi) \n\t" + + "movq 40(%%esi), %%mm7 \n\t" + "pand %%mm5, %%mm7 \n\t" + "movq %%mm5, %%mm6 \n\t" + "pandn 40(%%edi), %%mm6 \n\t" + "por %%mm6, %%mm7 \n\t" + "movq %%mm7, 40(%%edi) \n\t" + + "addl $48, %%esi \n\t" // inc by 48 bytes processed + "addl $48, %%edi \n\t" + "subl $8, %%ecx \n\t" // dec by 8 pixels processed + + "ja mainloop48 \n\t" + + "mainloop48end: \n\t" +// preload "movl diff, %%ecx \n\t" // (diff is in eax) + "movl %%eax, %%ecx \n\t" + "cmpl $0, %%ecx \n\t" + "jz end48 \n\t" +// preload "movl mask, %%edx \n\t" + "sall $24, %%edx \n\t" // make low byte, high byte + + "secondloop48: \n\t" + "sall %%edx \n\t" // move high bit to CF + "jnc skip48 \n\t" // if CF = 0 + "movl (%%esi), %%eax \n\t" + "movl %%eax, (%%edi) \n\t" + + "skip48: \n\t" + "addl $4, %%esi \n\t" + "addl $4, %%edi \n\t" + "decl %%ecx \n\t" + "jnz secondloop48 \n\t" + + "end48: \n\t" + "EMMS \n\t" // DONE + + : "=a" (dummy_value_a), // output regs (dummy) + "=d" (dummy_value_d), + "=c" (dummy_value_c), + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "3" (srcptr), // esi // input regs + "4" (dstptr), // edi + "0" (diff), // eax +// was (unmask) "b" RESERVED // ebx // Global Offset Table idx + "2" (len), // ecx + "1" (mask) // edx + +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1", "%mm2", "%mm3" // clobber list + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + else /* mmx _not supported - Use modified C routine */ +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + register png_uint_32 i; + png_uint_32 initial_val = BPP6 * png_pass_start[png_ptr->pass]; + /* png.c: png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; */ + register int stride = BPP6 * png_pass_inc[png_ptr->pass]; + /* png.c: png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; */ + register int rep_bytes = BPP6 * png_pass_width[png_ptr->pass]; + /* png.c: png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; */ + png_uint_32 len = png_ptr->width &~7; /* reduce to mult. of 8 */ + int diff = (int) (png_ptr->width & 7); /* amount lost */ + register png_uint_32 final_val = BPP6 * len; /* GRR bugfix */ + + srcptr = png_ptr->row_buf + 1 + initial_val; + dstptr = row + initial_val; + + for (i = initial_val; i < final_val; i += stride) + { + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + if (diff) /* number of leftover pixels: 3 for pngtest */ + { + final_val+=diff*BPP6; + for (; i < final_val; i += stride) + { + if (rep_bytes > (int)(final_val-i)) + rep_bytes = (int)(final_val-i); + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + } + } /* end of else (_mmx_supported) */ + + break; + } /* end 48 bpp */ + + case 64: /* png_ptr->row_info.pixel_depth */ + { + png_bytep srcptr; + png_bytep dstptr; + register png_uint_32 i; + png_uint_32 initial_val = BPP8 * png_pass_start[png_ptr->pass]; + /* png.c: png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; */ + register int stride = BPP8 * png_pass_inc[png_ptr->pass]; + /* png.c: png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; */ + register int rep_bytes = BPP8 * png_pass_width[png_ptr->pass]; + /* png.c: png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; */ + png_uint_32 len = png_ptr->width &~7; /* reduce to mult. of 8 */ + int diff = (int) (png_ptr->width & 7); /* amount lost */ + register png_uint_32 final_val = BPP8 * len; /* GRR bugfix */ + + srcptr = png_ptr->row_buf + 1 + initial_val; + dstptr = row + initial_val; + + for (i = initial_val; i < final_val; i += stride) + { + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + if (diff) /* number of leftover pixels: 3 for pngtest */ + { + final_val+=diff*BPP8; + for (; i < final_val; i += stride) + { + if (rep_bytes > (int)(final_val-i)) + rep_bytes = (int)(final_val-i); + png_memcpy(dstptr, srcptr, rep_bytes); + srcptr += stride; + dstptr += stride; + } + } + + break; + } /* end 64 bpp */ + + default: /* png_ptr->row_info.pixel_depth != 1,2,4,8,16,24,32,48,64 */ + { + /* this should never happen */ + png_warning(png_ptr, "Invalid row_info.pixel_depth in pnggccrd"); + break; + } + } /* end switch (png_ptr->row_info.pixel_depth) */ + + } /* end if (non-trivial mask) */ + +} /* end png_combine_row() */ + +#endif /* PNG_HAVE_ASSEMBLER_COMBINE_ROW */ + + + + +/*===========================================================================*/ +/* */ +/* P N G _ D O _ R E A D _ I N T E R L A C E */ +/* */ +/*===========================================================================*/ + +#if defined(PNG_READ_INTERLACING_SUPPORTED) +#if defined(PNG_HAVE_ASSEMBLER_READ_INTERLACE) + +/* png_do_read_interlace() is called after any 16-bit to 8-bit conversion + * has taken place. [GRR: what other steps come before and/or after?] + */ + +void /* PRIVATE */ +png_do_read_interlace(png_structp png_ptr) +{ + png_row_infop row_info = &(png_ptr->row_info); + png_bytep row = png_ptr->row_buf + 1; + int pass = png_ptr->pass; +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + png_uint_32 transformations = png_ptr->transformations; +#endif + + png_debug(1, "in png_do_read_interlace (pnggccrd.c)\n"); + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) + if (_mmx_supported == 2) { +#if !defined(PNG_1_0_X) + /* this should have happened in png_init_mmx_flags() already */ + png_warning(png_ptr, "asm_flags may not have been initialized"); +#endif + png_mmx_support(); + } +#endif + + if (row != NULL && row_info != NULL) + { + png_uint_32 final_width; + + final_width = row_info->width * png_pass_inc[pass]; + + switch (row_info->pixel_depth) + { + case 1: + { + png_bytep sp, dp; + int sshift, dshift; + int s_start, s_end, s_inc; + png_byte v; + png_uint_32 i; + int j; + + sp = row + (png_size_t)((row_info->width - 1) >> 3); + dp = row + (png_size_t)((final_width - 1) >> 3); +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (int)((row_info->width + 7) & 7); + dshift = (int)((final_width + 7) & 7); + s_start = 7; + s_end = 0; + s_inc = -1; + } + else +#endif + { + sshift = 7 - (int)((row_info->width + 7) & 7); + dshift = 7 - (int)((final_width + 7) & 7); + s_start = 0; + s_end = 7; + s_inc = 1; + } + + for (i = row_info->width; i; i--) + { + v = (png_byte)((*sp >> sshift) & 0x1); + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + + case 2: + { + png_bytep sp, dp; + int sshift, dshift; + int s_start, s_end, s_inc; + png_uint_32 i; + + sp = row + (png_size_t)((row_info->width - 1) >> 2); + dp = row + (png_size_t)((final_width - 1) >> 2); +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (png_size_t)(((row_info->width + 3) & 3) << 1); + dshift = (png_size_t)(((final_width + 3) & 3) << 1); + s_start = 6; + s_end = 0; + s_inc = -2; + } + else +#endif + { + sshift = (png_size_t)((3 - ((row_info->width + 3) & 3)) << 1); + dshift = (png_size_t)((3 - ((final_width + 3) & 3)) << 1); + s_start = 0; + s_end = 6; + s_inc = 2; + } + + for (i = row_info->width; i; i--) + { + png_byte v; + int j; + + v = (png_byte)((*sp >> sshift) & 0x3); + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + + case 4: + { + png_bytep sp, dp; + int sshift, dshift; + int s_start, s_end, s_inc; + png_uint_32 i; + + sp = row + (png_size_t)((row_info->width - 1) >> 1); + dp = row + (png_size_t)((final_width - 1) >> 1); +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (png_size_t)(((row_info->width + 1) & 1) << 2); + dshift = (png_size_t)(((final_width + 1) & 1) << 2); + s_start = 4; + s_end = 0; + s_inc = -4; + } + else +#endif + { + sshift = (png_size_t)((1 - ((row_info->width + 1) & 1)) << 2); + dshift = (png_size_t)((1 - ((final_width + 1) & 1)) << 2); + s_start = 0; + s_end = 4; + s_inc = 4; + } + + for (i = row_info->width; i; i--) + { + png_byte v; + int j; + + v = (png_byte)((*sp >> sshift) & 0xf); + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + + /*====================================================================*/ + + default: /* 8-bit or larger (this is where the routine is modified) */ + { +#if 0 +// static unsigned long long _const4 = 0x0000000000FFFFFFLL; no good +// static unsigned long long const4 = 0x0000000000FFFFFFLL; no good +// unsigned long long _const4 = 0x0000000000FFFFFFLL; no good +// unsigned long long const4 = 0x0000000000FFFFFFLL; no good +#endif + png_bytep sptr, dp; + png_uint_32 i; + png_size_t pixel_bytes; + int width = (int)row_info->width; + + pixel_bytes = (row_info->pixel_depth >> 3); + + /* point sptr at the last pixel in the pre-expanded row: */ + sptr = row + (width - 1) * pixel_bytes; + + /* point dp at the last pixel position in the expanded row: */ + dp = row + (final_width - 1) * pixel_bytes; + + /* New code by Nirav Chhatrapati - Intel Corporation */ + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_INTERLACE) + /* && _mmx_supported */ ) +#else + if (_mmx_supported) +#endif + { + //-------------------------------------------------------------- + if (pixel_bytes == 3) + { + if (((pass == 0) || (pass == 1)) && width) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $21, %%edi \n\t" + // (png_pass_inc[pass] - 1)*pixel_bytes + + ".loop3_pass0: \n\t" + "movd (%%esi), %%mm0 \n\t" // x x x x x 2 1 0 + "pand _const4, %%mm0 \n\t" // z z z z z 2 1 0 + "movq %%mm0, %%mm1 \n\t" // z z z z z 2 1 0 + "psllq $16, %%mm0 \n\t" // z z z 2 1 0 z z + "movq %%mm0, %%mm2 \n\t" // z z z 2 1 0 z z + "psllq $24, %%mm0 \n\t" // 2 1 0 z z z z z + "psrlq $8, %%mm1 \n\t" // z z z z z z 2 1 + "por %%mm2, %%mm0 \n\t" // 2 1 0 2 1 0 z z + "por %%mm1, %%mm0 \n\t" // 2 1 0 2 1 0 2 1 + "movq %%mm0, %%mm3 \n\t" // 2 1 0 2 1 0 2 1 + "psllq $16, %%mm0 \n\t" // 0 2 1 0 2 1 z z + "movq %%mm3, %%mm4 \n\t" // 2 1 0 2 1 0 2 1 + "punpckhdq %%mm0, %%mm3 \n\t" // 0 2 1 0 2 1 0 2 + "movq %%mm4, 16(%%edi) \n\t" + "psrlq $32, %%mm0 \n\t" // z z z z 0 2 1 0 + "movq %%mm3, 8(%%edi) \n\t" + "punpckldq %%mm4, %%mm0 \n\t" // 1 0 2 1 0 2 1 0 + "subl $3, %%esi \n\t" + "movq %%mm0, (%%edi) \n\t" + "subl $24, %%edi \n\t" + "decl %%ecx \n\t" + "jnz .loop3_pass0 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width), // ecx + "rim" (_const4) // %1(?) (0x0000000000FFFFFFLL) + +#if 0 /* %mm0, ..., %mm4 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1", "%mm2" // clobber list + , "%mm3", "%mm4" +#endif + ); + } + else if (((pass == 2) || (pass == 3)) && width) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $9, %%edi \n\t" + // (png_pass_inc[pass] - 1)*pixel_bytes + + ".loop3_pass2: \n\t" + "movd (%%esi), %%mm0 \n\t" // x x x x x 2 1 0 + "pand _const4, %%mm0 \n\t" // z z z z z 2 1 0 + "movq %%mm0, %%mm1 \n\t" // z z z z z 2 1 0 + "psllq $16, %%mm0 \n\t" // z z z 2 1 0 z z + "movq %%mm0, %%mm2 \n\t" // z z z 2 1 0 z z + "psllq $24, %%mm0 \n\t" // 2 1 0 z z z z z + "psrlq $8, %%mm1 \n\t" // z z z z z z 2 1 + "por %%mm2, %%mm0 \n\t" // 2 1 0 2 1 0 z z + "por %%mm1, %%mm0 \n\t" // 2 1 0 2 1 0 2 1 + "movq %%mm0, 4(%%edi) \n\t" + "psrlq $16, %%mm0 \n\t" // z z 2 1 0 2 1 0 + "subl $3, %%esi \n\t" + "movd %%mm0, (%%edi) \n\t" + "subl $12, %%edi \n\t" + "decl %%ecx \n\t" + "jnz .loop3_pass2 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width), // ecx + "rim" (_const4) // (0x0000000000FFFFFFLL) + +#if 0 /* %mm0, ..., %mm2 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1", "%mm2" // clobber list +#endif + ); + } + else if (width) /* && ((pass == 4) || (pass == 5)) */ + { + int width_mmx = ((width >> 1) << 1) - 8; // GRR: huh? + if (width_mmx < 0) + width_mmx = 0; + width -= width_mmx; // 8 or 9 pix, 24 or 27 bytes + if (width_mmx) + { + // png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; + // sptr points at last pixel in pre-expanded row + // dp points at last pixel position in expanded row + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $3, %%esi \n\t" + "subl $9, %%edi \n\t" + // (png_pass_inc[pass] + 1)*pixel_bytes + + ".loop3_pass4: \n\t" + "movq (%%esi), %%mm0 \n\t" // x x 5 4 3 2 1 0 + "movq %%mm0, %%mm1 \n\t" // x x 5 4 3 2 1 0 + "movq %%mm0, %%mm2 \n\t" // x x 5 4 3 2 1 0 + "psllq $24, %%mm0 \n\t" // 4 3 2 1 0 z z z + "pand _const4, %%mm1 \n\t" // z z z z z 2 1 0 + "psrlq $24, %%mm2 \n\t" // z z z x x 5 4 3 + "por %%mm1, %%mm0 \n\t" // 4 3 2 1 0 2 1 0 + "movq %%mm2, %%mm3 \n\t" // z z z x x 5 4 3 + "psllq $8, %%mm2 \n\t" // z z x x 5 4 3 z + "movq %%mm0, (%%edi) \n\t" + "psrlq $16, %%mm3 \n\t" // z z z z z x x 5 + "pand _const6, %%mm3 \n\t" // z z z z z z z 5 + "por %%mm3, %%mm2 \n\t" // z z x x 5 4 3 5 + "subl $6, %%esi \n\t" + "movd %%mm2, 8(%%edi) \n\t" + "subl $12, %%edi \n\t" + "subl $2, %%ecx \n\t" + "jnz .loop3_pass4 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx), // ecx + "rim" (_const4), // 0x0000000000FFFFFFLL + "rim" (_const6) // 0x00000000000000FFLL + +#if 0 /* %mm0, ..., %mm3 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1" // clobber list + , "%mm2", "%mm3" +#endif + ); + } + + sptr -= width_mmx*3; + dp -= width_mmx*6; + for (i = width; i; i--) + { + png_byte v[8]; + int j; + + png_memcpy(v, sptr, 3); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, 3); + dp -= 3; + } + sptr -= 3; + } + } + } /* end of pixel_bytes == 3 */ + + //-------------------------------------------------------------- + else if (pixel_bytes == 1) + { + if (((pass == 0) || (pass == 1)) && width) + { + int width_mmx = ((width >> 2) << 2); + width -= width_mmx; // 0-3 pixels => 0-3 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $3, %%esi \n\t" + "subl $31, %%edi \n\t" + + ".loop1_pass0: \n\t" + "movd (%%esi), %%mm0 \n\t" // x x x x 3 2 1 0 + "movq %%mm0, %%mm1 \n\t" // x x x x 3 2 1 0 + "punpcklbw %%mm0, %%mm0 \n\t" // 3 3 2 2 1 1 0 0 + "movq %%mm0, %%mm2 \n\t" // 3 3 2 2 1 1 0 0 + "punpcklwd %%mm0, %%mm0 \n\t" // 1 1 1 1 0 0 0 0 + "movq %%mm0, %%mm3 \n\t" // 1 1 1 1 0 0 0 0 + "punpckldq %%mm0, %%mm0 \n\t" // 0 0 0 0 0 0 0 0 + "punpckhdq %%mm3, %%mm3 \n\t" // 1 1 1 1 1 1 1 1 + "movq %%mm0, (%%edi) \n\t" + "punpckhwd %%mm2, %%mm2 \n\t" // 3 3 3 3 2 2 2 2 + "movq %%mm3, 8(%%edi) \n\t" + "movq %%mm2, %%mm4 \n\t" // 3 3 3 3 2 2 2 2 + "punpckldq %%mm2, %%mm2 \n\t" // 2 2 2 2 2 2 2 2 + "punpckhdq %%mm4, %%mm4 \n\t" // 3 3 3 3 3 3 3 3 + "movq %%mm2, 16(%%edi) \n\t" + "subl $4, %%esi \n\t" + "movq %%mm4, 24(%%edi) \n\t" + "subl $32, %%edi \n\t" + "subl $4, %%ecx \n\t" + "jnz .loop1_pass0 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0, ..., %mm4 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1", "%mm2" // clobber list + , "%mm3", "%mm4" +#endif + ); + } + + sptr -= width_mmx; + dp -= width_mmx*8; + for (i = width; i; i--) + { + int j; + + /* I simplified this part in version 1.0.4e + * here and in several other instances where + * pixel_bytes == 1 -- GR-P + * + * Original code: + * + * png_byte v[8]; + * png_memcpy(v, sptr, pixel_bytes); + * for (j = 0; j < png_pass_inc[pass]; j++) + * { + * png_memcpy(dp, v, pixel_bytes); + * dp -= pixel_bytes; + * } + * sptr -= pixel_bytes; + * + * Replacement code is in the next three lines: + */ + + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp-- = *sptr; + } + --sptr; + } + } + else if (((pass == 2) || (pass == 3)) && width) + { + int width_mmx = ((width >> 2) << 2); + width -= width_mmx; // 0-3 pixels => 0-3 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $3, %%esi \n\t" + "subl $15, %%edi \n\t" + + ".loop1_pass2: \n\t" + "movd (%%esi), %%mm0 \n\t" // x x x x 3 2 1 0 + "punpcklbw %%mm0, %%mm0 \n\t" // 3 3 2 2 1 1 0 0 + "movq %%mm0, %%mm1 \n\t" // 3 3 2 2 1 1 0 0 + "punpcklwd %%mm0, %%mm0 \n\t" // 1 1 1 1 0 0 0 0 + "punpckhwd %%mm1, %%mm1 \n\t" // 3 3 3 3 2 2 2 2 + "movq %%mm0, (%%edi) \n\t" + "subl $4, %%esi \n\t" + "movq %%mm1, 8(%%edi) \n\t" + "subl $16, %%edi \n\t" + "subl $4, %%ecx \n\t" + "jnz .loop1_pass2 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0, %mm1 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1" // clobber list +#endif + ); + } + + sptr -= width_mmx; + dp -= width_mmx*4; + for (i = width; i; i--) + { + int j; + + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp-- = *sptr; + } + --sptr; + } + } + else if (width) /* && ((pass == 4) || (pass == 5)) */ + { + int width_mmx = ((width >> 3) << 3); + width -= width_mmx; // 0-3 pixels => 0-3 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $7, %%esi \n\t" + "subl $15, %%edi \n\t" + + ".loop1_pass4: \n\t" + "movq (%%esi), %%mm0 \n\t" // 7 6 5 4 3 2 1 0 + "movq %%mm0, %%mm1 \n\t" // 7 6 5 4 3 2 1 0 + "punpcklbw %%mm0, %%mm0 \n\t" // 3 3 2 2 1 1 0 0 + "punpckhbw %%mm1, %%mm1 \n\t" // 7 7 6 6 5 5 4 4 + "movq %%mm1, 8(%%edi) \n\t" + "subl $8, %%esi \n\t" + "movq %%mm0, (%%edi) \n\t" + "subl $16, %%edi \n\t" + "subl $8, %%ecx \n\t" + "jnz .loop1_pass4 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (none) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0, %mm1 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1" // clobber list +#endif + ); + } + + sptr -= width_mmx; + dp -= width_mmx*2; + for (i = width; i; i--) + { + int j; + + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp-- = *sptr; + } + --sptr; + } + } + } /* end of pixel_bytes == 1 */ + + //-------------------------------------------------------------- + else if (pixel_bytes == 2) + { + if (((pass == 0) || (pass == 1)) && width) + { + int width_mmx = ((width >> 1) << 1); + width -= width_mmx; // 0,1 pixels => 0,2 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $2, %%esi \n\t" + "subl $30, %%edi \n\t" + + ".loop2_pass0: \n\t" + "movd (%%esi), %%mm0 \n\t" // x x x x 3 2 1 0 + "punpcklwd %%mm0, %%mm0 \n\t" // 3 2 3 2 1 0 1 0 + "movq %%mm0, %%mm1 \n\t" // 3 2 3 2 1 0 1 0 + "punpckldq %%mm0, %%mm0 \n\t" // 1 0 1 0 1 0 1 0 + "punpckhdq %%mm1, %%mm1 \n\t" // 3 2 3 2 3 2 3 2 + "movq %%mm0, (%%edi) \n\t" + "movq %%mm0, 8(%%edi) \n\t" + "movq %%mm1, 16(%%edi) \n\t" + "subl $4, %%esi \n\t" + "movq %%mm1, 24(%%edi) \n\t" + "subl $32, %%edi \n\t" + "subl $2, %%ecx \n\t" + "jnz .loop2_pass0 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0, %mm1 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1" // clobber list +#endif + ); + } + + sptr -= (width_mmx*2 - 2); // sign fixed + dp -= (width_mmx*16 - 2); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 2; + png_memcpy(v, sptr, 2); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 2; + png_memcpy(dp, v, 2); + } + } + } + else if (((pass == 2) || (pass == 3)) && width) + { + int width_mmx = ((width >> 1) << 1) ; + width -= width_mmx; // 0,1 pixels => 0,2 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $2, %%esi \n\t" + "subl $14, %%edi \n\t" + + ".loop2_pass2: \n\t" + "movd (%%esi), %%mm0 \n\t" // x x x x 3 2 1 0 + "punpcklwd %%mm0, %%mm0 \n\t" // 3 2 3 2 1 0 1 0 + "movq %%mm0, %%mm1 \n\t" // 3 2 3 2 1 0 1 0 + "punpckldq %%mm0, %%mm0 \n\t" // 1 0 1 0 1 0 1 0 + "punpckhdq %%mm1, %%mm1 \n\t" // 3 2 3 2 3 2 3 2 + "movq %%mm0, (%%edi) \n\t" + "subl $4, %%esi \n\t" + "movq %%mm1, 8(%%edi) \n\t" + "subl $16, %%edi \n\t" + "subl $2, %%ecx \n\t" + "jnz .loop2_pass2 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0, %mm1 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1" // clobber list +#endif + ); + } + + sptr -= (width_mmx*2 - 2); // sign fixed + dp -= (width_mmx*8 - 2); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 2; + png_memcpy(v, sptr, 2); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 2; + png_memcpy(dp, v, 2); + } + } + } + else if (width) // pass == 4 or 5 + { + int width_mmx = ((width >> 1) << 1) ; + width -= width_mmx; // 0,1 pixels => 0,2 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $2, %%esi \n\t" + "subl $6, %%edi \n\t" + + ".loop2_pass4: \n\t" + "movd (%%esi), %%mm0 \n\t" // x x x x 3 2 1 0 + "punpcklwd %%mm0, %%mm0 \n\t" // 3 2 3 2 1 0 1 0 + "subl $4, %%esi \n\t" + "movq %%mm0, (%%edi) \n\t" + "subl $8, %%edi \n\t" + "subl $2, %%ecx \n\t" + "jnz .loop2_pass4 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0" // clobber list +#endif + ); + } + + sptr -= (width_mmx*2 - 2); // sign fixed + dp -= (width_mmx*4 - 2); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 2; + png_memcpy(v, sptr, 2); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 2; + png_memcpy(dp, v, 2); + } + } + } + } /* end of pixel_bytes == 2 */ + + //-------------------------------------------------------------- + else if (pixel_bytes == 4) + { + if (((pass == 0) || (pass == 1)) && width) + { + int width_mmx = ((width >> 1) << 1); + width -= width_mmx; // 0,1 pixels => 0,4 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $4, %%esi \n\t" + "subl $60, %%edi \n\t" + + ".loop4_pass0: \n\t" + "movq (%%esi), %%mm0 \n\t" // 7 6 5 4 3 2 1 0 + "movq %%mm0, %%mm1 \n\t" // 7 6 5 4 3 2 1 0 + "punpckldq %%mm0, %%mm0 \n\t" // 3 2 1 0 3 2 1 0 + "punpckhdq %%mm1, %%mm1 \n\t" // 7 6 5 4 7 6 5 4 + "movq %%mm0, (%%edi) \n\t" + "movq %%mm0, 8(%%edi) \n\t" + "movq %%mm0, 16(%%edi) \n\t" + "movq %%mm0, 24(%%edi) \n\t" + "movq %%mm1, 32(%%edi) \n\t" + "movq %%mm1, 40(%%edi) \n\t" + "movq %%mm1, 48(%%edi) \n\t" + "subl $8, %%esi \n\t" + "movq %%mm1, 56(%%edi) \n\t" + "subl $64, %%edi \n\t" + "subl $2, %%ecx \n\t" + "jnz .loop4_pass0 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0, %mm1 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1" // clobber list +#endif + ); + } + + sptr -= (width_mmx*4 - 4); // sign fixed + dp -= (width_mmx*32 - 4); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 4; + png_memcpy(v, sptr, 4); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 4; + png_memcpy(dp, v, 4); + } + } + } + else if (((pass == 2) || (pass == 3)) && width) + { + int width_mmx = ((width >> 1) << 1); + width -= width_mmx; // 0,1 pixels => 0,4 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $4, %%esi \n\t" + "subl $28, %%edi \n\t" + + ".loop4_pass2: \n\t" + "movq (%%esi), %%mm0 \n\t" // 7 6 5 4 3 2 1 0 + "movq %%mm0, %%mm1 \n\t" // 7 6 5 4 3 2 1 0 + "punpckldq %%mm0, %%mm0 \n\t" // 3 2 1 0 3 2 1 0 + "punpckhdq %%mm1, %%mm1 \n\t" // 7 6 5 4 7 6 5 4 + "movq %%mm0, (%%edi) \n\t" + "movq %%mm0, 8(%%edi) \n\t" + "movq %%mm1, 16(%%edi) \n\t" + "movq %%mm1, 24(%%edi) \n\t" + "subl $8, %%esi \n\t" + "subl $32, %%edi \n\t" + "subl $2, %%ecx \n\t" + "jnz .loop4_pass2 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0, %mm1 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1" // clobber list +#endif + ); + } + + sptr -= (width_mmx*4 - 4); // sign fixed + dp -= (width_mmx*16 - 4); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 4; + png_memcpy(v, sptr, 4); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 4; + png_memcpy(dp, v, 4); + } + } + } + else if (width) // pass == 4 or 5 + { + int width_mmx = ((width >> 1) << 1) ; + width -= width_mmx; // 0,1 pixels => 0,4 bytes + if (width_mmx) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $4, %%esi \n\t" + "subl $12, %%edi \n\t" + + ".loop4_pass4: \n\t" + "movq (%%esi), %%mm0 \n\t" // 7 6 5 4 3 2 1 0 + "movq %%mm0, %%mm1 \n\t" // 7 6 5 4 3 2 1 0 + "punpckldq %%mm0, %%mm0 \n\t" // 3 2 1 0 3 2 1 0 + "punpckhdq %%mm1, %%mm1 \n\t" // 7 6 5 4 7 6 5 4 + "movq %%mm0, (%%edi) \n\t" + "subl $8, %%esi \n\t" + "movq %%mm1, 8(%%edi) \n\t" + "subl $16, %%edi \n\t" + "subl $2, %%ecx \n\t" + "jnz .loop4_pass4 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width_mmx) // ecx + +#if 0 /* %mm0, %mm1 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0", "%mm1" // clobber list +#endif + ); + } + + sptr -= (width_mmx*4 - 4); // sign fixed + dp -= (width_mmx*8 - 4); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 4; + png_memcpy(v, sptr, 4); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 4; + png_memcpy(dp, v, 4); + } + } + } + } /* end of pixel_bytes == 4 */ + + //-------------------------------------------------------------- + else if (pixel_bytes == 8) + { +// GRR TEST: should work, but needs testing (special 64-bit version of rpng2?) + // GRR NOTE: no need to combine passes here! + if (((pass == 0) || (pass == 1)) && width) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + // source is 8-byte RRGGBBAA + // dest is 64-byte RRGGBBAA RRGGBBAA RRGGBBAA RRGGBBAA ... + __asm__ __volatile__ ( + "subl $56, %%edi \n\t" // start of last block + + ".loop8_pass0: \n\t" + "movq (%%esi), %%mm0 \n\t" // 7 6 5 4 3 2 1 0 + "movq %%mm0, (%%edi) \n\t" + "movq %%mm0, 8(%%edi) \n\t" + "movq %%mm0, 16(%%edi) \n\t" + "movq %%mm0, 24(%%edi) \n\t" + "movq %%mm0, 32(%%edi) \n\t" + "movq %%mm0, 40(%%edi) \n\t" + "movq %%mm0, 48(%%edi) \n\t" + "subl $8, %%esi \n\t" + "movq %%mm0, 56(%%edi) \n\t" + "subl $64, %%edi \n\t" + "decl %%ecx \n\t" + "jnz .loop8_pass0 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width) // ecx + +#if 0 /* %mm0 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0" // clobber list +#endif + ); + } + else if (((pass == 2) || (pass == 3)) && width) + { + // source is 8-byte RRGGBBAA + // dest is 32-byte RRGGBBAA RRGGBBAA RRGGBBAA RRGGBBAA + // (recall that expansion is _in place_: sptr and dp + // both point at locations within same row buffer) + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $24, %%edi \n\t" // start of last block + + ".loop8_pass2: \n\t" + "movq (%%esi), %%mm0 \n\t" // 7 6 5 4 3 2 1 0 + "movq %%mm0, (%%edi) \n\t" + "movq %%mm0, 8(%%edi) \n\t" + "movq %%mm0, 16(%%edi) \n\t" + "subl $8, %%esi \n\t" + "movq %%mm0, 24(%%edi) \n\t" + "subl $32, %%edi \n\t" + "decl %%ecx \n\t" + "jnz .loop8_pass2 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width) // ecx + +#if 0 /* %mm0 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0" // clobber list +#endif + ); + } + } + else if (width) // pass == 4 or 5 + { + // source is 8-byte RRGGBBAA + // dest is 16-byte RRGGBBAA RRGGBBAA + { + int dummy_value_c; // fix 'forbidden register spilled' + int dummy_value_S; + int dummy_value_D; + + __asm__ __volatile__ ( + "subl $8, %%edi \n\t" // start of last block + + ".loop8_pass4: \n\t" + "movq (%%esi), %%mm0 \n\t" // 7 6 5 4 3 2 1 0 + "movq %%mm0, (%%edi) \n\t" + "subl $8, %%esi \n\t" + "movq %%mm0, 8(%%edi) \n\t" + "subl $16, %%edi \n\t" + "decl %%ecx \n\t" + "jnz .loop8_pass4 \n\t" + "EMMS \n\t" // DONE + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "1" (sptr), // esi // input regs + "2" (dp), // edi + "0" (width) // ecx + +#if 0 /* %mm0 not supported by gcc 2.7.2.3 or egcs 1.1 */ + : "%mm0" // clobber list +#endif + ); + } + } + + } /* end of pixel_bytes == 8 */ + + //-------------------------------------------------------------- + else if (pixel_bytes == 6) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, 6); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, 6); + dp -= 6; + } + sptr -= 6; + } + } /* end of pixel_bytes == 6 */ + + //-------------------------------------------------------------- + else + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, pixel_bytes); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sptr-= pixel_bytes; + } + } + } // end of _mmx_supported ======================================== + + else /* MMX not supported: use modified C code - takes advantage + * of inlining of png_memcpy for a constant */ + /* GRR 19991007: does it? or should pixel_bytes in each + * block be replaced with immediate value (e.g., 1)? */ + /* GRR 19991017: replaced with constants in each case */ +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + if (pixel_bytes == 1) + { + for (i = width; i; i--) + { + int j; + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp-- = *sptr; + } + --sptr; + } + } + else if (pixel_bytes == 3) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, 3); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, 3); + dp -= 3; + } + sptr -= 3; + } + } + else if (pixel_bytes == 2) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, 2); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, 2); + dp -= 2; + } + sptr -= 2; + } + } + else if (pixel_bytes == 4) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, 4); + for (j = 0; j < png_pass_inc[pass]; j++) + { +#ifdef PNG_DEBUG + if (dp < row || dp+3 > row+png_ptr->row_buf_size) + { + printf("dp out of bounds: row=%d, dp=%d, rp=%d\n", + row, dp, row+png_ptr->row_buf_size); + printf("row_buf=%d\n",png_ptr->row_buf_size); + } +#endif + png_memcpy(dp, v, 4); + dp -= 4; + } + sptr -= 4; + } + } + else if (pixel_bytes == 6) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, 6); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, 6); + dp -= 6; + } + sptr -= 6; + } + } + else if (pixel_bytes == 8) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, 8); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, 8); + dp -= 8; + } + sptr -= 8; + } + } + else /* GRR: should never be reached */ + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, pixel_bytes); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sptr -= pixel_bytes; + } + } + + } /* end if (MMX not supported) */ + break; + } + } /* end switch (row_info->pixel_depth) */ + + row_info->width = final_width; + + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width); + } + +} /* end png_do_read_interlace() */ + +#endif /* PNG_HAVE_ASSEMBLER_READ_INTERLACE */ +#endif /* PNG_READ_INTERLACING_SUPPORTED */ + + + +#if defined(PNG_HAVE_ASSEMBLER_READ_FILTER_ROW) +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) + +// These variables are utilized in the functions below. They are declared +// globally here to ensure alignment on 8-byte boundaries. + +union uAll { + long long use; + double align; +} _LBCarryMask = {0x0101010101010101LL}, + _HBClearMask = {0x7f7f7f7f7f7f7f7fLL}, + _ActiveMask, _ActiveMask2, _ActiveMaskEnd, _ShiftBpp, _ShiftRem; + +#ifdef PNG_THREAD_UNSAFE_OK +//===========================================================================// +// // +// P N G _ R E A D _ F I L T E R _ R O W _ M M X _ A V G // +// // +//===========================================================================// + +// Optimized code for PNG Average filter decoder + +static void /* PRIVATE */ +png_read_filter_row_mmx_avg(png_row_infop row_info, png_bytep row, + png_bytep prev_row) +{ + int bpp; + int dummy_value_c; // fix 'forbidden register 2 (cx) was spilled' error + int dummy_value_S; + int dummy_value_D; + + bpp = (row_info->pixel_depth + 7) >> 3; // get # bytes per pixel + _FullLength = row_info->rowbytes; // # of bytes to filter + + __asm__ __volatile__ ( + // initialize address pointers and offset +#ifdef __PIC__ + "pushl %%ebx \n\t" // save index to Global Offset Table +#endif +//pre "movl row, %%edi \n\t" // edi: Avg(x) + "xorl %%ebx, %%ebx \n\t" // ebx: x + "movl %%edi, %%edx \n\t" +//pre "movl prev_row, %%esi \n\t" // esi: Prior(x) +//pre "subl bpp, %%edx \n\t" // (bpp is preloaded into ecx) + "subl %%ecx, %%edx \n\t" // edx: Raw(x-bpp) + + "xorl %%eax,%%eax \n\t" + + // Compute the Raw value for the first bpp bytes + // Raw(x) = Avg(x) + (Prior(x)/2) + "avg_rlp: \n\t" + "movb (%%esi,%%ebx,),%%al \n\t" // load al with Prior(x) + "incl %%ebx \n\t" + "shrb %%al \n\t" // divide by 2 + "addb -1(%%edi,%%ebx,),%%al \n\t" // add Avg(x); -1 to offset inc ebx +//pre "cmpl bpp, %%ebx \n\t" // (bpp is preloaded into ecx) + "cmpl %%ecx, %%ebx \n\t" + "movb %%al,-1(%%edi,%%ebx,) \n\t" // write Raw(x); -1 to offset inc ebx + "jb avg_rlp \n\t" // mov does not affect flags + + // get # of bytes to alignment + "movl %%edi, _dif \n\t" // take start of row + "addl %%ebx, _dif \n\t" // add bpp + "addl $0xf, _dif \n\t" // add 7+8 to incr past alignment bdry + "andl $0xfffffff8, _dif \n\t" // mask to alignment boundary + "subl %%edi, _dif \n\t" // subtract from start => value ebx at + "jz avg_go \n\t" // alignment + + // fix alignment + // Compute the Raw value for the bytes up to the alignment boundary + // Raw(x) = Avg(x) + ((Raw(x-bpp) + Prior(x))/2) + "xorl %%ecx, %%ecx \n\t" + + "avg_lp1: \n\t" + "xorl %%eax, %%eax \n\t" + "movb (%%esi,%%ebx,), %%cl \n\t" // load cl with Prior(x) + "movb (%%edx,%%ebx,), %%al \n\t" // load al with Raw(x-bpp) + "addw %%cx, %%ax \n\t" + "incl %%ebx \n\t" + "shrw %%ax \n\t" // divide by 2 + "addb -1(%%edi,%%ebx,), %%al \n\t" // add Avg(x); -1 to offset inc ebx + "cmpl _dif, %%ebx \n\t" // check if at alignment boundary + "movb %%al, -1(%%edi,%%ebx,) \n\t" // write Raw(x); -1 to offset inc ebx + "jb avg_lp1 \n\t" // repeat until at alignment boundary + + "avg_go: \n\t" + "movl _FullLength, %%eax \n\t" + "movl %%eax, %%ecx \n\t" + "subl %%ebx, %%eax \n\t" // subtract alignment fix + "andl $0x00000007, %%eax \n\t" // calc bytes over mult of 8 + "subl %%eax, %%ecx \n\t" // drop over bytes from original length + "movl %%ecx, _MMXLength \n\t" +#ifdef __PIC__ + "popl %%ebx \n\t" // restore index to Global Offset Table +#endif + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "0" (bpp), // ecx // input regs + "1" (prev_row), // esi + "2" (row) // edi + + : "%eax", "%edx" // clobber list +#ifndef __PIC__ + , "%ebx" +#endif + // GRR: INCLUDE "memory" as clobbered? (_dif, _MMXLength) + // (seems to work fine without...) + ); + + // now do the math for the rest of the row + switch (bpp) + { + case 3: + { + _ActiveMask.use = 0x0000000000ffffffLL; + _ShiftBpp.use = 24; // == 3 * 8 + _ShiftRem.use = 40; // == 64 - 24 + + __asm__ __volatile__ ( + // re-init address pointers and offset + "movq _ActiveMask, %%mm7 \n\t" + "movl _dif, %%ecx \n\t" // ecx: x = offset to + "movq _LBCarryMask, %%mm5 \n\t" // alignment boundary +// preload "movl row, %%edi \n\t" // edi: Avg(x) + "movq _HBClearMask, %%mm4 \n\t" +// preload "movl prev_row, %%esi \n\t" // esi: Prior(x) + + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%ecx,), %%mm2 \n\t" // load previous aligned 8 bytes + // (correct pos. in loop below) + "avg_3lp: \n\t" + "movq (%%edi,%%ecx,), %%mm0 \n\t" // load mm0 with Avg(x) + "movq %%mm5, %%mm3 \n\t" + "psrlq _ShiftRem, %%mm2 \n\t" // correct position Raw(x-bpp) + // data + "movq (%%esi,%%ecx,), %%mm1 \n\t" // load mm1 with Prior(x) + "movq %%mm7, %%mm6 \n\t" + "pand %%mm1, %%mm3 \n\t" // get lsb for each prev_row byte + "psrlq $1, %%mm1 \n\t" // divide prev_row bytes by 2 + "pand %%mm4, %%mm1 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm0 \n\t" // add (Prev_row/2) to Avg for + // each byte + // add 1st active group (Raw(x-bpp)/2) to average with LBCarry + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both + // lsb's were == 1 (only valid for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm6, %%mm2 \n\t" // leave only Active Group 1 + // bytes to add to Avg + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to + // Avg for each Active + // byte + // add 2nd active group (Raw(x-bpp)/2) to average with _LBCarry + "psllq _ShiftBpp, %%mm6 \n\t" // shift the mm6 mask to cover + // bytes 3-5 + "movq %%mm0, %%mm2 \n\t" // mov updated Raws to mm2 + "psllq _ShiftBpp, %%mm2 \n\t" // shift data to pos. correctly + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both + // lsb's were == 1 (only valid for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm6, %%mm2 \n\t" // leave only Active Group 2 + // bytes to add to Avg + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to + // Avg for each Active + // byte + + // add 3rd active group (Raw(x-bpp)/2) to average with _LBCarry + "psllq _ShiftBpp, %%mm6 \n\t" // shift mm6 mask to cover last + // two + // bytes + "movq %%mm0, %%mm2 \n\t" // mov updated Raws to mm2 + "psllq _ShiftBpp, %%mm2 \n\t" // shift data to pos. correctly + // Data only needs to be shifted once here to + // get the correct x-bpp offset. + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both + // lsb's were == 1 (only valid for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm6, %%mm2 \n\t" // leave only Active Group 2 + // bytes to add to Avg + "addl $8, %%ecx \n\t" + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to + // Avg for each Active + // byte + // now ready to write back to memory + "movq %%mm0, -8(%%edi,%%ecx,) \n\t" + // move updated Raw(x) to use as Raw(x-bpp) for next loop + "cmpl _MMXLength, %%ecx \n\t" + "movq %%mm0, %%mm2 \n\t" // mov updated Raw(x) to mm2 + "jb avg_3lp \n\t" + + : "=S" (dummy_value_S), // output regs (dummy) + "=D" (dummy_value_D) + + : "0" (prev_row), // esi // input regs + "1" (row) // edi + + : "%ecx" // clobber list +#if 0 /* %mm0, ..., %mm7 not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; // end 3 bpp + + case 6: + case 4: + //case 7: // who wrote this? PNG doesn't support 5 or 7 bytes/pixel + //case 5: // GRR BOGUS + { + _ActiveMask.use = 0xffffffffffffffffLL; // use shift below to clear + // appropriate inactive bytes + _ShiftBpp.use = bpp << 3; + _ShiftRem.use = 64 - _ShiftBpp.use; + + __asm__ __volatile__ ( + "movq _HBClearMask, %%mm4 \n\t" + + // re-init address pointers and offset + "movl _dif, %%ecx \n\t" // ecx: x = offset to + // alignment boundary + + // load _ActiveMask and clear all bytes except for 1st active group + "movq _ActiveMask, %%mm7 \n\t" +// preload "movl row, %%edi \n\t" // edi: Avg(x) + "psrlq _ShiftRem, %%mm7 \n\t" +// preload "movl prev_row, %%esi \n\t" // esi: Prior(x) + "movq %%mm7, %%mm6 \n\t" + "movq _LBCarryMask, %%mm5 \n\t" + "psllq _ShiftBpp, %%mm6 \n\t" // create mask for 2nd active + // group + + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%ecx,), %%mm2 \n\t" // load previous aligned 8 bytes + // (we correct pos. in loop below) + "avg_4lp: \n\t" + "movq (%%edi,%%ecx,), %%mm0 \n\t" + "psrlq _ShiftRem, %%mm2 \n\t" // shift data to pos. correctly + "movq (%%esi,%%ecx,), %%mm1 \n\t" + // add (Prev_row/2) to average + "movq %%mm5, %%mm3 \n\t" + "pand %%mm1, %%mm3 \n\t" // get lsb for each prev_row byte + "psrlq $1, %%mm1 \n\t" // divide prev_row bytes by 2 + "pand %%mm4, %%mm1 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm0 \n\t" // add (Prev_row/2) to Avg for + // each byte + // add 1st active group (Raw(x-bpp)/2) to average with _LBCarry + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both + // lsb's were == 1 (only valid for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm7, %%mm2 \n\t" // leave only Active Group 1 + // bytes to add to Avg + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to Avg + // for each Active + // byte + // add 2nd active group (Raw(x-bpp)/2) to average with _LBCarry + "movq %%mm0, %%mm2 \n\t" // mov updated Raws to mm2 + "psllq _ShiftBpp, %%mm2 \n\t" // shift data to pos. correctly + "addl $8, %%ecx \n\t" + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both + // lsb's were == 1 (only valid for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm6, %%mm2 \n\t" // leave only Active Group 2 + // bytes to add to Avg + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to + // Avg for each Active + // byte + "cmpl _MMXLength, %%ecx \n\t" + // now ready to write back to memory + "movq %%mm0, -8(%%edi,%%ecx,) \n\t" + // prep Raw(x-bpp) for next loop + "movq %%mm0, %%mm2 \n\t" // mov updated Raws to mm2 + "jb avg_4lp \n\t" + + : "=S" (dummy_value_S), // output regs (dummy) + "=D" (dummy_value_D) + + : "0" (prev_row), // esi // input regs + "1" (row) // edi + + : "%ecx" // clobber list +#if 0 /* %mm0, ..., %mm7 not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; // end 4,6 bpp + + case 2: + { + _ActiveMask.use = 0x000000000000ffffLL; + _ShiftBpp.use = 16; // == 2 * 8 + _ShiftRem.use = 48; // == 64 - 16 + + __asm__ __volatile__ ( + // load _ActiveMask + "movq _ActiveMask, %%mm7 \n\t" + // re-init address pointers and offset + "movl _dif, %%ecx \n\t" // ecx: x = offset to alignment + // boundary + "movq _LBCarryMask, %%mm5 \n\t" +// preload "movl row, %%edi \n\t" // edi: Avg(x) + "movq _HBClearMask, %%mm4 \n\t" +// preload "movl prev_row, %%esi \n\t" // esi: Prior(x) + + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%ecx,), %%mm2 \n\t" // load previous aligned 8 bytes + // (we correct pos. in loop below) + "avg_2lp: \n\t" + "movq (%%edi,%%ecx,), %%mm0 \n\t" + "psrlq _ShiftRem, %%mm2 \n\t" // shift data to pos. correctly + "movq (%%esi,%%ecx,), %%mm1 \n\t" // (GRR BUGFIX: was psllq) + // add (Prev_row/2) to average + "movq %%mm5, %%mm3 \n\t" + "pand %%mm1, %%mm3 \n\t" // get lsb for each prev_row byte + "psrlq $1, %%mm1 \n\t" // divide prev_row bytes by 2 + "pand %%mm4, %%mm1 \n\t" // clear invalid bit 7 of each + // byte + "movq %%mm7, %%mm6 \n\t" + "paddb %%mm1, %%mm0 \n\t" // add (Prev_row/2) to Avg for + // each byte + + // add 1st active group (Raw(x-bpp)/2) to average with _LBCarry + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both + // lsb's were == 1 (only valid + // for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm6, %%mm2 \n\t" // leave only Active Group 1 + // bytes to add to Avg + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to Avg + // for each Active byte + + // add 2nd active group (Raw(x-bpp)/2) to average with _LBCarry + "psllq _ShiftBpp, %%mm6 \n\t" // shift the mm6 mask to cover + // bytes 2 & 3 + "movq %%mm0, %%mm2 \n\t" // mov updated Raws to mm2 + "psllq _ShiftBpp, %%mm2 \n\t" // shift data to pos. correctly + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both + // lsb's were == 1 (only valid + // for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm6, %%mm2 \n\t" // leave only Active Group 2 + // bytes to add to Avg + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to + // Avg for each Active byte + + // add 3rd active group (Raw(x-bpp)/2) to average with _LBCarry + "psllq _ShiftBpp, %%mm6 \n\t" // shift the mm6 mask to cover + // bytes 4 & 5 + "movq %%mm0, %%mm2 \n\t" // mov updated Raws to mm2 + "psllq _ShiftBpp, %%mm2 \n\t" // shift data to pos. correctly + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both lsb's were == 1 + // (only valid for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm6, %%mm2 \n\t" // leave only Active Group 2 + // bytes to add to Avg + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to + // Avg for each Active byte + + // add 4th active group (Raw(x-bpp)/2) to average with _LBCarry + "psllq _ShiftBpp, %%mm6 \n\t" // shift the mm6 mask to cover + // bytes 6 & 7 + "movq %%mm0, %%mm2 \n\t" // mov updated Raws to mm2 + "psllq _ShiftBpp, %%mm2 \n\t" // shift data to pos. correctly + "addl $8, %%ecx \n\t" + "movq %%mm3, %%mm1 \n\t" // now use mm1 for getting + // LBCarrys + "pand %%mm2, %%mm1 \n\t" // get LBCarrys for each byte + // where both + // lsb's were == 1 (only valid + // for active group) + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm2 \n\t" // add LBCarrys to (Raw(x-bpp)/2) + // for each byte + "pand %%mm6, %%mm2 \n\t" // leave only Active Group 2 + // bytes to add to Avg + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) + LBCarrys to + // Avg for each Active byte + + "cmpl _MMXLength, %%ecx \n\t" + // now ready to write back to memory + "movq %%mm0, -8(%%edi,%%ecx,) \n\t" + // prep Raw(x-bpp) for next loop + "movq %%mm0, %%mm2 \n\t" // mov updated Raws to mm2 + "jb avg_2lp \n\t" + + : "=S" (dummy_value_S), // output regs (dummy) + "=D" (dummy_value_D) + + : "0" (prev_row), // esi // input regs + "1" (row) // edi + + : "%ecx" // clobber list +#if 0 /* %mm0, ..., %mm7 not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; // end 2 bpp + + case 1: + { + __asm__ __volatile__ ( + // re-init address pointers and offset +#ifdef __PIC__ + "pushl %%ebx \n\t" // save Global Offset Table index +#endif + "movl _dif, %%ebx \n\t" // ebx: x = offset to alignment + // boundary +// preload "movl row, %%edi \n\t" // edi: Avg(x) + "cmpl _FullLength, %%ebx \n\t" // test if offset at end of array + "jnb avg_1end \n\t" + // do Paeth decode for remaining bytes +// preload "movl prev_row, %%esi \n\t" // esi: Prior(x) + "movl %%edi, %%edx \n\t" +// preload "subl bpp, %%edx \n\t" // (bpp is preloaded into ecx) + "subl %%ecx, %%edx \n\t" // edx: Raw(x-bpp) + "xorl %%ecx, %%ecx \n\t" // zero ecx before using cl & cx + // in loop below + "avg_1lp: \n\t" + // Raw(x) = Avg(x) + ((Raw(x-bpp) + Prior(x))/2) + "xorl %%eax, %%eax \n\t" + "movb (%%esi,%%ebx,), %%cl \n\t" // load cl with Prior(x) + "movb (%%edx,%%ebx,), %%al \n\t" // load al with Raw(x-bpp) + "addw %%cx, %%ax \n\t" + "incl %%ebx \n\t" + "shrw %%ax \n\t" // divide by 2 + "addb -1(%%edi,%%ebx,), %%al \n\t" // add Avg(x); -1 to offset + // inc ebx + "cmpl _FullLength, %%ebx \n\t" // check if at end of array + "movb %%al, -1(%%edi,%%ebx,) \n\t" // write back Raw(x); + // mov does not affect flags; -1 to offset inc ebx + "jb avg_1lp \n\t" + + "avg_1end: \n\t" +#ifdef __PIC__ + "popl %%ebx \n\t" // Global Offset Table index +#endif + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "0" (bpp), // ecx // input regs + "1" (prev_row), // esi + "2" (row) // edi + + : "%eax", "%edx" // clobber list +#ifndef __PIC__ + , "%ebx" +#endif + ); + } + return; // end 1 bpp + + case 8: + { + __asm__ __volatile__ ( + // re-init address pointers and offset + "movl _dif, %%ecx \n\t" // ecx: x == offset to alignment + "movq _LBCarryMask, %%mm5 \n\t" // boundary +// preload "movl row, %%edi \n\t" // edi: Avg(x) + "movq _HBClearMask, %%mm4 \n\t" +// preload "movl prev_row, %%esi \n\t" // esi: Prior(x) + + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%ecx,), %%mm2 \n\t" // load previous aligned 8 bytes + // (NO NEED to correct pos. in loop below) + + "avg_8lp: \n\t" + "movq (%%edi,%%ecx,), %%mm0 \n\t" + "movq %%mm5, %%mm3 \n\t" + "movq (%%esi,%%ecx,), %%mm1 \n\t" + "addl $8, %%ecx \n\t" + "pand %%mm1, %%mm3 \n\t" // get lsb for each prev_row byte + "psrlq $1, %%mm1 \n\t" // divide prev_row bytes by 2 + "pand %%mm2, %%mm3 \n\t" // get LBCarrys for each byte + // where both lsb's were == 1 + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm1 \n\t" // clear invalid bit 7, each byte + "paddb %%mm3, %%mm0 \n\t" // add LBCarrys to Avg, each byte + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7, each byte + "paddb %%mm1, %%mm0 \n\t" // add (Prev_row/2) to Avg, each + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) to Avg for each + "cmpl _MMXLength, %%ecx \n\t" + "movq %%mm0, -8(%%edi,%%ecx,) \n\t" + "movq %%mm0, %%mm2 \n\t" // reuse as Raw(x-bpp) + "jb avg_8lp \n\t" + + : "=S" (dummy_value_S), // output regs (dummy) + "=D" (dummy_value_D) + + : "0" (prev_row), // esi // input regs + "1" (row) // edi + + : "%ecx" // clobber list +#if 0 /* %mm0, ..., %mm5 not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2" + , "%mm3", "%mm4", "%mm5" +#endif + ); + } + break; // end 8 bpp + + default: // bpp greater than 8 (!= 1,2,3,4,[5],6,[7],8) + { + +#ifdef PNG_DEBUG + // GRR: PRINT ERROR HERE: SHOULD NEVER BE REACHED + png_debug(1, + "Internal logic error in pnggccrd (png_read_filter_row_mmx_avg())\n"); +#endif + +#if 0 + __asm__ __volatile__ ( + "movq _LBCarryMask, %%mm5 \n\t" + // re-init address pointers and offset + "movl _dif, %%ebx \n\t" // ebx: x = offset to + // alignment boundary + "movl row, %%edi \n\t" // edi: Avg(x) + "movq _HBClearMask, %%mm4 \n\t" + "movl %%edi, %%edx \n\t" + "movl prev_row, %%esi \n\t" // esi: Prior(x) + "subl bpp, %%edx \n\t" // edx: Raw(x-bpp) + "avg_Alp: \n\t" + "movq (%%edi,%%ebx,), %%mm0 \n\t" + "movq %%mm5, %%mm3 \n\t" + "movq (%%esi,%%ebx,), %%mm1 \n\t" + "pand %%mm1, %%mm3 \n\t" // get lsb for each prev_row byte + "movq (%%edx,%%ebx,), %%mm2 \n\t" + "psrlq $1, %%mm1 \n\t" // divide prev_row bytes by 2 + "pand %%mm2, %%mm3 \n\t" // get LBCarrys for each byte + // where both lsb's were == 1 + "psrlq $1, %%mm2 \n\t" // divide raw bytes by 2 + "pand %%mm4, %%mm1 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm3, %%mm0 \n\t" // add LBCarrys to Avg for each + // byte + "pand %%mm4, %%mm2 \n\t" // clear invalid bit 7 of each + // byte + "paddb %%mm1, %%mm0 \n\t" // add (Prev_row/2) to Avg for + // each byte + "addl $8, %%ebx \n\t" + "paddb %%mm2, %%mm0 \n\t" // add (Raw/2) to Avg for each + // byte + "cmpl _MMXLength, %%ebx \n\t" + "movq %%mm0, -8(%%edi,%%ebx,) \n\t" + "jb avg_Alp \n\t" + + : // FIXASM: output regs/vars go here, e.g.: "=m" (memory_var) + + : // FIXASM: input regs, e.g.: "c" (count), "S" (src), "D" (dest) + + : "%ebx", "%edx", "%edi", "%esi" // CHECKASM: clobber list + ); +#endif /* 0 - NEVER REACHED */ + } + break; + + } // end switch (bpp) + + __asm__ __volatile__ ( + // MMX acceleration complete; now do clean-up + // check if any remaining bytes left to decode +#ifdef __PIC__ + "pushl %%ebx \n\t" // save index to Global Offset Table +#endif + "movl _MMXLength, %%ebx \n\t" // ebx: x == offset bytes after MMX +//pre "movl row, %%edi \n\t" // edi: Avg(x) + "cmpl _FullLength, %%ebx \n\t" // test if offset at end of array + "jnb avg_end \n\t" + + // do Avg decode for remaining bytes +//pre "movl prev_row, %%esi \n\t" // esi: Prior(x) + "movl %%edi, %%edx \n\t" +//pre "subl bpp, %%edx \n\t" // (bpp is preloaded into ecx) + "subl %%ecx, %%edx \n\t" // edx: Raw(x-bpp) + "xorl %%ecx, %%ecx \n\t" // zero ecx before using cl & cx below + + "avg_lp2: \n\t" + // Raw(x) = Avg(x) + ((Raw(x-bpp) + Prior(x))/2) + "xorl %%eax, %%eax \n\t" + "movb (%%esi,%%ebx,), %%cl \n\t" // load cl with Prior(x) + "movb (%%edx,%%ebx,), %%al \n\t" // load al with Raw(x-bpp) + "addw %%cx, %%ax \n\t" + "incl %%ebx \n\t" + "shrw %%ax \n\t" // divide by 2 + "addb -1(%%edi,%%ebx,), %%al \n\t" // add Avg(x); -1 to offset inc ebx + "cmpl _FullLength, %%ebx \n\t" // check if at end of array + "movb %%al, -1(%%edi,%%ebx,) \n\t" // write back Raw(x) [mov does not + "jb avg_lp2 \n\t" // affect flags; -1 to offset inc ebx] + + "avg_end: \n\t" + "EMMS \n\t" // end MMX; prep for poss. FP instrs. +#ifdef __PIC__ + "popl %%ebx \n\t" // restore index to Global Offset Table +#endif + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "0" (bpp), // ecx // input regs + "1" (prev_row), // esi + "2" (row) // edi + + : "%eax", "%edx" // clobber list +#ifndef __PIC__ + , "%ebx" +#endif + ); + +} /* end png_read_filter_row_mmx_avg() */ +#endif + + + +#ifdef PNG_THREAD_UNSAFE_OK +//===========================================================================// +// // +// P N G _ R E A D _ F I L T E R _ R O W _ M M X _ P A E T H // +// // +//===========================================================================// + +// Optimized code for PNG Paeth filter decoder + +static void /* PRIVATE */ +png_read_filter_row_mmx_paeth(png_row_infop row_info, png_bytep row, + png_bytep prev_row) +{ + int bpp; + int dummy_value_c; // fix 'forbidden register 2 (cx) was spilled' error + int dummy_value_S; + int dummy_value_D; + + bpp = (row_info->pixel_depth + 7) >> 3; // Get # bytes per pixel + _FullLength = row_info->rowbytes; // # of bytes to filter + + __asm__ __volatile__ ( +#ifdef __PIC__ + "pushl %%ebx \n\t" // save index to Global Offset Table +#endif + "xorl %%ebx, %%ebx \n\t" // ebx: x offset +//pre "movl row, %%edi \n\t" + "xorl %%edx, %%edx \n\t" // edx: x-bpp offset +//pre "movl prev_row, %%esi \n\t" + "xorl %%eax, %%eax \n\t" + + // Compute the Raw value for the first bpp bytes + // Note: the formula works out to be always + // Paeth(x) = Raw(x) + Prior(x) where x < bpp + "paeth_rlp: \n\t" + "movb (%%edi,%%ebx,), %%al \n\t" + "addb (%%esi,%%ebx,), %%al \n\t" + "incl %%ebx \n\t" +//pre "cmpl bpp, %%ebx \n\t" (bpp is preloaded into ecx) + "cmpl %%ecx, %%ebx \n\t" + "movb %%al, -1(%%edi,%%ebx,) \n\t" + "jb paeth_rlp \n\t" + // get # of bytes to alignment + "movl %%edi, _dif \n\t" // take start of row + "addl %%ebx, _dif \n\t" // add bpp + "xorl %%ecx, %%ecx \n\t" + "addl $0xf, _dif \n\t" // add 7 + 8 to incr past alignment + // boundary + "andl $0xfffffff8, _dif \n\t" // mask to alignment boundary + "subl %%edi, _dif \n\t" // subtract from start ==> value ebx + // at alignment + "jz paeth_go \n\t" + // fix alignment + + "paeth_lp1: \n\t" + "xorl %%eax, %%eax \n\t" + // pav = p - a = (a + b - c) - a = b - c + "movb (%%esi,%%ebx,), %%al \n\t" // load Prior(x) into al + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "subl %%ecx, %%eax \n\t" // subtract Prior(x-bpp) + "movl %%eax, _patemp \n\t" // Save pav for later use + "xorl %%eax, %%eax \n\t" + // pbv = p - b = (a + b - c) - b = a - c + "movb (%%edi,%%edx,), %%al \n\t" // load Raw(x-bpp) into al + "subl %%ecx, %%eax \n\t" // subtract Prior(x-bpp) + "movl %%eax, %%ecx \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "addl _patemp, %%eax \n\t" // pcv = pav + pbv + // pc = abs(pcv) + "testl $0x80000000, %%eax \n\t" + "jz paeth_pca \n\t" + "negl %%eax \n\t" // reverse sign of neg values + + "paeth_pca: \n\t" + "movl %%eax, _pctemp \n\t" // save pc for later use + // pb = abs(pbv) + "testl $0x80000000, %%ecx \n\t" + "jz paeth_pba \n\t" + "negl %%ecx \n\t" // reverse sign of neg values + + "paeth_pba: \n\t" + "movl %%ecx, _pbtemp \n\t" // save pb for later use + // pa = abs(pav) + "movl _patemp, %%eax \n\t" + "testl $0x80000000, %%eax \n\t" + "jz paeth_paa \n\t" + "negl %%eax \n\t" // reverse sign of neg values + + "paeth_paa: \n\t" + "movl %%eax, _patemp \n\t" // save pa for later use + // test if pa <= pb + "cmpl %%ecx, %%eax \n\t" + "jna paeth_abb \n\t" + // pa > pb; now test if pb <= pc + "cmpl _pctemp, %%ecx \n\t" + "jna paeth_bbc \n\t" + // pb > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "jmp paeth_paeth \n\t" + + "paeth_bbc: \n\t" + // pb <= pc; Raw(x) = Paeth(x) + Prior(x) + "movb (%%esi,%%ebx,), %%cl \n\t" // load Prior(x) into cl + "jmp paeth_paeth \n\t" + + "paeth_abb: \n\t" + // pa <= pb; now test if pa <= pc + "cmpl _pctemp, %%eax \n\t" + "jna paeth_abc \n\t" + // pa > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "jmp paeth_paeth \n\t" + + "paeth_abc: \n\t" + // pa <= pc; Raw(x) = Paeth(x) + Raw(x-bpp) + "movb (%%edi,%%edx,), %%cl \n\t" // load Raw(x-bpp) into cl + + "paeth_paeth: \n\t" + "incl %%ebx \n\t" + "incl %%edx \n\t" + // Raw(x) = (Paeth(x) + Paeth_Predictor( a, b, c )) mod 256 + "addb %%cl, -1(%%edi,%%ebx,) \n\t" + "cmpl _dif, %%ebx \n\t" + "jb paeth_lp1 \n\t" + + "paeth_go: \n\t" + "movl _FullLength, %%ecx \n\t" + "movl %%ecx, %%eax \n\t" + "subl %%ebx, %%eax \n\t" // subtract alignment fix + "andl $0x00000007, %%eax \n\t" // calc bytes over mult of 8 + "subl %%eax, %%ecx \n\t" // drop over bytes from original length + "movl %%ecx, _MMXLength \n\t" +#ifdef __PIC__ + "popl %%ebx \n\t" // restore index to Global Offset Table +#endif + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "0" (bpp), // ecx // input regs + "1" (prev_row), // esi + "2" (row) // edi + + : "%eax", "%edx" // clobber list +#ifndef __PIC__ + , "%ebx" +#endif + ); + + // now do the math for the rest of the row + switch (bpp) + { + case 3: + { + _ActiveMask.use = 0x0000000000ffffffLL; + _ActiveMaskEnd.use = 0xffff000000000000LL; + _ShiftBpp.use = 24; // == bpp(3) * 8 + _ShiftRem.use = 40; // == 64 - 24 + + __asm__ __volatile__ ( + "movl _dif, %%ecx \n\t" +// preload "movl row, %%edi \n\t" +// preload "movl prev_row, %%esi \n\t" + "pxor %%mm0, %%mm0 \n\t" + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%ecx,), %%mm1 \n\t" + "paeth_3lp: \n\t" + "psrlq _ShiftRem, %%mm1 \n\t" // shift last 3 bytes to 1st + // 3 bytes + "movq (%%esi,%%ecx,), %%mm2 \n\t" // load b=Prior(x) + "punpcklbw %%mm0, %%mm1 \n\t" // unpack High bytes of a + "movq -8(%%esi,%%ecx,), %%mm3 \n\t" // prep c=Prior(x-bpp) bytes + "punpcklbw %%mm0, %%mm2 \n\t" // unpack High bytes of b + "psrlq _ShiftRem, %%mm3 \n\t" // shift last 3 bytes to 1st + // 3 bytes + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + "punpcklbw %%mm0, %%mm3 \n\t" // unpack High bytes of c + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + "psubw %%mm3, %%mm4 \n\t" + "pxor %%mm7, %%mm7 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "movq %%mm4, %%mm6 \n\t" + "psubw %%mm3, %%mm5 \n\t" + + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm4, %%mm0 \n\t" // create mask pav bytes < 0 + "paddw %%mm5, %%mm6 \n\t" + "pand %%mm4, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "pcmpgtw %%mm5, %%mm7 \n\t" // create mask pbv bytes < 0 + "psubw %%mm0, %%mm4 \n\t" + "pand %%mm5, %%mm7 \n\t" // only pbv bytes < 0 in mm0 + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm7, %%mm5 \n\t" + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "pxor %%mm1, %%mm1 \n\t" + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "packuswb %%mm1, %%mm7 \n\t" + "movq (%%esi,%%ecx,), %%mm3 \n\t" // load c=Prior(x-bpp) + "pand _ActiveMask, %%mm7 \n\t" + "movq %%mm3, %%mm2 \n\t" // load b=Prior(x) step 1 + "paddb (%%edi,%%ecx,), %%mm7 \n\t" // add Paeth predictor with Raw(x) + "punpcklbw %%mm0, %%mm3 \n\t" // unpack High bytes of c + "movq %%mm7, (%%edi,%%ecx,) \n\t" // write back updated value + "movq %%mm7, %%mm1 \n\t" // now mm1 will be used as + // Raw(x-bpp) + // now do Paeth for 2nd set of bytes (3-5) + "psrlq _ShiftBpp, %%mm2 \n\t" // load b=Prior(x) step 2 + "punpcklbw %%mm0, %%mm1 \n\t" // unpack High bytes of a + "pxor %%mm7, %%mm7 \n\t" + "punpcklbw %%mm0, %%mm2 \n\t" // unpack High bytes of b + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + "psubw %%mm3, %%mm5 \n\t" + "psubw %%mm3, %%mm4 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = + // pav + pbv = pbv + pav + "movq %%mm5, %%mm6 \n\t" + "paddw %%mm4, %%mm6 \n\t" + + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm5, %%mm0 \n\t" // create mask pbv bytes < 0 + "pcmpgtw %%mm4, %%mm7 \n\t" // create mask pav bytes < 0 + "pand %%mm5, %%mm0 \n\t" // only pbv bytes < 0 in mm0 + "pand %%mm4, %%mm7 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm0, %%mm5 \n\t" + "psubw %%mm7, %%mm4 \n\t" + "psubw %%mm0, %%mm5 \n\t" + "psubw %%mm7, %%mm4 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "movq (%%esi,%%ecx,), %%mm2 \n\t" // load b=Prior(x) + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "pxor %%mm1, %%mm1 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "packuswb %%mm1, %%mm7 \n\t" + "movq %%mm2, %%mm3 \n\t" // load c=Prior(x-bpp) step 1 + "pand _ActiveMask, %%mm7 \n\t" + "punpckhbw %%mm0, %%mm2 \n\t" // unpack High bytes of b + "psllq _ShiftBpp, %%mm7 \n\t" // shift bytes to 2nd group of + // 3 bytes + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + "paddb (%%edi,%%ecx,), %%mm7 \n\t" // add Paeth predictor with Raw(x) + "psllq _ShiftBpp, %%mm3 \n\t" // load c=Prior(x-bpp) step 2 + "movq %%mm7, (%%edi,%%ecx,) \n\t" // write back updated value + "movq %%mm7, %%mm1 \n\t" + "punpckhbw %%mm0, %%mm3 \n\t" // unpack High bytes of c + "psllq _ShiftBpp, %%mm1 \n\t" // shift bytes + // now mm1 will be used as Raw(x-bpp) + // now do Paeth for 3rd, and final, set of bytes (6-7) + "pxor %%mm7, %%mm7 \n\t" + "punpckhbw %%mm0, %%mm1 \n\t" // unpack High bytes of a + "psubw %%mm3, %%mm4 \n\t" + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "movq %%mm4, %%mm6 \n\t" + "psubw %%mm3, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "paddw %%mm5, %%mm6 \n\t" + + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm4, %%mm0 \n\t" // create mask pav bytes < 0 + "pcmpgtw %%mm5, %%mm7 \n\t" // create mask pbv bytes < 0 + "pand %%mm4, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "pand %%mm5, %%mm7 \n\t" // only pbv bytes < 0 in mm0 + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm1, %%mm1 \n\t" + "packuswb %%mm7, %%mm1 \n\t" + // step ecx to next set of 8 bytes and repeat loop til done + "addl $8, %%ecx \n\t" + "pand _ActiveMaskEnd, %%mm1 \n\t" + "paddb -8(%%edi,%%ecx,), %%mm1 \n\t" // add Paeth predictor with + // Raw(x) + + "cmpl _MMXLength, %%ecx \n\t" + "pxor %%mm0, %%mm0 \n\t" // pxor does not affect flags + "movq %%mm1, -8(%%edi,%%ecx,) \n\t" // write back updated value + // mm1 will be used as Raw(x-bpp) next loop + // mm3 ready to be used as Prior(x-bpp) next loop + "jb paeth_3lp \n\t" + + : "=S" (dummy_value_S), // output regs (dummy) + "=D" (dummy_value_D) + + : "0" (prev_row), // esi // input regs + "1" (row) // edi + + : "%ecx" // clobber list +#if 0 /* %mm0, ..., %mm7 not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; // end 3 bpp + + case 6: + //case 7: // GRR BOGUS + //case 5: // GRR BOGUS + { + _ActiveMask.use = 0x00000000ffffffffLL; + _ActiveMask2.use = 0xffffffff00000000LL; + _ShiftBpp.use = bpp << 3; // == bpp * 8 + _ShiftRem.use = 64 - _ShiftBpp.use; + + __asm__ __volatile__ ( + "movl _dif, %%ecx \n\t" +// preload "movl row, %%edi \n\t" +// preload "movl prev_row, %%esi \n\t" + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%ecx,), %%mm1 \n\t" + "pxor %%mm0, %%mm0 \n\t" + + "paeth_6lp: \n\t" + // must shift to position Raw(x-bpp) data + "psrlq _ShiftRem, %%mm1 \n\t" + // do first set of 4 bytes + "movq -8(%%esi,%%ecx,), %%mm3 \n\t" // read c=Prior(x-bpp) bytes + "punpcklbw %%mm0, %%mm1 \n\t" // unpack Low bytes of a + "movq (%%esi,%%ecx,), %%mm2 \n\t" // load b=Prior(x) + "punpcklbw %%mm0, %%mm2 \n\t" // unpack Low bytes of b + // must shift to position Prior(x-bpp) data + "psrlq _ShiftRem, %%mm3 \n\t" + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + "punpcklbw %%mm0, %%mm3 \n\t" // unpack Low bytes of c + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + "psubw %%mm3, %%mm4 \n\t" + "pxor %%mm7, %%mm7 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "movq %%mm4, %%mm6 \n\t" + "psubw %%mm3, %%mm5 \n\t" + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm4, %%mm0 \n\t" // create mask pav bytes < 0 + "paddw %%mm5, %%mm6 \n\t" + "pand %%mm4, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "pcmpgtw %%mm5, %%mm7 \n\t" // create mask pbv bytes < 0 + "psubw %%mm0, %%mm4 \n\t" + "pand %%mm5, %%mm7 \n\t" // only pbv bytes < 0 in mm0 + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm7, %%mm5 \n\t" + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "pxor %%mm1, %%mm1 \n\t" + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "packuswb %%mm1, %%mm7 \n\t" + "movq -8(%%esi,%%ecx,), %%mm3 \n\t" // load c=Prior(x-bpp) + "pand _ActiveMask, %%mm7 \n\t" + "psrlq _ShiftRem, %%mm3 \n\t" + "movq (%%esi,%%ecx,), %%mm2 \n\t" // load b=Prior(x) step 1 + "paddb (%%edi,%%ecx,), %%mm7 \n\t" // add Paeth predictor and Raw(x) + "movq %%mm2, %%mm6 \n\t" + "movq %%mm7, (%%edi,%%ecx,) \n\t" // write back updated value + "movq -8(%%edi,%%ecx,), %%mm1 \n\t" + "psllq _ShiftBpp, %%mm6 \n\t" + "movq %%mm7, %%mm5 \n\t" + "psrlq _ShiftRem, %%mm1 \n\t" + "por %%mm6, %%mm3 \n\t" + "psllq _ShiftBpp, %%mm5 \n\t" + "punpckhbw %%mm0, %%mm3 \n\t" // unpack High bytes of c + "por %%mm5, %%mm1 \n\t" + // do second set of 4 bytes + "punpckhbw %%mm0, %%mm2 \n\t" // unpack High bytes of b + "punpckhbw %%mm0, %%mm1 \n\t" // unpack High bytes of a + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + "psubw %%mm3, %%mm4 \n\t" + "pxor %%mm7, %%mm7 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "movq %%mm4, %%mm6 \n\t" + "psubw %%mm3, %%mm5 \n\t" + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm4, %%mm0 \n\t" // create mask pav bytes < 0 + "paddw %%mm5, %%mm6 \n\t" + "pand %%mm4, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "pcmpgtw %%mm5, %%mm7 \n\t" // create mask pbv bytes < 0 + "psubw %%mm0, %%mm4 \n\t" + "pand %%mm5, %%mm7 \n\t" // only pbv bytes < 0 in mm0 + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm7, %%mm5 \n\t" + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "pxor %%mm1, %%mm1 \n\t" + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "pxor %%mm1, %%mm1 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm0, %%mm0 \n\t" + // step ecx to next set of 8 bytes and repeat loop til done + "addl $8, %%ecx \n\t" + "packuswb %%mm7, %%mm1 \n\t" + "paddb -8(%%edi,%%ecx,), %%mm1 \n\t" // add Paeth predictor with Raw(x) + "cmpl _MMXLength, %%ecx \n\t" + "movq %%mm1, -8(%%edi,%%ecx,) \n\t" // write back updated value + // mm1 will be used as Raw(x-bpp) next loop + "jb paeth_6lp \n\t" + + : "=S" (dummy_value_S), // output regs (dummy) + "=D" (dummy_value_D) + + : "0" (prev_row), // esi // input regs + "1" (row) // edi + + : "%ecx" // clobber list +#if 0 /* %mm0, ..., %mm7 not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; // end 6 bpp + + case 4: + { + _ActiveMask.use = 0x00000000ffffffffLL; + + __asm__ __volatile__ ( + "movl _dif, %%ecx \n\t" +// preload "movl row, %%edi \n\t" +// preload "movl prev_row, %%esi \n\t" + "pxor %%mm0, %%mm0 \n\t" + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%ecx,), %%mm1 \n\t" // only time should need to read + // a=Raw(x-bpp) bytes + "paeth_4lp: \n\t" + // do first set of 4 bytes + "movq -8(%%esi,%%ecx,), %%mm3 \n\t" // read c=Prior(x-bpp) bytes + "punpckhbw %%mm0, %%mm1 \n\t" // unpack Low bytes of a + "movq (%%esi,%%ecx,), %%mm2 \n\t" // load b=Prior(x) + "punpcklbw %%mm0, %%mm2 \n\t" // unpack High bytes of b + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + "punpckhbw %%mm0, %%mm3 \n\t" // unpack High bytes of c + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + "psubw %%mm3, %%mm4 \n\t" + "pxor %%mm7, %%mm7 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "movq %%mm4, %%mm6 \n\t" + "psubw %%mm3, %%mm5 \n\t" + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm4, %%mm0 \n\t" // create mask pav bytes < 0 + "paddw %%mm5, %%mm6 \n\t" + "pand %%mm4, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "pcmpgtw %%mm5, %%mm7 \n\t" // create mask pbv bytes < 0 + "psubw %%mm0, %%mm4 \n\t" + "pand %%mm5, %%mm7 \n\t" // only pbv bytes < 0 in mm0 + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm7, %%mm5 \n\t" + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "pxor %%mm1, %%mm1 \n\t" + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "packuswb %%mm1, %%mm7 \n\t" + "movq (%%esi,%%ecx,), %%mm3 \n\t" // load c=Prior(x-bpp) + "pand _ActiveMask, %%mm7 \n\t" + "movq %%mm3, %%mm2 \n\t" // load b=Prior(x) step 1 + "paddb (%%edi,%%ecx,), %%mm7 \n\t" // add Paeth predictor with Raw(x) + "punpcklbw %%mm0, %%mm3 \n\t" // unpack High bytes of c + "movq %%mm7, (%%edi,%%ecx,) \n\t" // write back updated value + "movq %%mm7, %%mm1 \n\t" // now mm1 will be used as Raw(x-bpp) + // do second set of 4 bytes + "punpckhbw %%mm0, %%mm2 \n\t" // unpack Low bytes of b + "punpcklbw %%mm0, %%mm1 \n\t" // unpack Low bytes of a + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + "psubw %%mm3, %%mm4 \n\t" + "pxor %%mm7, %%mm7 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "movq %%mm4, %%mm6 \n\t" + "psubw %%mm3, %%mm5 \n\t" + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm4, %%mm0 \n\t" // create mask pav bytes < 0 + "paddw %%mm5, %%mm6 \n\t" + "pand %%mm4, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "pcmpgtw %%mm5, %%mm7 \n\t" // create mask pbv bytes < 0 + "psubw %%mm0, %%mm4 \n\t" + "pand %%mm5, %%mm7 \n\t" // only pbv bytes < 0 in mm0 + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm7, %%mm5 \n\t" + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "pxor %%mm1, %%mm1 \n\t" + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "pxor %%mm1, %%mm1 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm0, %%mm0 \n\t" + // step ecx to next set of 8 bytes and repeat loop til done + "addl $8, %%ecx \n\t" + "packuswb %%mm7, %%mm1 \n\t" + "paddb -8(%%edi,%%ecx,), %%mm1 \n\t" // add predictor with Raw(x) + "cmpl _MMXLength, %%ecx \n\t" + "movq %%mm1, -8(%%edi,%%ecx,) \n\t" // write back updated value + // mm1 will be used as Raw(x-bpp) next loop + "jb paeth_4lp \n\t" + + : "=S" (dummy_value_S), // output regs (dummy) + "=D" (dummy_value_D) + + : "0" (prev_row), // esi // input regs + "1" (row) // edi + + : "%ecx" // clobber list +#if 0 /* %mm0, ..., %mm7 not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; // end 4 bpp + + case 8: // bpp == 8 + { + _ActiveMask.use = 0x00000000ffffffffLL; + + __asm__ __volatile__ ( + "movl _dif, %%ecx \n\t" +// preload "movl row, %%edi \n\t" +// preload "movl prev_row, %%esi \n\t" + "pxor %%mm0, %%mm0 \n\t" + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%ecx,), %%mm1 \n\t" // only time should need to read + // a=Raw(x-bpp) bytes + "paeth_8lp: \n\t" + // do first set of 4 bytes + "movq -8(%%esi,%%ecx,), %%mm3 \n\t" // read c=Prior(x-bpp) bytes + "punpcklbw %%mm0, %%mm1 \n\t" // unpack Low bytes of a + "movq (%%esi,%%ecx,), %%mm2 \n\t" // load b=Prior(x) + "punpcklbw %%mm0, %%mm2 \n\t" // unpack Low bytes of b + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + "punpcklbw %%mm0, %%mm3 \n\t" // unpack Low bytes of c + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + "psubw %%mm3, %%mm4 \n\t" + "pxor %%mm7, %%mm7 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "movq %%mm4, %%mm6 \n\t" + "psubw %%mm3, %%mm5 \n\t" + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm4, %%mm0 \n\t" // create mask pav bytes < 0 + "paddw %%mm5, %%mm6 \n\t" + "pand %%mm4, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "pcmpgtw %%mm5, %%mm7 \n\t" // create mask pbv bytes < 0 + "psubw %%mm0, %%mm4 \n\t" + "pand %%mm5, %%mm7 \n\t" // only pbv bytes < 0 in mm0 + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm7, %%mm5 \n\t" + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "pxor %%mm1, %%mm1 \n\t" + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "packuswb %%mm1, %%mm7 \n\t" + "movq -8(%%esi,%%ecx,), %%mm3 \n\t" // read c=Prior(x-bpp) bytes + "pand _ActiveMask, %%mm7 \n\t" + "movq (%%esi,%%ecx,), %%mm2 \n\t" // load b=Prior(x) + "paddb (%%edi,%%ecx,), %%mm7 \n\t" // add Paeth predictor with Raw(x) + "punpckhbw %%mm0, %%mm3 \n\t" // unpack High bytes of c + "movq %%mm7, (%%edi,%%ecx,) \n\t" // write back updated value + "movq -8(%%edi,%%ecx,), %%mm1 \n\t" // read a=Raw(x-bpp) bytes + + // do second set of 4 bytes + "punpckhbw %%mm0, %%mm2 \n\t" // unpack High bytes of b + "punpckhbw %%mm0, %%mm1 \n\t" // unpack High bytes of a + // pav = p - a = (a + b - c) - a = b - c + "movq %%mm2, %%mm4 \n\t" + // pbv = p - b = (a + b - c) - b = a - c + "movq %%mm1, %%mm5 \n\t" + "psubw %%mm3, %%mm4 \n\t" + "pxor %%mm7, %%mm7 \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "movq %%mm4, %%mm6 \n\t" + "psubw %%mm3, %%mm5 \n\t" + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + "pcmpgtw %%mm4, %%mm0 \n\t" // create mask pav bytes < 0 + "paddw %%mm5, %%mm6 \n\t" + "pand %%mm4, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "pcmpgtw %%mm5, %%mm7 \n\t" // create mask pbv bytes < 0 + "psubw %%mm0, %%mm4 \n\t" + "pand %%mm5, %%mm7 \n\t" // only pbv bytes < 0 in mm0 + "psubw %%mm0, %%mm4 \n\t" + "psubw %%mm7, %%mm5 \n\t" + "pxor %%mm0, %%mm0 \n\t" + "pcmpgtw %%mm6, %%mm0 \n\t" // create mask pcv bytes < 0 + "pand %%mm6, %%mm0 \n\t" // only pav bytes < 0 in mm7 + "psubw %%mm7, %%mm5 \n\t" + "psubw %%mm0, %%mm6 \n\t" + // test pa <= pb + "movq %%mm4, %%mm7 \n\t" + "psubw %%mm0, %%mm6 \n\t" + "pcmpgtw %%mm5, %%mm7 \n\t" // pa > pb? + "movq %%mm7, %%mm0 \n\t" + // use mm7 mask to merge pa & pb + "pand %%mm7, %%mm5 \n\t" + // use mm0 mask copy to merge a & b + "pand %%mm0, %%mm2 \n\t" + "pandn %%mm4, %%mm7 \n\t" + "pandn %%mm1, %%mm0 \n\t" + "paddw %%mm5, %%mm7 \n\t" + "paddw %%mm2, %%mm0 \n\t" + // test ((pa <= pb)? pa:pb) <= pc + "pcmpgtw %%mm6, %%mm7 \n\t" // pab > pc? + "pxor %%mm1, %%mm1 \n\t" + "pand %%mm7, %%mm3 \n\t" + "pandn %%mm0, %%mm7 \n\t" + "pxor %%mm1, %%mm1 \n\t" + "paddw %%mm3, %%mm7 \n\t" + "pxor %%mm0, %%mm0 \n\t" + // step ecx to next set of 8 bytes and repeat loop til done + "addl $8, %%ecx \n\t" + "packuswb %%mm7, %%mm1 \n\t" + "paddb -8(%%edi,%%ecx,), %%mm1 \n\t" // add Paeth predictor with Raw(x) + "cmpl _MMXLength, %%ecx \n\t" + "movq %%mm1, -8(%%edi,%%ecx,) \n\t" // write back updated value + // mm1 will be used as Raw(x-bpp) next loop + "jb paeth_8lp \n\t" + + : "=S" (dummy_value_S), // output regs (dummy) + "=D" (dummy_value_D) + + : "0" (prev_row), // esi // input regs + "1" (row) // edi + + : "%ecx" // clobber list +#if 0 /* %mm0, ..., %mm7 not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; // end 8 bpp + + case 1: // bpp = 1 + case 2: // bpp = 2 + default: // bpp > 8 + { + __asm__ __volatile__ ( +#ifdef __PIC__ + "pushl %%ebx \n\t" // save Global Offset Table index +#endif + "movl _dif, %%ebx \n\t" + "cmpl _FullLength, %%ebx \n\t" + "jnb paeth_dend \n\t" + +// preload "movl row, %%edi \n\t" +// preload "movl prev_row, %%esi \n\t" + // do Paeth decode for remaining bytes + "movl %%ebx, %%edx \n\t" +// preload "subl bpp, %%edx \n\t" // (bpp is preloaded into ecx) + "subl %%ecx, %%edx \n\t" // edx = ebx - bpp + "xorl %%ecx, %%ecx \n\t" // zero ecx before using cl & cx + + "paeth_dlp: \n\t" + "xorl %%eax, %%eax \n\t" + // pav = p - a = (a + b - c) - a = b - c + "movb (%%esi,%%ebx,), %%al \n\t" // load Prior(x) into al + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "subl %%ecx, %%eax \n\t" // subtract Prior(x-bpp) + "movl %%eax, _patemp \n\t" // Save pav for later use + "xorl %%eax, %%eax \n\t" + // pbv = p - b = (a + b - c) - b = a - c + "movb (%%edi,%%edx,), %%al \n\t" // load Raw(x-bpp) into al + "subl %%ecx, %%eax \n\t" // subtract Prior(x-bpp) + "movl %%eax, %%ecx \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "addl _patemp, %%eax \n\t" // pcv = pav + pbv + // pc = abs(pcv) + "testl $0x80000000, %%eax \n\t" + "jz paeth_dpca \n\t" + "negl %%eax \n\t" // reverse sign of neg values + + "paeth_dpca: \n\t" + "movl %%eax, _pctemp \n\t" // save pc for later use + // pb = abs(pbv) + "testl $0x80000000, %%ecx \n\t" + "jz paeth_dpba \n\t" + "negl %%ecx \n\t" // reverse sign of neg values + + "paeth_dpba: \n\t" + "movl %%ecx, _pbtemp \n\t" // save pb for later use + // pa = abs(pav) + "movl _patemp, %%eax \n\t" + "testl $0x80000000, %%eax \n\t" + "jz paeth_dpaa \n\t" + "negl %%eax \n\t" // reverse sign of neg values + + "paeth_dpaa: \n\t" + "movl %%eax, _patemp \n\t" // save pa for later use + // test if pa <= pb + "cmpl %%ecx, %%eax \n\t" + "jna paeth_dabb \n\t" + // pa > pb; now test if pb <= pc + "cmpl _pctemp, %%ecx \n\t" + "jna paeth_dbbc \n\t" + // pb > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "jmp paeth_dpaeth \n\t" + + "paeth_dbbc: \n\t" + // pb <= pc; Raw(x) = Paeth(x) + Prior(x) + "movb (%%esi,%%ebx,), %%cl \n\t" // load Prior(x) into cl + "jmp paeth_dpaeth \n\t" + + "paeth_dabb: \n\t" + // pa <= pb; now test if pa <= pc + "cmpl _pctemp, %%eax \n\t" + "jna paeth_dabc \n\t" + // pa > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "jmp paeth_dpaeth \n\t" + + "paeth_dabc: \n\t" + // pa <= pc; Raw(x) = Paeth(x) + Raw(x-bpp) + "movb (%%edi,%%edx,), %%cl \n\t" // load Raw(x-bpp) into cl + + "paeth_dpaeth: \n\t" + "incl %%ebx \n\t" + "incl %%edx \n\t" + // Raw(x) = (Paeth(x) + Paeth_Predictor( a, b, c )) mod 256 + "addb %%cl, -1(%%edi,%%ebx,) \n\t" + "cmpl _FullLength, %%ebx \n\t" + "jb paeth_dlp \n\t" + + "paeth_dend: \n\t" +#ifdef __PIC__ + "popl %%ebx \n\t" // index to Global Offset Table +#endif + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "0" (bpp), // ecx // input regs + "1" (prev_row), // esi + "2" (row) // edi + + : "%eax", "%edx" // clobber list +#ifndef __PIC__ + , "%ebx" +#endif + ); + } + return; // No need to go further with this one + + } // end switch (bpp) + + __asm__ __volatile__ ( + // MMX acceleration complete; now do clean-up + // check if any remaining bytes left to decode +#ifdef __PIC__ + "pushl %%ebx \n\t" // save index to Global Offset Table +#endif + "movl _MMXLength, %%ebx \n\t" + "cmpl _FullLength, %%ebx \n\t" + "jnb paeth_end \n\t" +//pre "movl row, %%edi \n\t" +//pre "movl prev_row, %%esi \n\t" + // do Paeth decode for remaining bytes + "movl %%ebx, %%edx \n\t" +//pre "subl bpp, %%edx \n\t" // (bpp is preloaded into ecx) + "subl %%ecx, %%edx \n\t" // edx = ebx - bpp + "xorl %%ecx, %%ecx \n\t" // zero ecx before using cl & cx below + + "paeth_lp2: \n\t" + "xorl %%eax, %%eax \n\t" + // pav = p - a = (a + b - c) - a = b - c + "movb (%%esi,%%ebx,), %%al \n\t" // load Prior(x) into al + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "subl %%ecx, %%eax \n\t" // subtract Prior(x-bpp) + "movl %%eax, _patemp \n\t" // Save pav for later use + "xorl %%eax, %%eax \n\t" + // pbv = p - b = (a + b - c) - b = a - c + "movb (%%edi,%%edx,), %%al \n\t" // load Raw(x-bpp) into al + "subl %%ecx, %%eax \n\t" // subtract Prior(x-bpp) + "movl %%eax, %%ecx \n\t" + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + "addl _patemp, %%eax \n\t" // pcv = pav + pbv + // pc = abs(pcv) + "testl $0x80000000, %%eax \n\t" + "jz paeth_pca2 \n\t" + "negl %%eax \n\t" // reverse sign of neg values + + "paeth_pca2: \n\t" + "movl %%eax, _pctemp \n\t" // save pc for later use + // pb = abs(pbv) + "testl $0x80000000, %%ecx \n\t" + "jz paeth_pba2 \n\t" + "negl %%ecx \n\t" // reverse sign of neg values + + "paeth_pba2: \n\t" + "movl %%ecx, _pbtemp \n\t" // save pb for later use + // pa = abs(pav) + "movl _patemp, %%eax \n\t" + "testl $0x80000000, %%eax \n\t" + "jz paeth_paa2 \n\t" + "negl %%eax \n\t" // reverse sign of neg values + + "paeth_paa2: \n\t" + "movl %%eax, _patemp \n\t" // save pa for later use + // test if pa <= pb + "cmpl %%ecx, %%eax \n\t" + "jna paeth_abb2 \n\t" + // pa > pb; now test if pb <= pc + "cmpl _pctemp, %%ecx \n\t" + "jna paeth_bbc2 \n\t" + // pb > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "jmp paeth_paeth2 \n\t" + + "paeth_bbc2: \n\t" + // pb <= pc; Raw(x) = Paeth(x) + Prior(x) + "movb (%%esi,%%ebx,), %%cl \n\t" // load Prior(x) into cl + "jmp paeth_paeth2 \n\t" + + "paeth_abb2: \n\t" + // pa <= pb; now test if pa <= pc + "cmpl _pctemp, %%eax \n\t" + "jna paeth_abc2 \n\t" + // pa > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + "movb (%%esi,%%edx,), %%cl \n\t" // load Prior(x-bpp) into cl + "jmp paeth_paeth2 \n\t" + + "paeth_abc2: \n\t" + // pa <= pc; Raw(x) = Paeth(x) + Raw(x-bpp) + "movb (%%edi,%%edx,), %%cl \n\t" // load Raw(x-bpp) into cl + + "paeth_paeth2: \n\t" + "incl %%ebx \n\t" + "incl %%edx \n\t" + // Raw(x) = (Paeth(x) + Paeth_Predictor( a, b, c )) mod 256 + "addb %%cl, -1(%%edi,%%ebx,) \n\t" + "cmpl _FullLength, %%ebx \n\t" + "jb paeth_lp2 \n\t" + + "paeth_end: \n\t" + "EMMS \n\t" // end MMX; prep for poss. FP instrs. +#ifdef __PIC__ + "popl %%ebx \n\t" // restore index to Global Offset Table +#endif + + : "=c" (dummy_value_c), // output regs (dummy) + "=S" (dummy_value_S), + "=D" (dummy_value_D) + + : "0" (bpp), // ecx // input regs + "1" (prev_row), // esi + "2" (row) // edi + + : "%eax", "%edx" // clobber list (no input regs!) +#ifndef __PIC__ + , "%ebx" +#endif + ); + +} /* end png_read_filter_row_mmx_paeth() */ +#endif + + + + +#ifdef PNG_THREAD_UNSAFE_OK +//===========================================================================// +// // +// P N G _ R E A D _ F I L T E R _ R O W _ M M X _ S U B // +// // +//===========================================================================// + +// Optimized code for PNG Sub filter decoder + +static void /* PRIVATE */ +png_read_filter_row_mmx_sub(png_row_infop row_info, png_bytep row) +{ + int bpp; + int dummy_value_a; + int dummy_value_D; + + bpp = (row_info->pixel_depth + 7) >> 3; // calc number of bytes per pixel + _FullLength = row_info->rowbytes - bpp; // number of bytes to filter + + __asm__ __volatile__ ( +//pre "movl row, %%edi \n\t" + "movl %%edi, %%esi \n\t" // lp = row +//pre "movl bpp, %%eax \n\t" + "addl %%eax, %%edi \n\t" // rp = row + bpp +//irr "xorl %%eax, %%eax \n\t" + // get # of bytes to alignment + "movl %%edi, _dif \n\t" // take start of row + "addl $0xf, _dif \n\t" // add 7 + 8 to incr past + // alignment boundary + "xorl %%ecx, %%ecx \n\t" + "andl $0xfffffff8, _dif \n\t" // mask to alignment boundary + "subl %%edi, _dif \n\t" // subtract from start ==> value + "jz sub_go \n\t" // ecx at alignment + + "sub_lp1: \n\t" // fix alignment + "movb (%%esi,%%ecx,), %%al \n\t" + "addb %%al, (%%edi,%%ecx,) \n\t" + "incl %%ecx \n\t" + "cmpl _dif, %%ecx \n\t" + "jb sub_lp1 \n\t" + + "sub_go: \n\t" + "movl _FullLength, %%eax \n\t" + "movl %%eax, %%edx \n\t" + "subl %%ecx, %%edx \n\t" // subtract alignment fix + "andl $0x00000007, %%edx \n\t" // calc bytes over mult of 8 + "subl %%edx, %%eax \n\t" // drop over bytes from length + "movl %%eax, _MMXLength \n\t" + + : "=a" (dummy_value_a), // 0 // output regs (dummy) + "=D" (dummy_value_D) // 1 + + : "0" (bpp), // eax // input regs + "1" (row) // edi + + : "%esi", "%ecx", "%edx" // clobber list + +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + + // now do the math for the rest of the row + switch (bpp) + { + case 3: + { + _ActiveMask.use = 0x0000ffffff000000LL; + _ShiftBpp.use = 24; // == 3 * 8 + _ShiftRem.use = 40; // == 64 - 24 + + __asm__ __volatile__ ( +// preload "movl row, %%edi \n\t" + "movq _ActiveMask, %%mm7 \n\t" // load _ActiveMask for 2nd + // active byte group + "movl %%edi, %%esi \n\t" // lp = row +// preload "movl bpp, %%eax \n\t" + "addl %%eax, %%edi \n\t" // rp = row + bpp + "movq %%mm7, %%mm6 \n\t" + "movl _dif, %%edx \n\t" + "psllq _ShiftBpp, %%mm6 \n\t" // move mask in mm6 to cover + // 3rd active byte group + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%edx,), %%mm1 \n\t" + + "sub_3lp: \n\t" // shift data for adding first + "psrlq _ShiftRem, %%mm1 \n\t" // bpp bytes (no need for mask; + // shift clears inactive bytes) + // add 1st active group + "movq (%%edi,%%edx,), %%mm0 \n\t" + "paddb %%mm1, %%mm0 \n\t" + + // add 2nd active group + "movq %%mm0, %%mm1 \n\t" // mov updated Raws to mm1 + "psllq _ShiftBpp, %%mm1 \n\t" // shift data to pos. correctly + "pand %%mm7, %%mm1 \n\t" // mask to use 2nd active group + "paddb %%mm1, %%mm0 \n\t" + + // add 3rd active group + "movq %%mm0, %%mm1 \n\t" // mov updated Raws to mm1 + "psllq _ShiftBpp, %%mm1 \n\t" // shift data to pos. correctly + "pand %%mm6, %%mm1 \n\t" // mask to use 3rd active group + "addl $8, %%edx \n\t" + "paddb %%mm1, %%mm0 \n\t" + + "cmpl _MMXLength, %%edx \n\t" + "movq %%mm0, -8(%%edi,%%edx,) \n\t" // write updated Raws to array + "movq %%mm0, %%mm1 \n\t" // prep 1st add at top of loop + "jb sub_3lp \n\t" + + : "=a" (dummy_value_a), // 0 // output regs (dummy) + "=D" (dummy_value_D) // 1 + + : "0" (bpp), // eax // input regs + "1" (row) // edi + + : "%edx", "%esi" // clobber list +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm6", "%mm7" +#endif + ); + } + break; + + case 1: + { + __asm__ __volatile__ ( + "movl _dif, %%edx \n\t" +// preload "movl row, %%edi \n\t" + "cmpl _FullLength, %%edx \n\t" + "jnb sub_1end \n\t" + "movl %%edi, %%esi \n\t" // lp = row + "xorl %%eax, %%eax \n\t" +// preload "movl bpp, %%eax \n\t" + "addl %%eax, %%edi \n\t" // rp = row + bpp + + "sub_1lp: \n\t" + "movb (%%esi,%%edx,), %%al \n\t" + "addb %%al, (%%edi,%%edx,) \n\t" + "incl %%edx \n\t" + "cmpl _FullLength, %%edx \n\t" + "jb sub_1lp \n\t" + + "sub_1end: \n\t" + + : "=a" (dummy_value_a), // 0 // output regs (dummy) + "=D" (dummy_value_D) // 1 + + : "0" (bpp), // eax // input regs + "1" (row) // edi + + : "%edx", "%esi" // clobber list + ); + } + return; + + case 6: + case 4: + //case 7: // GRR BOGUS + //case 5: // GRR BOGUS + { + _ShiftBpp.use = bpp << 3; + _ShiftRem.use = 64 - _ShiftBpp.use; + + __asm__ __volatile__ ( +// preload "movl row, %%edi \n\t" + "movl _dif, %%edx \n\t" + "movl %%edi, %%esi \n\t" // lp = row +// preload "movl bpp, %%eax \n\t" + "addl %%eax, %%edi \n\t" // rp = row + bpp + + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%edx,), %%mm1 \n\t" + + "sub_4lp: \n\t" // shift data for adding first + "psrlq _ShiftRem, %%mm1 \n\t" // bpp bytes (no need for mask; + // shift clears inactive bytes) + "movq (%%edi,%%edx,), %%mm0 \n\t" + "paddb %%mm1, %%mm0 \n\t" + + // add 2nd active group + "movq %%mm0, %%mm1 \n\t" // mov updated Raws to mm1 + "psllq _ShiftBpp, %%mm1 \n\t" // shift data to pos. correctly + "addl $8, %%edx \n\t" + "paddb %%mm1, %%mm0 \n\t" + + "cmpl _MMXLength, %%edx \n\t" + "movq %%mm0, -8(%%edi,%%edx,) \n\t" + "movq %%mm0, %%mm1 \n\t" // prep 1st add at top of loop + "jb sub_4lp \n\t" + + : "=a" (dummy_value_a), // 0 // output regs (dummy) + "=D" (dummy_value_D) // 1 + + : "0" (bpp), // eax // input regs + "1" (row) // edi + + : "%edx", "%esi" // clobber list +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1" +#endif + ); + } + break; + + case 2: + { + _ActiveMask.use = 0x00000000ffff0000LL; + _ShiftBpp.use = 16; // == 2 * 8 + _ShiftRem.use = 48; // == 64 - 16 + + __asm__ __volatile__ ( + "movq _ActiveMask, %%mm7 \n\t" // load _ActiveMask for 2nd + // active byte group + "movl _dif, %%edx \n\t" + "movq %%mm7, %%mm6 \n\t" +// preload "movl row, %%edi \n\t" + "psllq _ShiftBpp, %%mm6 \n\t" // move mask in mm6 to cover + // 3rd active byte group + "movl %%edi, %%esi \n\t" // lp = row + "movq %%mm6, %%mm5 \n\t" +// preload "movl bpp, %%eax \n\t" + "addl %%eax, %%edi \n\t" // rp = row + bpp + "psllq _ShiftBpp, %%mm5 \n\t" // move mask in mm5 to cover + // 4th active byte group + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%edx,), %%mm1 \n\t" + + "sub_2lp: \n\t" // shift data for adding first + "psrlq _ShiftRem, %%mm1 \n\t" // bpp bytes (no need for mask; + // shift clears inactive bytes) + // add 1st active group + "movq (%%edi,%%edx,), %%mm0 \n\t" + "paddb %%mm1, %%mm0 \n\t" + + // add 2nd active group + "movq %%mm0, %%mm1 \n\t" // mov updated Raws to mm1 + "psllq _ShiftBpp, %%mm1 \n\t" // shift data to pos. correctly + "pand %%mm7, %%mm1 \n\t" // mask to use 2nd active group + "paddb %%mm1, %%mm0 \n\t" + + // add 3rd active group + "movq %%mm0, %%mm1 \n\t" // mov updated Raws to mm1 + "psllq _ShiftBpp, %%mm1 \n\t" // shift data to pos. correctly + "pand %%mm6, %%mm1 \n\t" // mask to use 3rd active group + "paddb %%mm1, %%mm0 \n\t" + + // add 4th active group + "movq %%mm0, %%mm1 \n\t" // mov updated Raws to mm1 + "psllq _ShiftBpp, %%mm1 \n\t" // shift data to pos. correctly + "pand %%mm5, %%mm1 \n\t" // mask to use 4th active group + "addl $8, %%edx \n\t" + "paddb %%mm1, %%mm0 \n\t" + "cmpl _MMXLength, %%edx \n\t" + "movq %%mm0, -8(%%edi,%%edx,) \n\t" // write updated Raws to array + "movq %%mm0, %%mm1 \n\t" // prep 1st add at top of loop + "jb sub_2lp \n\t" + + : "=a" (dummy_value_a), // 0 // output regs (dummy) + "=D" (dummy_value_D) // 1 + + : "0" (bpp), // eax // input regs + "1" (row) // edi + + : "%edx", "%esi" // clobber list +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; + + case 8: + { + __asm__ __volatile__ ( +// preload "movl row, %%edi \n\t" + "movl _dif, %%edx \n\t" + "movl %%edi, %%esi \n\t" // lp = row +// preload "movl bpp, %%eax \n\t" + "addl %%eax, %%edi \n\t" // rp = row + bpp + "movl _MMXLength, %%ecx \n\t" + + // prime the pump: load the first Raw(x-bpp) data set + "movq -8(%%edi,%%edx,), %%mm7 \n\t" + "andl $0x0000003f, %%ecx \n\t" // calc bytes over mult of 64 + + "sub_8lp: \n\t" + "movq (%%edi,%%edx,), %%mm0 \n\t" // load Sub(x) for 1st 8 bytes + "paddb %%mm7, %%mm0 \n\t" + "movq 8(%%edi,%%edx,), %%mm1 \n\t" // load Sub(x) for 2nd 8 bytes + "movq %%mm0, (%%edi,%%edx,) \n\t" // write Raw(x) for 1st 8 bytes + + // Now mm0 will be used as Raw(x-bpp) for the 2nd group of 8 bytes. + // This will be repeated for each group of 8 bytes with the 8th + // group being used as the Raw(x-bpp) for the 1st group of the + // next loop. + + "paddb %%mm0, %%mm1 \n\t" + "movq 16(%%edi,%%edx,), %%mm2 \n\t" // load Sub(x) for 3rd 8 bytes + "movq %%mm1, 8(%%edi,%%edx,) \n\t" // write Raw(x) for 2nd 8 bytes + "paddb %%mm1, %%mm2 \n\t" + "movq 24(%%edi,%%edx,), %%mm3 \n\t" // load Sub(x) for 4th 8 bytes + "movq %%mm2, 16(%%edi,%%edx,) \n\t" // write Raw(x) for 3rd 8 bytes + "paddb %%mm2, %%mm3 \n\t" + "movq 32(%%edi,%%edx,), %%mm4 \n\t" // load Sub(x) for 5th 8 bytes + "movq %%mm3, 24(%%edi,%%edx,) \n\t" // write Raw(x) for 4th 8 bytes + "paddb %%mm3, %%mm4 \n\t" + "movq 40(%%edi,%%edx,), %%mm5 \n\t" // load Sub(x) for 6th 8 bytes + "movq %%mm4, 32(%%edi,%%edx,) \n\t" // write Raw(x) for 5th 8 bytes + "paddb %%mm4, %%mm5 \n\t" + "movq 48(%%edi,%%edx,), %%mm6 \n\t" // load Sub(x) for 7th 8 bytes + "movq %%mm5, 40(%%edi,%%edx,) \n\t" // write Raw(x) for 6th 8 bytes + "paddb %%mm5, %%mm6 \n\t" + "movq 56(%%edi,%%edx,), %%mm7 \n\t" // load Sub(x) for 8th 8 bytes + "movq %%mm6, 48(%%edi,%%edx,) \n\t" // write Raw(x) for 7th 8 bytes + "addl $64, %%edx \n\t" + "paddb %%mm6, %%mm7 \n\t" + "cmpl %%ecx, %%edx \n\t" + "movq %%mm7, -8(%%edi,%%edx,) \n\t" // write Raw(x) for 8th 8 bytes + "jb sub_8lp \n\t" + + "cmpl _MMXLength, %%edx \n\t" + "jnb sub_8lt8 \n\t" + + "sub_8lpA: \n\t" + "movq (%%edi,%%edx,), %%mm0 \n\t" + "addl $8, %%edx \n\t" + "paddb %%mm7, %%mm0 \n\t" + "cmpl _MMXLength, %%edx \n\t" + "movq %%mm0, -8(%%edi,%%edx,) \n\t" // -8 to offset early addl edx + "movq %%mm0, %%mm7 \n\t" // move calculated Raw(x) data + // to mm1 to be new Raw(x-bpp) + // for next loop + "jb sub_8lpA \n\t" + + "sub_8lt8: \n\t" + + : "=a" (dummy_value_a), // 0 // output regs (dummy) + "=D" (dummy_value_D) // 1 + + : "0" (bpp), // eax // input regs + "1" (row) // edi + + : "%ecx", "%edx", "%esi" // clobber list +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + } + break; + + default: // bpp greater than 8 bytes GRR BOGUS + { + __asm__ __volatile__ ( + "movl _dif, %%edx \n\t" +// preload "movl row, %%edi \n\t" + "movl %%edi, %%esi \n\t" // lp = row +// preload "movl bpp, %%eax \n\t" + "addl %%eax, %%edi \n\t" // rp = row + bpp + + "sub_Alp: \n\t" + "movq (%%edi,%%edx,), %%mm0 \n\t" + "movq (%%esi,%%edx,), %%mm1 \n\t" + "addl $8, %%edx \n\t" + "paddb %%mm1, %%mm0 \n\t" + "cmpl _MMXLength, %%edx \n\t" + "movq %%mm0, -8(%%edi,%%edx,) \n\t" // mov does not affect flags; + // -8 to offset addl edx + "jb sub_Alp \n\t" + + : "=a" (dummy_value_a), // 0 // output regs (dummy) + "=D" (dummy_value_D) // 1 + + : "0" (bpp), // eax // input regs + "1" (row) // edi + + : "%edx", "%esi" // clobber list +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1" +#endif + ); + } + break; + + } // end switch (bpp) + + __asm__ __volatile__ ( + "movl _MMXLength, %%edx \n\t" +//pre "movl row, %%edi \n\t" + "cmpl _FullLength, %%edx \n\t" + "jnb sub_end \n\t" + + "movl %%edi, %%esi \n\t" // lp = row +//pre "movl bpp, %%eax \n\t" + "addl %%eax, %%edi \n\t" // rp = row + bpp + "xorl %%eax, %%eax \n\t" + + "sub_lp2: \n\t" + "movb (%%esi,%%edx,), %%al \n\t" + "addb %%al, (%%edi,%%edx,) \n\t" + "incl %%edx \n\t" + "cmpl _FullLength, %%edx \n\t" + "jb sub_lp2 \n\t" + + "sub_end: \n\t" + "EMMS \n\t" // end MMX instructions + + : "=a" (dummy_value_a), // 0 // output regs (dummy) + "=D" (dummy_value_D) // 1 + + : "0" (bpp), // eax // input regs + "1" (row) // edi + + : "%edx", "%esi" // clobber list + ); + +} // end of png_read_filter_row_mmx_sub() +#endif + + + + +//===========================================================================// +// // +// P N G _ R E A D _ F I L T E R _ R O W _ M M X _ U P // +// // +//===========================================================================// + +// Optimized code for PNG Up filter decoder + +static void /* PRIVATE */ +png_read_filter_row_mmx_up(png_row_infop row_info, png_bytep row, + png_bytep prev_row) +{ + png_uint_32 len; + int dummy_value_d; // fix 'forbidden register 3 (dx) was spilled' error + int dummy_value_S; + int dummy_value_D; + + len = row_info->rowbytes; // number of bytes to filter + + __asm__ __volatile__ ( +//pre "movl row, %%edi \n\t" + // get # of bytes to alignment +#ifdef __PIC__ + "pushl %%ebx \n\t" +#endif + "movl %%edi, %%ecx \n\t" + "xorl %%ebx, %%ebx \n\t" + "addl $0x7, %%ecx \n\t" + "xorl %%eax, %%eax \n\t" + "andl $0xfffffff8, %%ecx \n\t" +//pre "movl prev_row, %%esi \n\t" + "subl %%edi, %%ecx \n\t" + "jz up_go \n\t" + + "up_lp1: \n\t" // fix alignment + "movb (%%edi,%%ebx,), %%al \n\t" + "addb (%%esi,%%ebx,), %%al \n\t" + "incl %%ebx \n\t" + "cmpl %%ecx, %%ebx \n\t" + "movb %%al, -1(%%edi,%%ebx,) \n\t" // mov does not affect flags; -1 to + "jb up_lp1 \n\t" // offset incl ebx + + "up_go: \n\t" +//pre "movl len, %%edx \n\t" + "movl %%edx, %%ecx \n\t" + "subl %%ebx, %%edx \n\t" // subtract alignment fix + "andl $0x0000003f, %%edx \n\t" // calc bytes over mult of 64 + "subl %%edx, %%ecx \n\t" // drop over bytes from length + + // unrolled loop - use all MMX registers and interleave to reduce + // number of branch instructions (loops) and reduce partial stalls + "up_loop: \n\t" + "movq (%%esi,%%ebx,), %%mm1 \n\t" + "movq (%%edi,%%ebx,), %%mm0 \n\t" + "movq 8(%%esi,%%ebx,), %%mm3 \n\t" + "paddb %%mm1, %%mm0 \n\t" + "movq 8(%%edi,%%ebx,), %%mm2 \n\t" + "movq %%mm0, (%%edi,%%ebx,) \n\t" + "paddb %%mm3, %%mm2 \n\t" + "movq 16(%%esi,%%ebx,), %%mm5 \n\t" + "movq %%mm2, 8(%%edi,%%ebx,) \n\t" + "movq 16(%%edi,%%ebx,), %%mm4 \n\t" + "movq 24(%%esi,%%ebx,), %%mm7 \n\t" + "paddb %%mm5, %%mm4 \n\t" + "movq 24(%%edi,%%ebx,), %%mm6 \n\t" + "movq %%mm4, 16(%%edi,%%ebx,) \n\t" + "paddb %%mm7, %%mm6 \n\t" + "movq 32(%%esi,%%ebx,), %%mm1 \n\t" + "movq %%mm6, 24(%%edi,%%ebx,) \n\t" + "movq 32(%%edi,%%ebx,), %%mm0 \n\t" + "movq 40(%%esi,%%ebx,), %%mm3 \n\t" + "paddb %%mm1, %%mm0 \n\t" + "movq 40(%%edi,%%ebx,), %%mm2 \n\t" + "movq %%mm0, 32(%%edi,%%ebx,) \n\t" + "paddb %%mm3, %%mm2 \n\t" + "movq 48(%%esi,%%ebx,), %%mm5 \n\t" + "movq %%mm2, 40(%%edi,%%ebx,) \n\t" + "movq 48(%%edi,%%ebx,), %%mm4 \n\t" + "movq 56(%%esi,%%ebx,), %%mm7 \n\t" + "paddb %%mm5, %%mm4 \n\t" + "movq 56(%%edi,%%ebx,), %%mm6 \n\t" + "movq %%mm4, 48(%%edi,%%ebx,) \n\t" + "addl $64, %%ebx \n\t" + "paddb %%mm7, %%mm6 \n\t" + "cmpl %%ecx, %%ebx \n\t" + "movq %%mm6, -8(%%edi,%%ebx,) \n\t" // (+56)movq does not affect flags; + "jb up_loop \n\t" // -8 to offset addl ebx + + "cmpl $0, %%edx \n\t" // test for bytes over mult of 64 + "jz up_end \n\t" + + "cmpl $8, %%edx \n\t" // test for less than 8 bytes + "jb up_lt8 \n\t" // [added by lcreeve@netins.net] + + "addl %%edx, %%ecx \n\t" + "andl $0x00000007, %%edx \n\t" // calc bytes over mult of 8 + "subl %%edx, %%ecx \n\t" // drop over bytes from length + "jz up_lt8 \n\t" + + "up_lpA: \n\t" // use MMX regs to update 8 bytes sim. + "movq (%%esi,%%ebx,), %%mm1 \n\t" + "movq (%%edi,%%ebx,), %%mm0 \n\t" + "addl $8, %%ebx \n\t" + "paddb %%mm1, %%mm0 \n\t" + "cmpl %%ecx, %%ebx \n\t" + "movq %%mm0, -8(%%edi,%%ebx,) \n\t" // movq does not affect flags; -8 to + "jb up_lpA \n\t" // offset add ebx + "cmpl $0, %%edx \n\t" // test for bytes over mult of 8 + "jz up_end \n\t" + + "up_lt8: \n\t" + "xorl %%eax, %%eax \n\t" + "addl %%edx, %%ecx \n\t" // move over byte count into counter + + "up_lp2: \n\t" // use x86 regs for remaining bytes + "movb (%%edi,%%ebx,), %%al \n\t" + "addb (%%esi,%%ebx,), %%al \n\t" + "incl %%ebx \n\t" + "cmpl %%ecx, %%ebx \n\t" + "movb %%al, -1(%%edi,%%ebx,) \n\t" // mov does not affect flags; -1 to + "jb up_lp2 \n\t" // offset inc ebx + + "up_end: \n\t" + "EMMS \n\t" // conversion of filtered row complete +#ifdef __PIC__ + "popl %%ebx \n\t" +#endif + + : "=d" (dummy_value_d), // 0 // output regs (dummy) + "=S" (dummy_value_S), // 1 + "=D" (dummy_value_D) // 2 + + : "0" (len), // edx // input regs + "1" (prev_row), // esi + "2" (row) // edi + + : "%eax", "%ecx" // clobber list (no input regs!) +#ifndef __PIC__ + , "%ebx" +#endif + +#if 0 /* MMX regs (%mm0, etc.) not supported by gcc 2.7.2.3 or egcs 1.1 */ + , "%mm0", "%mm1", "%mm2", "%mm3" + , "%mm4", "%mm5", "%mm6", "%mm7" +#endif + ); + +} // end of png_read_filter_row_mmx_up() + +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + + + + +/*===========================================================================*/ +/* */ +/* P N G _ R E A D _ F I L T E R _ R O W */ +/* */ +/*===========================================================================*/ + + +/* Optimized png_read_filter_row routines */ + +void /* PRIVATE */ +png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep + row, png_bytep prev_row, int filter) +{ +#ifdef PNG_DEBUG + char filnm[10]; +#endif + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) +/* GRR: these are superseded by png_ptr->asm_flags: */ +#define UseMMX_sub 1 // GRR: converted 20000730 +#define UseMMX_up 1 // GRR: converted 20000729 +#define UseMMX_avg 1 // GRR: converted 20000828 (+ 16-bit bugfix 20000916) +#define UseMMX_paeth 1 // GRR: converted 20000828 + + if (_mmx_supported == 2) { + /* this should have happened in png_init_mmx_flags() already */ +#if !defined(PNG_1_0_X) + png_warning(png_ptr, "asm_flags may not have been initialized"); +#endif + png_mmx_support(); + } +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + +#ifdef PNG_DEBUG + png_debug(1, "in png_read_filter_row (pnggccrd.c)\n"); + switch (filter) + { + case 0: sprintf(filnm, "none"); + break; + case 1: sprintf(filnm, "sub-%s", +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + (png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_SUB)? "MMX" : +#endif +#endif +"x86"); + break; + case 2: sprintf(filnm, "up-%s", +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED +#if !defined(PNG_1_0_X) + (png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_UP)? "MMX" : +#endif +#endif + "x86"); + break; + case 3: sprintf(filnm, "avg-%s", +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + (png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_AVG)? "MMX" : +#endif +#endif + "x86"); + break; + case 4: sprintf(filnm, "Paeth-%s", +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + (png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_PAETH)? "MMX": +#endif +#endif +"x86"); + break; + default: sprintf(filnm, "unknw"); + break; + } + png_debug2(0, "row_number=%5ld, %5s, ", png_ptr->row_number, filnm); + png_debug1(0, "row=0x%08lx, ", (unsigned long)row); + png_debug2(0, "pixdepth=%2d, bytes=%d, ", (int)row_info->pixel_depth, + (int)((row_info->pixel_depth + 7) >> 3)); + png_debug1(0,"rowbytes=%8ld\n", row_info->rowbytes); +#endif /* PNG_DEBUG */ + + switch (filter) + { + case PNG_FILTER_VALUE_NONE: + break; + + case PNG_FILTER_VALUE_SUB: +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_SUB) && + (row_info->pixel_depth >= png_ptr->mmx_bitdepth_threshold) && + (row_info->rowbytes >= png_ptr->mmx_rowbytes_threshold)) +#else + if (_mmx_supported) +#endif + { + png_read_filter_row_mmx_sub(row_info, row); + } + else +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_bytep rp = row + bpp; + png_bytep lp = row; + + for (i = bpp; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff); + rp++; + } + } /* end !UseMMX_sub */ + break; + + case PNG_FILTER_VALUE_UP: +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_UP) && + (row_info->pixel_depth >= png_ptr->mmx_bitdepth_threshold) && + (row_info->rowbytes >= png_ptr->mmx_rowbytes_threshold)) +#else + if (_mmx_supported) +#endif + { + png_read_filter_row_mmx_up(row_info, row, prev_row); + } + else +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_bytep rp = row; + png_bytep pp = prev_row; + + for (i = 0; i < istop; ++i) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + } /* end !UseMMX_up */ + break; + + case PNG_FILTER_VALUE_AVG: +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_AVG) && + (row_info->pixel_depth >= png_ptr->mmx_bitdepth_threshold) && + (row_info->rowbytes >= png_ptr->mmx_rowbytes_threshold)) +#else + if (_mmx_supported) +#endif + { + png_read_filter_row_mmx_avg(row_info, row, prev_row); + } + else +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop = row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + + ((int)(*pp++) >> 1)) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + + ((int)(*pp++ + *lp++) >> 1)) & 0xff); + rp++; + } + } /* end !UseMMX_avg */ + break; + + case PNG_FILTER_VALUE_PAETH: +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_THREAD_UNSAFE_OK) +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_PAETH) && + (row_info->pixel_depth >= png_ptr->mmx_bitdepth_threshold) && + (row_info->rowbytes >= png_ptr->mmx_rowbytes_threshold)) +#else + if (_mmx_supported) +#endif + { + png_read_filter_row_mmx_paeth(row_info, row, prev_row); + } + else +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_bytep cp = prev_row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop = row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) /* use leftover rp,pp */ + { + int a, b, c, pa, pb, pc, p; + + a = *lp++; + b = *pp++; + c = *cp++; + + p = b - c; + pc = a - c; + +#ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +#else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +#endif + + /* + if (pa <= pb && pa <= pc) + p = a; + else if (pb <= pc) + p = b; + else + p = c; + */ + + p = (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c; + + *rp = (png_byte)(((int)(*rp) + p) & 0xff); + rp++; + } + } /* end !UseMMX_paeth */ + break; + + default: + png_warning(png_ptr, "Ignoring bad row-filter type"); + *row=0; + break; + } +} + +#endif /* PNG_HAVE_ASSEMBLER_READ_FILTER_ROW */ + + +/*===========================================================================*/ +/* */ +/* P N G _ M M X _ S U P P O R T */ +/* */ +/*===========================================================================*/ + +/* GRR NOTES: (1) the following code assumes 386 or better (pushfl/popfl) + * (2) all instructions compile with gcc 2.7.2.3 and later + * (3) the function is moved down here to prevent gcc from + * inlining it in multiple places and then barfing be- + * cause the ".NOT_SUPPORTED" label is multiply defined + * [is there a way to signal that a *single* function should + * not be inlined? is there a way to modify the label for + * each inlined instance, e.g., by appending _1, _2, etc.? + * maybe if don't use leading "." in label name? (nope...sigh)] + */ + +int PNGAPI +png_mmx_support(void) +{ +#if defined(PNG_MMX_CODE_SUPPORTED) + __asm__ __volatile__ ( + "pushl %%ebx \n\t" // ebx gets clobbered by CPUID instruction + "pushl %%ecx \n\t" // so does ecx... + "pushl %%edx \n\t" // ...and edx (but ecx & edx safe on Linux) +// ".byte 0x66 \n\t" // convert 16-bit pushf to 32-bit pushfd +// "pushf \n\t" // 16-bit pushf + "pushfl \n\t" // save Eflag to stack + "popl %%eax \n\t" // get Eflag from stack into eax + "movl %%eax, %%ecx \n\t" // make another copy of Eflag in ecx + "xorl $0x200000, %%eax \n\t" // toggle ID bit in Eflag (i.e., bit 21) + "pushl %%eax \n\t" // save modified Eflag back to stack +// ".byte 0x66 \n\t" // convert 16-bit popf to 32-bit popfd +// "popf \n\t" // 16-bit popf + "popfl \n\t" // restore modified value to Eflag reg + "pushfl \n\t" // save Eflag to stack + "popl %%eax \n\t" // get Eflag from stack + "pushl %%ecx \n\t" // save original Eflag to stack + "popfl \n\t" // restore original Eflag + "xorl %%ecx, %%eax \n\t" // compare new Eflag with original Eflag + "jz 0f \n\t" // if same, CPUID instr. is not supported + + "xorl %%eax, %%eax \n\t" // set eax to zero +// ".byte 0x0f, 0xa2 \n\t" // CPUID instruction (two-byte opcode) + "cpuid \n\t" // get the CPU identification info + "cmpl $1, %%eax \n\t" // make sure eax return non-zero value + "jl 0f \n\t" // if eax is zero, MMX is not supported + + "xorl %%eax, %%eax \n\t" // set eax to zero and... + "incl %%eax \n\t" // ...increment eax to 1. This pair is + // faster than the instruction "mov eax, 1" + "cpuid \n\t" // get the CPU identification info again + "andl $0x800000, %%edx \n\t" // mask out all bits but MMX bit (23) + "cmpl $0, %%edx \n\t" // 0 = MMX not supported + "jz 0f \n\t" // non-zero = yes, MMX IS supported + + "movl $1, %%eax \n\t" // set return value to 1 + "jmp 1f \n\t" // DONE: have MMX support + + "0: \n\t" // .NOT_SUPPORTED: target label for jump instructions + "movl $0, %%eax \n\t" // set return value to 0 + "1: \n\t" // .RETURN: target label for jump instructions + "movl %%eax, _mmx_supported \n\t" // save in global static variable, too + "popl %%edx \n\t" // restore edx + "popl %%ecx \n\t" // restore ecx + "popl %%ebx \n\t" // restore ebx + +// "ret \n\t" // DONE: no MMX support + // (fall through to standard C "ret") + + : // output list (none) + + : // any variables used on input (none) + + : "%eax" // clobber list +// , "%ebx", "%ecx", "%edx" // GRR: we handle these manually +// , "memory" // if write to a variable gcc thought was in a reg +// , "cc" // "condition codes" (flag bits) + ); +#else + _mmx_supported = 0; +#endif /* PNG_MMX_CODE_SUPPORTED */ + + return _mmx_supported; +} + + +#endif /* PNG_USE_PNGGCCRD */ diff --git a/SlnkDWFImpl/CxImage/png/pngget.c b/SlnkDWFImpl/CxImage/png/pngget.c new file mode 100644 index 0000000..af9bd10 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngget.c @@ -0,0 +1,934 @@ + +/* pngget.c - retrieval of values from info struct + * + * libpng 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + */ + +#define PNG_INTERNAL +#include "png.h" + +png_uint_32 PNGAPI +png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag) +{ + if (png_ptr != NULL && info_ptr != NULL) + return(info_ptr->valid & flag); + else + return(0); +} + +png_uint_32 PNGAPI +png_get_rowbytes(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + return(info_ptr->rowbytes); + else + return(0); +} + +#if defined(PNG_INFO_IMAGE_SUPPORTED) +png_bytepp PNGAPI +png_get_rows(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + return(info_ptr->row_pointers); + else + return(0); +} +#endif + +#ifdef PNG_EASY_ACCESS_SUPPORTED +/* easy access to info, added in libpng-0.99 */ +png_uint_32 PNGAPI +png_get_image_width(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + { + return info_ptr->width; + } + return (0); +} + +png_uint_32 PNGAPI +png_get_image_height(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + { + return info_ptr->height; + } + return (0); +} + +png_byte PNGAPI +png_get_bit_depth(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + { + return info_ptr->bit_depth; + } + return (0); +} + +png_byte PNGAPI +png_get_color_type(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + { + return info_ptr->color_type; + } + return (0); +} + +png_byte PNGAPI +png_get_filter_type(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + { + return info_ptr->filter_type; + } + return (0); +} + +png_byte PNGAPI +png_get_interlace_type(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + { + return info_ptr->interlace_type; + } + return (0); +} + +png_byte PNGAPI +png_get_compression_type(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + { + return info_ptr->compression_type; + } + return (0); +} + +png_uint_32 PNGAPI +png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) +#if defined(PNG_pHYs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_pHYs) + { + png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter"); + if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER) + return (0); + else return (info_ptr->x_pixels_per_unit); + } +#else + return (0); +#endif + return (0); +} + +png_uint_32 PNGAPI +png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) +#if defined(PNG_pHYs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_pHYs) + { + png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter"); + if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER) + return (0); + else return (info_ptr->y_pixels_per_unit); + } +#else + return (0); +#endif + return (0); +} + +png_uint_32 PNGAPI +png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) +#if defined(PNG_pHYs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_pHYs) + { + png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter"); + if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER || + info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit) + return (0); + else return (info_ptr->x_pixels_per_unit); + } +#else + return (0); +#endif + return (0); +} + +#ifdef PNG_FLOATING_POINT_SUPPORTED +float PNGAPI +png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr) + { + if (png_ptr != NULL && info_ptr != NULL) +#if defined(PNG_pHYs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_pHYs) + { + png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio"); + if (info_ptr->x_pixels_per_unit == 0) + return ((float)0.0); + else + return ((float)((float)info_ptr->y_pixels_per_unit + /(float)info_ptr->x_pixels_per_unit)); + } +#else + return (0.0); +#endif + return ((float)0.0); +} +#endif + +png_int_32 PNGAPI +png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) +#if defined(PNG_oFFs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_oFFs) + { + png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns"); + if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER) + return (0); + else return (info_ptr->x_offset); + } +#else + return (0); +#endif + return (0); +} + +png_int_32 PNGAPI +png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) +#if defined(PNG_oFFs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_oFFs) + { + png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns"); + if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER) + return (0); + else return (info_ptr->y_offset); + } +#else + return (0); +#endif + return (0); +} + +png_int_32 PNGAPI +png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) +#if defined(PNG_oFFs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_oFFs) + { + png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns"); + if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL) + return (0); + else return (info_ptr->x_offset); + } +#else + return (0); +#endif + return (0); +} + +png_int_32 PNGAPI +png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) +#if defined(PNG_oFFs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_oFFs) + { + png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns"); + if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL) + return (0); + else return (info_ptr->y_offset); + } +#else + return (0); +#endif + return (0); +} + +#if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED) +png_uint_32 PNGAPI +png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr) +{ + return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr) + *.0254 +.5)); +} + +png_uint_32 PNGAPI +png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr) +{ + return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr) + *.0254 +.5)); +} + +png_uint_32 PNGAPI +png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr) +{ + return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr) + *.0254 +.5)); +} + +float PNGAPI +png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr) +{ + return ((float)png_get_x_offset_microns(png_ptr, info_ptr) + *.00003937); +} + +float PNGAPI +png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr) +{ + return ((float)png_get_y_offset_microns(png_ptr, info_ptr) + *.00003937); +} + +#if defined(PNG_pHYs_SUPPORTED) +png_uint_32 PNGAPI +png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr, + png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type) +{ + png_uint_32 retval = 0; + + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs)) + { + png_debug1(1, "in %s retrieval function\n", "pHYs"); + if (res_x != NULL) + { + *res_x = info_ptr->x_pixels_per_unit; + retval |= PNG_INFO_pHYs; + } + if (res_y != NULL) + { + *res_y = info_ptr->y_pixels_per_unit; + retval |= PNG_INFO_pHYs; + } + if (unit_type != NULL) + { + *unit_type = (int)info_ptr->phys_unit_type; + retval |= PNG_INFO_pHYs; + if(*unit_type == 1) + { + if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50); + if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50); + } + } + } + return (retval); +} +#endif /* PNG_pHYs_SUPPORTED */ +#endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */ + +/* png_get_channels really belongs in here, too, but it's been around longer */ + +#endif /* PNG_EASY_ACCESS_SUPPORTED */ + +png_byte PNGAPI +png_get_channels(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + return(info_ptr->channels); + else + return (0); +} + +png_bytep PNGAPI +png_get_signature(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr != NULL && info_ptr != NULL) + return(info_ptr->signature); + else + return (NULL); +} + +#if defined(PNG_bKGD_SUPPORTED) +png_uint_32 PNGAPI +png_get_bKGD(png_structp png_ptr, png_infop info_ptr, + png_color_16p *background) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) + && background != NULL) + { + png_debug1(1, "in %s retrieval function\n", "bKGD"); + *background = &(info_ptr->background); + return (PNG_INFO_bKGD); + } + return (0); +} +#endif + +#if defined(PNG_cHRM_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +png_uint_32 PNGAPI +png_get_cHRM(png_structp png_ptr, png_infop info_ptr, + double *white_x, double *white_y, double *red_x, double *red_y, + double *green_x, double *green_y, double *blue_x, double *blue_y) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)) + { + png_debug1(1, "in %s retrieval function\n", "cHRM"); + if (white_x != NULL) + *white_x = (double)info_ptr->x_white; + if (white_y != NULL) + *white_y = (double)info_ptr->y_white; + if (red_x != NULL) + *red_x = (double)info_ptr->x_red; + if (red_y != NULL) + *red_y = (double)info_ptr->y_red; + if (green_x != NULL) + *green_x = (double)info_ptr->x_green; + if (green_y != NULL) + *green_y = (double)info_ptr->y_green; + if (blue_x != NULL) + *blue_x = (double)info_ptr->x_blue; + if (blue_y != NULL) + *blue_y = (double)info_ptr->y_blue; + return (PNG_INFO_cHRM); + } + return (0); +} +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +png_uint_32 PNGAPI +png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr, + png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x, + png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y, + png_fixed_point *blue_x, png_fixed_point *blue_y) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)) + { + png_debug1(1, "in %s retrieval function\n", "cHRM"); + if (white_x != NULL) + *white_x = info_ptr->int_x_white; + if (white_y != NULL) + *white_y = info_ptr->int_y_white; + if (red_x != NULL) + *red_x = info_ptr->int_x_red; + if (red_y != NULL) + *red_y = info_ptr->int_y_red; + if (green_x != NULL) + *green_x = info_ptr->int_x_green; + if (green_y != NULL) + *green_y = info_ptr->int_y_green; + if (blue_x != NULL) + *blue_x = info_ptr->int_x_blue; + if (blue_y != NULL) + *blue_y = info_ptr->int_y_blue; + return (PNG_INFO_cHRM); + } + return (0); +} +#endif +#endif + +#if defined(PNG_gAMA_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +png_uint_32 PNGAPI +png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA) + && file_gamma != NULL) + { + png_debug1(1, "in %s retrieval function\n", "gAMA"); + *file_gamma = (double)info_ptr->gamma; + return (PNG_INFO_gAMA); + } + return (0); +} +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +png_uint_32 PNGAPI +png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, + png_fixed_point *int_file_gamma) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA) + && int_file_gamma != NULL) + { + png_debug1(1, "in %s retrieval function\n", "gAMA"); + *int_file_gamma = info_ptr->int_gamma; + return (PNG_INFO_gAMA); + } + return (0); +} +#endif +#endif + +#if defined(PNG_sRGB_SUPPORTED) +png_uint_32 PNGAPI +png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB) + && file_srgb_intent != NULL) + { + png_debug1(1, "in %s retrieval function\n", "sRGB"); + *file_srgb_intent = (int)info_ptr->srgb_intent; + return (PNG_INFO_sRGB); + } + return (0); +} +#endif + +#if defined(PNG_iCCP_SUPPORTED) +png_uint_32 PNGAPI +png_get_iCCP(png_structp png_ptr, png_infop info_ptr, + png_charpp name, int *compression_type, + png_charpp profile, png_uint_32 *proflen) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP) + && name != NULL && profile != NULL && proflen != NULL) + { + png_debug1(1, "in %s retrieval function\n", "iCCP"); + *name = info_ptr->iccp_name; + *profile = info_ptr->iccp_profile; + /* compression_type is a dummy so the API won't have to change + if we introduce multiple compression types later. */ + *proflen = (int)info_ptr->iccp_proflen; + *compression_type = (int)info_ptr->iccp_compression; + return (PNG_INFO_iCCP); + } + return (0); +} +#endif + +#if defined(PNG_sPLT_SUPPORTED) +png_uint_32 PNGAPI +png_get_sPLT(png_structp png_ptr, png_infop info_ptr, + png_sPLT_tpp spalettes) +{ + if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL) + *spalettes = info_ptr->splt_palettes; + return ((png_uint_32)info_ptr->splt_palettes_num); +} +#endif + +#if defined(PNG_hIST_SUPPORTED) +png_uint_32 PNGAPI +png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) + && hist != NULL) + { + png_debug1(1, "in %s retrieval function\n", "hIST"); + *hist = info_ptr->hist; + return (PNG_INFO_hIST); + } + return (0); +} +#endif + +png_uint_32 PNGAPI +png_get_IHDR(png_structp png_ptr, png_infop info_ptr, + png_uint_32 *width, png_uint_32 *height, int *bit_depth, + int *color_type, int *interlace_type, int *compression_type, + int *filter_type) + +{ + if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL && + bit_depth != NULL && color_type != NULL) + { + png_debug1(1, "in %s retrieval function\n", "IHDR"); + *width = info_ptr->width; + *height = info_ptr->height; + *bit_depth = info_ptr->bit_depth; + if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16) + png_error(png_ptr, "Invalid bit depth"); + *color_type = info_ptr->color_type; + if (info_ptr->color_type > 6) + png_error(png_ptr, "Invalid color type"); + if (compression_type != NULL) + *compression_type = info_ptr->compression_type; + if (filter_type != NULL) + *filter_type = info_ptr->filter_type; + if (interlace_type != NULL) + *interlace_type = info_ptr->interlace_type; + + /* check for potential overflow of rowbytes */ + if (width == 0 || *width > PNG_UINT_31_MAX) + png_error(png_ptr, "Invalid image width"); + if (height == 0 || *height > PNG_UINT_31_MAX) + png_error(png_ptr, "Invalid image height"); + if (info_ptr->width > (PNG_UINT_32_MAX + >> 3) /* 8-byte RGBA pixels */ + - 64 /* bigrowbuf hack */ + - 1 /* filter byte */ + - 7*8 /* rounding of width to multiple of 8 pixels */ + - 8) /* extra max_pixel_depth pad */ + { + png_warning(png_ptr, + "Width too large for libpng to process image data."); + } + return (1); + } + return (0); +} + +#if defined(PNG_oFFs_SUPPORTED) +png_uint_32 PNGAPI +png_get_oFFs(png_structp png_ptr, png_infop info_ptr, + png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) + && offset_x != NULL && offset_y != NULL && unit_type != NULL) + { + png_debug1(1, "in %s retrieval function\n", "oFFs"); + *offset_x = info_ptr->x_offset; + *offset_y = info_ptr->y_offset; + *unit_type = (int)info_ptr->offset_unit_type; + return (PNG_INFO_oFFs); + } + return (0); +} +#endif + +#if defined(PNG_pCAL_SUPPORTED) +png_uint_32 PNGAPI +png_get_pCAL(png_structp png_ptr, png_infop info_ptr, + png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams, + png_charp *units, png_charpp *params) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) + && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL && + nparams != NULL && units != NULL && params != NULL) + { + png_debug1(1, "in %s retrieval function\n", "pCAL"); + *purpose = info_ptr->pcal_purpose; + *X0 = info_ptr->pcal_X0; + *X1 = info_ptr->pcal_X1; + *type = (int)info_ptr->pcal_type; + *nparams = (int)info_ptr->pcal_nparams; + *units = info_ptr->pcal_units; + *params = info_ptr->pcal_params; + return (PNG_INFO_pCAL); + } + return (0); +} +#endif + +#if defined(PNG_sCAL_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +png_uint_32 PNGAPI +png_get_sCAL(png_structp png_ptr, png_infop info_ptr, + int *unit, double *width, double *height) +{ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_sCAL)) + { + *unit = info_ptr->scal_unit; + *width = info_ptr->scal_pixel_width; + *height = info_ptr->scal_pixel_height; + return (PNG_INFO_sCAL); + } + return(0); +} +#else +#ifdef PNG_FIXED_POINT_SUPPORTED +png_uint_32 PNGAPI +png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr, + int *unit, png_charpp width, png_charpp height) +{ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_sCAL)) + { + *unit = info_ptr->scal_unit; + *width = info_ptr->scal_s_width; + *height = info_ptr->scal_s_height; + return (PNG_INFO_sCAL); + } + return(0); +} +#endif +#endif +#endif + +#if defined(PNG_pHYs_SUPPORTED) +png_uint_32 PNGAPI +png_get_pHYs(png_structp png_ptr, png_infop info_ptr, + png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type) +{ + png_uint_32 retval = 0; + + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_pHYs)) + { + png_debug1(1, "in %s retrieval function\n", "pHYs"); + if (res_x != NULL) + { + *res_x = info_ptr->x_pixels_per_unit; + retval |= PNG_INFO_pHYs; + } + if (res_y != NULL) + { + *res_y = info_ptr->y_pixels_per_unit; + retval |= PNG_INFO_pHYs; + } + if (unit_type != NULL) + { + *unit_type = (int)info_ptr->phys_unit_type; + retval |= PNG_INFO_pHYs; + } + } + return (retval); +} +#endif + +png_uint_32 PNGAPI +png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette, + int *num_palette) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE) + && palette != NULL) + { + png_debug1(1, "in %s retrieval function\n", "PLTE"); + *palette = info_ptr->palette; + *num_palette = info_ptr->num_palette; + png_debug1(3, "num_palette = %d\n", *num_palette); + return (PNG_INFO_PLTE); + } + return (0); +} + +#if defined(PNG_sBIT_SUPPORTED) +png_uint_32 PNGAPI +png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) + && sig_bit != NULL) + { + png_debug1(1, "in %s retrieval function\n", "sBIT"); + *sig_bit = &(info_ptr->sig_bit); + return (PNG_INFO_sBIT); + } + return (0); +} +#endif + +#if defined(PNG_TEXT_SUPPORTED) +png_uint_32 PNGAPI +png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr, + int *num_text) +{ + if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0) + { + png_debug1(1, "in %s retrieval function\n", + (png_ptr->chunk_name[0] == '\0' ? "text" + : (png_const_charp)png_ptr->chunk_name)); + if (text_ptr != NULL) + *text_ptr = info_ptr->text; + if (num_text != NULL) + *num_text = info_ptr->num_text; + return ((png_uint_32)info_ptr->num_text); + } + if (num_text != NULL) + *num_text = 0; + return(0); +} +#endif + +#if defined(PNG_tIME_SUPPORTED) +png_uint_32 PNGAPI +png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time) +{ + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) + && mod_time != NULL) + { + png_debug1(1, "in %s retrieval function\n", "tIME"); + *mod_time = &(info_ptr->mod_time); + return (PNG_INFO_tIME); + } + return (0); +} +#endif + +#if defined(PNG_tRNS_SUPPORTED) +png_uint_32 PNGAPI +png_get_tRNS(png_structp png_ptr, png_infop info_ptr, + png_bytep *trans, int *num_trans, png_color_16p *trans_values) +{ + png_uint_32 retval = 0; + if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS)) + { + png_debug1(1, "in %s retrieval function\n", "tRNS"); + if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + if (trans != NULL) + { + *trans = info_ptr->trans; + retval |= PNG_INFO_tRNS; + } + if (trans_values != NULL) + *trans_values = &(info_ptr->trans_values); + } + else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */ + { + if (trans_values != NULL) + { + *trans_values = &(info_ptr->trans_values); + retval |= PNG_INFO_tRNS; + } + if(trans != NULL) + *trans = NULL; + } + if(num_trans != NULL) + { + *num_trans = info_ptr->num_trans; + retval |= PNG_INFO_tRNS; + } + } + return (retval); +} +#endif + +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) +png_uint_32 PNGAPI +png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr, + png_unknown_chunkpp unknowns) +{ + if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL) + *unknowns = info_ptr->unknown_chunks; + return ((png_uint_32)info_ptr->unknown_chunks_num); +} +#endif + +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) +png_byte PNGAPI +png_get_rgb_to_gray_status (png_structp png_ptr) +{ + return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0); +} +#endif + +#if defined(PNG_USER_CHUNKS_SUPPORTED) +png_voidp PNGAPI +png_get_user_chunk_ptr(png_structp png_ptr) +{ + return (png_ptr? png_ptr->user_chunk_ptr : NULL); +} +#endif + +#ifdef PNG_WRITE_SUPPORTED +png_uint_32 PNGAPI +png_get_compression_buffer_size(png_structp png_ptr) +{ + return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L); +} +#endif + +#ifndef PNG_1_0_X +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED +/* this function was added to libpng 1.2.0 and should exist by default */ +png_uint_32 PNGAPI +png_get_asm_flags (png_structp png_ptr) +{ + return (png_uint_32)(png_ptr? png_ptr->asm_flags : 0L); +} + +/* this function was added to libpng 1.2.0 and should exist by default */ +png_uint_32 PNGAPI +png_get_asm_flagmask (int flag_select) +{ + png_uint_32 settable_asm_flags = 0; + + if (flag_select & PNG_SELECT_READ) + settable_asm_flags |= + PNG_ASM_FLAG_MMX_READ_COMBINE_ROW | + PNG_ASM_FLAG_MMX_READ_INTERLACE | + PNG_ASM_FLAG_MMX_READ_FILTER_SUB | + PNG_ASM_FLAG_MMX_READ_FILTER_UP | + PNG_ASM_FLAG_MMX_READ_FILTER_AVG | + PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ; + /* no non-MMX flags yet */ + +#if 0 + /* GRR: no write-flags yet, either, but someday... */ + if (flag_select & PNG_SELECT_WRITE) + settable_asm_flags |= + PNG_ASM_FLAG_MMX_WRITE_ [whatever] ; +#endif /* 0 */ + + return settable_asm_flags; /* _theoretically_ settable capabilities only */ +} +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */ + + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) + /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */ +/* this function was added to libpng 1.2.0 */ +png_uint_32 PNGAPI +png_get_mmx_flagmask (int flag_select, int *compilerID) +{ + png_uint_32 settable_mmx_flags = 0; + + if (flag_select & PNG_SELECT_READ) + settable_mmx_flags |= + PNG_ASM_FLAG_MMX_READ_COMBINE_ROW | + PNG_ASM_FLAG_MMX_READ_INTERLACE | + PNG_ASM_FLAG_MMX_READ_FILTER_SUB | + PNG_ASM_FLAG_MMX_READ_FILTER_UP | + PNG_ASM_FLAG_MMX_READ_FILTER_AVG | + PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ; +#if 0 + /* GRR: no MMX write support yet, but someday... */ + if (flag_select & PNG_SELECT_WRITE) + settable_mmx_flags |= + PNG_ASM_FLAG_MMX_WRITE_ [whatever] ; +#endif /* 0 */ + + if (compilerID != NULL) { +#ifdef PNG_USE_PNGVCRD + *compilerID = 1; /* MSVC */ +#else +#ifdef PNG_USE_PNGGCCRD + *compilerID = 2; /* gcc/gas */ +#else + *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */ +#endif +#endif + } + + return settable_mmx_flags; /* _theoretically_ settable capabilities only */ +} + +/* this function was added to libpng 1.2.0 */ +png_byte PNGAPI +png_get_mmx_bitdepth_threshold (png_structp png_ptr) +{ + return (png_byte)(png_ptr? png_ptr->mmx_bitdepth_threshold : 0); +} + +/* this function was added to libpng 1.2.0 */ +png_uint_32 PNGAPI +png_get_mmx_rowbytes_threshold (png_structp png_ptr) +{ + return (png_uint_32)(png_ptr? png_ptr->mmx_rowbytes_threshold : 0L); +} +#endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */ + +#ifdef PNG_SET_USER_LIMITS_SUPPORTED +/* these functions were added to libpng 1.2.6 */ +png_uint_32 PNGAPI +png_get_user_width_max (png_structp png_ptr) +{ + return (png_ptr? png_ptr->user_width_max : 0); +} +png_uint_32 PNGAPI +png_get_user_height_max (png_structp png_ptr) +{ + return (png_ptr? png_ptr->user_height_max : 0); +} +#endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */ + +#endif /* ?PNG_1_0_X */ diff --git a/SlnkDWFImpl/CxImage/png/pngmem.c b/SlnkDWFImpl/CxImage/png/pngmem.c new file mode 100644 index 0000000..8e2b966 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngmem.c @@ -0,0 +1,595 @@ + +/* pngmem.c - stub functions for memory allocation + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * This file provides a location for all memory allocation. Users who + * need special memory handling are expected to supply replacement + * functions for png_malloc() and png_free(), and to use + * png_create_read_struct_2() and png_create_write_struct_2() to + * identify the replacement functions. + */ + +#define PNG_INTERNAL +#include "png.h" + +/* Borland DOS special memory handler */ +#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__) +/* if you change this, be sure to change the one in png.h also */ + +/* Allocate memory for a png_struct. The malloc and memset can be replaced + by a single call to calloc() if this is thought to improve performance. */ +png_voidp /* PRIVATE */ +png_create_struct(int type) +{ +#ifdef PNG_USER_MEM_SUPPORTED + return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL)); +} + +/* Alternate version of png_create_struct, for use with user-defined malloc. */ +png_voidp /* PRIVATE */ +png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr) +{ +#endif /* PNG_USER_MEM_SUPPORTED */ + png_size_t size; + png_voidp struct_ptr; + + if (type == PNG_STRUCT_INFO) + size = png_sizeof(png_info); + else if (type == PNG_STRUCT_PNG) + size = png_sizeof(png_struct); + else + return (png_get_copyright(NULL)); + +#ifdef PNG_USER_MEM_SUPPORTED + if(malloc_fn != NULL) + { + png_struct dummy_struct; + png_structp png_ptr = &dummy_struct; + png_ptr->mem_ptr=mem_ptr; + struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size); + } + else +#endif /* PNG_USER_MEM_SUPPORTED */ + struct_ptr = (png_voidp)farmalloc(size); + if (struct_ptr != NULL) + png_memset(struct_ptr, 0, size); + return (struct_ptr); +} + +/* Free memory allocated by a png_create_struct() call */ +void /* PRIVATE */ +png_destroy_struct(png_voidp struct_ptr) +{ +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL); +} + +/* Free memory allocated by a png_create_struct() call */ +void /* PRIVATE */ +png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn, + png_voidp mem_ptr) +{ +#endif + if (struct_ptr != NULL) + { +#ifdef PNG_USER_MEM_SUPPORTED + if(free_fn != NULL) + { + png_struct dummy_struct; + png_structp png_ptr = &dummy_struct; + png_ptr->mem_ptr=mem_ptr; + (*(free_fn))(png_ptr, struct_ptr); + return; + } +#endif /* PNG_USER_MEM_SUPPORTED */ + farfree (struct_ptr); + } +} + +/* Allocate memory. For reasonable files, size should never exceed + * 64K. However, zlib may allocate more then 64K if you don't tell + * it not to. See zconf.h and png.h for more information. zlib does + * need to allocate exactly 64K, so whatever you call here must + * have the ability to do that. + * + * Borland seems to have a problem in DOS mode for exactly 64K. + * It gives you a segment with an offset of 8 (perhaps to store its + * memory stuff). zlib doesn't like this at all, so we have to + * detect and deal with it. This code should not be needed in + * Windows or OS/2 modes, and only in 16 bit mode. This code has + * been updated by Alexander Lehmann for version 0.89 to waste less + * memory. + * + * Note that we can't use png_size_t for the "size" declaration, + * since on some systems a png_size_t is a 16-bit quantity, and as a + * result, we would be truncating potentially larger memory requests + * (which should cause a fatal error) and introducing major problems. + */ + +png_voidp PNGAPI +png_malloc(png_structp png_ptr, png_uint_32 size) +{ + png_voidp ret; + + if (png_ptr == NULL || size == 0) + return (NULL); + +#ifdef PNG_USER_MEM_SUPPORTED + if(png_ptr->malloc_fn != NULL) + ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size)); + else + ret = (png_malloc_default(png_ptr, size)); + if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, "Out of memory!"); + return (ret); +} + +png_voidp PNGAPI +png_malloc_default(png_structp png_ptr, png_uint_32 size) +{ + png_voidp ret; +#endif /* PNG_USER_MEM_SUPPORTED */ + +#ifdef PNG_MAX_MALLOC_64K + if (size > (png_uint_32)65536L) + { + png_warning(png_ptr, "Cannot Allocate > 64K"); + ret = NULL; + } + else +#endif + + if (size != (size_t)size) + ret = NULL; + else if (size == (png_uint_32)65536L) + { + if (png_ptr->offset_table == NULL) + { + /* try to see if we need to do any of this fancy stuff */ + ret = farmalloc(size); + if (ret == NULL || ((png_size_t)ret & 0xffff)) + { + int num_blocks; + png_uint_32 total_size; + png_bytep table; + int i; + png_byte huge * hptr; + + if (ret != NULL) + { + farfree(ret); + ret = NULL; + } + + if(png_ptr->zlib_window_bits > 14) + num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14)); + else + num_blocks = 1; + if (png_ptr->zlib_mem_level >= 7) + num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7)); + else + num_blocks++; + + total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16; + + table = farmalloc(total_size); + + if (table == NULL) + { +#ifndef PNG_USER_MEM_SUPPORTED + if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */ + else + png_warning(png_ptr, "Out Of Memory."); +#endif + return (NULL); + } + + if ((png_size_t)table & 0xfff0) + { +#ifndef PNG_USER_MEM_SUPPORTED + if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, + "Farmalloc didn't return normalized pointer"); + else + png_warning(png_ptr, + "Farmalloc didn't return normalized pointer"); +#endif + return (NULL); + } + + png_ptr->offset_table = table; + png_ptr->offset_table_ptr = farmalloc(num_blocks * + png_sizeof (png_bytep)); + + if (png_ptr->offset_table_ptr == NULL) + { +#ifndef PNG_USER_MEM_SUPPORTED + if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */ + else + png_warning(png_ptr, "Out Of memory."); +#endif + return (NULL); + } + + hptr = (png_byte huge *)table; + if ((png_size_t)hptr & 0xf) + { + hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L); + hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */ + } + for (i = 0; i < num_blocks; i++) + { + png_ptr->offset_table_ptr[i] = (png_bytep)hptr; + hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */ + } + + png_ptr->offset_table_number = num_blocks; + png_ptr->offset_table_count = 0; + png_ptr->offset_table_count_free = 0; + } + } + + if (png_ptr->offset_table_count >= png_ptr->offset_table_number) + { +#ifndef PNG_USER_MEM_SUPPORTED + if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */ + else + png_warning(png_ptr, "Out of Memory."); +#endif + return (NULL); + } + + ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++]; + } + else + ret = farmalloc(size); + +#ifndef PNG_USER_MEM_SUPPORTED + if (ret == NULL) + { + if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */ + else + png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */ + } +#endif + + return (ret); +} + +/* free a pointer allocated by png_malloc(). In the default + configuration, png_ptr is not used, but is passed in case it + is needed. If ptr is NULL, return without taking any action. */ +void PNGAPI +png_free(png_structp png_ptr, png_voidp ptr) +{ + if (png_ptr == NULL || ptr == NULL) + return; + +#ifdef PNG_USER_MEM_SUPPORTED + if (png_ptr->free_fn != NULL) + { + (*(png_ptr->free_fn))(png_ptr, ptr); + return; + } + else png_free_default(png_ptr, ptr); +} + +void PNGAPI +png_free_default(png_structp png_ptr, png_voidp ptr) +{ +#endif /* PNG_USER_MEM_SUPPORTED */ + + if (png_ptr->offset_table != NULL) + { + int i; + + for (i = 0; i < png_ptr->offset_table_count; i++) + { + if (ptr == png_ptr->offset_table_ptr[i]) + { + ptr = NULL; + png_ptr->offset_table_count_free++; + break; + } + } + if (png_ptr->offset_table_count_free == png_ptr->offset_table_count) + { + farfree(png_ptr->offset_table); + farfree(png_ptr->offset_table_ptr); + png_ptr->offset_table = NULL; + png_ptr->offset_table_ptr = NULL; + } + } + + if (ptr != NULL) + { + farfree(ptr); + } +} + +#else /* Not the Borland DOS special memory handler */ + +/* Allocate memory for a png_struct or a png_info. The malloc and + memset can be replaced by a single call to calloc() if this is thought + to improve performance noticably. */ +png_voidp /* PRIVATE */ +png_create_struct(int type) +{ +#ifdef PNG_USER_MEM_SUPPORTED + return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL)); +} + +/* Allocate memory for a png_struct or a png_info. The malloc and + memset can be replaced by a single call to calloc() if this is thought + to improve performance noticably. */ +png_voidp /* PRIVATE */ +png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr) +{ +#endif /* PNG_USER_MEM_SUPPORTED */ + png_size_t size; + png_voidp struct_ptr; + + if (type == PNG_STRUCT_INFO) + size = png_sizeof(png_info); + else if (type == PNG_STRUCT_PNG) + size = png_sizeof(png_struct); + else + return (NULL); + +#ifdef PNG_USER_MEM_SUPPORTED + if(malloc_fn != NULL) + { + png_struct dummy_struct; + png_structp png_ptr = &dummy_struct; + png_ptr->mem_ptr=mem_ptr; + struct_ptr = (*(malloc_fn))(png_ptr, size); + if (struct_ptr != NULL) + png_memset(struct_ptr, 0, size); + return (struct_ptr); + } +#endif /* PNG_USER_MEM_SUPPORTED */ + +#if defined(__TURBOC__) && !defined(__FLAT__) + struct_ptr = (png_voidp)farmalloc(size); +#else +# if defined(_MSC_VER) && defined(MAXSEG_64K) + struct_ptr = (png_voidp)halloc(size,1); +# else + struct_ptr = (png_voidp)malloc(size); +# endif +#endif + if (struct_ptr != NULL) + png_memset(struct_ptr, 0, size); + + return (struct_ptr); +} + + +/* Free memory allocated by a png_create_struct() call */ +void /* PRIVATE */ +png_destroy_struct(png_voidp struct_ptr) +{ +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL); +} + +/* Free memory allocated by a png_create_struct() call */ +void /* PRIVATE */ +png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn, + png_voidp mem_ptr) +{ +#endif /* PNG_USER_MEM_SUPPORTED */ + if (struct_ptr != NULL) + { +#ifdef PNG_USER_MEM_SUPPORTED + if(free_fn != NULL) + { + png_struct dummy_struct; + png_structp png_ptr = &dummy_struct; + png_ptr->mem_ptr=mem_ptr; + (*(free_fn))(png_ptr, struct_ptr); + return; + } +#endif /* PNG_USER_MEM_SUPPORTED */ +#if defined(__TURBOC__) && !defined(__FLAT__) + farfree(struct_ptr); +#else +# if defined(_MSC_VER) && defined(MAXSEG_64K) + hfree(struct_ptr); +# else + free(struct_ptr); +# endif +#endif + } +} + +/* Allocate memory. For reasonable files, size should never exceed + 64K. However, zlib may allocate more then 64K if you don't tell + it not to. See zconf.h and png.h for more information. zlib does + need to allocate exactly 64K, so whatever you call here must + have the ability to do that. */ + +png_voidp PNGAPI +png_malloc(png_structp png_ptr, png_uint_32 size) +{ + png_voidp ret; + +#ifdef PNG_USER_MEM_SUPPORTED + if (png_ptr == NULL || size == 0) + return (NULL); + + if(png_ptr->malloc_fn != NULL) + ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size)); + else + ret = (png_malloc_default(png_ptr, size)); + if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, "Out of Memory!"); + return (ret); +} + +png_voidp PNGAPI +png_malloc_default(png_structp png_ptr, png_uint_32 size) +{ + png_voidp ret; +#endif /* PNG_USER_MEM_SUPPORTED */ + + if (png_ptr == NULL || size == 0) + return (NULL); + +#ifdef PNG_MAX_MALLOC_64K + if (size > (png_uint_32)65536L) + { +#ifndef PNG_USER_MEM_SUPPORTED + if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, "Cannot Allocate > 64K"); + else +#endif + return NULL; + } +#endif + + /* Check for overflow */ +#if defined(__TURBOC__) && !defined(__FLAT__) + if (size != (unsigned long)size) + ret = NULL; + else + ret = farmalloc(size); +#else +# if defined(_MSC_VER) && defined(MAXSEG_64K) + if (size != (unsigned long)size) + ret = NULL; + else + ret = halloc(size, 1); +# else + if (size != (size_t)size) + ret = NULL; + else + ret = malloc((size_t)size); +# endif +#endif + +#ifndef PNG_USER_MEM_SUPPORTED + if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0) + png_error(png_ptr, "Out of Memory"); +#endif + + return (ret); +} + +/* Free a pointer allocated by png_malloc(). If ptr is NULL, return + without taking any action. */ +void PNGAPI +png_free(png_structp png_ptr, png_voidp ptr) +{ + if (png_ptr == NULL || ptr == NULL) + return; + +#ifdef PNG_USER_MEM_SUPPORTED + if (png_ptr->free_fn != NULL) + { + (*(png_ptr->free_fn))(png_ptr, ptr); + return; + } + else png_free_default(png_ptr, ptr); +} +void PNGAPI +png_free_default(png_structp png_ptr, png_voidp ptr) +{ + if (png_ptr == NULL || ptr == NULL) + return; + +#endif /* PNG_USER_MEM_SUPPORTED */ + +#if defined(__TURBOC__) && !defined(__FLAT__) + farfree(ptr); +#else +# if defined(_MSC_VER) && defined(MAXSEG_64K) + hfree(ptr); +# else + free(ptr); +# endif +#endif +} + +#endif /* Not Borland DOS special memory handler */ + +#if defined(PNG_1_0_X) +# define png_malloc_warn png_malloc +#else +/* This function was added at libpng version 1.2.3. The png_malloc_warn() + * function will set up png_malloc() to issue a png_warning and return NULL + * instead of issuing a png_error, if it fails to allocate the requested + * memory. + */ +png_voidp PNGAPI +png_malloc_warn(png_structp png_ptr, png_uint_32 size) +{ + png_voidp ptr; + png_uint_32 save_flags=png_ptr->flags; + + png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; + ptr = (png_voidp)png_malloc((png_structp)png_ptr, size); + png_ptr->flags=save_flags; + return(ptr); +} +#endif + +png_voidp PNGAPI +png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2, + png_uint_32 length) +{ + png_size_t size; + + size = (png_size_t)length; + if ((png_uint_32)size != length) + png_error(png_ptr,"Overflow in png_memcpy_check."); + + return(png_memcpy (s1, s2, size)); +} + +png_voidp PNGAPI +png_memset_check (png_structp png_ptr, png_voidp s1, int value, + png_uint_32 length) +{ + png_size_t size; + + size = (png_size_t)length; + if ((png_uint_32)size != length) + png_error(png_ptr,"Overflow in png_memset_check."); + + return (png_memset (s1, value, size)); + +} + +#ifdef PNG_USER_MEM_SUPPORTED +/* This function is called when the application wants to use another method + * of allocating and freeing memory. + */ +void PNGAPI +png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr + malloc_fn, png_free_ptr free_fn) +{ + png_ptr->mem_ptr = mem_ptr; + png_ptr->malloc_fn = malloc_fn; + png_ptr->free_fn = free_fn; +} + +/* This function returns a pointer to the mem_ptr associated with the user + * functions. The application should free any memory associated with this + * pointer before png_write_destroy and png_read_destroy are called. + */ +png_voidp PNGAPI +png_get_mem_ptr(png_structp png_ptr) +{ + return ((png_voidp)png_ptr->mem_ptr); +} +#endif /* PNG_USER_MEM_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/png/pngpread.c b/SlnkDWFImpl/CxImage/png/pngpread.c new file mode 100644 index 0000000..9cc590e --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngpread.c @@ -0,0 +1,1573 @@ + +/* pngpread.c - read a png file in push mode + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + */ + +#define PNG_INTERNAL +#include "png.h" + +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED + +/* push model modes */ +#define PNG_READ_SIG_MODE 0 +#define PNG_READ_CHUNK_MODE 1 +#define PNG_READ_IDAT_MODE 2 +#define PNG_SKIP_MODE 3 +#define PNG_READ_tEXt_MODE 4 +#define PNG_READ_zTXt_MODE 5 +#define PNG_READ_DONE_MODE 6 +#define PNG_READ_iTXt_MODE 7 +#define PNG_ERROR_MODE 8 + +void PNGAPI +png_process_data(png_structp png_ptr, png_infop info_ptr, + png_bytep buffer, png_size_t buffer_size) +{ + png_push_restore_buffer(png_ptr, buffer, buffer_size); + + while (png_ptr->buffer_size) + { + png_process_some_data(png_ptr, info_ptr); + } +} + +/* What we do with the incoming data depends on what we were previously + * doing before we ran out of data... + */ +void /* PRIVATE */ +png_process_some_data(png_structp png_ptr, png_infop info_ptr) +{ + switch (png_ptr->process_mode) + { + case PNG_READ_SIG_MODE: + { + png_push_read_sig(png_ptr, info_ptr); + break; + } + case PNG_READ_CHUNK_MODE: + { + png_push_read_chunk(png_ptr, info_ptr); + break; + } + case PNG_READ_IDAT_MODE: + { + png_push_read_IDAT(png_ptr); + break; + } +#if defined(PNG_READ_tEXt_SUPPORTED) + case PNG_READ_tEXt_MODE: + { + png_push_read_tEXt(png_ptr, info_ptr); + break; + } +#endif +#if defined(PNG_READ_zTXt_SUPPORTED) + case PNG_READ_zTXt_MODE: + { + png_push_read_zTXt(png_ptr, info_ptr); + break; + } +#endif +#if defined(PNG_READ_iTXt_SUPPORTED) + case PNG_READ_iTXt_MODE: + { + png_push_read_iTXt(png_ptr, info_ptr); + break; + } +#endif + case PNG_SKIP_MODE: + { + png_push_crc_finish(png_ptr); + break; + } + default: + { + png_ptr->buffer_size = 0; + break; + } + } +} + +/* Read any remaining signature bytes from the stream and compare them with + * the correct PNG signature. It is possible that this routine is called + * with bytes already read from the signature, either because they have been + * checked by the calling application, or because of multiple calls to this + * routine. + */ +void /* PRIVATE */ +png_push_read_sig(png_structp png_ptr, png_infop info_ptr) +{ + png_size_t num_checked = png_ptr->sig_bytes, + num_to_check = 8 - num_checked; + + if (png_ptr->buffer_size < num_to_check) + { + num_to_check = png_ptr->buffer_size; + } + + png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]), + num_to_check); + png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check); + + if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check)) + { + if (num_checked < 4 && + png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4)) + png_error(png_ptr, "Not a PNG file"); + else + png_error(png_ptr, "PNG file corrupted by ASCII conversion"); + } + else + { + if (png_ptr->sig_bytes >= 8) + { + png_ptr->process_mode = PNG_READ_CHUNK_MODE; + } + } +} + +void /* PRIVATE */ +png_push_read_chunk(png_structp png_ptr, png_infop info_ptr) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IHDR; + PNG_IDAT; + PNG_IEND; + PNG_PLTE; +#if defined(PNG_READ_bKGD_SUPPORTED) + PNG_bKGD; +#endif +#if defined(PNG_READ_cHRM_SUPPORTED) + PNG_cHRM; +#endif +#if defined(PNG_READ_gAMA_SUPPORTED) + PNG_gAMA; +#endif +#if defined(PNG_READ_hIST_SUPPORTED) + PNG_hIST; +#endif +#if defined(PNG_READ_iCCP_SUPPORTED) + PNG_iCCP; +#endif +#if defined(PNG_READ_iTXt_SUPPORTED) + PNG_iTXt; +#endif +#if defined(PNG_READ_oFFs_SUPPORTED) + PNG_oFFs; +#endif +#if defined(PNG_READ_pCAL_SUPPORTED) + PNG_pCAL; +#endif +#if defined(PNG_READ_pHYs_SUPPORTED) + PNG_pHYs; +#endif +#if defined(PNG_READ_sBIT_SUPPORTED) + PNG_sBIT; +#endif +#if defined(PNG_READ_sCAL_SUPPORTED) + PNG_sCAL; +#endif +#if defined(PNG_READ_sRGB_SUPPORTED) + PNG_sRGB; +#endif +#if defined(PNG_READ_sPLT_SUPPORTED) + PNG_sPLT; +#endif +#if defined(PNG_READ_tEXt_SUPPORTED) + PNG_tEXt; +#endif +#if defined(PNG_READ_tIME_SUPPORTED) + PNG_tIME; +#endif +#if defined(PNG_READ_tRNS_SUPPORTED) + PNG_tRNS; +#endif +#if defined(PNG_READ_zTXt_SUPPORTED) + PNG_zTXt; +#endif +#endif /* PNG_USE_LOCAL_ARRAYS */ + /* First we make sure we have enough data for the 4 byte chunk name + * and the 4 byte chunk length before proceeding with decoding the + * chunk data. To fully decode each of these chunks, we also make + * sure we have enough data in the buffer for the 4 byte CRC at the + * end of every chunk (except IDAT, which is handled separately). + */ + if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER)) + { + png_byte chunk_length[4]; + + if (png_ptr->buffer_size < 8) + { + png_push_save_buffer(png_ptr); + return; + } + + png_push_fill_buffer(png_ptr, chunk_length, 4); + png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length); + png_reset_crc(png_ptr); + png_crc_read(png_ptr, png_ptr->chunk_name, 4); + png_ptr->mode |= PNG_HAVE_CHUNK_HEADER; + } + + if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length); + } + else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length); + + png_ptr->process_mode = PNG_READ_DONE_MODE; + png_push_have_end(png_ptr, info_ptr); + } +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED + else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) + png_ptr->mode |= PNG_HAVE_IDAT; + png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length); + if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4)) + png_ptr->mode |= PNG_HAVE_PLTE; + else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) + { + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before IDAT"); + else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && + !(png_ptr->mode & PNG_HAVE_PLTE)) + png_error(png_ptr, "Missing PLTE before IDAT"); + } + } +#endif + else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length); + } + else if (!png_memcmp(png_ptr->chunk_name, (png_bytep)png_IDAT, 4)) + { + /* If we reach an IDAT chunk, this means we have read all of the + * header chunks, and we can start reading the image (or if this + * is called after the image has been read - we have an error). + */ + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before IDAT"); + else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && + !(png_ptr->mode & PNG_HAVE_PLTE)) + png_error(png_ptr, "Missing PLTE before IDAT"); + + if (png_ptr->mode & PNG_HAVE_IDAT) + { + if (png_ptr->push_length == 0) + return; + + if (png_ptr->mode & PNG_AFTER_IDAT) + png_error(png_ptr, "Too many IDAT's found"); + } + + png_ptr->idat_size = png_ptr->push_length; + png_ptr->mode |= PNG_HAVE_IDAT; + png_ptr->process_mode = PNG_READ_IDAT_MODE; + png_push_have_info(png_ptr, info_ptr); + png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes; + png_ptr->zstream.next_out = png_ptr->row_buf; + return; + } +#if defined(PNG_READ_gAMA_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_sBIT_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_cHRM_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_sRGB_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_iCCP_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_sPLT_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_tRNS_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_bKGD_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_hIST_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_pHYs_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_oFFs_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_pCAL_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_sCAL_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_tIME_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_tEXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_zTXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length); + } +#endif +#if defined(PNG_READ_iTXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4)) + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length); + } +#endif + else + { + if (png_ptr->push_length + 4 > png_ptr->buffer_size) + { + png_push_save_buffer(png_ptr); + return; + } + png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length); + } + + png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER; +} + +void /* PRIVATE */ +png_push_crc_skip(png_structp png_ptr, png_uint_32 skip) +{ + png_ptr->process_mode = PNG_SKIP_MODE; + png_ptr->skip_length = skip; +} + +void /* PRIVATE */ +png_push_crc_finish(png_structp png_ptr) +{ + if (png_ptr->skip_length && png_ptr->save_buffer_size) + { + png_size_t save_size; + + if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size) + save_size = (png_size_t)png_ptr->skip_length; + else + save_size = png_ptr->save_buffer_size; + + png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size); + + png_ptr->skip_length -= save_size; + png_ptr->buffer_size -= save_size; + png_ptr->save_buffer_size -= save_size; + png_ptr->save_buffer_ptr += save_size; + } + if (png_ptr->skip_length && png_ptr->current_buffer_size) + { + png_size_t save_size; + + if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size) + save_size = (png_size_t)png_ptr->skip_length; + else + save_size = png_ptr->current_buffer_size; + + png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size); + + png_ptr->skip_length -= save_size; + png_ptr->buffer_size -= save_size; + png_ptr->current_buffer_size -= save_size; + png_ptr->current_buffer_ptr += save_size; + } + if (!png_ptr->skip_length) + { + if (png_ptr->buffer_size < 4) + { + png_push_save_buffer(png_ptr); + return; + } + + png_crc_finish(png_ptr, 0); + png_ptr->process_mode = PNG_READ_CHUNK_MODE; + } +} + +void PNGAPI +png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length) +{ + png_bytep ptr; + + ptr = buffer; + if (png_ptr->save_buffer_size) + { + png_size_t save_size; + + if (length < png_ptr->save_buffer_size) + save_size = length; + else + save_size = png_ptr->save_buffer_size; + + png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size); + length -= save_size; + ptr += save_size; + png_ptr->buffer_size -= save_size; + png_ptr->save_buffer_size -= save_size; + png_ptr->save_buffer_ptr += save_size; + } + if (length && png_ptr->current_buffer_size) + { + png_size_t save_size; + + if (length < png_ptr->current_buffer_size) + save_size = length; + else + save_size = png_ptr->current_buffer_size; + + png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size); + png_ptr->buffer_size -= save_size; + png_ptr->current_buffer_size -= save_size; + png_ptr->current_buffer_ptr += save_size; + } +} + +void /* PRIVATE */ +png_push_save_buffer(png_structp png_ptr) +{ + if (png_ptr->save_buffer_size) + { + if (png_ptr->save_buffer_ptr != png_ptr->save_buffer) + { + png_size_t i,istop; + png_bytep sp; + png_bytep dp; + + istop = png_ptr->save_buffer_size; + for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer; + i < istop; i++, sp++, dp++) + { + *dp = *sp; + } + } + } + if (png_ptr->save_buffer_size + png_ptr->current_buffer_size > + png_ptr->save_buffer_max) + { + png_size_t new_max; + png_bytep old_buffer; + + if (png_ptr->save_buffer_size > PNG_SIZE_MAX - + (png_ptr->current_buffer_size + 256)) + { + png_error(png_ptr, "Potential overflow of save_buffer"); + } + new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256; + old_buffer = png_ptr->save_buffer; + png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr, + (png_uint_32)new_max); + png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size); + png_free(png_ptr, old_buffer); + png_ptr->save_buffer_max = new_max; + } + if (png_ptr->current_buffer_size) + { + png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size, + png_ptr->current_buffer_ptr, png_ptr->current_buffer_size); + png_ptr->save_buffer_size += png_ptr->current_buffer_size; + png_ptr->current_buffer_size = 0; + } + png_ptr->save_buffer_ptr = png_ptr->save_buffer; + png_ptr->buffer_size = 0; +} + +void /* PRIVATE */ +png_push_restore_buffer(png_structp png_ptr, png_bytep buffer, + png_size_t buffer_length) +{ + png_ptr->current_buffer = buffer; + png_ptr->current_buffer_size = buffer_length; + png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size; + png_ptr->current_buffer_ptr = png_ptr->current_buffer; +} + +void /* PRIVATE */ +png_push_read_IDAT(png_structp png_ptr) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IDAT; +#endif + if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER)) + { + png_byte chunk_length[4]; + + if (png_ptr->buffer_size < 8) + { + png_push_save_buffer(png_ptr); + return; + } + + png_push_fill_buffer(png_ptr, chunk_length, 4); + png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length); + png_reset_crc(png_ptr); + png_crc_read(png_ptr, png_ptr->chunk_name, 4); + png_ptr->mode |= PNG_HAVE_CHUNK_HEADER; + + if (png_memcmp(png_ptr->chunk_name, (png_bytep)png_IDAT, 4)) + { + png_ptr->process_mode = PNG_READ_CHUNK_MODE; + if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED)) + png_error(png_ptr, "Not enough compressed data"); + return; + } + + png_ptr->idat_size = png_ptr->push_length; + } + if (png_ptr->idat_size && png_ptr->save_buffer_size) + { + png_size_t save_size; + + if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size) + { + save_size = (png_size_t)png_ptr->idat_size; + /* check for overflow */ + if((png_uint_32)save_size != png_ptr->idat_size) + png_error(png_ptr, "save_size overflowed in pngpread"); + } + else + save_size = png_ptr->save_buffer_size; + + png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size); + if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED)) + png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size); + png_ptr->idat_size -= save_size; + png_ptr->buffer_size -= save_size; + png_ptr->save_buffer_size -= save_size; + png_ptr->save_buffer_ptr += save_size; + } + if (png_ptr->idat_size && png_ptr->current_buffer_size) + { + png_size_t save_size; + + if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size) + { + save_size = (png_size_t)png_ptr->idat_size; + /* check for overflow */ + if((png_uint_32)save_size != png_ptr->idat_size) + png_error(png_ptr, "save_size overflowed in pngpread"); + } + else + save_size = png_ptr->current_buffer_size; + + png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size); + if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED)) + png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size); + + png_ptr->idat_size -= save_size; + png_ptr->buffer_size -= save_size; + png_ptr->current_buffer_size -= save_size; + png_ptr->current_buffer_ptr += save_size; + } + if (!png_ptr->idat_size) + { + if (png_ptr->buffer_size < 4) + { + png_push_save_buffer(png_ptr); + return; + } + + png_crc_finish(png_ptr, 0); + png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER; + png_ptr->mode |= PNG_AFTER_IDAT; + } +} + +void /* PRIVATE */ +png_process_IDAT_data(png_structp png_ptr, png_bytep buffer, + png_size_t buffer_length) +{ + int ret; + + if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length) + png_error(png_ptr, "Extra compression data"); + + png_ptr->zstream.next_in = buffer; + png_ptr->zstream.avail_in = (uInt)buffer_length; + for(;;) + { + ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH); + if (ret != Z_OK) + { + if (ret == Z_STREAM_END) + { + if (png_ptr->zstream.avail_in) + png_error(png_ptr, "Extra compressed data"); + if (!(png_ptr->zstream.avail_out)) + { + png_push_process_row(png_ptr); + } + + png_ptr->mode |= PNG_AFTER_IDAT; + png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; + break; + } + else if (ret == Z_BUF_ERROR) + break; + else + png_error(png_ptr, "Decompression Error"); + } + if (!(png_ptr->zstream.avail_out)) + { + if (( +#if defined(PNG_READ_INTERLACING_SUPPORTED) + png_ptr->interlaced && png_ptr->pass > 6) || + (!png_ptr->interlaced && +#endif + png_ptr->row_number == png_ptr->num_rows)) + { + if (png_ptr->zstream.avail_in) + png_warning(png_ptr, "Too much data in IDAT chunks"); + png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; + break; + } + png_push_process_row(png_ptr); + png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes; + png_ptr->zstream.next_out = png_ptr->row_buf; + } + else + break; + } +} + +void /* PRIVATE */ +png_push_process_row(png_structp png_ptr) +{ + png_ptr->row_info.color_type = png_ptr->color_type; + png_ptr->row_info.width = png_ptr->iwidth; + png_ptr->row_info.channels = png_ptr->channels; + png_ptr->row_info.bit_depth = png_ptr->bit_depth; + png_ptr->row_info.pixel_depth = png_ptr->pixel_depth; + + png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, + png_ptr->row_info.width); + + png_read_filter_row(png_ptr, &(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->prev_row + 1, + (int)(png_ptr->row_buf[0])); + + png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf, + png_ptr->rowbytes + 1); + + if (png_ptr->transformations) + png_do_read_transformations(png_ptr); + +#if defined(PNG_READ_INTERLACING_SUPPORTED) + /* blow up interlaced rows to full size */ + if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) + { + if (png_ptr->pass < 6) +/* old interface (pre-1.0.9): + png_do_read_interlace(&(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations); + */ + png_do_read_interlace(png_ptr); + + switch (png_ptr->pass) + { + case 0: + { + int i; + for (i = 0; i < 8 && png_ptr->pass == 0; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */ + } + if (png_ptr->pass == 2) /* pass 1 might be empty */ + { + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + if (png_ptr->pass == 4 && png_ptr->height <= 4) + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + if (png_ptr->pass == 6 && png_ptr->height <= 4) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + break; + } + case 1: + { + int i; + for (i = 0; i < 8 && png_ptr->pass == 1; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + if (png_ptr->pass == 2) /* skip top 4 generated rows */ + { + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + break; + } + case 2: + { + int i; + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + if (png_ptr->pass == 4) /* pass 3 might be empty */ + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + break; + } + case 3: + { + int i; + for (i = 0; i < 4 && png_ptr->pass == 3; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + if (png_ptr->pass == 4) /* skip top two generated rows */ + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + break; + } + case 4: + { + int i; + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + if (png_ptr->pass == 6) /* pass 5 might be empty */ + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + break; + } + case 5: + { + int i; + for (i = 0; i < 2 && png_ptr->pass == 5; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + if (png_ptr->pass == 6) /* skip top generated row */ + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + break; + } + case 6: + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + if (png_ptr->pass != 6) + break; + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + } + else +#endif + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } +} + +void /* PRIVATE */ +png_read_push_finish_row(png_structp png_ptr) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ + + /* start of interlace block */ + const int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0}; + + /* offset to next interlace block */ + const int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1}; + + /* start of interlace block in the y direction */ + const int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1}; + + /* offset to next interlace block in the y direction */ + const int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2}; + + /* Width of interlace block. This is not currently used - if you need + * it, uncomment it here and in png.h + const int FARDATA png_pass_width[] = {8, 4, 4, 2, 2, 1, 1}; + */ + + /* Height of interlace block. This is not currently used - if you need + * it, uncomment it here and in png.h + const int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1}; + */ +#endif + + png_ptr->row_number++; + if (png_ptr->row_number < png_ptr->num_rows) + return; + + if (png_ptr->interlaced) + { + png_ptr->row_number = 0; + png_memset_check(png_ptr, png_ptr->prev_row, 0, + png_ptr->rowbytes + 1); + do + { + png_ptr->pass++; + if ((png_ptr->pass == 1 && png_ptr->width < 5) || + (png_ptr->pass == 3 && png_ptr->width < 3) || + (png_ptr->pass == 5 && png_ptr->width < 2)) + png_ptr->pass++; + + if (png_ptr->pass > 7) + png_ptr->pass--; + if (png_ptr->pass >= 7) + break; + + png_ptr->iwidth = (png_ptr->width + + png_pass_inc[png_ptr->pass] - 1 - + png_pass_start[png_ptr->pass]) / + png_pass_inc[png_ptr->pass]; + + png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, + png_ptr->iwidth) + 1; + + if (png_ptr->transformations & PNG_INTERLACE) + break; + + png_ptr->num_rows = (png_ptr->height + + png_pass_yinc[png_ptr->pass] - 1 - + png_pass_ystart[png_ptr->pass]) / + png_pass_yinc[png_ptr->pass]; + + } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0); + } +} + +#if defined(PNG_READ_tEXt_SUPPORTED) +void /* PRIVATE */ +png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 + length) +{ + if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND)) + { + png_error(png_ptr, "Out of place tEXt"); + /* to quiet some compiler warnings */ + if(info_ptr == NULL) return; + } + +#ifdef PNG_MAX_MALLOC_64K + png_ptr->skip_length = 0; /* This may not be necessary */ + + if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */ + { + png_warning(png_ptr, "tEXt chunk too large to fit in memory"); + png_ptr->skip_length = length - (png_uint_32)65535L; + length = (png_uint_32)65535L; + } +#endif + + png_ptr->current_text = (png_charp)png_malloc(png_ptr, + (png_uint_32)(length+1)); + png_ptr->current_text[length] = '\0'; + png_ptr->current_text_ptr = png_ptr->current_text; + png_ptr->current_text_size = (png_size_t)length; + png_ptr->current_text_left = (png_size_t)length; + png_ptr->process_mode = PNG_READ_tEXt_MODE; +} + +void /* PRIVATE */ +png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr->buffer_size && png_ptr->current_text_left) + { + png_size_t text_size; + + if (png_ptr->buffer_size < png_ptr->current_text_left) + text_size = png_ptr->buffer_size; + else + text_size = png_ptr->current_text_left; + png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size); + png_ptr->current_text_left -= text_size; + png_ptr->current_text_ptr += text_size; + } + if (!(png_ptr->current_text_left)) + { + png_textp text_ptr; + png_charp text; + png_charp key; + int ret; + + if (png_ptr->buffer_size < 4) + { + png_push_save_buffer(png_ptr); + return; + } + + png_push_crc_finish(png_ptr); + +#if defined(PNG_MAX_MALLOC_64K) + if (png_ptr->skip_length) + return; +#endif + + key = png_ptr->current_text; + + for (text = key; *text; text++) + /* empty loop */ ; + + if (text != key + png_ptr->current_text_size) + text++; + + text_ptr = (png_textp)png_malloc(png_ptr, + (png_uint_32)png_sizeof(png_text)); + text_ptr->compression = PNG_TEXT_COMPRESSION_NONE; + text_ptr->key = key; +#ifdef PNG_iTXt_SUPPORTED + text_ptr->lang = NULL; + text_ptr->lang_key = NULL; +#endif + text_ptr->text = text; + + ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1); + + png_free(png_ptr, key); + png_free(png_ptr, text_ptr); + png_ptr->current_text = NULL; + + if (ret) + png_warning(png_ptr, "Insufficient memory to store text chunk."); + } +} +#endif + +#if defined(PNG_READ_zTXt_SUPPORTED) +void /* PRIVATE */ +png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 + length) +{ + if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND)) + { + png_error(png_ptr, "Out of place zTXt"); + /* to quiet some compiler warnings */ + if(info_ptr == NULL) return; + } + +#ifdef PNG_MAX_MALLOC_64K + /* We can't handle zTXt chunks > 64K, since we don't have enough space + * to be able to store the uncompressed data. Actually, the threshold + * is probably around 32K, but it isn't as definite as 64K is. + */ + if (length > (png_uint_32)65535L) + { + png_warning(png_ptr, "zTXt chunk too large to fit in memory"); + png_push_crc_skip(png_ptr, length); + return; + } +#endif + + png_ptr->current_text = (png_charp)png_malloc(png_ptr, + (png_uint_32)(length+1)); + png_ptr->current_text[length] = '\0'; + png_ptr->current_text_ptr = png_ptr->current_text; + png_ptr->current_text_size = (png_size_t)length; + png_ptr->current_text_left = (png_size_t)length; + png_ptr->process_mode = PNG_READ_zTXt_MODE; +} + +void /* PRIVATE */ +png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr->buffer_size && png_ptr->current_text_left) + { + png_size_t text_size; + + if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left) + text_size = png_ptr->buffer_size; + else + text_size = png_ptr->current_text_left; + png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size); + png_ptr->current_text_left -= text_size; + png_ptr->current_text_ptr += text_size; + } + if (!(png_ptr->current_text_left)) + { + png_textp text_ptr; + png_charp text; + png_charp key; + int ret; + png_size_t text_size, key_size; + + if (png_ptr->buffer_size < 4) + { + png_push_save_buffer(png_ptr); + return; + } + + png_push_crc_finish(png_ptr); + + key = png_ptr->current_text; + + for (text = key; *text; text++) + /* empty loop */ ; + + /* zTXt can't have zero text */ + if (text == key + png_ptr->current_text_size) + { + png_ptr->current_text = NULL; + png_free(png_ptr, key); + return; + } + + text++; + + if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */ + { + png_ptr->current_text = NULL; + png_free(png_ptr, key); + return; + } + + text++; + + png_ptr->zstream.next_in = (png_bytep )text; + png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size - + (text - key)); + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + + key_size = text - key; + text_size = 0; + text = NULL; + ret = Z_STREAM_END; + + while (png_ptr->zstream.avail_in) + { + ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH); + if (ret != Z_OK && ret != Z_STREAM_END) + { + inflateReset(&png_ptr->zstream); + png_ptr->zstream.avail_in = 0; + png_ptr->current_text = NULL; + png_free(png_ptr, key); + png_free(png_ptr, text); + return; + } + if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END) + { + if (text == NULL) + { + text = (png_charp)png_malloc(png_ptr, + (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out + + key_size + 1)); + png_memcpy(text + key_size, png_ptr->zbuf, + png_ptr->zbuf_size - png_ptr->zstream.avail_out); + png_memcpy(text, key, key_size); + text_size = key_size + png_ptr->zbuf_size - + png_ptr->zstream.avail_out; + *(text + text_size) = '\0'; + } + else + { + png_charp tmp; + + tmp = text; + text = (png_charp)png_malloc(png_ptr, text_size + + (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out + + 1)); + png_memcpy(text, tmp, text_size); + png_free(png_ptr, tmp); + png_memcpy(text + text_size, png_ptr->zbuf, + png_ptr->zbuf_size - png_ptr->zstream.avail_out); + text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out; + *(text + text_size) = '\0'; + } + if (ret != Z_STREAM_END) + { + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + } + } + else + { + break; + } + + if (ret == Z_STREAM_END) + break; + } + + inflateReset(&png_ptr->zstream); + png_ptr->zstream.avail_in = 0; + + if (ret != Z_STREAM_END) + { + png_ptr->current_text = NULL; + png_free(png_ptr, key); + png_free(png_ptr, text); + return; + } + + png_ptr->current_text = NULL; + png_free(png_ptr, key); + key = text; + text += key_size; + + text_ptr = (png_textp)png_malloc(png_ptr, + (png_uint_32)png_sizeof(png_text)); + text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt; + text_ptr->key = key; +#ifdef PNG_iTXt_SUPPORTED + text_ptr->lang = NULL; + text_ptr->lang_key = NULL; +#endif + text_ptr->text = text; + + ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1); + + png_free(png_ptr, key); + png_free(png_ptr, text_ptr); + + if (ret) + png_warning(png_ptr, "Insufficient memory to store text chunk."); + } +} +#endif + +#if defined(PNG_READ_iTXt_SUPPORTED) +void /* PRIVATE */ +png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 + length) +{ + if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND)) + { + png_error(png_ptr, "Out of place iTXt"); + /* to quiet some compiler warnings */ + if(info_ptr == NULL) return; + } + +#ifdef PNG_MAX_MALLOC_64K + png_ptr->skip_length = 0; /* This may not be necessary */ + + if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */ + { + png_warning(png_ptr, "iTXt chunk too large to fit in memory"); + png_ptr->skip_length = length - (png_uint_32)65535L; + length = (png_uint_32)65535L; + } +#endif + + png_ptr->current_text = (png_charp)png_malloc(png_ptr, + (png_uint_32)(length+1)); + png_ptr->current_text[length] = '\0'; + png_ptr->current_text_ptr = png_ptr->current_text; + png_ptr->current_text_size = (png_size_t)length; + png_ptr->current_text_left = (png_size_t)length; + png_ptr->process_mode = PNG_READ_iTXt_MODE; +} + +void /* PRIVATE */ +png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr) +{ + + if (png_ptr->buffer_size && png_ptr->current_text_left) + { + png_size_t text_size; + + if (png_ptr->buffer_size < png_ptr->current_text_left) + text_size = png_ptr->buffer_size; + else + text_size = png_ptr->current_text_left; + png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size); + png_ptr->current_text_left -= text_size; + png_ptr->current_text_ptr += text_size; + } + if (!(png_ptr->current_text_left)) + { + png_textp text_ptr; + png_charp key; + int comp_flag; + png_charp lang; + png_charp lang_key; + png_charp text; + int ret; + + if (png_ptr->buffer_size < 4) + { + png_push_save_buffer(png_ptr); + return; + } + + png_push_crc_finish(png_ptr); + +#if defined(PNG_MAX_MALLOC_64K) + if (png_ptr->skip_length) + return; +#endif + + key = png_ptr->current_text; + + for (lang = key; *lang; lang++) + /* empty loop */ ; + + if (lang != key + png_ptr->current_text_size) + lang++; + + comp_flag = *lang++; + lang++; /* skip comp_type, always zero */ + + for (lang_key = lang; *lang_key; lang_key++) + /* empty loop */ ; + lang_key++; /* skip NUL separator */ + + for (text = lang_key; *text; text++) + /* empty loop */ ; + + if (text != key + png_ptr->current_text_size) + text++; + + text_ptr = (png_textp)png_malloc(png_ptr, + (png_uint_32)png_sizeof(png_text)); + text_ptr->compression = comp_flag + 2; + text_ptr->key = key; + text_ptr->lang = lang; + text_ptr->lang_key = lang_key; + text_ptr->text = text; + text_ptr->text_length = 0; + text_ptr->itxt_length = png_strlen(text); + + ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1); + + png_ptr->current_text = NULL; + + png_free(png_ptr, text_ptr); + if (ret) + png_warning(png_ptr, "Insufficient memory to store iTXt chunk."); + } +} +#endif + +/* This function is called when we haven't found a handler for this + * chunk. If there isn't a problem with the chunk itself (ie a bad chunk + * name or a critical chunk), the chunk is (currently) silently ignored. + */ +void /* PRIVATE */ +png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 + length) +{ + png_uint_32 skip=0; + png_check_chunk_name(png_ptr, png_ptr->chunk_name); + + if (!(png_ptr->chunk_name[0] & 0x20)) + { +#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) + if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) != + PNG_HANDLE_CHUNK_ALWAYS +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED) + && png_ptr->read_user_chunk_fn == NULL +#endif + ) +#endif + png_chunk_error(png_ptr, "unknown critical chunk"); + + /* to quiet compiler warnings about unused info_ptr */ + if (info_ptr == NULL) + return; + } + +#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) + if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) + { + png_unknown_chunk chunk; + +#ifdef PNG_MAX_MALLOC_64K + if (length > (png_uint_32)65535L) + { + png_warning(png_ptr, "unknown chunk too large to fit in memory"); + skip = length - (png_uint_32)65535L; + length = (png_uint_32)65535L; + } +#endif + + png_strcpy((png_charp)chunk.name, (png_charp)png_ptr->chunk_name); + chunk.data = (png_bytep)png_malloc(png_ptr, length); + png_crc_read(png_ptr, chunk.data, length); + chunk.size = length; +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED) + if(png_ptr->read_user_chunk_fn != NULL) + { + /* callback to user unknown chunk handler */ + if ((*(png_ptr->read_user_chunk_fn)) (png_ptr, &chunk) <= 0) + { + if (!(png_ptr->chunk_name[0] & 0x20)) + if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) != + PNG_HANDLE_CHUNK_ALWAYS) + png_chunk_error(png_ptr, "unknown critical chunk"); + } + png_set_unknown_chunks(png_ptr, info_ptr, &chunk, 1); + } + else +#endif + png_set_unknown_chunks(png_ptr, info_ptr, &chunk, 1); + png_free(png_ptr, chunk.data); + } + else +#endif + skip=length; + png_push_crc_skip(png_ptr, skip); +} + +void /* PRIVATE */ +png_push_have_info(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr->info_fn != NULL) + (*(png_ptr->info_fn))(png_ptr, info_ptr); +} + +void /* PRIVATE */ +png_push_have_end(png_structp png_ptr, png_infop info_ptr) +{ + if (png_ptr->end_fn != NULL) + (*(png_ptr->end_fn))(png_ptr, info_ptr); +} + +void /* PRIVATE */ +png_push_have_row(png_structp png_ptr, png_bytep row) +{ + if (png_ptr->row_fn != NULL) + (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number, + (int)png_ptr->pass); +} + +void PNGAPI +png_progressive_combine_row (png_structp png_ptr, + png_bytep old_row, png_bytep new_row) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + const int FARDATA png_pass_dsp_mask[7] = + {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff}; +#endif + if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */ + png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]); +} + +void PNGAPI +png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr, + png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn, + png_progressive_end_ptr end_fn) +{ + png_ptr->info_fn = info_fn; + png_ptr->row_fn = row_fn; + png_ptr->end_fn = end_fn; + + png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer); +} + +png_voidp PNGAPI +png_get_progressive_ptr(png_structp png_ptr) +{ + return png_ptr->io_ptr; +} +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/png/pngread.c b/SlnkDWFImpl/CxImage/png/pngread.c new file mode 100644 index 0000000..23f3993 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngread.c @@ -0,0 +1,1453 @@ + +/* pngread.c - read a PNG file + * + * libpng 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * This file contains routines that an application calls directly to + * read a PNG file or stream. + */ + +#define PNG_INTERNAL +#include "png.h" + +/* Create a PNG structure for reading, and allocate any memory needed. */ +png_structp PNGAPI +png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warn_fn) +{ + +#ifdef PNG_USER_MEM_SUPPORTED + return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn, + warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL)); +} + +/* Alternate create PNG structure for reading, and allocate any memory needed. */ +png_structp PNGAPI +png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, + png_malloc_ptr malloc_fn, png_free_ptr free_fn) +{ +#endif /* PNG_USER_MEM_SUPPORTED */ + + png_structp png_ptr; + +#ifdef PNG_SETJMP_SUPPORTED +#ifdef USE_FAR_KEYWORD + jmp_buf jmpbuf; +#endif +#endif + + int i; + + png_debug(1, "in png_create_read_struct\n"); +#ifdef PNG_USER_MEM_SUPPORTED + png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG, + (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr); +#else + png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); +#endif + if (png_ptr == NULL) + return (NULL); + +#if !defined(PNG_1_0_X) +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED + png_init_mmx_flags(png_ptr); /* 1.2.0 addition */ +#endif +#endif /* PNG_1_0_X */ + + /* added at libpng-1.2.6 */ +#ifdef PNG_SET_USER_LIMITS_SUPPORTED + png_ptr->user_width_max=PNG_USER_WIDTH_MAX; + png_ptr->user_height_max=PNG_USER_HEIGHT_MAX; +#endif + +#ifdef PNG_SETJMP_SUPPORTED +#ifdef USE_FAR_KEYWORD + if (setjmp(jmpbuf)) +#else + if (setjmp(png_ptr->jmpbuf)) +#endif + { + png_free(png_ptr, png_ptr->zbuf); + png_ptr->zbuf=NULL; +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2((png_voidp)png_ptr, + (png_free_ptr)free_fn, (png_voidp)mem_ptr); +#else + png_destroy_struct((png_voidp)png_ptr); +#endif + return (NULL); + } +#ifdef USE_FAR_KEYWORD + png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf)); +#endif +#endif + +#ifdef PNG_USER_MEM_SUPPORTED + png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn); +#endif + + png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn); + + i=0; + do + { + if(user_png_ver[i] != png_libpng_ver[i]) + png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; + } while (png_libpng_ver[i++]); + + if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) + { + /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so + * we must recompile any applications that use any older library version. + * For versions after libpng 1.0, we will be compatible, so we need + * only check the first digit. + */ + if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] || + (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) || + (user_png_ver[0] == '0' && user_png_ver[2] < '9')) + { +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + char msg[80]; + if (user_png_ver) + { + sprintf(msg, "Application was compiled with png.h from libpng-%.20s", + user_png_ver); + png_warning(png_ptr, msg); + } + sprintf(msg, "Application is running with png.c from libpng-%.20s", + png_libpng_ver); + png_warning(png_ptr, msg); +#endif +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + png_ptr->flags=0; +#endif + png_error(png_ptr, + "Incompatible libpng version in application and library"); + } + } + + /* initialize zbuf - compression buffer */ + png_ptr->zbuf_size = PNG_ZBUF_SIZE; + png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, + (png_uint_32)png_ptr->zbuf_size); + png_ptr->zstream.zalloc = png_zalloc; + png_ptr->zstream.zfree = png_zfree; + png_ptr->zstream.opaque = (voidpf)png_ptr; + + switch (inflateInit(&png_ptr->zstream)) + { + case Z_OK: /* Do nothing */ break; + case Z_MEM_ERROR: + case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break; + case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break; + default: png_error(png_ptr, "Unknown zlib error"); + } + + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + + png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL); + +#ifdef PNG_SETJMP_SUPPORTED +/* Applications that neglect to set up their own setjmp() and then encounter + a png_error() will longjmp here. Since the jmpbuf is then meaningless we + abort instead of returning. */ +#ifdef USE_FAR_KEYWORD + if (setjmp(jmpbuf)) + PNG_ABORT(); + png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf)); +#else + if (setjmp(png_ptr->jmpbuf)) + PNG_ABORT(); +#endif +#endif + return (png_ptr); +} + +/* Initialize PNG structure for reading, and allocate any memory needed. + This interface is deprecated in favour of the png_create_read_struct(), + and it will eventually disappear. */ +#undef png_read_init +void PNGAPI +png_read_init(png_structp png_ptr) +{ + /* We only come here via pre-1.0.7-compiled applications */ + png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0); +} + +void PNGAPI +png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver, + png_size_t png_struct_size, png_size_t png_info_size) +{ + /* We only come here via pre-1.0.12-compiled applications */ +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + if(png_sizeof(png_struct) > png_struct_size || + png_sizeof(png_info) > png_info_size) + { + char msg[80]; + png_ptr->warning_fn=NULL; + if (user_png_ver) + { + sprintf(msg, "Application was compiled with png.h from libpng-%.20s", + user_png_ver); + png_warning(png_ptr, msg); + } + sprintf(msg, "Application is running with png.c from libpng-%.20s", + png_libpng_ver); + png_warning(png_ptr, msg); + } +#endif + if(png_sizeof(png_struct) > png_struct_size) + { + png_ptr->error_fn=NULL; +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + png_ptr->flags=0; +#endif + png_error(png_ptr, + "The png struct allocated by the application for reading is too small."); + } + if(png_sizeof(png_info) > png_info_size) + { + png_ptr->error_fn=NULL; +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + png_ptr->flags=0; +#endif + png_error(png_ptr, + "The info struct allocated by application for reading is too small."); + } + png_read_init_3(&png_ptr, user_png_ver, png_struct_size); +} + +void PNGAPI +png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, + png_size_t png_struct_size) +{ +#ifdef PNG_SETJMP_SUPPORTED + jmp_buf tmp_jmp; /* to save current jump buffer */ +#endif + + int i=0; + + png_structp png_ptr=*ptr_ptr; + + do + { + if(user_png_ver[i] != png_libpng_ver[i]) + { +#ifdef PNG_LEGACY_SUPPORTED + png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; +#else + png_ptr->warning_fn=NULL; + png_warning(png_ptr, + "Application uses deprecated png_read_init() and should be recompiled."); + break; +#endif + } + } while (png_libpng_ver[i++]); + + png_debug(1, "in png_read_init_3\n"); + +#ifdef PNG_SETJMP_SUPPORTED + /* save jump buffer and error functions */ + png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf)); +#endif + + if(png_sizeof(png_struct) > png_struct_size) + { + png_destroy_struct(png_ptr); + *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); + png_ptr = *ptr_ptr; + } + + /* reset all variables to 0 */ + png_memset(png_ptr, 0, png_sizeof (png_struct)); + +#ifdef PNG_SETJMP_SUPPORTED + /* restore jump buffer */ + png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf)); +#endif + + /* added at libpng-1.2.6 */ +#ifdef PNG_SET_USER_LIMITS_SUPPORTED + png_ptr->user_width_max=PNG_USER_WIDTH_MAX; + png_ptr->user_height_max=PNG_USER_HEIGHT_MAX; +#endif + + /* initialize zbuf - compression buffer */ + png_ptr->zbuf_size = PNG_ZBUF_SIZE; + png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, + (png_uint_32)png_ptr->zbuf_size); + png_ptr->zstream.zalloc = png_zalloc; + png_ptr->zstream.zfree = png_zfree; + png_ptr->zstream.opaque = (voidpf)png_ptr; + + switch (inflateInit(&png_ptr->zstream)) + { + case Z_OK: /* Do nothing */ break; + case Z_MEM_ERROR: + case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break; + case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break; + default: png_error(png_ptr, "Unknown zlib error"); + } + + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + + png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL); +} + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* Read the information before the actual image data. This has been + * changed in v0.90 to allow reading a file that already has the magic + * bytes read from the stream. You can tell libpng how many bytes have + * been read from the beginning of the stream (up to the maximum of 8) + * via png_set_sig_bytes(), and we will only check the remaining bytes + * here. The application can then have access to the signature bytes we + * read if it is determined that this isn't a valid PNG file. + */ +void PNGAPI +png_read_info(png_structp png_ptr, png_infop info_ptr) +{ + png_debug(1, "in png_read_info\n"); + /* If we haven't checked all of the PNG signature bytes, do so now. */ + if (png_ptr->sig_bytes < 8) + { + png_size_t num_checked = png_ptr->sig_bytes, + num_to_check = 8 - num_checked; + + png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check); + png_ptr->sig_bytes = 8; + + if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check)) + { + if (num_checked < 4 && + png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4)) + png_error(png_ptr, "Not a PNG file"); + else + png_error(png_ptr, "PNG file corrupted by ASCII conversion"); + } + if (num_checked < 3) + png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE; + } + + for(;;) + { +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IHDR; + PNG_IDAT; + PNG_IEND; + PNG_PLTE; +#if defined(PNG_READ_bKGD_SUPPORTED) + PNG_bKGD; +#endif +#if defined(PNG_READ_cHRM_SUPPORTED) + PNG_cHRM; +#endif +#if defined(PNG_READ_gAMA_SUPPORTED) + PNG_gAMA; +#endif +#if defined(PNG_READ_hIST_SUPPORTED) + PNG_hIST; +#endif +#if defined(PNG_READ_iCCP_SUPPORTED) + PNG_iCCP; +#endif +#if defined(PNG_READ_iTXt_SUPPORTED) + PNG_iTXt; +#endif +#if defined(PNG_READ_oFFs_SUPPORTED) + PNG_oFFs; +#endif +#if defined(PNG_READ_pCAL_SUPPORTED) + PNG_pCAL; +#endif +#if defined(PNG_READ_pHYs_SUPPORTED) + PNG_pHYs; +#endif +#if defined(PNG_READ_sBIT_SUPPORTED) + PNG_sBIT; +#endif +#if defined(PNG_READ_sCAL_SUPPORTED) + PNG_sCAL; +#endif +#if defined(PNG_READ_sPLT_SUPPORTED) + PNG_sPLT; +#endif +#if defined(PNG_READ_sRGB_SUPPORTED) + PNG_sRGB; +#endif +#if defined(PNG_READ_tEXt_SUPPORTED) + PNG_tEXt; +#endif +#if defined(PNG_READ_tIME_SUPPORTED) + PNG_tIME; +#endif +#if defined(PNG_READ_tRNS_SUPPORTED) + PNG_tRNS; +#endif +#if defined(PNG_READ_zTXt_SUPPORTED) + PNG_zTXt; +#endif +#endif /* PNG_GLOBAL_ARRAYS */ + png_byte chunk_length[4]; + png_uint_32 length; + + png_read_data(png_ptr, chunk_length, 4); + length = png_get_uint_31(png_ptr,chunk_length); + + png_reset_crc(png_ptr); + png_crc_read(png_ptr, png_ptr->chunk_name, 4); + + png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name, + length); + + /* This should be a binary subdivision search or a hash for + * matching the chunk name rather than a linear search. + */ + if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4)) + png_handle_IHDR(png_ptr, info_ptr, length); + else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4)) + png_handle_IEND(png_ptr, info_ptr, length); +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED + else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name)) + { + if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) + png_ptr->mode |= PNG_HAVE_IDAT; + png_handle_unknown(png_ptr, info_ptr, length); + if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4)) + png_ptr->mode |= PNG_HAVE_PLTE; + else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) + { + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before IDAT"); + else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && + !(png_ptr->mode & PNG_HAVE_PLTE)) + png_error(png_ptr, "Missing PLTE before IDAT"); + break; + } + } +#endif + else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4)) + png_handle_PLTE(png_ptr, info_ptr, length); + else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) + { + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before IDAT"); + else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && + !(png_ptr->mode & PNG_HAVE_PLTE)) + png_error(png_ptr, "Missing PLTE before IDAT"); + + png_ptr->idat_size = length; + png_ptr->mode |= PNG_HAVE_IDAT; + break; + } +#if defined(PNG_READ_bKGD_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4)) + png_handle_bKGD(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_cHRM_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4)) + png_handle_cHRM(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_gAMA_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4)) + png_handle_gAMA(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_hIST_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4)) + png_handle_hIST(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_oFFs_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4)) + png_handle_oFFs(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_pCAL_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4)) + png_handle_pCAL(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_sCAL_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4)) + png_handle_sCAL(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_pHYs_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4)) + png_handle_pHYs(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_sBIT_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4)) + png_handle_sBIT(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_sRGB_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4)) + png_handle_sRGB(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_iCCP_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4)) + png_handle_iCCP(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_sPLT_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4)) + png_handle_sPLT(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_tEXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4)) + png_handle_tEXt(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_tIME_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4)) + png_handle_tIME(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_tRNS_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4)) + png_handle_tRNS(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_zTXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4)) + png_handle_zTXt(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_iTXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4)) + png_handle_iTXt(png_ptr, info_ptr, length); +#endif + else + png_handle_unknown(png_ptr, info_ptr, length); + } +} +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */ + +/* optional call to update the users info_ptr structure */ +void PNGAPI +png_read_update_info(png_structp png_ptr, png_infop info_ptr) +{ + png_debug(1, "in png_read_update_info\n"); + if (!(png_ptr->flags & PNG_FLAG_ROW_INIT)) + png_read_start_row(png_ptr); + else + png_warning(png_ptr, + "Ignoring extra png_read_update_info() call; row buffer not reallocated"); + png_read_transform_info(png_ptr, info_ptr); +} + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* Initialize palette, background, etc, after transformations + * are set, but before any reading takes place. This allows + * the user to obtain a gamma-corrected palette, for example. + * If the user doesn't call this, we will do it ourselves. + */ +void PNGAPI +png_start_read_image(png_structp png_ptr) +{ + png_debug(1, "in png_start_read_image\n"); + if (!(png_ptr->flags & PNG_FLAG_ROW_INIT)) + png_read_start_row(png_ptr); +} +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */ + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +void PNGAPI +png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IDAT; + const int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff}; + const int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff}; +#endif + int ret; + png_debug2(1, "in png_read_row (row %lu, pass %d)\n", + png_ptr->row_number, png_ptr->pass); + if (!(png_ptr->flags & PNG_FLAG_ROW_INIT)) + png_read_start_row(png_ptr); + if (png_ptr->row_number == 0 && png_ptr->pass == 0) + { + /* check for transforms that have been set but were defined out */ +#if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED) + if (png_ptr->transformations & PNG_INVERT_MONO) + png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined."); +#endif +#if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED) + if (png_ptr->transformations & PNG_FILLER) + png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined."); +#endif +#if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined."); +#endif +#if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED) + if (png_ptr->transformations & PNG_PACK) + png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined."); +#endif +#if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) + if (png_ptr->transformations & PNG_SHIFT) + png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined."); +#endif +#if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED) + if (png_ptr->transformations & PNG_BGR) + png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined."); +#endif +#if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED) + if (png_ptr->transformations & PNG_SWAP_BYTES) + png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined."); +#endif + } + +#if defined(PNG_READ_INTERLACING_SUPPORTED) + /* if interlaced and we do not need a new row, combine row and return */ + if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) + { + switch (png_ptr->pass) + { + case 0: + if (png_ptr->row_number & 0x07) + { + if (dsp_row != NULL) + png_combine_row(png_ptr, dsp_row, + png_pass_dsp_mask[png_ptr->pass]); + png_read_finish_row(png_ptr); + return; + } + break; + case 1: + if ((png_ptr->row_number & 0x07) || png_ptr->width < 5) + { + if (dsp_row != NULL) + png_combine_row(png_ptr, dsp_row, + png_pass_dsp_mask[png_ptr->pass]); + png_read_finish_row(png_ptr); + return; + } + break; + case 2: + if ((png_ptr->row_number & 0x07) != 4) + { + if (dsp_row != NULL && (png_ptr->row_number & 4)) + png_combine_row(png_ptr, dsp_row, + png_pass_dsp_mask[png_ptr->pass]); + png_read_finish_row(png_ptr); + return; + } + break; + case 3: + if ((png_ptr->row_number & 3) || png_ptr->width < 3) + { + if (dsp_row != NULL) + png_combine_row(png_ptr, dsp_row, + png_pass_dsp_mask[png_ptr->pass]); + png_read_finish_row(png_ptr); + return; + } + break; + case 4: + if ((png_ptr->row_number & 3) != 2) + { + if (dsp_row != NULL && (png_ptr->row_number & 2)) + png_combine_row(png_ptr, dsp_row, + png_pass_dsp_mask[png_ptr->pass]); + png_read_finish_row(png_ptr); + return; + } + break; + case 5: + if ((png_ptr->row_number & 1) || png_ptr->width < 2) + { + if (dsp_row != NULL) + png_combine_row(png_ptr, dsp_row, + png_pass_dsp_mask[png_ptr->pass]); + png_read_finish_row(png_ptr); + return; + } + break; + case 6: + if (!(png_ptr->row_number & 1)) + { + png_read_finish_row(png_ptr); + return; + } + break; + } + } +#endif + + if (!(png_ptr->mode & PNG_HAVE_IDAT)) + png_error(png_ptr, "Invalid attempt to read row data"); + + png_ptr->zstream.next_out = png_ptr->row_buf; + png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes; + do + { + if (!(png_ptr->zstream.avail_in)) + { + while (!png_ptr->idat_size) + { + png_byte chunk_length[4]; + + png_crc_finish(png_ptr, 0); + + png_read_data(png_ptr, chunk_length, 4); + png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length); + + png_reset_crc(png_ptr); + png_crc_read(png_ptr, png_ptr->chunk_name, 4); + if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) + png_error(png_ptr, "Not enough image data"); + } + png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size; + png_ptr->zstream.next_in = png_ptr->zbuf; + if (png_ptr->zbuf_size > png_ptr->idat_size) + png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size; + png_crc_read(png_ptr, png_ptr->zbuf, + (png_size_t)png_ptr->zstream.avail_in); + png_ptr->idat_size -= png_ptr->zstream.avail_in; + } + ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH); + if (ret == Z_STREAM_END) + { + if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in || + png_ptr->idat_size) + png_error(png_ptr, "Extra compressed data"); + png_ptr->mode |= PNG_AFTER_IDAT; + png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; + break; + } + if (ret != Z_OK) + png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg : + "Decompression error"); + + } while (png_ptr->zstream.avail_out); + + png_ptr->row_info.color_type = png_ptr->color_type; + png_ptr->row_info.width = png_ptr->iwidth; + png_ptr->row_info.channels = png_ptr->channels; + png_ptr->row_info.bit_depth = png_ptr->bit_depth; + png_ptr->row_info.pixel_depth = png_ptr->pixel_depth; + png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, + png_ptr->row_info.width); + + if(png_ptr->row_buf[0]) + png_read_filter_row(png_ptr, &(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->prev_row + 1, + (int)(png_ptr->row_buf[0])); + + png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf, + png_ptr->rowbytes + 1); + +#if defined(PNG_MNG_FEATURES_SUPPORTED) + if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && + (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING)) + { + /* Intrapixel differencing */ + png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1); + } +#endif + + if (png_ptr->transformations) + png_do_read_transformations(png_ptr); + +#if defined(PNG_READ_INTERLACING_SUPPORTED) + /* blow up interlaced rows to full size */ + if (png_ptr->interlaced && + (png_ptr->transformations & PNG_INTERLACE)) + { + if (png_ptr->pass < 6) +/* old interface (pre-1.0.9): + png_do_read_interlace(&(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations); + */ + png_do_read_interlace(png_ptr); + + if (dsp_row != NULL) + png_combine_row(png_ptr, dsp_row, + png_pass_dsp_mask[png_ptr->pass]); + if (row != NULL) + png_combine_row(png_ptr, row, + png_pass_mask[png_ptr->pass]); + } + else +#endif + { + if (row != NULL) + png_combine_row(png_ptr, row, 0xff); + if (dsp_row != NULL) + png_combine_row(png_ptr, dsp_row, 0xff); + } + png_read_finish_row(png_ptr); + + if (png_ptr->read_row_fn != NULL) + (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass); +} +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */ + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* Read one or more rows of image data. If the image is interlaced, + * and png_set_interlace_handling() has been called, the rows need to + * contain the contents of the rows from the previous pass. If the + * image has alpha or transparency, and png_handle_alpha()[*] has been + * called, the rows contents must be initialized to the contents of the + * screen. + * + * "row" holds the actual image, and pixels are placed in it + * as they arrive. If the image is displayed after each pass, it will + * appear to "sparkle" in. "display_row" can be used to display a + * "chunky" progressive image, with finer detail added as it becomes + * available. If you do not want this "chunky" display, you may pass + * NULL for display_row. If you do not want the sparkle display, and + * you have not called png_handle_alpha(), you may pass NULL for rows. + * If you have called png_handle_alpha(), and the image has either an + * alpha channel or a transparency chunk, you must provide a buffer for + * rows. In this case, you do not have to provide a display_row buffer + * also, but you may. If the image is not interlaced, or if you have + * not called png_set_interlace_handling(), the display_row buffer will + * be ignored, so pass NULL to it. + * + * [*] png_handle_alpha() does not exist yet, as of libpng version 1.2.7 + */ + +void PNGAPI +png_read_rows(png_structp png_ptr, png_bytepp row, + png_bytepp display_row, png_uint_32 num_rows) +{ + png_uint_32 i; + png_bytepp rp; + png_bytepp dp; + + png_debug(1, "in png_read_rows\n"); + rp = row; + dp = display_row; + if (rp != NULL && dp != NULL) + for (i = 0; i < num_rows; i++) + { + png_bytep rptr = *rp++; + png_bytep dptr = *dp++; + + png_read_row(png_ptr, rptr, dptr); + } + else if(rp != NULL) + for (i = 0; i < num_rows; i++) + { + png_bytep rptr = *rp; + png_read_row(png_ptr, rptr, png_bytep_NULL); + rp++; + } + else if(dp != NULL) + for (i = 0; i < num_rows; i++) + { + png_bytep dptr = *dp; + png_read_row(png_ptr, png_bytep_NULL, dptr); + dp++; + } +} +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */ + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* Read the entire image. If the image has an alpha channel or a tRNS + * chunk, and you have called png_handle_alpha()[*], you will need to + * initialize the image to the current image that PNG will be overlaying. + * We set the num_rows again here, in case it was incorrectly set in + * png_read_start_row() by a call to png_read_update_info() or + * png_start_read_image() if png_set_interlace_handling() wasn't called + * prior to either of these functions like it should have been. You can + * only call this function once. If you desire to have an image for + * each pass of a interlaced image, use png_read_rows() instead. + * + * [*] png_handle_alpha() does not exist yet, as of libpng version 1.2.7 + */ +void PNGAPI +png_read_image(png_structp png_ptr, png_bytepp image) +{ + png_uint_32 i,image_height; + int pass, j; + png_bytepp rp; + + png_debug(1, "in png_read_image\n"); + +#ifdef PNG_READ_INTERLACING_SUPPORTED + pass = png_set_interlace_handling(png_ptr); +#else + if (png_ptr->interlaced) + png_error(png_ptr, + "Cannot read interlaced image -- interlace handler disabled."); + pass = 1; +#endif + + + image_height=png_ptr->height; + png_ptr->num_rows = image_height; /* Make sure this is set correctly */ + + for (j = 0; j < pass; j++) + { + rp = image; + for (i = 0; i < image_height; i++) + { + png_read_row(png_ptr, *rp, png_bytep_NULL); + rp++; + } + } +} +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */ + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +/* Read the end of the PNG file. Will not read past the end of the + * file, will verify the end is accurate, and will read any comments + * or time information at the end of the file, if info is not NULL. + */ +void PNGAPI +png_read_end(png_structp png_ptr, png_infop info_ptr) +{ + png_byte chunk_length[4]; + png_uint_32 length; + + png_debug(1, "in png_read_end\n"); + png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */ + + do + { +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IHDR; + PNG_IDAT; + PNG_IEND; + PNG_PLTE; +#if defined(PNG_READ_bKGD_SUPPORTED) + PNG_bKGD; +#endif +#if defined(PNG_READ_cHRM_SUPPORTED) + PNG_cHRM; +#endif +#if defined(PNG_READ_gAMA_SUPPORTED) + PNG_gAMA; +#endif +#if defined(PNG_READ_hIST_SUPPORTED) + PNG_hIST; +#endif +#if defined(PNG_READ_iCCP_SUPPORTED) + PNG_iCCP; +#endif +#if defined(PNG_READ_iTXt_SUPPORTED) + PNG_iTXt; +#endif +#if defined(PNG_READ_oFFs_SUPPORTED) + PNG_oFFs; +#endif +#if defined(PNG_READ_pCAL_SUPPORTED) + PNG_pCAL; +#endif +#if defined(PNG_READ_pHYs_SUPPORTED) + PNG_pHYs; +#endif +#if defined(PNG_READ_sBIT_SUPPORTED) + PNG_sBIT; +#endif +#if defined(PNG_READ_sCAL_SUPPORTED) + PNG_sCAL; +#endif +#if defined(PNG_READ_sPLT_SUPPORTED) + PNG_sPLT; +#endif +#if defined(PNG_READ_sRGB_SUPPORTED) + PNG_sRGB; +#endif +#if defined(PNG_READ_tEXt_SUPPORTED) + PNG_tEXt; +#endif +#if defined(PNG_READ_tIME_SUPPORTED) + PNG_tIME; +#endif +#if defined(PNG_READ_tRNS_SUPPORTED) + PNG_tRNS; +#endif +#if defined(PNG_READ_zTXt_SUPPORTED) + PNG_zTXt; +#endif +#endif /* PNG_GLOBAL_ARRAYS */ + + png_read_data(png_ptr, chunk_length, 4); + length = png_get_uint_31(png_ptr,chunk_length); + + png_reset_crc(png_ptr); + png_crc_read(png_ptr, png_ptr->chunk_name, 4); + + png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name); + + if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4)) + png_handle_IHDR(png_ptr, info_ptr, length); + else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4)) + png_handle_IEND(png_ptr, info_ptr, length); +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED + else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name)) + { + if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) + { + if (length > 0 || png_ptr->mode & PNG_AFTER_IDAT) + png_error(png_ptr, "Too many IDAT's found"); + } + else + png_ptr->mode |= PNG_AFTER_IDAT; + png_handle_unknown(png_ptr, info_ptr, length); + if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4)) + png_ptr->mode |= PNG_HAVE_PLTE; + } +#endif + else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) + { + /* Zero length IDATs are legal after the last IDAT has been + * read, but not after other chunks have been read. + */ + if (length > 0 || png_ptr->mode & PNG_AFTER_IDAT) + png_error(png_ptr, "Too many IDAT's found"); + png_crc_finish(png_ptr, length); + } + else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4)) + png_handle_PLTE(png_ptr, info_ptr, length); +#if defined(PNG_READ_bKGD_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4)) + png_handle_bKGD(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_cHRM_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4)) + png_handle_cHRM(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_gAMA_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4)) + png_handle_gAMA(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_hIST_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4)) + png_handle_hIST(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_oFFs_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4)) + png_handle_oFFs(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_pCAL_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4)) + png_handle_pCAL(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_sCAL_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4)) + png_handle_sCAL(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_pHYs_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4)) + png_handle_pHYs(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_sBIT_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4)) + png_handle_sBIT(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_sRGB_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4)) + png_handle_sRGB(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_iCCP_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4)) + png_handle_iCCP(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_sPLT_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4)) + png_handle_sPLT(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_tEXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4)) + png_handle_tEXt(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_tIME_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4)) + png_handle_tIME(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_tRNS_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4)) + png_handle_tRNS(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_zTXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4)) + png_handle_zTXt(png_ptr, info_ptr, length); +#endif +#if defined(PNG_READ_iTXt_SUPPORTED) + else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4)) + png_handle_iTXt(png_ptr, info_ptr, length); +#endif + else + png_handle_unknown(png_ptr, info_ptr, length); + } while (!(png_ptr->mode & PNG_HAVE_IEND)); +} +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */ + +/* free all memory used by the read */ +void PNGAPI +png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr, + png_infopp end_info_ptr_ptr) +{ + png_structp png_ptr = NULL; + png_infop info_ptr = NULL, end_info_ptr = NULL; +#ifdef PNG_USER_MEM_SUPPORTED + png_free_ptr free_fn; + png_voidp mem_ptr; +#endif + + png_debug(1, "in png_destroy_read_struct\n"); + if (png_ptr_ptr != NULL) + png_ptr = *png_ptr_ptr; + + if (info_ptr_ptr != NULL) + info_ptr = *info_ptr_ptr; + + if (end_info_ptr_ptr != NULL) + end_info_ptr = *end_info_ptr_ptr; + +#ifdef PNG_USER_MEM_SUPPORTED + free_fn = png_ptr->free_fn; + mem_ptr = png_ptr->mem_ptr; +#endif + + png_read_destroy(png_ptr, info_ptr, end_info_ptr); + + if (info_ptr != NULL) + { +#if defined(PNG_TEXT_SUPPORTED) + png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1); +#endif + +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn, + (png_voidp)mem_ptr); +#else + png_destroy_struct((png_voidp)info_ptr); +#endif + *info_ptr_ptr = NULL; + } + + if (end_info_ptr != NULL) + { +#if defined(PNG_READ_TEXT_SUPPORTED) + png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1); +#endif +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn, + (png_voidp)mem_ptr); +#else + png_destroy_struct((png_voidp)end_info_ptr); +#endif + *end_info_ptr_ptr = NULL; + } + + if (png_ptr != NULL) + { +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn, + (png_voidp)mem_ptr); +#else + png_destroy_struct((png_voidp)png_ptr); +#endif + *png_ptr_ptr = NULL; + } +} + +/* free all memory used by the read (old method) */ +void /* PRIVATE */ +png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr) +{ +#ifdef PNG_SETJMP_SUPPORTED + jmp_buf tmp_jmp; +#endif + png_error_ptr error_fn; + png_error_ptr warning_fn; + png_voidp error_ptr; +#ifdef PNG_USER_MEM_SUPPORTED + png_free_ptr free_fn; +#endif + + png_debug(1, "in png_read_destroy\n"); + if (info_ptr != NULL) + png_info_destroy(png_ptr, info_ptr); + + if (end_info_ptr != NULL) + png_info_destroy(png_ptr, end_info_ptr); + + png_free(png_ptr, png_ptr->zbuf); + png_free(png_ptr, png_ptr->big_row_buf); + png_free(png_ptr, png_ptr->prev_row); +#if defined(PNG_READ_DITHER_SUPPORTED) + png_free(png_ptr, png_ptr->palette_lookup); + png_free(png_ptr, png_ptr->dither_index); +#endif +#if defined(PNG_READ_GAMMA_SUPPORTED) + png_free(png_ptr, png_ptr->gamma_table); +#endif +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + png_free(png_ptr, png_ptr->gamma_from_1); + png_free(png_ptr, png_ptr->gamma_to_1); +#endif +#ifdef PNG_FREE_ME_SUPPORTED + if (png_ptr->free_me & PNG_FREE_PLTE) + png_zfree(png_ptr, png_ptr->palette); + png_ptr->free_me &= ~PNG_FREE_PLTE; +#else + if (png_ptr->flags & PNG_FLAG_FREE_PLTE) + png_zfree(png_ptr, png_ptr->palette); + png_ptr->flags &= ~PNG_FLAG_FREE_PLTE; +#endif +#if defined(PNG_tRNS_SUPPORTED) || \ + defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) +#ifdef PNG_FREE_ME_SUPPORTED + if (png_ptr->free_me & PNG_FREE_TRNS) + png_free(png_ptr, png_ptr->trans); + png_ptr->free_me &= ~PNG_FREE_TRNS; +#else + if (png_ptr->flags & PNG_FLAG_FREE_TRNS) + png_free(png_ptr, png_ptr->trans); + png_ptr->flags &= ~PNG_FLAG_FREE_TRNS; +#endif +#endif +#if defined(PNG_READ_hIST_SUPPORTED) +#ifdef PNG_FREE_ME_SUPPORTED + if (png_ptr->free_me & PNG_FREE_HIST) + png_free(png_ptr, png_ptr->hist); + png_ptr->free_me &= ~PNG_FREE_HIST; +#else + if (png_ptr->flags & PNG_FLAG_FREE_HIST) + png_free(png_ptr, png_ptr->hist); + png_ptr->flags &= ~PNG_FLAG_FREE_HIST; +#endif +#endif +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (png_ptr->gamma_16_table != NULL) + { + int i; + int istop = (1 << (8 - png_ptr->gamma_shift)); + for (i = 0; i < istop; i++) + { + png_free(png_ptr, png_ptr->gamma_16_table[i]); + } + png_free(png_ptr, png_ptr->gamma_16_table); + } +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + if (png_ptr->gamma_16_from_1 != NULL) + { + int i; + int istop = (1 << (8 - png_ptr->gamma_shift)); + for (i = 0; i < istop; i++) + { + png_free(png_ptr, png_ptr->gamma_16_from_1[i]); + } + png_free(png_ptr, png_ptr->gamma_16_from_1); + } + if (png_ptr->gamma_16_to_1 != NULL) + { + int i; + int istop = (1 << (8 - png_ptr->gamma_shift)); + for (i = 0; i < istop; i++) + { + png_free(png_ptr, png_ptr->gamma_16_to_1[i]); + } + png_free(png_ptr, png_ptr->gamma_16_to_1); + } +#endif +#endif +#if defined(PNG_TIME_RFC1123_SUPPORTED) + png_free(png_ptr, png_ptr->time_buffer); +#endif + + inflateEnd(&png_ptr->zstream); +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED + png_free(png_ptr, png_ptr->save_buffer); +#endif + +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED +#ifdef PNG_TEXT_SUPPORTED + png_free(png_ptr, png_ptr->current_text); +#endif /* PNG_TEXT_SUPPORTED */ +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */ + + /* Save the important info out of the png_struct, in case it is + * being used again. + */ +#ifdef PNG_SETJMP_SUPPORTED + png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf)); +#endif + + error_fn = png_ptr->error_fn; + warning_fn = png_ptr->warning_fn; + error_ptr = png_ptr->error_ptr; +#ifdef PNG_USER_MEM_SUPPORTED + free_fn = png_ptr->free_fn; +#endif + + png_memset(png_ptr, 0, png_sizeof (png_struct)); + + png_ptr->error_fn = error_fn; + png_ptr->warning_fn = warning_fn; + png_ptr->error_ptr = error_ptr; +#ifdef PNG_USER_MEM_SUPPORTED + png_ptr->free_fn = free_fn; +#endif + +#ifdef PNG_SETJMP_SUPPORTED + png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf)); +#endif + +} + +void PNGAPI +png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn) +{ + png_ptr->read_row_fn = read_row_fn; +} + + +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED +#if defined(PNG_INFO_IMAGE_SUPPORTED) +void PNGAPI +png_read_png(png_structp png_ptr, png_infop info_ptr, + int transforms, + voidp params) +{ + int row; + +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) + /* invert the alpha channel from opacity to transparency + */ + if (transforms & PNG_TRANSFORM_INVERT_ALPHA) + png_set_invert_alpha(png_ptr); +#endif + + /* png_read_info() gives us all of the information from the + * PNG file before the first IDAT (image data chunk). + */ + png_read_info(png_ptr, info_ptr); + if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep)) + png_error(png_ptr,"Image is too high to process with png_read_png()"); + + /* -------------- image transformations start here ------------------- */ + +#if defined(PNG_READ_16_TO_8_SUPPORTED) + /* tell libpng to strip 16 bit/color files down to 8 bits per color + */ + if (transforms & PNG_TRANSFORM_STRIP_16) + png_set_strip_16(png_ptr); +#endif + +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED) + /* Strip alpha bytes from the input data without combining with + * the background (not recommended). + */ + if (transforms & PNG_TRANSFORM_STRIP_ALPHA) + png_set_strip_alpha(png_ptr); +#endif + +#if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED) + /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single + * byte into separate bytes (useful for paletted and grayscale images). + */ + if (transforms & PNG_TRANSFORM_PACKING) + png_set_packing(png_ptr); +#endif + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + /* Change the order of packed pixels to least significant bit first + * (not useful if you are using png_set_packing). + */ + if (transforms & PNG_TRANSFORM_PACKSWAP) + png_set_packswap(png_ptr); +#endif + +#if defined(PNG_READ_EXPAND_SUPPORTED) + /* Expand paletted colors into true RGB triplets + * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel + * Expand paletted or RGB images with transparency to full alpha + * channels so the data will be available as RGBA quartets. + */ + if (transforms & PNG_TRANSFORM_EXPAND) + if ((png_ptr->bit_depth < 8) || + (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) || + (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))) + png_set_expand(png_ptr); +#endif + + /* We don't handle background color or gamma transformation or dithering. + */ + +#if defined(PNG_READ_INVERT_SUPPORTED) + /* invert monochrome files to have 0 as white and 1 as black + */ + if (transforms & PNG_TRANSFORM_INVERT_MONO) + png_set_invert_mono(png_ptr); +#endif + +#if defined(PNG_READ_SHIFT_SUPPORTED) + /* If you want to shift the pixel values from the range [0,255] or + * [0,65535] to the original [0,7] or [0,31], or whatever range the + * colors were originally in: + */ + if ((transforms & PNG_TRANSFORM_SHIFT) + && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT)) + { + png_color_8p sig_bit; + + png_get_sBIT(png_ptr, info_ptr, &sig_bit); + png_set_shift(png_ptr, sig_bit); + } +#endif + +#if defined(PNG_READ_BGR_SUPPORTED) + /* flip the RGB pixels to BGR (or RGBA to BGRA) + */ + if (transforms & PNG_TRANSFORM_BGR) + png_set_bgr(png_ptr); +#endif + +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) + /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) + */ + if (transforms & PNG_TRANSFORM_SWAP_ALPHA) + png_set_swap_alpha(png_ptr); +#endif + +#if defined(PNG_READ_SWAP_SUPPORTED) + /* swap bytes of 16 bit files to least significant byte first + */ + if (transforms & PNG_TRANSFORM_SWAP_ENDIAN) + png_set_swap(png_ptr); +#endif + + /* We don't handle adding filler bytes */ + + /* Optional call to gamma correct and add the background to the palette + * and update info structure. REQUIRED if you are expecting libpng to + * update the palette for you (i.e., you selected such a transform above). + */ + png_read_update_info(png_ptr, info_ptr); + + /* -------------- image transformations end here ------------------- */ + +#ifdef PNG_FREE_ME_SUPPORTED + png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0); +#endif + if(info_ptr->row_pointers == NULL) + { + info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr, + info_ptr->height * png_sizeof(png_bytep)); +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_ROWS; +#endif + for (row = 0; row < (int)info_ptr->height; row++) + { + info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr, + png_get_rowbytes(png_ptr, info_ptr)); + } + } + + png_read_image(png_ptr, info_ptr->row_pointers); + info_ptr->valid |= PNG_INFO_IDAT; + + /* read rest of file, and get additional chunks in info_ptr - REQUIRED */ + png_read_end(png_ptr, info_ptr); + + if(transforms == 0 || params == NULL) + /* quiet compiler warnings */ return; + +} +#endif +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/png/pngrio.c b/SlnkDWFImpl/CxImage/png/pngrio.c new file mode 100644 index 0000000..0a9269c --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngrio.c @@ -0,0 +1,161 @@ + +/* pngrio.c - functions for data input + * + * libpng 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * This file provides a location for all input. Users who need + * special handling are expected to write a function that has the same + * arguments as this and performs a similar function, but that possibly + * has a different input method. Note that you shouldn't change this + * function, but rather write a replacement function and then make + * libpng use it at run time with png_set_read_fn(...). + */ + +#define PNG_INTERNAL +#include "png.h" + +/* Read the data from whatever input you are using. The default routine + reads from a file pointer. Note that this routine sometimes gets called + with very small lengths, so you should implement some kind of simple + buffering if you are using unbuffered reads. This should never be asked + to read more then 64K on a 16 bit machine. */ +void /* PRIVATE */ +png_read_data(png_structp png_ptr, png_bytep data, png_size_t length) +{ + png_debug1(4,"reading %d bytes\n", (int)length); + if (png_ptr->read_data_fn != NULL) + (*(png_ptr->read_data_fn))(png_ptr, data, length); + else + png_error(png_ptr, "Call to NULL read function"); +} + +#if !defined(PNG_NO_STDIO) +/* This is the function that does the actual reading of data. If you are + not reading from a standard C stream, you should create a replacement + read_data function and use it at run time with png_set_read_fn(), rather + than changing the library. */ +#ifndef USE_FAR_KEYWORD +void PNGAPI +png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length) +{ + png_size_t check; + + /* fread() returns 0 on error, so it is OK to store this in a png_size_t + * instead of an int, which is what fread() actually returns. + */ +#if defined(_WIN32_WCE) + if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) ) + check = 0; +#else + check = (png_size_t)fread(data, (png_size_t)1, length, + (png_FILE_p)png_ptr->io_ptr); +#endif + + if (check != length) + png_error(png_ptr, "Read Error"); +} +#else +/* this is the model-independent version. Since the standard I/O library + can't handle far buffers in the medium and small models, we have to copy + the data. +*/ + +#define NEAR_BUF_SIZE 1024 +#define MIN(a,b) (a <= b ? a : b) + +static void /* PRIVATE */ +png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length) +{ + int check; + png_byte *n_data; + png_FILE_p io_ptr; + + /* Check if data really is near. If so, use usual code. */ + n_data = (png_byte *)CVT_PTR_NOCHECK(data); + io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr); + if ((png_bytep)n_data == data) + { +#if defined(_WIN32_WCE) + if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) ) + check = 0; +#else + check = fread(n_data, 1, length, io_ptr); +#endif + } + else + { + png_byte buf[NEAR_BUF_SIZE]; + png_size_t read, remaining, err; + check = 0; + remaining = length; + do + { + read = MIN(NEAR_BUF_SIZE, remaining); +#if defined(_WIN32_WCE) + if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) ) + err = 0; +#else + err = fread(buf, (png_size_t)1, read, io_ptr); +#endif + png_memcpy(data, buf, read); /* copy far buffer to near buffer */ + if(err != read) + break; + else + check += err; + data += read; + remaining -= read; + } + while (remaining != 0); + } + if ((png_uint_32)check != (png_uint_32)length) + png_error(png_ptr, "read Error"); +} +#endif +#endif + +/* This function allows the application to supply a new input function + for libpng if standard C streams aren't being used. + + This function takes as its arguments: + png_ptr - pointer to a png input data structure + io_ptr - pointer to user supplied structure containing info about + the input functions. May be NULL. + read_data_fn - pointer to a new input function that takes as its + arguments a pointer to a png_struct, a pointer to + a location where input data can be stored, and a 32-bit + unsigned int that is the number of bytes to be read. + To exit and output any fatal error messages the new write + function should call png_error(png_ptr, "Error msg"). */ +void PNGAPI +png_set_read_fn(png_structp png_ptr, png_voidp io_ptr, + png_rw_ptr read_data_fn) +{ + png_ptr->io_ptr = io_ptr; + +#if !defined(PNG_NO_STDIO) + if (read_data_fn != NULL) + png_ptr->read_data_fn = read_data_fn; + else + png_ptr->read_data_fn = png_default_read_data; +#else + png_ptr->read_data_fn = read_data_fn; +#endif + + /* It is an error to write to a read device */ + if (png_ptr->write_data_fn != NULL) + { + png_ptr->write_data_fn = NULL; + png_warning(png_ptr, + "It's an error to set both read_data_fn and write_data_fn in the "); + png_warning(png_ptr, + "same structure. Resetting write_data_fn to NULL."); + } + +#if defined(PNG_WRITE_FLUSH_SUPPORTED) + png_ptr->output_flush_fn = NULL; +#endif +} diff --git a/SlnkDWFImpl/CxImage/png/pngrtran.c b/SlnkDWFImpl/CxImage/png/pngrtran.c new file mode 100644 index 0000000..9cf1c5c --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngrtran.c @@ -0,0 +1,4177 @@ + +/* pngrtran.c - transforms the data in a row for PNG readers + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * This file contains functions optionally called by an application + * in order to tell libpng how to handle data when reading a PNG. + * Transformations that are used in both reading and writing are + * in pngtrans.c. + */ + +#define PNG_INTERNAL +#include "png.h" + +/* Set the action on getting a CRC error for an ancillary or critical chunk. */ +void PNGAPI +png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action) +{ + png_debug(1, "in png_set_crc_action\n"); + /* Tell libpng how we react to CRC errors in critical chunks */ + switch (crit_action) + { + case PNG_CRC_NO_CHANGE: /* leave setting as is */ + break; + case PNG_CRC_WARN_USE: /* warn/use data */ + png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK; + png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE; + break; + case PNG_CRC_QUIET_USE: /* quiet/use data */ + png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK; + png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE | + PNG_FLAG_CRC_CRITICAL_IGNORE; + break; + case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */ + png_warning(png_ptr, "Can't discard critical data on CRC error."); + case PNG_CRC_ERROR_QUIT: /* error/quit */ + case PNG_CRC_DEFAULT: + default: + png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK; + break; + } + + switch (ancil_action) + { + case PNG_CRC_NO_CHANGE: /* leave setting as is */ + break; + case PNG_CRC_WARN_USE: /* warn/use data */ + png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK; + png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE; + break; + case PNG_CRC_QUIET_USE: /* quiet/use data */ + png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK; + png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE | + PNG_FLAG_CRC_ANCILLARY_NOWARN; + break; + case PNG_CRC_ERROR_QUIT: /* error/quit */ + png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK; + png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN; + break; + case PNG_CRC_WARN_DISCARD: /* warn/discard data */ + case PNG_CRC_DEFAULT: + default: + png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK; + break; + } +} + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) && \ + defined(PNG_FLOATING_POINT_SUPPORTED) +/* handle alpha and tRNS via a background color */ +void PNGAPI +png_set_background(png_structp png_ptr, + png_color_16p background_color, int background_gamma_code, + int need_expand, double background_gamma) +{ + png_debug(1, "in png_set_background\n"); + if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN) + { + png_warning(png_ptr, "Application must supply a known background gamma"); + return; + } + + png_ptr->transformations |= PNG_BACKGROUND; + png_memcpy(&(png_ptr->background), background_color, + png_sizeof(png_color_16)); + png_ptr->background_gamma = (float)background_gamma; + png_ptr->background_gamma_type = (png_byte)(background_gamma_code); + png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0); + + /* Note: if need_expand is set and color_type is either RGB or RGB_ALPHA + * (in which case need_expand is superfluous anyway), the background color + * might actually be gray yet not be flagged as such. This is not a problem + * for the current code, which uses PNG_BACKGROUND_IS_GRAY only to + * decide when to do the png_do_gray_to_rgb() transformation. + */ + if ((need_expand && !(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) || + (!need_expand && background_color->red == background_color->green && + background_color->red == background_color->blue)) + png_ptr->mode |= PNG_BACKGROUND_IS_GRAY; +} +#endif + +#if defined(PNG_READ_16_TO_8_SUPPORTED) +/* strip 16 bit depth files to 8 bit depth */ +void PNGAPI +png_set_strip_16(png_structp png_ptr) +{ + png_debug(1, "in png_set_strip_16\n"); + png_ptr->transformations |= PNG_16_TO_8; +} +#endif + +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED) +void PNGAPI +png_set_strip_alpha(png_structp png_ptr) +{ + png_debug(1, "in png_set_strip_alpha\n"); + png_ptr->transformations |= PNG_STRIP_ALPHA; +} +#endif + +#if defined(PNG_READ_DITHER_SUPPORTED) +/* Dither file to 8 bit. Supply a palette, the current number + * of elements in the palette, the maximum number of elements + * allowed, and a histogram if possible. If the current number + * of colors is greater then the maximum number, the palette will be + * modified to fit in the maximum number. "full_dither" indicates + * whether we need a dithering cube set up for RGB images, or if we + * simply are reducing the number of colors in a paletted image. + */ + +typedef struct png_dsort_struct +{ + struct png_dsort_struct FAR * next; + png_byte left; + png_byte right; +} png_dsort; +typedef png_dsort FAR * png_dsortp; +typedef png_dsort FAR * FAR * png_dsortpp; + +void PNGAPI +png_set_dither(png_structp png_ptr, png_colorp palette, + int num_palette, int maximum_colors, png_uint_16p histogram, + int full_dither) +{ + png_debug(1, "in png_set_dither\n"); + png_ptr->transformations |= PNG_DITHER; + + if (!full_dither) + { + int i; + + png_ptr->dither_index = (png_bytep)png_malloc(png_ptr, + (png_uint_32)(num_palette * png_sizeof (png_byte))); + for (i = 0; i < num_palette; i++) + png_ptr->dither_index[i] = (png_byte)i; + } + + if (num_palette > maximum_colors) + { + if (histogram != NULL) + { + /* This is easy enough, just throw out the least used colors. + Perhaps not the best solution, but good enough. */ + + int i; + + /* initialize an array to sort colors */ + png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr, + (png_uint_32)(num_palette * png_sizeof (png_byte))); + + /* initialize the dither_sort array */ + for (i = 0; i < num_palette; i++) + png_ptr->dither_sort[i] = (png_byte)i; + + /* Find the least used palette entries by starting a + bubble sort, and running it until we have sorted + out enough colors. Note that we don't care about + sorting all the colors, just finding which are + least used. */ + + for (i = num_palette - 1; i >= maximum_colors; i--) + { + int done; /* to stop early if the list is pre-sorted */ + int j; + + done = 1; + for (j = 0; j < i; j++) + { + if (histogram[png_ptr->dither_sort[j]] + < histogram[png_ptr->dither_sort[j + 1]]) + { + png_byte t; + + t = png_ptr->dither_sort[j]; + png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1]; + png_ptr->dither_sort[j + 1] = t; + done = 0; + } + } + if (done) + break; + } + + /* swap the palette around, and set up a table, if necessary */ + if (full_dither) + { + int j = num_palette; + + /* put all the useful colors within the max, but don't + move the others */ + for (i = 0; i < maximum_colors; i++) + { + if ((int)png_ptr->dither_sort[i] >= maximum_colors) + { + do + j--; + while ((int)png_ptr->dither_sort[j] >= maximum_colors); + palette[i] = palette[j]; + } + } + } + else + { + int j = num_palette; + + /* move all the used colors inside the max limit, and + develop a translation table */ + for (i = 0; i < maximum_colors; i++) + { + /* only move the colors we need to */ + if ((int)png_ptr->dither_sort[i] >= maximum_colors) + { + png_color tmp_color; + + do + j--; + while ((int)png_ptr->dither_sort[j] >= maximum_colors); + + tmp_color = palette[j]; + palette[j] = palette[i]; + palette[i] = tmp_color; + /* indicate where the color went */ + png_ptr->dither_index[j] = (png_byte)i; + png_ptr->dither_index[i] = (png_byte)j; + } + } + + /* find closest color for those colors we are not using */ + for (i = 0; i < num_palette; i++) + { + if ((int)png_ptr->dither_index[i] >= maximum_colors) + { + int min_d, k, min_k, d_index; + + /* find the closest color to one we threw out */ + d_index = png_ptr->dither_index[i]; + min_d = PNG_COLOR_DIST(palette[d_index], palette[0]); + for (k = 1, min_k = 0; k < maximum_colors; k++) + { + int d; + + d = PNG_COLOR_DIST(palette[d_index], palette[k]); + + if (d < min_d) + { + min_d = d; + min_k = k; + } + } + /* point to closest color */ + png_ptr->dither_index[i] = (png_byte)min_k; + } + } + } + png_free(png_ptr, png_ptr->dither_sort); + png_ptr->dither_sort=NULL; + } + else + { + /* This is much harder to do simply (and quickly). Perhaps + we need to go through a median cut routine, but those + don't always behave themselves with only a few colors + as input. So we will just find the closest two colors, + and throw out one of them (chosen somewhat randomly). + [We don't understand this at all, so if someone wants to + work on improving it, be our guest - AED, GRP] + */ + int i; + int max_d; + int num_new_palette; + png_dsortp t; + png_dsortpp hash; + + t=NULL; + + /* initialize palette index arrays */ + png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr, + (png_uint_32)(num_palette * png_sizeof (png_byte))); + png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr, + (png_uint_32)(num_palette * png_sizeof (png_byte))); + + /* initialize the sort array */ + for (i = 0; i < num_palette; i++) + { + png_ptr->index_to_palette[i] = (png_byte)i; + png_ptr->palette_to_index[i] = (png_byte)i; + } + + hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 * + png_sizeof (png_dsortp))); + for (i = 0; i < 769; i++) + hash[i] = NULL; +/* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */ + + num_new_palette = num_palette; + + /* initial wild guess at how far apart the farthest pixel + pair we will be eliminating will be. Larger + numbers mean more areas will be allocated, Smaller + numbers run the risk of not saving enough data, and + having to do this all over again. + + I have not done extensive checking on this number. + */ + max_d = 96; + + while (num_new_palette > maximum_colors) + { + for (i = 0; i < num_new_palette - 1; i++) + { + int j; + + for (j = i + 1; j < num_new_palette; j++) + { + int d; + + d = PNG_COLOR_DIST(palette[i], palette[j]); + + if (d <= max_d) + { + + t = (png_dsortp)png_malloc_warn(png_ptr, + (png_uint_32)(png_sizeof(png_dsort))); + if (t == NULL) + break; + t->next = hash[d]; + t->left = (png_byte)i; + t->right = (png_byte)j; + hash[d] = t; + } + } + if (t == NULL) + break; + } + + if (t != NULL) + for (i = 0; i <= max_d; i++) + { + if (hash[i] != NULL) + { + png_dsortp p; + + for (p = hash[i]; p; p = p->next) + { + if ((int)png_ptr->index_to_palette[p->left] + < num_new_palette && + (int)png_ptr->index_to_palette[p->right] + < num_new_palette) + { + int j, next_j; + + if (num_new_palette & 0x01) + { + j = p->left; + next_j = p->right; + } + else + { + j = p->right; + next_j = p->left; + } + + num_new_palette--; + palette[png_ptr->index_to_palette[j]] + = palette[num_new_palette]; + if (!full_dither) + { + int k; + + for (k = 0; k < num_palette; k++) + { + if (png_ptr->dither_index[k] == + png_ptr->index_to_palette[j]) + png_ptr->dither_index[k] = + png_ptr->index_to_palette[next_j]; + if ((int)png_ptr->dither_index[k] == + num_new_palette) + png_ptr->dither_index[k] = + png_ptr->index_to_palette[j]; + } + } + + png_ptr->index_to_palette[png_ptr->palette_to_index + [num_new_palette]] = png_ptr->index_to_palette[j]; + png_ptr->palette_to_index[png_ptr->index_to_palette[j]] + = png_ptr->palette_to_index[num_new_palette]; + + png_ptr->index_to_palette[j] = (png_byte)num_new_palette; + png_ptr->palette_to_index[num_new_palette] = (png_byte)j; + } + if (num_new_palette <= maximum_colors) + break; + } + if (num_new_palette <= maximum_colors) + break; + } + } + + for (i = 0; i < 769; i++) + { + if (hash[i] != NULL) + { + png_dsortp p = hash[i]; + while (p) + { + t = p->next; + png_free(png_ptr, p); + p = t; + } + } + hash[i] = 0; + } + max_d += 96; + } + png_free(png_ptr, hash); + png_free(png_ptr, png_ptr->palette_to_index); + png_free(png_ptr, png_ptr->index_to_palette); + png_ptr->palette_to_index=NULL; + png_ptr->index_to_palette=NULL; + } + num_palette = maximum_colors; + } + if (png_ptr->palette == NULL) + { + png_ptr->palette = palette; + } + png_ptr->num_palette = (png_uint_16)num_palette; + + if (full_dither) + { + int i; + png_bytep distance; + int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS + + PNG_DITHER_BLUE_BITS; + int num_red = (1 << PNG_DITHER_RED_BITS); + int num_green = (1 << PNG_DITHER_GREEN_BITS); + int num_blue = (1 << PNG_DITHER_BLUE_BITS); + png_size_t num_entries = ((png_size_t)1 << total_bits); + + png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr, + (png_uint_32)(num_entries * png_sizeof (png_byte))); + + png_memset(png_ptr->palette_lookup, 0, num_entries * + png_sizeof (png_byte)); + + distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries * + png_sizeof(png_byte))); + + png_memset(distance, 0xff, num_entries * png_sizeof(png_byte)); + + for (i = 0; i < num_palette; i++) + { + int ir, ig, ib; + int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS)); + int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS)); + int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS)); + + for (ir = 0; ir < num_red; ir++) + { + /* int dr = abs(ir - r); */ + int dr = ((ir > r) ? ir - r : r - ir); + int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS)); + + for (ig = 0; ig < num_green; ig++) + { + /* int dg = abs(ig - g); */ + int dg = ((ig > g) ? ig - g : g - ig); + int dt = dr + dg; + int dm = ((dr > dg) ? dr : dg); + int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS); + + for (ib = 0; ib < num_blue; ib++) + { + int d_index = index_g | ib; + /* int db = abs(ib - b); */ + int db = ((ib > b) ? ib - b : b - ib); + int dmax = ((dm > db) ? dm : db); + int d = dmax + dt + db; + + if (d < (int)distance[d_index]) + { + distance[d_index] = (png_byte)d; + png_ptr->palette_lookup[d_index] = (png_byte)i; + } + } + } + } + } + + png_free(png_ptr, distance); + } +} +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED) +/* Transform the image from the file_gamma to the screen_gamma. We + * only do transformations on images where the file_gamma and screen_gamma + * are not close reciprocals, otherwise it slows things down slightly, and + * also needlessly introduces small errors. + * + * We will turn off gamma transformation later if no semitransparent entries + * are present in the tRNS array for palette images. We can't do it here + * because we don't necessarily have the tRNS chunk yet. + */ +void PNGAPI +png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma) +{ + png_debug(1, "in png_set_gamma\n"); + if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) || + (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) || + (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)) + png_ptr->transformations |= PNG_GAMMA; + png_ptr->gamma = (float)file_gamma; + png_ptr->screen_gamma = (float)scrn_gamma; +} +#endif + +#if defined(PNG_READ_EXPAND_SUPPORTED) +/* Expand paletted images to RGB, expand grayscale images of + * less than 8-bit depth to 8-bit depth, and expand tRNS chunks + * to alpha channels. + */ +void PNGAPI +png_set_expand(png_structp png_ptr) +{ + png_debug(1, "in png_set_expand\n"); + png_ptr->transformations |= PNG_EXPAND; +} + +/* GRR 19990627: the following three functions currently are identical + * to png_set_expand(). However, it is entirely reasonable that someone + * might wish to expand an indexed image to RGB but *not* expand a single, + * fully transparent palette entry to a full alpha channel--perhaps instead + * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace + * the transparent color with a particular RGB value, or drop tRNS entirely. + * IOW, a future version of the library may make the transformations flag + * a bit more fine-grained, with separate bits for each of these three + * functions. + * + * More to the point, these functions make it obvious what libpng will be + * doing, whereas "expand" can (and does) mean any number of things. + */ + +/* Expand paletted images to RGB. */ +void PNGAPI +png_set_palette_to_rgb(png_structp png_ptr) +{ + png_debug(1, "in png_set_expand\n"); + png_ptr->transformations |= PNG_EXPAND; +} + +/* Expand grayscale images of less than 8-bit depth to 8 bits. */ +void PNGAPI +png_set_gray_1_2_4_to_8(png_structp png_ptr) +{ + png_debug(1, "in png_set_expand\n"); + png_ptr->transformations |= PNG_EXPAND; +} + +/* Expand tRNS chunks to alpha channels. */ +void PNGAPI +png_set_tRNS_to_alpha(png_structp png_ptr) +{ + png_debug(1, "in png_set_expand\n"); + png_ptr->transformations |= PNG_EXPAND; +} +#endif /* defined(PNG_READ_EXPAND_SUPPORTED) */ + +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) +void PNGAPI +png_set_gray_to_rgb(png_structp png_ptr) +{ + png_debug(1, "in png_set_gray_to_rgb\n"); + png_ptr->transformations |= PNG_GRAY_TO_RGB; +} +#endif + +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) +#if defined(PNG_FLOATING_POINT_SUPPORTED) +/* Convert a RGB image to a grayscale of the same width. This allows us, + * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image. + */ + +void PNGAPI +png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red, + double green) +{ + int red_fixed = (int)((float)red*100000.0 + 0.5); + int green_fixed = (int)((float)green*100000.0 + 0.5); + png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed); +} +#endif + +void PNGAPI +png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action, + png_fixed_point red, png_fixed_point green) +{ + png_debug(1, "in png_set_rgb_to_gray\n"); + switch(error_action) + { + case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY; + break; + case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN; + break; + case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR; + } + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) +#if defined(PNG_READ_EXPAND_SUPPORTED) + png_ptr->transformations |= PNG_EXPAND; +#else + { + png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED."); + png_ptr->transformations &= ~PNG_RGB_TO_GRAY; + } +#endif + { + png_uint_16 red_int, green_int; + if(red < 0 || green < 0) + { + red_int = 6968; /* .212671 * 32768 + .5 */ + green_int = 23434; /* .715160 * 32768 + .5 */ + } + else if(red + green < 100000L) + { + red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L); + green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L); + } + else + { + png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients"); + red_int = 6968; + green_int = 23434; + } + png_ptr->rgb_to_gray_red_coeff = red_int; + png_ptr->rgb_to_gray_green_coeff = green_int; + png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int); + } +} +#endif + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_LEGACY_SUPPORTED) +void PNGAPI +png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr + read_user_transform_fn) +{ + png_debug(1, "in png_set_read_user_transform_fn\n"); +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) + png_ptr->transformations |= PNG_USER_TRANSFORM; + png_ptr->read_user_transform_fn = read_user_transform_fn; +#endif +#ifdef PNG_LEGACY_SUPPORTED + if(read_user_transform_fn) + png_warning(png_ptr, + "This version of libpng does not support user transforms"); +#endif +} +#endif + +/* Initialize everything needed for the read. This includes modifying + * the palette. + */ +void /* PRIVATE */ +png_init_read_transformations(png_structp png_ptr) +{ + png_debug(1, "in png_init_read_transformations\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if(png_ptr != NULL) +#endif + { +#if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \ + || defined(PNG_READ_GAMMA_SUPPORTED) + int color_type = png_ptr->color_type; +#endif + +#if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED) + if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) && + (png_ptr->transformations & PNG_EXPAND)) + { + if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */ + { + /* expand background chunk. */ + switch (png_ptr->bit_depth) + { + case 1: + png_ptr->background.gray *= (png_uint_16)0xff; + png_ptr->background.red = png_ptr->background.green + = png_ptr->background.blue = png_ptr->background.gray; + break; + case 2: + png_ptr->background.gray *= (png_uint_16)0x55; + png_ptr->background.red = png_ptr->background.green + = png_ptr->background.blue = png_ptr->background.gray; + break; + case 4: + png_ptr->background.gray *= (png_uint_16)0x11; + png_ptr->background.red = png_ptr->background.green + = png_ptr->background.blue = png_ptr->background.gray; + break; + case 8: + case 16: + png_ptr->background.red = png_ptr->background.green + = png_ptr->background.blue = png_ptr->background.gray; + break; + } + } + else if (color_type == PNG_COLOR_TYPE_PALETTE) + { + png_ptr->background.red = + png_ptr->palette[png_ptr->background.index].red; + png_ptr->background.green = + png_ptr->palette[png_ptr->background.index].green; + png_ptr->background.blue = + png_ptr->palette[png_ptr->background.index].blue; + +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) + if (png_ptr->transformations & PNG_INVERT_ALPHA) + { +#if defined(PNG_READ_EXPAND_SUPPORTED) + if (!(png_ptr->transformations & PNG_EXPAND)) +#endif + { + /* invert the alpha channel (in tRNS) unless the pixels are + going to be expanded, in which case leave it for later */ + int i,istop; + istop=(int)png_ptr->num_trans; + for (i=0; itrans[i] = (png_byte)(255 - png_ptr->trans[i]); + } + } +#endif + + } + } +#endif + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED) + png_ptr->background_1 = png_ptr->background; +#endif +#if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED) + + if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0) + && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0) + < PNG_GAMMA_THRESHOLD)) + { + int i,k; + k=0; + for (i=0; inum_trans; i++) + { + if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff) + k=1; /* partial transparency is present */ + } + if (k == 0) + png_ptr->transformations &= (~PNG_GAMMA); + } + + if (png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) + { + png_build_gamma_table(png_ptr); +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + if (png_ptr->transformations & PNG_BACKGROUND) + { + if (color_type == PNG_COLOR_TYPE_PALETTE) + { + /* could skip if no transparency and + */ + png_color back, back_1; + png_colorp palette = png_ptr->palette; + int num_palette = png_ptr->num_palette; + int i; + if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE) + { + back.red = png_ptr->gamma_table[png_ptr->background.red]; + back.green = png_ptr->gamma_table[png_ptr->background.green]; + back.blue = png_ptr->gamma_table[png_ptr->background.blue]; + + back_1.red = png_ptr->gamma_to_1[png_ptr->background.red]; + back_1.green = png_ptr->gamma_to_1[png_ptr->background.green]; + back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue]; + } + else + { + double g, gs; + + switch (png_ptr->background_gamma_type) + { + case PNG_BACKGROUND_GAMMA_SCREEN: + g = (png_ptr->screen_gamma); + gs = 1.0; + break; + case PNG_BACKGROUND_GAMMA_FILE: + g = 1.0 / (png_ptr->gamma); + gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma); + break; + case PNG_BACKGROUND_GAMMA_UNIQUE: + g = 1.0 / (png_ptr->background_gamma); + gs = 1.0 / (png_ptr->background_gamma * + png_ptr->screen_gamma); + break; + default: + g = 1.0; /* back_1 */ + gs = 1.0; /* back */ + } + + if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD) + { + back.red = (png_byte)png_ptr->background.red; + back.green = (png_byte)png_ptr->background.green; + back.blue = (png_byte)png_ptr->background.blue; + } + else + { + back.red = (png_byte)(pow( + (double)png_ptr->background.red/255, gs) * 255.0 + .5); + back.green = (png_byte)(pow( + (double)png_ptr->background.green/255, gs) * 255.0 + .5); + back.blue = (png_byte)(pow( + (double)png_ptr->background.blue/255, gs) * 255.0 + .5); + } + + back_1.red = (png_byte)(pow( + (double)png_ptr->background.red/255, g) * 255.0 + .5); + back_1.green = (png_byte)(pow( + (double)png_ptr->background.green/255, g) * 255.0 + .5); + back_1.blue = (png_byte)(pow( + (double)png_ptr->background.blue/255, g) * 255.0 + .5); + } + for (i = 0; i < num_palette; i++) + { + if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff) + { + if (png_ptr->trans[i] == 0) + { + palette[i] = back; + } + else /* if (png_ptr->trans[i] != 0xff) */ + { + png_byte v, w; + + v = png_ptr->gamma_to_1[palette[i].red]; + png_composite(w, v, png_ptr->trans[i], back_1.red); + palette[i].red = png_ptr->gamma_from_1[w]; + + v = png_ptr->gamma_to_1[palette[i].green]; + png_composite(w, v, png_ptr->trans[i], back_1.green); + palette[i].green = png_ptr->gamma_from_1[w]; + + v = png_ptr->gamma_to_1[palette[i].blue]; + png_composite(w, v, png_ptr->trans[i], back_1.blue); + palette[i].blue = png_ptr->gamma_from_1[w]; + } + } + else + { + palette[i].red = png_ptr->gamma_table[palette[i].red]; + palette[i].green = png_ptr->gamma_table[palette[i].green]; + palette[i].blue = png_ptr->gamma_table[palette[i].blue]; + } + } + } + /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */ + else + /* color_type != PNG_COLOR_TYPE_PALETTE */ + { + double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1); + double g = 1.0; + double gs = 1.0; + + switch (png_ptr->background_gamma_type) + { + case PNG_BACKGROUND_GAMMA_SCREEN: + g = (png_ptr->screen_gamma); + gs = 1.0; + break; + case PNG_BACKGROUND_GAMMA_FILE: + g = 1.0 / (png_ptr->gamma); + gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma); + break; + case PNG_BACKGROUND_GAMMA_UNIQUE: + g = 1.0 / (png_ptr->background_gamma); + gs = 1.0 / (png_ptr->background_gamma * + png_ptr->screen_gamma); + break; + } + + png_ptr->background_1.gray = (png_uint_16)(pow( + (double)png_ptr->background.gray / m, g) * m + .5); + png_ptr->background.gray = (png_uint_16)(pow( + (double)png_ptr->background.gray / m, gs) * m + .5); + + if ((png_ptr->background.red != png_ptr->background.green) || + (png_ptr->background.red != png_ptr->background.blue) || + (png_ptr->background.red != png_ptr->background.gray)) + { + /* RGB or RGBA with color background */ + png_ptr->background_1.red = (png_uint_16)(pow( + (double)png_ptr->background.red / m, g) * m + .5); + png_ptr->background_1.green = (png_uint_16)(pow( + (double)png_ptr->background.green / m, g) * m + .5); + png_ptr->background_1.blue = (png_uint_16)(pow( + (double)png_ptr->background.blue / m, g) * m + .5); + png_ptr->background.red = (png_uint_16)(pow( + (double)png_ptr->background.red / m, gs) * m + .5); + png_ptr->background.green = (png_uint_16)(pow( + (double)png_ptr->background.green / m, gs) * m + .5); + png_ptr->background.blue = (png_uint_16)(pow( + (double)png_ptr->background.blue / m, gs) * m + .5); + } + else + { + /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */ + png_ptr->background_1.red = png_ptr->background_1.green + = png_ptr->background_1.blue = png_ptr->background_1.gray; + png_ptr->background.red = png_ptr->background.green + = png_ptr->background.blue = png_ptr->background.gray; + } + } + } + else + /* transformation does not include PNG_BACKGROUND */ +#endif /* PNG_READ_BACKGROUND_SUPPORTED */ + if (color_type == PNG_COLOR_TYPE_PALETTE) + { + png_colorp palette = png_ptr->palette; + int num_palette = png_ptr->num_palette; + int i; + + for (i = 0; i < num_palette; i++) + { + palette[i].red = png_ptr->gamma_table[palette[i].red]; + palette[i].green = png_ptr->gamma_table[palette[i].green]; + palette[i].blue = png_ptr->gamma_table[palette[i].blue]; + } + } + } +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + else +#endif +#endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */ +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + /* No GAMMA transformation */ + if ((png_ptr->transformations & PNG_BACKGROUND) && + (color_type == PNG_COLOR_TYPE_PALETTE)) + { + int i; + int istop = (int)png_ptr->num_trans; + png_color back; + png_colorp palette = png_ptr->palette; + + back.red = (png_byte)png_ptr->background.red; + back.green = (png_byte)png_ptr->background.green; + back.blue = (png_byte)png_ptr->background.blue; + + for (i = 0; i < istop; i++) + { + if (png_ptr->trans[i] == 0) + { + palette[i] = back; + } + else if (png_ptr->trans[i] != 0xff) + { + /* The png_composite() macro is defined in png.h */ + png_composite(palette[i].red, palette[i].red, + png_ptr->trans[i], back.red); + png_composite(palette[i].green, palette[i].green, + png_ptr->trans[i], back.green); + png_composite(palette[i].blue, palette[i].blue, + png_ptr->trans[i], back.blue); + } + } + } +#endif /* PNG_READ_BACKGROUND_SUPPORTED */ + +#if defined(PNG_READ_SHIFT_SUPPORTED) + if ((png_ptr->transformations & PNG_SHIFT) && + (color_type == PNG_COLOR_TYPE_PALETTE)) + { + png_uint_16 i; + png_uint_16 istop = png_ptr->num_palette; + int sr = 8 - png_ptr->sig_bit.red; + int sg = 8 - png_ptr->sig_bit.green; + int sb = 8 - png_ptr->sig_bit.blue; + + if (sr < 0 || sr > 8) + sr = 0; + if (sg < 0 || sg > 8) + sg = 0; + if (sb < 0 || sb > 8) + sb = 0; + for (i = 0; i < istop; i++) + { + png_ptr->palette[i].red >>= sr; + png_ptr->palette[i].green >>= sg; + png_ptr->palette[i].blue >>= sb; + } + } +#endif /* PNG_READ_SHIFT_SUPPORTED */ + } +#if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \ + && !defined(PNG_READ_BACKGROUND_SUPPORTED) + if(png_ptr) + return; +#endif +} + +/* Modify the info structure to reflect the transformations. The + * info should be updated so a PNG file could be written with it, + * assuming the transformations result in valid PNG data. + */ +void /* PRIVATE */ +png_read_transform_info(png_structp png_ptr, png_infop info_ptr) +{ + png_debug(1, "in png_read_transform_info\n"); +#if defined(PNG_READ_EXPAND_SUPPORTED) + if (png_ptr->transformations & PNG_EXPAND) + { + if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + if (png_ptr->num_trans) + info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA; + else + info_ptr->color_type = PNG_COLOR_TYPE_RGB; + info_ptr->bit_depth = 8; + info_ptr->num_trans = 0; + } + else + { + if (png_ptr->num_trans) + info_ptr->color_type |= PNG_COLOR_MASK_ALPHA; + if (info_ptr->bit_depth < 8) + info_ptr->bit_depth = 8; + info_ptr->num_trans = 0; + } + } +#endif + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + if (png_ptr->transformations & PNG_BACKGROUND) + { + info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA; + info_ptr->num_trans = 0; + info_ptr->background = png_ptr->background; + } +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (png_ptr->transformations & PNG_GAMMA) + { +#ifdef PNG_FLOATING_POINT_SUPPORTED + info_ptr->gamma = png_ptr->gamma; +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED + info_ptr->int_gamma = png_ptr->int_gamma; +#endif + } +#endif + +#if defined(PNG_READ_16_TO_8_SUPPORTED) + if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16)) + info_ptr->bit_depth = 8; +#endif + +#if defined(PNG_READ_DITHER_SUPPORTED) + if (png_ptr->transformations & PNG_DITHER) + { + if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) || + (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) && + png_ptr->palette_lookup && info_ptr->bit_depth == 8) + { + info_ptr->color_type = PNG_COLOR_TYPE_PALETTE; + } + } +#endif + +#if defined(PNG_READ_PACK_SUPPORTED) + if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8)) + info_ptr->bit_depth = 8; +#endif + +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) + if (png_ptr->transformations & PNG_GRAY_TO_RGB) + info_ptr->color_type |= PNG_COLOR_MASK_COLOR; +#endif + +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) + if (png_ptr->transformations & PNG_RGB_TO_GRAY) + info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR; +#endif + + if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + info_ptr->channels = 1; + else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) + info_ptr->channels = 3; + else + info_ptr->channels = 1; + +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED) + if (png_ptr->transformations & PNG_STRIP_ALPHA) + info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA; +#endif + + if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) + info_ptr->channels++; + +#if defined(PNG_READ_FILLER_SUPPORTED) + /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */ + if ((png_ptr->transformations & PNG_FILLER) && + ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) || + (info_ptr->color_type == PNG_COLOR_TYPE_GRAY))) + { + info_ptr->channels++; + /* if adding a true alpha channel not just filler */ +#if !defined(PNG_1_0_X) + if (png_ptr->transformations & PNG_ADD_ALPHA) + info_ptr->color_type |= PNG_COLOR_MASK_ALPHA; +#endif + } +#endif + +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \ +defined(PNG_READ_USER_TRANSFORM_SUPPORTED) + if(png_ptr->transformations & PNG_USER_TRANSFORM) + { + if(info_ptr->bit_depth < png_ptr->user_transform_depth) + info_ptr->bit_depth = png_ptr->user_transform_depth; + if(info_ptr->channels < png_ptr->user_transform_channels) + info_ptr->channels = png_ptr->user_transform_channels; + } +#endif + + info_ptr->pixel_depth = (png_byte)(info_ptr->channels * + info_ptr->bit_depth); + + info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width); + +#if !defined(PNG_READ_EXPAND_SUPPORTED) + if(png_ptr) + return; +#endif +} + +/* Transform the row. The order of transformations is significant, + * and is very touchy. If you add a transformation, take care to + * decide how it fits in with the other transformations here. + */ +void /* PRIVATE */ +png_do_read_transformations(png_structp png_ptr) +{ + png_debug(1, "in png_do_read_transformations\n"); +#if !defined(PNG_USELESS_TESTS_SUPPORTED) + if (png_ptr->row_buf == NULL) + { +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + char msg[50]; + + sprintf(msg, "NULL row buffer for row %ld, pass %d", png_ptr->row_number, + png_ptr->pass); + png_error(png_ptr, msg); +#else + png_error(png_ptr, "NULL row buffer"); +#endif + } +#endif + +#if defined(PNG_READ_EXPAND_SUPPORTED) + if (png_ptr->transformations & PNG_EXPAND) + { + if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE) + { + png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1, + png_ptr->palette, png_ptr->trans, png_ptr->num_trans); + } + else + { + if (png_ptr->num_trans) + png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1, + &(png_ptr->trans_values)); + else + png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1, + NULL); + } + } +#endif + +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED) + if (png_ptr->transformations & PNG_STRIP_ALPHA) + png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1, + PNG_FLAG_FILLER_AFTER); +#endif + +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) + if (png_ptr->transformations & PNG_RGB_TO_GRAY) + { + int rgb_error = + png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1); + if(rgb_error) + { + png_ptr->rgb_to_gray_status=1; + if(png_ptr->transformations == PNG_RGB_TO_GRAY_WARN) + png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel"); + if(png_ptr->transformations == PNG_RGB_TO_GRAY_ERR) + png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel"); + } + } +#endif + +/* +From Andreas Dilger e-mail to png-implement, 26 March 1998: + + In most cases, the "simple transparency" should be done prior to doing + gray-to-RGB, or you will have to test 3x as many bytes to check if a + pixel is transparent. You would also need to make sure that the + transparency information is upgraded to RGB. + + To summarize, the current flow is: + - Gray + simple transparency -> compare 1 or 2 gray bytes and composite + with background "in place" if transparent, + convert to RGB if necessary + - Gray + alpha -> composite with gray background and remove alpha bytes, + convert to RGB if necessary + + To support RGB backgrounds for gray images we need: + - Gray + simple transparency -> convert to RGB + simple transparency, compare + 3 or 6 bytes and composite with background + "in place" if transparent (3x compare/pixel + compared to doing composite with gray bkgrnd) + - Gray + alpha -> convert to RGB + alpha, composite with background and + remove alpha bytes (3x float operations/pixel + compared with composite on gray background) + + Greg's change will do this. The reason it wasn't done before is for + performance, as this increases the per-pixel operations. If we would check + in advance if the background was gray or RGB, and position the gray-to-RGB + transform appropriately, then it would save a lot of work/time. + */ + +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) + /* if gray -> RGB, do so now only if background is non-gray; else do later + * for performance reasons */ + if ((png_ptr->transformations & PNG_GRAY_TO_RGB) && + !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY)) + png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + if ((png_ptr->transformations & PNG_BACKGROUND) && + ((png_ptr->num_trans != 0 ) || + (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) + png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1, + &(png_ptr->trans_values), &(png_ptr->background) +#if defined(PNG_READ_GAMMA_SUPPORTED) + , &(png_ptr->background_1), + png_ptr->gamma_table, png_ptr->gamma_from_1, + png_ptr->gamma_to_1, png_ptr->gamma_16_table, + png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1, + png_ptr->gamma_shift +#endif +); +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) + if ((png_ptr->transformations & PNG_GAMMA) && +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + !((png_ptr->transformations & PNG_BACKGROUND) && + ((png_ptr->num_trans != 0) || + (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) && +#endif + (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)) + png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1, + png_ptr->gamma_table, png_ptr->gamma_16_table, + png_ptr->gamma_shift); +#endif + +#if defined(PNG_READ_16_TO_8_SUPPORTED) + if (png_ptr->transformations & PNG_16_TO_8) + png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_DITHER_SUPPORTED) + if (png_ptr->transformations & PNG_DITHER) + { + png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1, + png_ptr->palette_lookup, png_ptr->dither_index); + if(png_ptr->row_info.rowbytes == (png_uint_32)0) + png_error(png_ptr, "png_do_dither returned rowbytes=0"); + } +#endif + +#if defined(PNG_READ_INVERT_SUPPORTED) + if (png_ptr->transformations & PNG_INVERT_MONO) + png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_SHIFT_SUPPORTED) + if (png_ptr->transformations & PNG_SHIFT) + png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1, + &(png_ptr->shift)); +#endif + +#if defined(PNG_READ_PACK_SUPPORTED) + if (png_ptr->transformations & PNG_PACK) + png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_BGR_SUPPORTED) + if (png_ptr->transformations & PNG_BGR) + png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) + /* if gray -> RGB, do so now only if we did not do so above */ + if ((png_ptr->transformations & PNG_GRAY_TO_RGB) && + (png_ptr->mode & PNG_BACKGROUND_IS_GRAY)) + png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_FILLER_SUPPORTED) + if (png_ptr->transformations & PNG_FILLER) + png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1, + (png_uint_32)png_ptr->filler, png_ptr->flags); +#endif + +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) + if (png_ptr->transformations & PNG_INVERT_ALPHA) + png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) + if (png_ptr->transformations & PNG_SWAP_ALPHA) + png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_SWAP_SUPPORTED) + if (png_ptr->transformations & PNG_SWAP_BYTES) + png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) + if (png_ptr->transformations & PNG_USER_TRANSFORM) + { + if(png_ptr->read_user_transform_fn != NULL) + (*(png_ptr->read_user_transform_fn)) /* user read transform function */ + (png_ptr, /* png_ptr */ + &(png_ptr->row_info), /* row_info: */ + /* png_uint_32 width; width of row */ + /* png_uint_32 rowbytes; number of bytes in row */ + /* png_byte color_type; color type of pixels */ + /* png_byte bit_depth; bit depth of samples */ + /* png_byte channels; number of channels (1-4) */ + /* png_byte pixel_depth; bits per pixel (depth*channels) */ + png_ptr->row_buf + 1); /* start of pixel data for row */ +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) + if(png_ptr->user_transform_depth) + png_ptr->row_info.bit_depth = png_ptr->user_transform_depth; + if(png_ptr->user_transform_channels) + png_ptr->row_info.channels = png_ptr->user_transform_channels; +#endif + png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth * + png_ptr->row_info.channels); + png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, + png_ptr->row_info.width); + } +#endif + +} + +#if defined(PNG_READ_PACK_SUPPORTED) +/* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel, + * without changing the actual values. Thus, if you had a row with + * a bit depth of 1, you would end up with bytes that only contained + * the numbers 0 or 1. If you would rather they contain 0 and 255, use + * png_do_shift() after this. + */ +void /* PRIVATE */ +png_do_unpack(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_unpack\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL && row_info->bit_depth < 8) +#else + if (row_info->bit_depth < 8) +#endif + { + png_uint_32 i; + png_uint_32 row_width=row_info->width; + + switch (row_info->bit_depth) + { + case 1: + { + png_bytep sp = row + (png_size_t)((row_width - 1) >> 3); + png_bytep dp = row + (png_size_t)row_width - 1; + png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07); + for (i = 0; i < row_width; i++) + { + *dp = (png_byte)((*sp >> shift) & 0x01); + if (shift == 7) + { + shift = 0; + sp--; + } + else + shift++; + + dp--; + } + break; + } + case 2: + { + + png_bytep sp = row + (png_size_t)((row_width - 1) >> 2); + png_bytep dp = row + (png_size_t)row_width - 1; + png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1); + for (i = 0; i < row_width; i++) + { + *dp = (png_byte)((*sp >> shift) & 0x03); + if (shift == 6) + { + shift = 0; + sp--; + } + else + shift += 2; + + dp--; + } + break; + } + case 4: + { + png_bytep sp = row + (png_size_t)((row_width - 1) >> 1); + png_bytep dp = row + (png_size_t)row_width - 1; + png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2); + for (i = 0; i < row_width; i++) + { + *dp = (png_byte)((*sp >> shift) & 0x0f); + if (shift == 4) + { + shift = 0; + sp--; + } + else + shift = 4; + + dp--; + } + break; + } + } + row_info->bit_depth = 8; + row_info->pixel_depth = (png_byte)(8 * row_info->channels); + row_info->rowbytes = row_width * row_info->channels; + } +} +#endif + +#if defined(PNG_READ_SHIFT_SUPPORTED) +/* Reverse the effects of png_do_shift. This routine merely shifts the + * pixels back to their significant bits values. Thus, if you have + * a row of bit depth 8, but only 5 are significant, this will shift + * the values back to 0 through 31. + */ +void /* PRIVATE */ +png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits) +{ + png_debug(1, "in png_do_unshift\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && sig_bits != NULL && +#endif + row_info->color_type != PNG_COLOR_TYPE_PALETTE) + { + int shift[4]; + int channels = 0; + int c; + png_uint_16 value = 0; + png_uint_32 row_width = row_info->width; + + if (row_info->color_type & PNG_COLOR_MASK_COLOR) + { + shift[channels++] = row_info->bit_depth - sig_bits->red; + shift[channels++] = row_info->bit_depth - sig_bits->green; + shift[channels++] = row_info->bit_depth - sig_bits->blue; + } + else + { + shift[channels++] = row_info->bit_depth - sig_bits->gray; + } + if (row_info->color_type & PNG_COLOR_MASK_ALPHA) + { + shift[channels++] = row_info->bit_depth - sig_bits->alpha; + } + + for (c = 0; c < channels; c++) + { + if (shift[c] <= 0) + shift[c] = 0; + else + value = 1; + } + + if (!value) + return; + + switch (row_info->bit_depth) + { + case 2: + { + png_bytep bp; + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + + for (bp = row, i = 0; i < istop; i++) + { + *bp >>= 1; + *bp++ &= 0x55; + } + break; + } + case 4: + { + png_bytep bp = row; + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) | + (png_byte)((int)0xf >> shift[0])); + + for (i = 0; i < istop; i++) + { + *bp >>= shift[0]; + *bp++ &= mask; + } + break; + } + case 8: + { + png_bytep bp = row; + png_uint_32 i; + png_uint_32 istop = row_width * channels; + + for (i = 0; i < istop; i++) + { + *bp++ >>= shift[i%channels]; + } + break; + } + case 16: + { + png_bytep bp = row; + png_uint_32 i; + png_uint_32 istop = channels * row_width; + + for (i = 0; i < istop; i++) + { + value = (png_uint_16)((*bp << 8) + *(bp + 1)); + value >>= shift[i%channels]; + *bp++ = (png_byte)(value >> 8); + *bp++ = (png_byte)(value & 0xff); + } + break; + } + } + } +} +#endif + +#if defined(PNG_READ_16_TO_8_SUPPORTED) +/* chop rows of bit depth 16 down to 8 */ +void /* PRIVATE */ +png_do_chop(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_chop\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL && row_info->bit_depth == 16) +#else + if (row_info->bit_depth == 16) +#endif + { + png_bytep sp = row; + png_bytep dp = row; + png_uint_32 i; + png_uint_32 istop = row_info->width * row_info->channels; + + for (i = 0; i> 8)) >> 8; + * + * Approximate calculation with shift/add instead of multiply/divide: + * *dp = ((((png_uint_32)(*sp) << 8) | + * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8; + * + * What we actually do to avoid extra shifting and conversion: + */ + + *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0); +#else + /* Simply discard the low order byte */ + *dp = *sp; +#endif + } + row_info->bit_depth = 8; + row_info->pixel_depth = (png_byte)(8 * row_info->channels); + row_info->rowbytes = row_info->width * row_info->channels; + } +} +#endif + +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) +void /* PRIVATE */ +png_do_read_swap_alpha(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_read_swap_alpha\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL) +#endif + { + png_uint_32 row_width = row_info->width; + if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + { + /* This converts from RGBA to ARGB */ + if (row_info->bit_depth == 8) + { + png_bytep sp = row + row_info->rowbytes; + png_bytep dp = sp; + png_byte save; + png_uint_32 i; + + for (i = 0; i < row_width; i++) + { + save = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = save; + } + } + /* This converts from RRGGBBAA to AARRGGBB */ + else + { + png_bytep sp = row + row_info->rowbytes; + png_bytep dp = sp; + png_byte save[2]; + png_uint_32 i; + + for (i = 0; i < row_width; i++) + { + save[0] = *(--sp); + save[1] = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = save[0]; + *(--dp) = save[1]; + } + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + { + /* This converts from GA to AG */ + if (row_info->bit_depth == 8) + { + png_bytep sp = row + row_info->rowbytes; + png_bytep dp = sp; + png_byte save; + png_uint_32 i; + + for (i = 0; i < row_width; i++) + { + save = *(--sp); + *(--dp) = *(--sp); + *(--dp) = save; + } + } + /* This converts from GGAA to AAGG */ + else + { + png_bytep sp = row + row_info->rowbytes; + png_bytep dp = sp; + png_byte save[2]; + png_uint_32 i; + + for (i = 0; i < row_width; i++) + { + save[0] = *(--sp); + save[1] = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = save[0]; + *(--dp) = save[1]; + } + } + } + } +} +#endif + +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) +void /* PRIVATE */ +png_do_read_invert_alpha(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_read_invert_alpha\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL) +#endif + { + png_uint_32 row_width = row_info->width; + if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + { + /* This inverts the alpha channel in RGBA */ + if (row_info->bit_depth == 8) + { + png_bytep sp = row + row_info->rowbytes; + png_bytep dp = sp; + png_uint_32 i; + + for (i = 0; i < row_width; i++) + { + *(--dp) = (png_byte)(255 - *(--sp)); + +/* This does nothing: + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + We can replace it with: +*/ + sp-=3; + dp=sp; + } + } + /* This inverts the alpha channel in RRGGBBAA */ + else + { + png_bytep sp = row + row_info->rowbytes; + png_bytep dp = sp; + png_uint_32 i; + + for (i = 0; i < row_width; i++) + { + *(--dp) = (png_byte)(255 - *(--sp)); + *(--dp) = (png_byte)(255 - *(--sp)); + +/* This does nothing: + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + We can replace it with: +*/ + sp-=6; + dp=sp; + } + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + { + /* This inverts the alpha channel in GA */ + if (row_info->bit_depth == 8) + { + png_bytep sp = row + row_info->rowbytes; + png_bytep dp = sp; + png_uint_32 i; + + for (i = 0; i < row_width; i++) + { + *(--dp) = (png_byte)(255 - *(--sp)); + *(--dp) = *(--sp); + } + } + /* This inverts the alpha channel in GGAA */ + else + { + png_bytep sp = row + row_info->rowbytes; + png_bytep dp = sp; + png_uint_32 i; + + for (i = 0; i < row_width; i++) + { + *(--dp) = (png_byte)(255 - *(--sp)); + *(--dp) = (png_byte)(255 - *(--sp)); +/* + *(--dp) = *(--sp); + *(--dp) = *(--sp); +*/ + sp-=2; + dp=sp; + } + } + } + } +} +#endif + +#if defined(PNG_READ_FILLER_SUPPORTED) +/* Add filler channel if we have RGB color */ +void /* PRIVATE */ +png_do_read_filler(png_row_infop row_info, png_bytep row, + png_uint_32 filler, png_uint_32 flags) +{ + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + png_byte hi_filler = (png_byte)((filler>>8) & 0xff); + png_byte lo_filler = (png_byte)(filler & 0xff); + + png_debug(1, "in png_do_read_filler\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + row_info->color_type == PNG_COLOR_TYPE_GRAY) + { + if(row_info->bit_depth == 8) + { + /* This changes the data from G to GX */ + if (flags & PNG_FLAG_FILLER_AFTER) + { + png_bytep sp = row + (png_size_t)row_width; + png_bytep dp = sp + (png_size_t)row_width; + for (i = 1; i < row_width; i++) + { + *(--dp) = lo_filler; + *(--dp) = *(--sp); + } + *(--dp) = lo_filler; + row_info->channels = 2; + row_info->pixel_depth = 16; + row_info->rowbytes = row_width * 2; + } + /* This changes the data from G to XG */ + else + { + png_bytep sp = row + (png_size_t)row_width; + png_bytep dp = sp + (png_size_t)row_width; + for (i = 0; i < row_width; i++) + { + *(--dp) = *(--sp); + *(--dp) = lo_filler; + } + row_info->channels = 2; + row_info->pixel_depth = 16; + row_info->rowbytes = row_width * 2; + } + } + else if(row_info->bit_depth == 16) + { + /* This changes the data from GG to GGXX */ + if (flags & PNG_FLAG_FILLER_AFTER) + { + png_bytep sp = row + (png_size_t)row_width * 2; + png_bytep dp = sp + (png_size_t)row_width * 2; + for (i = 1; i < row_width; i++) + { + *(--dp) = hi_filler; + *(--dp) = lo_filler; + *(--dp) = *(--sp); + *(--dp) = *(--sp); + } + *(--dp) = hi_filler; + *(--dp) = lo_filler; + row_info->channels = 2; + row_info->pixel_depth = 32; + row_info->rowbytes = row_width * 4; + } + /* This changes the data from GG to XXGG */ + else + { + png_bytep sp = row + (png_size_t)row_width * 2; + png_bytep dp = sp + (png_size_t)row_width * 2; + for (i = 0; i < row_width; i++) + { + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = hi_filler; + *(--dp) = lo_filler; + } + row_info->channels = 2; + row_info->pixel_depth = 32; + row_info->rowbytes = row_width * 4; + } + } + } /* COLOR_TYPE == GRAY */ + else if (row_info->color_type == PNG_COLOR_TYPE_RGB) + { + if(row_info->bit_depth == 8) + { + /* This changes the data from RGB to RGBX */ + if (flags & PNG_FLAG_FILLER_AFTER) + { + png_bytep sp = row + (png_size_t)row_width * 3; + png_bytep dp = sp + (png_size_t)row_width; + for (i = 1; i < row_width; i++) + { + *(--dp) = lo_filler; + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + } + *(--dp) = lo_filler; + row_info->channels = 4; + row_info->pixel_depth = 32; + row_info->rowbytes = row_width * 4; + } + /* This changes the data from RGB to XRGB */ + else + { + png_bytep sp = row + (png_size_t)row_width * 3; + png_bytep dp = sp + (png_size_t)row_width; + for (i = 0; i < row_width; i++) + { + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = lo_filler; + } + row_info->channels = 4; + row_info->pixel_depth = 32; + row_info->rowbytes = row_width * 4; + } + } + else if(row_info->bit_depth == 16) + { + /* This changes the data from RRGGBB to RRGGBBXX */ + if (flags & PNG_FLAG_FILLER_AFTER) + { + png_bytep sp = row + (png_size_t)row_width * 6; + png_bytep dp = sp + (png_size_t)row_width * 2; + for (i = 1; i < row_width; i++) + { + *(--dp) = hi_filler; + *(--dp) = lo_filler; + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + } + *(--dp) = hi_filler; + *(--dp) = lo_filler; + row_info->channels = 4; + row_info->pixel_depth = 64; + row_info->rowbytes = row_width * 8; + } + /* This changes the data from RRGGBB to XXRRGGBB */ + else + { + png_bytep sp = row + (png_size_t)row_width * 6; + png_bytep dp = sp + (png_size_t)row_width * 2; + for (i = 0; i < row_width; i++) + { + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = *(--sp); + *(--dp) = hi_filler; + *(--dp) = lo_filler; + } + row_info->channels = 4; + row_info->pixel_depth = 64; + row_info->rowbytes = row_width * 8; + } + } + } /* COLOR_TYPE == RGB */ +} +#endif + +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) +/* expand grayscale files to RGB, with or without alpha */ +void /* PRIVATE */ +png_do_gray_to_rgb(png_row_infop row_info, png_bytep row) +{ + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + png_debug(1, "in png_do_gray_to_rgb\n"); + if (row_info->bit_depth >= 8 && +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + !(row_info->color_type & PNG_COLOR_MASK_COLOR)) + { + if (row_info->color_type == PNG_COLOR_TYPE_GRAY) + { + if (row_info->bit_depth == 8) + { + png_bytep sp = row + (png_size_t)row_width - 1; + png_bytep dp = sp + (png_size_t)row_width * 2; + for (i = 0; i < row_width; i++) + { + *(dp--) = *sp; + *(dp--) = *sp; + *(dp--) = *(sp--); + } + } + else + { + png_bytep sp = row + (png_size_t)row_width * 2 - 1; + png_bytep dp = sp + (png_size_t)row_width * 4; + for (i = 0; i < row_width; i++) + { + *(dp--) = *sp; + *(dp--) = *(sp - 1); + *(dp--) = *sp; + *(dp--) = *(sp - 1); + *(dp--) = *(sp--); + *(dp--) = *(sp--); + } + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + { + if (row_info->bit_depth == 8) + { + png_bytep sp = row + (png_size_t)row_width * 2 - 1; + png_bytep dp = sp + (png_size_t)row_width * 2; + for (i = 0; i < row_width; i++) + { + *(dp--) = *(sp--); + *(dp--) = *sp; + *(dp--) = *sp; + *(dp--) = *(sp--); + } + } + else + { + png_bytep sp = row + (png_size_t)row_width * 4 - 1; + png_bytep dp = sp + (png_size_t)row_width * 4; + for (i = 0; i < row_width; i++) + { + *(dp--) = *(sp--); + *(dp--) = *(sp--); + *(dp--) = *sp; + *(dp--) = *(sp - 1); + *(dp--) = *sp; + *(dp--) = *(sp - 1); + *(dp--) = *(sp--); + *(dp--) = *(sp--); + } + } + } + row_info->channels += (png_byte)2; + row_info->color_type |= PNG_COLOR_MASK_COLOR; + row_info->pixel_depth = (png_byte)(row_info->channels * + row_info->bit_depth); + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width); + } +} +#endif + +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) +/* reduce RGB files to grayscale, with or without alpha + * using the equation given in Poynton's ColorFAQ at + * + * Copyright (c) 1998-01-04 Charles Poynton poynton@inforamp.net + * + * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B + * + * We approximate this with + * + * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B + * + * which can be expressed with integers as + * + * Y = (6969 * R + 23434 * G + 2365 * B)/32768 + * + * The calculation is to be done in a linear colorspace. + * + * Other integer coefficents can be used via png_set_rgb_to_gray(). + */ +int /* PRIVATE */ +png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row) + +{ + png_uint_32 i; + + png_uint_32 row_width = row_info->width; + int rgb_error = 0; + + png_debug(1, "in png_do_rgb_to_gray\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + (row_info->color_type & PNG_COLOR_MASK_COLOR)) + { + png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff; + png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff; + png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff; + + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + { + if (row_info->bit_depth == 8) + { +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) + if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) + { + png_bytep sp = row; + png_bytep dp = row; + + for (i = 0; i < row_width; i++) + { + png_byte red = png_ptr->gamma_to_1[*(sp++)]; + png_byte green = png_ptr->gamma_to_1[*(sp++)]; + png_byte blue = png_ptr->gamma_to_1[*(sp++)]; + if(red != green || red != blue) + { + rgb_error |= 1; + *(dp++) = png_ptr->gamma_from_1[ + (rc*red+gc*green+bc*blue)>>15]; + } + else + *(dp++) = *(sp-1); + } + } + else +#endif + { + png_bytep sp = row; + png_bytep dp = row; + for (i = 0; i < row_width; i++) + { + png_byte red = *(sp++); + png_byte green = *(sp++); + png_byte blue = *(sp++); + if(red != green || red != blue) + { + rgb_error |= 1; + *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15); + } + else + *(dp++) = *(sp-1); + } + } + } + + else /* RGB bit_depth == 16 */ + { +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) + if (png_ptr->gamma_16_to_1 != NULL && + png_ptr->gamma_16_from_1 != NULL) + { + png_bytep sp = row; + png_bytep dp = row; + for (i = 0; i < row_width; i++) + { + png_uint_16 red, green, blue, w; + + red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + + if(red == green && red == blue) + w = red; + else + { + png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> + png_ptr->gamma_shift][red>>8]; + png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> + png_ptr->gamma_shift][green>>8]; + png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> + png_ptr->gamma_shift][blue>>8]; + png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1 + + bc*blue_1)>>15); + w = png_ptr->gamma_16_from_1[(gray16&0xff) >> + png_ptr->gamma_shift][gray16 >> 8]; + rgb_error |= 1; + } + + *(dp++) = (png_byte)((w>>8) & 0xff); + *(dp++) = (png_byte)(w & 0xff); + } + } + else +#endif + { + png_bytep sp = row; + png_bytep dp = row; + for (i = 0; i < row_width; i++) + { + png_uint_16 red, green, blue, gray16; + + red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + + if(red != green || red != blue) + rgb_error |= 1; + gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); + *(dp++) = (png_byte)((gray16>>8) & 0xff); + *(dp++) = (png_byte)(gray16 & 0xff); + } + } + } + } + if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + { + if (row_info->bit_depth == 8) + { +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) + if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) + { + png_bytep sp = row; + png_bytep dp = row; + for (i = 0; i < row_width; i++) + { + png_byte red = png_ptr->gamma_to_1[*(sp++)]; + png_byte green = png_ptr->gamma_to_1[*(sp++)]; + png_byte blue = png_ptr->gamma_to_1[*(sp++)]; + if(red != green || red != blue) + rgb_error |= 1; + *(dp++) = png_ptr->gamma_from_1 + [(rc*red + gc*green + bc*blue)>>15]; + *(dp++) = *(sp++); /* alpha */ + } + } + else +#endif + { + png_bytep sp = row; + png_bytep dp = row; + for (i = 0; i < row_width; i++) + { + png_byte red = *(sp++); + png_byte green = *(sp++); + png_byte blue = *(sp++); + if(red != green || red != blue) + rgb_error |= 1; + *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); + *(dp++) = *(sp++); /* alpha */ + } + } + } + else /* RGBA bit_depth == 16 */ + { +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) + if (png_ptr->gamma_16_to_1 != NULL && + png_ptr->gamma_16_from_1 != NULL) + { + png_bytep sp = row; + png_bytep dp = row; + for (i = 0; i < row_width; i++) + { + png_uint_16 red, green, blue, w; + + red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; + + if(red == green && red == blue) + w = red; + else + { + png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> + png_ptr->gamma_shift][red>>8]; + png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> + png_ptr->gamma_shift][green>>8]; + png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> + png_ptr->gamma_shift][blue>>8]; + png_uint_16 gray16 = (png_uint_16)((rc * red_1 + + gc * green_1 + bc * blue_1)>>15); + w = png_ptr->gamma_16_from_1[(gray16&0xff) >> + png_ptr->gamma_shift][gray16 >> 8]; + rgb_error |= 1; + } + + *(dp++) = (png_byte)((w>>8) & 0xff); + *(dp++) = (png_byte)(w & 0xff); + *(dp++) = *(sp++); /* alpha */ + *(dp++) = *(sp++); + } + } + else +#endif + { + png_bytep sp = row; + png_bytep dp = row; + for (i = 0; i < row_width; i++) + { + png_uint_16 red, green, blue, gray16; + red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; + green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; + blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; + if(red != green || red != blue) + rgb_error |= 1; + gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); + *(dp++) = (png_byte)((gray16>>8) & 0xff); + *(dp++) = (png_byte)(gray16 & 0xff); + *(dp++) = *(sp++); /* alpha */ + *(dp++) = *(sp++); + } + } + } + } + row_info->channels -= (png_byte)2; + row_info->color_type &= ~PNG_COLOR_MASK_COLOR; + row_info->pixel_depth = (png_byte)(row_info->channels * + row_info->bit_depth); + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width); + } + return rgb_error; +} +#endif + +/* Build a grayscale palette. Palette is assumed to be 1 << bit_depth + * large of png_color. This lets grayscale images be treated as + * paletted. Most useful for gamma correction and simplification + * of code. + */ +void PNGAPI +png_build_grayscale_palette(int bit_depth, png_colorp palette) +{ + int num_palette; + int color_inc; + int i; + int v; + + png_debug(1, "in png_do_build_grayscale_palette\n"); + if (palette == NULL) + return; + + switch (bit_depth) + { + case 1: + num_palette = 2; + color_inc = 0xff; + break; + case 2: + num_palette = 4; + color_inc = 0x55; + break; + case 4: + num_palette = 16; + color_inc = 0x11; + break; + case 8: + num_palette = 256; + color_inc = 1; + break; + default: + num_palette = 0; + color_inc = 0; + break; + } + + for (i = 0, v = 0; i < num_palette; i++, v += color_inc) + { + palette[i].red = (png_byte)v; + palette[i].green = (png_byte)v; + palette[i].blue = (png_byte)v; + } +} + +/* This function is currently unused. Do we really need it? */ +#if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED) +void /* PRIVATE */ +png_correct_palette(png_structp png_ptr, png_colorp palette, + int num_palette) +{ + png_debug(1, "in png_correct_palette\n"); +#if defined(PNG_READ_BACKGROUND_SUPPORTED) && \ + defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED) + if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND)) + { + png_color back, back_1; + + if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE) + { + back.red = png_ptr->gamma_table[png_ptr->background.red]; + back.green = png_ptr->gamma_table[png_ptr->background.green]; + back.blue = png_ptr->gamma_table[png_ptr->background.blue]; + + back_1.red = png_ptr->gamma_to_1[png_ptr->background.red]; + back_1.green = png_ptr->gamma_to_1[png_ptr->background.green]; + back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue]; + } + else + { + double g; + + g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma); + + if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN || + fabs(g - 1.0) < PNG_GAMMA_THRESHOLD) + { + back.red = png_ptr->background.red; + back.green = png_ptr->background.green; + back.blue = png_ptr->background.blue; + } + else + { + back.red = + (png_byte)(pow((double)png_ptr->background.red/255, g) * + 255.0 + 0.5); + back.green = + (png_byte)(pow((double)png_ptr->background.green/255, g) * + 255.0 + 0.5); + back.blue = + (png_byte)(pow((double)png_ptr->background.blue/255, g) * + 255.0 + 0.5); + } + + g = 1.0 / png_ptr->background_gamma; + + back_1.red = + (png_byte)(pow((double)png_ptr->background.red/255, g) * + 255.0 + 0.5); + back_1.green = + (png_byte)(pow((double)png_ptr->background.green/255, g) * + 255.0 + 0.5); + back_1.blue = + (png_byte)(pow((double)png_ptr->background.blue/255, g) * + 255.0 + 0.5); + } + + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + png_uint_32 i; + + for (i = 0; i < (png_uint_32)num_palette; i++) + { + if (i < png_ptr->num_trans && png_ptr->trans[i] == 0) + { + palette[i] = back; + } + else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff) + { + png_byte v, w; + + v = png_ptr->gamma_to_1[png_ptr->palette[i].red]; + png_composite(w, v, png_ptr->trans[i], back_1.red); + palette[i].red = png_ptr->gamma_from_1[w]; + + v = png_ptr->gamma_to_1[png_ptr->palette[i].green]; + png_composite(w, v, png_ptr->trans[i], back_1.green); + palette[i].green = png_ptr->gamma_from_1[w]; + + v = png_ptr->gamma_to_1[png_ptr->palette[i].blue]; + png_composite(w, v, png_ptr->trans[i], back_1.blue); + palette[i].blue = png_ptr->gamma_from_1[w]; + } + else + { + palette[i].red = png_ptr->gamma_table[palette[i].red]; + palette[i].green = png_ptr->gamma_table[palette[i].green]; + palette[i].blue = png_ptr->gamma_table[palette[i].blue]; + } + } + } + else + { + int i; + + for (i = 0; i < num_palette; i++) + { + if (palette[i].red == (png_byte)png_ptr->trans_values.gray) + { + palette[i] = back; + } + else + { + palette[i].red = png_ptr->gamma_table[palette[i].red]; + palette[i].green = png_ptr->gamma_table[palette[i].green]; + palette[i].blue = png_ptr->gamma_table[palette[i].blue]; + } + } + } + } + else +#endif +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (png_ptr->transformations & PNG_GAMMA) + { + int i; + + for (i = 0; i < num_palette; i++) + { + palette[i].red = png_ptr->gamma_table[palette[i].red]; + palette[i].green = png_ptr->gamma_table[palette[i].green]; + palette[i].blue = png_ptr->gamma_table[palette[i].blue]; + } + } +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + else +#endif +#endif +#if defined(PNG_READ_BACKGROUND_SUPPORTED) + if (png_ptr->transformations & PNG_BACKGROUND) + { + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + png_color back; + + back.red = (png_byte)png_ptr->background.red; + back.green = (png_byte)png_ptr->background.green; + back.blue = (png_byte)png_ptr->background.blue; + + for (i = 0; i < (int)png_ptr->num_trans; i++) + { + if (png_ptr->trans[i] == 0) + { + palette[i].red = back.red; + palette[i].green = back.green; + palette[i].blue = back.blue; + } + else if (png_ptr->trans[i] != 0xff) + { + png_composite(palette[i].red, png_ptr->palette[i].red, + png_ptr->trans[i], back.red); + png_composite(palette[i].green, png_ptr->palette[i].green, + png_ptr->trans[i], back.green); + png_composite(palette[i].blue, png_ptr->palette[i].blue, + png_ptr->trans[i], back.blue); + } + } + } + else /* assume grayscale palette (what else could it be?) */ + { + int i; + + for (i = 0; i < num_palette; i++) + { + if (i == (png_byte)png_ptr->trans_values.gray) + { + palette[i].red = (png_byte)png_ptr->background.red; + palette[i].green = (png_byte)png_ptr->background.green; + palette[i].blue = (png_byte)png_ptr->background.blue; + } + } + } + } +#endif +} +#endif + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) +/* Replace any alpha or transparency with the supplied background color. + * "background" is already in the screen gamma, while "background_1" is + * at a gamma of 1.0. Paletted files have already been taken care of. + */ +void /* PRIVATE */ +png_do_background(png_row_infop row_info, png_bytep row, + png_color_16p trans_values, png_color_16p background +#if defined(PNG_READ_GAMMA_SUPPORTED) + , png_color_16p background_1, + png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1, + png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1, + png_uint_16pp gamma_16_to_1, int gamma_shift +#endif + ) +{ + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width=row_info->width; + int shift; + + png_debug(1, "in png_do_background\n"); + if (background != NULL && +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) || + (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values))) + { + switch (row_info->color_type) + { + case PNG_COLOR_TYPE_GRAY: + { + switch (row_info->bit_depth) + { + case 1: + { + sp = row; + shift = 7; + for (i = 0; i < row_width; i++) + { + if ((png_uint_16)((*sp >> shift) & 0x01) + == trans_values->gray) + { + *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff); + *sp |= (png_byte)(background->gray << shift); + } + if (!shift) + { + shift = 7; + sp++; + } + else + shift--; + } + break; + } + case 2: + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_table != NULL) + { + sp = row; + shift = 6; + for (i = 0; i < row_width; i++) + { + if ((png_uint_16)((*sp >> shift) & 0x03) + == trans_values->gray) + { + *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); + *sp |= (png_byte)(background->gray << shift); + } + else + { + png_byte p = (png_byte)((*sp >> shift) & 0x03); + png_byte g = (png_byte)((gamma_table [p | (p << 2) | + (p << 4) | (p << 6)] >> 6) & 0x03); + *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); + *sp |= (png_byte)(g << shift); + } + if (!shift) + { + shift = 6; + sp++; + } + else + shift -= 2; + } + } + else +#endif + { + sp = row; + shift = 6; + for (i = 0; i < row_width; i++) + { + if ((png_uint_16)((*sp >> shift) & 0x03) + == trans_values->gray) + { + *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); + *sp |= (png_byte)(background->gray << shift); + } + if (!shift) + { + shift = 6; + sp++; + } + else + shift -= 2; + } + } + break; + } + case 4: + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_table != NULL) + { + sp = row; + shift = 4; + for (i = 0; i < row_width; i++) + { + if ((png_uint_16)((*sp >> shift) & 0x0f) + == trans_values->gray) + { + *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); + *sp |= (png_byte)(background->gray << shift); + } + else + { + png_byte p = (png_byte)((*sp >> shift) & 0x0f); + png_byte g = (png_byte)((gamma_table[p | + (p << 4)] >> 4) & 0x0f); + *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); + *sp |= (png_byte)(g << shift); + } + if (!shift) + { + shift = 4; + sp++; + } + else + shift -= 4; + } + } + else +#endif + { + sp = row; + shift = 4; + for (i = 0; i < row_width; i++) + { + if ((png_uint_16)((*sp >> shift) & 0x0f) + == trans_values->gray) + { + *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); + *sp |= (png_byte)(background->gray << shift); + } + if (!shift) + { + shift = 4; + sp++; + } + else + shift -= 4; + } + } + break; + } + case 8: + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_table != NULL) + { + sp = row; + for (i = 0; i < row_width; i++, sp++) + { + if (*sp == trans_values->gray) + { + *sp = (png_byte)background->gray; + } + else + { + *sp = gamma_table[*sp]; + } + } + } + else +#endif + { + sp = row; + for (i = 0; i < row_width; i++, sp++) + { + if (*sp == trans_values->gray) + { + *sp = (png_byte)background->gray; + } + } + } + break; + } + case 16: + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_16 != NULL) + { + sp = row; + for (i = 0; i < row_width; i++, sp += 2) + { + png_uint_16 v; + + v = (png_uint_16)(((*sp) << 8) + *(sp + 1)); + if (v == trans_values->gray) + { + /* background is already in screen gamma */ + *sp = (png_byte)((background->gray >> 8) & 0xff); + *(sp + 1) = (png_byte)(background->gray & 0xff); + } + else + { + v = gamma_16[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + } + } + } + else +#endif + { + sp = row; + for (i = 0; i < row_width; i++, sp += 2) + { + png_uint_16 v; + + v = (png_uint_16)(((*sp) << 8) + *(sp + 1)); + if (v == trans_values->gray) + { + *sp = (png_byte)((background->gray >> 8) & 0xff); + *(sp + 1) = (png_byte)(background->gray & 0xff); + } + } + } + break; + } + } + break; + } + case PNG_COLOR_TYPE_RGB: + { + if (row_info->bit_depth == 8) + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_table != NULL) + { + sp = row; + for (i = 0; i < row_width; i++, sp += 3) + { + if (*sp == trans_values->red && + *(sp + 1) == trans_values->green && + *(sp + 2) == trans_values->blue) + { + *sp = (png_byte)background->red; + *(sp + 1) = (png_byte)background->green; + *(sp + 2) = (png_byte)background->blue; + } + else + { + *sp = gamma_table[*sp]; + *(sp + 1) = gamma_table[*(sp + 1)]; + *(sp + 2) = gamma_table[*(sp + 2)]; + } + } + } + else +#endif + { + sp = row; + for (i = 0; i < row_width; i++, sp += 3) + { + if (*sp == trans_values->red && + *(sp + 1) == trans_values->green && + *(sp + 2) == trans_values->blue) + { + *sp = (png_byte)background->red; + *(sp + 1) = (png_byte)background->green; + *(sp + 2) = (png_byte)background->blue; + } + } + } + } + else /* if (row_info->bit_depth == 16) */ + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_16 != NULL) + { + sp = row; + for (i = 0; i < row_width; i++, sp += 6) + { + png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1)); + png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3)); + png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5)); + if (r == trans_values->red && g == trans_values->green && + b == trans_values->blue) + { + /* background is already in screen gamma */ + *sp = (png_byte)((background->red >> 8) & 0xff); + *(sp + 1) = (png_byte)(background->red & 0xff); + *(sp + 2) = (png_byte)((background->green >> 8) & 0xff); + *(sp + 3) = (png_byte)(background->green & 0xff); + *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff); + *(sp + 5) = (png_byte)(background->blue & 0xff); + } + else + { + png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)]; + *(sp + 2) = (png_byte)((v >> 8) & 0xff); + *(sp + 3) = (png_byte)(v & 0xff); + v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)]; + *(sp + 4) = (png_byte)((v >> 8) & 0xff); + *(sp + 5) = (png_byte)(v & 0xff); + } + } + } + else +#endif + { + sp = row; + for (i = 0; i < row_width; i++, sp += 6) + { + png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1)); + png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3)); + png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5)); + + if (r == trans_values->red && g == trans_values->green && + b == trans_values->blue) + { + *sp = (png_byte)((background->red >> 8) & 0xff); + *(sp + 1) = (png_byte)(background->red & 0xff); + *(sp + 2) = (png_byte)((background->green >> 8) & 0xff); + *(sp + 3) = (png_byte)(background->green & 0xff); + *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff); + *(sp + 5) = (png_byte)(background->blue & 0xff); + } + } + } + } + break; + } + case PNG_COLOR_TYPE_GRAY_ALPHA: + { + if (row_info->bit_depth == 8) + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_to_1 != NULL && gamma_from_1 != NULL && + gamma_table != NULL) + { + sp = row; + dp = row; + for (i = 0; i < row_width; i++, sp += 2, dp++) + { + png_uint_16 a = *(sp + 1); + + if (a == 0xff) + { + *dp = gamma_table[*sp]; + } + else if (a == 0) + { + /* background is already in screen gamma */ + *dp = (png_byte)background->gray; + } + else + { + png_byte v, w; + + v = gamma_to_1[*sp]; + png_composite(w, v, a, background_1->gray); + *dp = gamma_from_1[w]; + } + } + } + else +#endif + { + sp = row; + dp = row; + for (i = 0; i < row_width; i++, sp += 2, dp++) + { + png_byte a = *(sp + 1); + + if (a == 0xff) + { + *dp = *sp; + } +#if defined(PNG_READ_GAMMA_SUPPORTED) + else if (a == 0) + { + *dp = (png_byte)background->gray; + } + else + { + png_composite(*dp, *sp, a, background_1->gray); + } +#else + *dp = (png_byte)background->gray; +#endif + } + } + } + else /* if (png_ptr->bit_depth == 16) */ + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_16 != NULL && gamma_16_from_1 != NULL && + gamma_16_to_1 != NULL) + { + sp = row; + dp = row; + for (i = 0; i < row_width; i++, sp += 4, dp += 2) + { + png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3)); + + if (a == (png_uint_16)0xffff) + { + png_uint_16 v; + + v = gamma_16[*(sp + 1) >> gamma_shift][*sp]; + *dp = (png_byte)((v >> 8) & 0xff); + *(dp + 1) = (png_byte)(v & 0xff); + } +#if defined(PNG_READ_GAMMA_SUPPORTED) + else if (a == 0) +#else + else +#endif + { + /* background is already in screen gamma */ + *dp = (png_byte)((background->gray >> 8) & 0xff); + *(dp + 1) = (png_byte)(background->gray & 0xff); + } +#if defined(PNG_READ_GAMMA_SUPPORTED) + else + { + png_uint_16 g, v, w; + + g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp]; + png_composite_16(v, g, a, background_1->gray); + w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8]; + *dp = (png_byte)((w >> 8) & 0xff); + *(dp + 1) = (png_byte)(w & 0xff); + } +#endif + } + } + else +#endif + { + sp = row; + dp = row; + for (i = 0; i < row_width; i++, sp += 4, dp += 2) + { + png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3)); + if (a == (png_uint_16)0xffff) + { + png_memcpy(dp, sp, 2); + } +#if defined(PNG_READ_GAMMA_SUPPORTED) + else if (a == 0) +#else + else +#endif + { + *dp = (png_byte)((background->gray >> 8) & 0xff); + *(dp + 1) = (png_byte)(background->gray & 0xff); + } +#if defined(PNG_READ_GAMMA_SUPPORTED) + else + { + png_uint_16 g, v; + + g = (png_uint_16)(((*sp) << 8) + *(sp + 1)); + png_composite_16(v, g, a, background_1->gray); + *dp = (png_byte)((v >> 8) & 0xff); + *(dp + 1) = (png_byte)(v & 0xff); + } +#endif + } + } + } + break; + } + case PNG_COLOR_TYPE_RGB_ALPHA: + { + if (row_info->bit_depth == 8) + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_to_1 != NULL && gamma_from_1 != NULL && + gamma_table != NULL) + { + sp = row; + dp = row; + for (i = 0; i < row_width; i++, sp += 4, dp += 3) + { + png_byte a = *(sp + 3); + + if (a == 0xff) + { + *dp = gamma_table[*sp]; + *(dp + 1) = gamma_table[*(sp + 1)]; + *(dp + 2) = gamma_table[*(sp + 2)]; + } + else if (a == 0) + { + /* background is already in screen gamma */ + *dp = (png_byte)background->red; + *(dp + 1) = (png_byte)background->green; + *(dp + 2) = (png_byte)background->blue; + } + else + { + png_byte v, w; + + v = gamma_to_1[*sp]; + png_composite(w, v, a, background_1->red); + *dp = gamma_from_1[w]; + v = gamma_to_1[*(sp + 1)]; + png_composite(w, v, a, background_1->green); + *(dp + 1) = gamma_from_1[w]; + v = gamma_to_1[*(sp + 2)]; + png_composite(w, v, a, background_1->blue); + *(dp + 2) = gamma_from_1[w]; + } + } + } + else +#endif + { + sp = row; + dp = row; + for (i = 0; i < row_width; i++, sp += 4, dp += 3) + { + png_byte a = *(sp + 3); + + if (a == 0xff) + { + *dp = *sp; + *(dp + 1) = *(sp + 1); + *(dp + 2) = *(sp + 2); + } + else if (a == 0) + { + *dp = (png_byte)background->red; + *(dp + 1) = (png_byte)background->green; + *(dp + 2) = (png_byte)background->blue; + } + else + { + png_composite(*dp, *sp, a, background->red); + png_composite(*(dp + 1), *(sp + 1), a, + background->green); + png_composite(*(dp + 2), *(sp + 2), a, + background->blue); + } + } + } + } + else /* if (row_info->bit_depth == 16) */ + { +#if defined(PNG_READ_GAMMA_SUPPORTED) + if (gamma_16 != NULL && gamma_16_from_1 != NULL && + gamma_16_to_1 != NULL) + { + sp = row; + dp = row; + for (i = 0; i < row_width; i++, sp += 8, dp += 6) + { + png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6)) + << 8) + (png_uint_16)(*(sp + 7))); + if (a == (png_uint_16)0xffff) + { + png_uint_16 v; + + v = gamma_16[*(sp + 1) >> gamma_shift][*sp]; + *dp = (png_byte)((v >> 8) & 0xff); + *(dp + 1) = (png_byte)(v & 0xff); + v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)]; + *(dp + 2) = (png_byte)((v >> 8) & 0xff); + *(dp + 3) = (png_byte)(v & 0xff); + v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)]; + *(dp + 4) = (png_byte)((v >> 8) & 0xff); + *(dp + 5) = (png_byte)(v & 0xff); + } + else if (a == 0) + { + /* background is already in screen gamma */ + *dp = (png_byte)((background->red >> 8) & 0xff); + *(dp + 1) = (png_byte)(background->red & 0xff); + *(dp + 2) = (png_byte)((background->green >> 8) & 0xff); + *(dp + 3) = (png_byte)(background->green & 0xff); + *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff); + *(dp + 5) = (png_byte)(background->blue & 0xff); + } + else + { + png_uint_16 v, w, x; + + v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp]; + png_composite_16(w, v, a, background_1->red); + x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8]; + *dp = (png_byte)((x >> 8) & 0xff); + *(dp + 1) = (png_byte)(x & 0xff); + v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)]; + png_composite_16(w, v, a, background_1->green); + x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8]; + *(dp + 2) = (png_byte)((x >> 8) & 0xff); + *(dp + 3) = (png_byte)(x & 0xff); + v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)]; + png_composite_16(w, v, a, background_1->blue); + x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8]; + *(dp + 4) = (png_byte)((x >> 8) & 0xff); + *(dp + 5) = (png_byte)(x & 0xff); + } + } + } + else +#endif + { + sp = row; + dp = row; + for (i = 0; i < row_width; i++, sp += 8, dp += 6) + { + png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6)) + << 8) + (png_uint_16)(*(sp + 7))); + if (a == (png_uint_16)0xffff) + { + png_memcpy(dp, sp, 6); + } + else if (a == 0) + { + *dp = (png_byte)((background->red >> 8) & 0xff); + *(dp + 1) = (png_byte)(background->red & 0xff); + *(dp + 2) = (png_byte)((background->green >> 8) & 0xff); + *(dp + 3) = (png_byte)(background->green & 0xff); + *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff); + *(dp + 5) = (png_byte)(background->blue & 0xff); + } + else + { + png_uint_16 v; + + png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1)); + png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8) + + *(sp + 3)); + png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8) + + *(sp + 5)); + + png_composite_16(v, r, a, background->red); + *dp = (png_byte)((v >> 8) & 0xff); + *(dp + 1) = (png_byte)(v & 0xff); + png_composite_16(v, g, a, background->green); + *(dp + 2) = (png_byte)((v >> 8) & 0xff); + *(dp + 3) = (png_byte)(v & 0xff); + png_composite_16(v, b, a, background->blue); + *(dp + 4) = (png_byte)((v >> 8) & 0xff); + *(dp + 5) = (png_byte)(v & 0xff); + } + } + } + } + break; + } + } + + if (row_info->color_type & PNG_COLOR_MASK_ALPHA) + { + row_info->color_type &= ~PNG_COLOR_MASK_ALPHA; + row_info->channels--; + row_info->pixel_depth = (png_byte)(row_info->channels * + row_info->bit_depth); + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width); + } + } +} +#endif + +#if defined(PNG_READ_GAMMA_SUPPORTED) +/* Gamma correct the image, avoiding the alpha channel. Make sure + * you do this after you deal with the transparency issue on grayscale + * or RGB images. If your bit depth is 8, use gamma_table, if it + * is 16, use gamma_16_table and gamma_shift. Build these with + * build_gamma_table(). + */ +void /* PRIVATE */ +png_do_gamma(png_row_infop row_info, png_bytep row, + png_bytep gamma_table, png_uint_16pp gamma_16_table, + int gamma_shift) +{ + png_bytep sp; + png_uint_32 i; + png_uint_32 row_width=row_info->width; + + png_debug(1, "in png_do_gamma\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + ((row_info->bit_depth <= 8 && gamma_table != NULL) || + (row_info->bit_depth == 16 && gamma_16_table != NULL))) + { + switch (row_info->color_type) + { + case PNG_COLOR_TYPE_RGB: + { + if (row_info->bit_depth == 8) + { + sp = row; + for (i = 0; i < row_width; i++) + { + *sp = gamma_table[*sp]; + sp++; + *sp = gamma_table[*sp]; + sp++; + *sp = gamma_table[*sp]; + sp++; + } + } + else /* if (row_info->bit_depth == 16) */ + { + sp = row; + for (i = 0; i < row_width; i++) + { + png_uint_16 v; + + v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + sp += 2; + v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + sp += 2; + v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + sp += 2; + } + } + break; + } + case PNG_COLOR_TYPE_RGB_ALPHA: + { + if (row_info->bit_depth == 8) + { + sp = row; + for (i = 0; i < row_width; i++) + { + *sp = gamma_table[*sp]; + sp++; + *sp = gamma_table[*sp]; + sp++; + *sp = gamma_table[*sp]; + sp++; + sp++; + } + } + else /* if (row_info->bit_depth == 16) */ + { + sp = row; + for (i = 0; i < row_width; i++) + { + png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + sp += 2; + v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + sp += 2; + v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + sp += 4; + } + } + break; + } + case PNG_COLOR_TYPE_GRAY_ALPHA: + { + if (row_info->bit_depth == 8) + { + sp = row; + for (i = 0; i < row_width; i++) + { + *sp = gamma_table[*sp]; + sp += 2; + } + } + else /* if (row_info->bit_depth == 16) */ + { + sp = row; + for (i = 0; i < row_width; i++) + { + png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + sp += 4; + } + } + break; + } + case PNG_COLOR_TYPE_GRAY: + { + if (row_info->bit_depth == 2) + { + sp = row; + for (i = 0; i < row_width; i += 4) + { + int a = *sp & 0xc0; + int b = *sp & 0x30; + int c = *sp & 0x0c; + int d = *sp & 0x03; + + *sp = (png_byte)( + ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)| + ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)| + ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)| + ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) )); + sp++; + } + } + if (row_info->bit_depth == 4) + { + sp = row; + for (i = 0; i < row_width; i += 2) + { + int msb = *sp & 0xf0; + int lsb = *sp & 0x0f; + + *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0) + | (((int)gamma_table[(lsb << 4) | lsb]) >> 4)); + sp++; + } + } + else if (row_info->bit_depth == 8) + { + sp = row; + for (i = 0; i < row_width; i++) + { + *sp = gamma_table[*sp]; + sp++; + } + } + else if (row_info->bit_depth == 16) + { + sp = row; + for (i = 0; i < row_width; i++) + { + png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; + *sp = (png_byte)((v >> 8) & 0xff); + *(sp + 1) = (png_byte)(v & 0xff); + sp += 2; + } + } + break; + } + } + } +} +#endif + +#if defined(PNG_READ_EXPAND_SUPPORTED) +/* Expands a palette row to an RGB or RGBA row depending + * upon whether you supply trans and num_trans. + */ +void /* PRIVATE */ +png_do_expand_palette(png_row_infop row_info, png_bytep row, + png_colorp palette, png_bytep trans, int num_trans) +{ + int shift, value; + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width=row_info->width; + + png_debug(1, "in png_do_expand_palette\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + row_info->color_type == PNG_COLOR_TYPE_PALETTE) + { + if (row_info->bit_depth < 8) + { + switch (row_info->bit_depth) + { + case 1: + { + sp = row + (png_size_t)((row_width - 1) >> 3); + dp = row + (png_size_t)row_width - 1; + shift = 7 - (int)((row_width + 7) & 0x07); + for (i = 0; i < row_width; i++) + { + if ((*sp >> shift) & 0x01) + *dp = 1; + else + *dp = 0; + if (shift == 7) + { + shift = 0; + sp--; + } + else + shift++; + + dp--; + } + break; + } + case 2: + { + sp = row + (png_size_t)((row_width - 1) >> 2); + dp = row + (png_size_t)row_width - 1; + shift = (int)((3 - ((row_width + 3) & 0x03)) << 1); + for (i = 0; i < row_width; i++) + { + value = (*sp >> shift) & 0x03; + *dp = (png_byte)value; + if (shift == 6) + { + shift = 0; + sp--; + } + else + shift += 2; + + dp--; + } + break; + } + case 4: + { + sp = row + (png_size_t)((row_width - 1) >> 1); + dp = row + (png_size_t)row_width - 1; + shift = (int)((row_width & 0x01) << 2); + for (i = 0; i < row_width; i++) + { + value = (*sp >> shift) & 0x0f; + *dp = (png_byte)value; + if (shift == 4) + { + shift = 0; + sp--; + } + else + shift += 4; + + dp--; + } + break; + } + } + row_info->bit_depth = 8; + row_info->pixel_depth = 8; + row_info->rowbytes = row_width; + } + switch (row_info->bit_depth) + { + case 8: + { + if (trans != NULL) + { + sp = row + (png_size_t)row_width - 1; + dp = row + (png_size_t)(row_width << 2) - 1; + + for (i = 0; i < row_width; i++) + { + if ((int)(*sp) >= num_trans) + *dp-- = 0xff; + else + *dp-- = trans[*sp]; + *dp-- = palette[*sp].blue; + *dp-- = palette[*sp].green; + *dp-- = palette[*sp].red; + sp--; + } + row_info->bit_depth = 8; + row_info->pixel_depth = 32; + row_info->rowbytes = row_width * 4; + row_info->color_type = 6; + row_info->channels = 4; + } + else + { + sp = row + (png_size_t)row_width - 1; + dp = row + (png_size_t)(row_width * 3) - 1; + + for (i = 0; i < row_width; i++) + { + *dp-- = palette[*sp].blue; + *dp-- = palette[*sp].green; + *dp-- = palette[*sp].red; + sp--; + } + row_info->bit_depth = 8; + row_info->pixel_depth = 24; + row_info->rowbytes = row_width * 3; + row_info->color_type = 2; + row_info->channels = 3; + } + break; + } + } + } +} + +/* If the bit depth < 8, it is expanded to 8. Also, if the + * transparency value is supplied, an alpha channel is built. + */ +void /* PRIVATE */ +png_do_expand(png_row_infop row_info, png_bytep row, + png_color_16p trans_value) +{ + int shift, value; + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width=row_info->width; + + png_debug(1, "in png_do_expand\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL) +#endif + { + if (row_info->color_type == PNG_COLOR_TYPE_GRAY) + { + png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0); + + if (row_info->bit_depth < 8) + { + switch (row_info->bit_depth) + { + case 1: + { + gray = (png_uint_16)(gray*0xff); + sp = row + (png_size_t)((row_width - 1) >> 3); + dp = row + (png_size_t)row_width - 1; + shift = 7 - (int)((row_width + 7) & 0x07); + for (i = 0; i < row_width; i++) + { + if ((*sp >> shift) & 0x01) + *dp = 0xff; + else + *dp = 0; + if (shift == 7) + { + shift = 0; + sp--; + } + else + shift++; + + dp--; + } + break; + } + case 2: + { + gray = (png_uint_16)(gray*0x55); + sp = row + (png_size_t)((row_width - 1) >> 2); + dp = row + (png_size_t)row_width - 1; + shift = (int)((3 - ((row_width + 3) & 0x03)) << 1); + for (i = 0; i < row_width; i++) + { + value = (*sp >> shift) & 0x03; + *dp = (png_byte)(value | (value << 2) | (value << 4) | + (value << 6)); + if (shift == 6) + { + shift = 0; + sp--; + } + else + shift += 2; + + dp--; + } + break; + } + case 4: + { + gray = (png_uint_16)(gray*0x11); + sp = row + (png_size_t)((row_width - 1) >> 1); + dp = row + (png_size_t)row_width - 1; + shift = (int)((1 - ((row_width + 1) & 0x01)) << 2); + for (i = 0; i < row_width; i++) + { + value = (*sp >> shift) & 0x0f; + *dp = (png_byte)(value | (value << 4)); + if (shift == 4) + { + shift = 0; + sp--; + } + else + shift = 4; + + dp--; + } + break; + } + } + row_info->bit_depth = 8; + row_info->pixel_depth = 8; + row_info->rowbytes = row_width; + } + + if (trans_value != NULL) + { + if (row_info->bit_depth == 8) + { + sp = row + (png_size_t)row_width - 1; + dp = row + (png_size_t)(row_width << 1) - 1; + for (i = 0; i < row_width; i++) + { + if (*sp == gray) + *dp-- = 0; + else + *dp-- = 0xff; + *dp-- = *sp--; + } + } + else if (row_info->bit_depth == 16) + { + sp = row + row_info->rowbytes - 1; + dp = row + (row_info->rowbytes << 1) - 1; + for (i = 0; i < row_width; i++) + { + if (((png_uint_16)*(sp) | + ((png_uint_16)*(sp - 1) << 8)) == gray) + { + *dp-- = 0; + *dp-- = 0; + } + else + { + *dp-- = 0xff; + *dp-- = 0xff; + } + *dp-- = *sp--; + *dp-- = *sp--; + } + } + row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA; + row_info->channels = 2; + row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1); + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, + row_width); + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value) + { + if (row_info->bit_depth == 8) + { + sp = row + (png_size_t)row_info->rowbytes - 1; + dp = row + (png_size_t)(row_width << 2) - 1; + for (i = 0; i < row_width; i++) + { + if (*(sp - 2) == trans_value->red && + *(sp - 1) == trans_value->green && + *(sp - 0) == trans_value->blue) + *dp-- = 0; + else + *dp-- = 0xff; + *dp-- = *sp--; + *dp-- = *sp--; + *dp-- = *sp--; + } + } + else if (row_info->bit_depth == 16) + { + sp = row + row_info->rowbytes - 1; + dp = row + (png_size_t)(row_width << 3) - 1; + for (i = 0; i < row_width; i++) + { + if ((((png_uint_16)*(sp - 4) | + ((png_uint_16)*(sp - 5) << 8)) == trans_value->red) && + (((png_uint_16)*(sp - 2) | + ((png_uint_16)*(sp - 3) << 8)) == trans_value->green) && + (((png_uint_16)*(sp - 0) | + ((png_uint_16)*(sp - 1) << 8)) == trans_value->blue)) + { + *dp-- = 0; + *dp-- = 0; + } + else + { + *dp-- = 0xff; + *dp-- = 0xff; + } + *dp-- = *sp--; + *dp-- = *sp--; + *dp-- = *sp--; + *dp-- = *sp--; + *dp-- = *sp--; + *dp-- = *sp--; + } + } + row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA; + row_info->channels = 4; + row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2); + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width); + } + } +} +#endif + +#if defined(PNG_READ_DITHER_SUPPORTED) +void /* PRIVATE */ +png_do_dither(png_row_infop row_info, png_bytep row, + png_bytep palette_lookup, png_bytep dither_lookup) +{ + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width=row_info->width; + + png_debug(1, "in png_do_dither\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL) +#endif + { + if (row_info->color_type == PNG_COLOR_TYPE_RGB && + palette_lookup && row_info->bit_depth == 8) + { + int r, g, b, p; + sp = row; + dp = row; + for (i = 0; i < row_width; i++) + { + r = *sp++; + g = *sp++; + b = *sp++; + + /* this looks real messy, but the compiler will reduce + it down to a reasonable formula. For example, with + 5 bits per color, we get: + p = (((r >> 3) & 0x1f) << 10) | + (((g >> 3) & 0x1f) << 5) | + ((b >> 3) & 0x1f); + */ + p = (((r >> (8 - PNG_DITHER_RED_BITS)) & + ((1 << PNG_DITHER_RED_BITS) - 1)) << + (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) | + (((g >> (8 - PNG_DITHER_GREEN_BITS)) & + ((1 << PNG_DITHER_GREEN_BITS) - 1)) << + (PNG_DITHER_BLUE_BITS)) | + ((b >> (8 - PNG_DITHER_BLUE_BITS)) & + ((1 << PNG_DITHER_BLUE_BITS) - 1)); + + *dp++ = palette_lookup[p]; + } + row_info->color_type = PNG_COLOR_TYPE_PALETTE; + row_info->channels = 1; + row_info->pixel_depth = row_info->bit_depth; + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width); + } + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA && + palette_lookup != NULL && row_info->bit_depth == 8) + { + int r, g, b, p; + sp = row; + dp = row; + for (i = 0; i < row_width; i++) + { + r = *sp++; + g = *sp++; + b = *sp++; + sp++; + + p = (((r >> (8 - PNG_DITHER_RED_BITS)) & + ((1 << PNG_DITHER_RED_BITS) - 1)) << + (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) | + (((g >> (8 - PNG_DITHER_GREEN_BITS)) & + ((1 << PNG_DITHER_GREEN_BITS) - 1)) << + (PNG_DITHER_BLUE_BITS)) | + ((b >> (8 - PNG_DITHER_BLUE_BITS)) & + ((1 << PNG_DITHER_BLUE_BITS) - 1)); + + *dp++ = palette_lookup[p]; + } + row_info->color_type = PNG_COLOR_TYPE_PALETTE; + row_info->channels = 1; + row_info->pixel_depth = row_info->bit_depth; + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width); + } + else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE && + dither_lookup && row_info->bit_depth == 8) + { + sp = row; + for (i = 0; i < row_width; i++, sp++) + { + *sp = dither_lookup[*sp]; + } + } + } +} +#endif + +#ifdef PNG_FLOATING_POINT_SUPPORTED +#if defined(PNG_READ_GAMMA_SUPPORTED) +static int png_gamma_shift[] = + {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0}; + +/* We build the 8- or 16-bit gamma tables here. Note that for 16-bit + * tables, we don't make a full table if we are reducing to 8-bit in + * the future. Note also how the gamma_16 tables are segmented so that + * we don't need to allocate > 64K chunks for a full 16-bit table. + */ +void /* PRIVATE */ +png_build_gamma_table(png_structp png_ptr) +{ + png_debug(1, "in png_build_gamma_table\n"); + if(png_ptr->gamma != 0.0) + { + if (png_ptr->bit_depth <= 8) + { + int i; + double g; + + if (png_ptr->screen_gamma > .000001) + g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma); + else + g = 1.0; + + png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr, + (png_uint_32)256); + + for (i = 0; i < 256; i++) + { + png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0, + g) * 255.0 + .5); + } + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \ + defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) + if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY)) + { + + g = 1.0 / (png_ptr->gamma); + + png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr, + (png_uint_32)256); + + for (i = 0; i < 256; i++) + { + png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0, + g) * 255.0 + .5); + } + + + png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr, + (png_uint_32)256); + + if(png_ptr->screen_gamma > 0.000001) + g = 1.0 / png_ptr->screen_gamma; + else + g = png_ptr->gamma; /* probably doing rgb_to_gray */ + + for (i = 0; i < 256; i++) + { + png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0, + g) * 255.0 + .5); + + } + } +#endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */ + } + else + { + double g; + int i, j, shift, num; + int sig_bit; + png_uint_32 ig; + + if (png_ptr->color_type & PNG_COLOR_MASK_COLOR) + { + sig_bit = (int)png_ptr->sig_bit.red; + if ((int)png_ptr->sig_bit.green > sig_bit) + sig_bit = png_ptr->sig_bit.green; + if ((int)png_ptr->sig_bit.blue > sig_bit) + sig_bit = png_ptr->sig_bit.blue; + } + else + { + sig_bit = (int)png_ptr->sig_bit.gray; + } + + if (sig_bit > 0) + shift = 16 - sig_bit; + else + shift = 0; + + if (png_ptr->transformations & PNG_16_TO_8) + { + if (shift < (16 - PNG_MAX_GAMMA_8)) + shift = (16 - PNG_MAX_GAMMA_8); + } + + if (shift > 8) + shift = 8; + if (shift < 0) + shift = 0; + + png_ptr->gamma_shift = (png_byte)shift; + + num = (1 << (8 - shift)); + + if (png_ptr->screen_gamma > .000001) + g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma); + else + g = 1.0; + + png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr, + (png_uint_32)(num * png_sizeof (png_uint_16p))); + + if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND)) + { + double fin, fout; + png_uint_32 last, max; + + for (i = 0; i < num; i++) + { + png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr, + (png_uint_32)(256 * png_sizeof (png_uint_16))); + } + + g = 1.0 / g; + last = 0; + for (i = 0; i < 256; i++) + { + fout = ((double)i + 0.5) / 256.0; + fin = pow(fout, g); + max = (png_uint_32)(fin * (double)((png_uint_32)num << 8)); + while (last <= max) + { + png_ptr->gamma_16_table[(int)(last & (0xff >> shift))] + [(int)(last >> (8 - shift))] = (png_uint_16)( + (png_uint_16)i | ((png_uint_16)i << 8)); + last++; + } + } + while (last < ((png_uint_32)num << 8)) + { + png_ptr->gamma_16_table[(int)(last & (0xff >> shift))] + [(int)(last >> (8 - shift))] = (png_uint_16)65535L; + last++; + } + } + else + { + for (i = 0; i < num; i++) + { + png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr, + (png_uint_32)(256 * png_sizeof (png_uint_16))); + + ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4); + for (j = 0; j < 256; j++) + { + png_ptr->gamma_16_table[i][j] = + (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) / + 65535.0, g) * 65535.0 + .5); + } + } + } + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \ + defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) + if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY)) + { + + g = 1.0 / (png_ptr->gamma); + + png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr, + (png_uint_32)(num * png_sizeof (png_uint_16p ))); + + for (i = 0; i < num; i++) + { + png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr, + (png_uint_32)(256 * png_sizeof (png_uint_16))); + + ig = (((png_uint_32)i * + (png_uint_32)png_gamma_shift[shift]) >> 4); + for (j = 0; j < 256; j++) + { + png_ptr->gamma_16_to_1[i][j] = + (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) / + 65535.0, g) * 65535.0 + .5); + } + } + + if(png_ptr->screen_gamma > 0.000001) + g = 1.0 / png_ptr->screen_gamma; + else + g = png_ptr->gamma; /* probably doing rgb_to_gray */ + + png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr, + (png_uint_32)(num * png_sizeof (png_uint_16p))); + + for (i = 0; i < num; i++) + { + png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr, + (png_uint_32)(256 * png_sizeof (png_uint_16))); + + ig = (((png_uint_32)i * + (png_uint_32)png_gamma_shift[shift]) >> 4); + for (j = 0; j < 256; j++) + { + png_ptr->gamma_16_from_1[i][j] = + (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) / + 65535.0, g) * 65535.0 + .5); + } + } + } +#endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */ + } + } +} +#endif +/* To do: install integer version of png_build_gamma_table here */ +#endif + +#if defined(PNG_MNG_FEATURES_SUPPORTED) +/* undoes intrapixel differencing */ +void /* PRIVATE */ +png_do_read_intrapixel(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_read_intrapixel\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + (row_info->color_type & PNG_COLOR_MASK_COLOR)) + { + int bytes_per_pixel; + png_uint_32 row_width = row_info->width; + if (row_info->bit_depth == 8) + { + png_bytep rp; + png_uint_32 i; + + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + bytes_per_pixel = 3; + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + bytes_per_pixel = 4; + else + return; + + for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) + { + *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff); + *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff); + } + } + else if (row_info->bit_depth == 16) + { + png_bytep rp; + png_uint_32 i; + + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + bytes_per_pixel = 6; + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + bytes_per_pixel = 8; + else + return; + + for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) + { + png_uint_32 s0 = (*(rp ) << 8) | *(rp+1); + png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3); + png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5); + png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL); + png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL); + *(rp ) = (png_byte)((red >> 8) & 0xff); + *(rp+1) = (png_byte)(red & 0xff); + *(rp+4) = (png_byte)((blue >> 8) & 0xff); + *(rp+5) = (png_byte)(blue & 0xff); + } + } + } +} +#endif /* PNG_MNG_FEATURES_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/png/pngrutil.c b/SlnkDWFImpl/CxImage/png/pngrutil.c new file mode 100644 index 0000000..7ebbd44 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngrutil.c @@ -0,0 +1,3124 @@ +/* pngrutil.c - utilities to read a PNG file + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * This file contains routines that are only called from within + * libpng itself during the course of reading an image. + */ + +#define PNG_INTERNAL +#include "png.h" + +#if defined(_WIN32_WCE) +/* strtod() function is not supported on WindowsCE */ +# ifdef PNG_FLOATING_POINT_SUPPORTED +__inline double strtod(const char *nptr, char **endptr) +{ + double result = 0; + int len; + wchar_t *str, *end; + + len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0); + str = (wchar_t *)malloc(len * sizeof(wchar_t)); + if ( NULL != str ) + { + MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len); + result = wcstod(str, &end); + len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL); + *endptr = (char *)nptr + (png_strlen(nptr) - len + 1); + free(str); + } + return result; +} +# endif +#endif + +png_uint_32 /* PRIVATE */ +png_get_uint_31(png_structp png_ptr, png_bytep buf) +{ + png_uint_32 i = png_get_uint_32(buf); + if (i > PNG_UINT_31_MAX) + png_error(png_ptr, "PNG unsigned integer out of range.\n"); + return (i); +} +#ifndef PNG_READ_BIG_ENDIAN_SUPPORTED +/* Grab an unsigned 32-bit integer from a buffer in big-endian format. */ +png_uint_32 /* PRIVATE */ +png_get_uint_32(png_bytep buf) +{ + png_uint_32 i = ((png_uint_32)(*buf) << 24) + + ((png_uint_32)(*(buf + 1)) << 16) + + ((png_uint_32)(*(buf + 2)) << 8) + + (png_uint_32)(*(buf + 3)); + + return (i); +} + +#if defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_oFFs_SUPPORTED) +/* Grab a signed 32-bit integer from a buffer in big-endian format. The + * data is stored in the PNG file in two's complement format, and it is + * assumed that the machine format for signed integers is the same. */ +png_int_32 /* PRIVATE */ +png_get_int_32(png_bytep buf) +{ + png_int_32 i = ((png_int_32)(*buf) << 24) + + ((png_int_32)(*(buf + 1)) << 16) + + ((png_int_32)(*(buf + 2)) << 8) + + (png_int_32)(*(buf + 3)); + + return (i); +} +#endif /* PNG_READ_pCAL_SUPPORTED */ + +/* Grab an unsigned 16-bit integer from a buffer in big-endian format. */ +png_uint_16 /* PRIVATE */ +png_get_uint_16(png_bytep buf) +{ + png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) + + (png_uint_16)(*(buf + 1))); + + return (i); +} +#endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */ + +/* Read data, and (optionally) run it through the CRC. */ +void /* PRIVATE */ +png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length) +{ + png_read_data(png_ptr, buf, length); + png_calculate_crc(png_ptr, buf, length); +} + +/* Optionally skip data and then check the CRC. Depending on whether we + are reading a ancillary or critical chunk, and how the program has set + things up, we may calculate the CRC on the data and print a message. + Returns '1' if there was a CRC error, '0' otherwise. */ +int /* PRIVATE */ +png_crc_finish(png_structp png_ptr, png_uint_32 skip) +{ + png_size_t i; + png_size_t istop = png_ptr->zbuf_size; + + for (i = (png_size_t)skip; i > istop; i -= istop) + { + png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); + } + if (i) + { + png_crc_read(png_ptr, png_ptr->zbuf, i); + } + + if (png_crc_error(png_ptr)) + { + if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */ + !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) || + (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */ + (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE))) + { + png_chunk_warning(png_ptr, "CRC error"); + } + else + { + png_chunk_error(png_ptr, "CRC error"); + } + return (1); + } + + return (0); +} + +/* Compare the CRC stored in the PNG file with that calculated by libpng from + the data it has read thus far. */ +int /* PRIVATE */ +png_crc_error(png_structp png_ptr) +{ + png_byte crc_bytes[4]; + png_uint_32 crc; + int need_crc = 1; + + if (png_ptr->chunk_name[0] & 0x20) /* ancillary */ + { + if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) == + (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN)) + need_crc = 0; + } + else /* critical */ + { + if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) + need_crc = 0; + } + + png_read_data(png_ptr, crc_bytes, 4); + + if (need_crc) + { + crc = png_get_uint_32(crc_bytes); + return ((int)(crc != png_ptr->crc)); + } + else + return (0); +} + +#if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \ + defined(PNG_READ_iCCP_SUPPORTED) +/* + * Decompress trailing data in a chunk. The assumption is that chunkdata + * points at an allocated area holding the contents of a chunk with a + * trailing compressed part. What we get back is an allocated area + * holding the original prefix part and an uncompressed version of the + * trailing part (the malloc area passed in is freed). + */ +png_charp /* PRIVATE */ +png_decompress_chunk(png_structp png_ptr, int comp_type, + png_charp chunkdata, png_size_t chunklength, + png_size_t prefix_size, png_size_t *newlength) +{ + static char msg[] = "Error decoding compressed text"; + png_charp text; + png_size_t text_size; + + if (comp_type == PNG_COMPRESSION_TYPE_BASE) + { + int ret = Z_OK; + png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size); + png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size); + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + + text_size = 0; + text = NULL; + + while (png_ptr->zstream.avail_in) + { + ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH); + if (ret != Z_OK && ret != Z_STREAM_END) + { + if (png_ptr->zstream.msg != NULL) + png_warning(png_ptr, png_ptr->zstream.msg); + else + png_warning(png_ptr, msg); + inflateReset(&png_ptr->zstream); + png_ptr->zstream.avail_in = 0; + + if (text == NULL) + { + text_size = prefix_size + png_sizeof(msg) + 1; + text = (png_charp)png_malloc_warn(png_ptr, text_size); + if (text == NULL) + { + png_free(png_ptr,chunkdata); + png_error(png_ptr,"Not enough memory to decompress chunk"); + } + png_memcpy(text, chunkdata, prefix_size); + } + + text[text_size - 1] = 0x00; + + /* Copy what we can of the error message into the text chunk */ + text_size = (png_size_t)(chunklength - (text - chunkdata) - 1); + text_size = png_sizeof(msg) > text_size ? text_size : + png_sizeof(msg); + png_memcpy(text + prefix_size, msg, text_size + 1); + break; + } + if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END) + { + if (text == NULL) + { + text_size = prefix_size + + png_ptr->zbuf_size - png_ptr->zstream.avail_out; + text = (png_charp)png_malloc_warn(png_ptr, text_size + 1); + if (text == NULL) + { + png_free(png_ptr,chunkdata); + png_error(png_ptr,"Not enough memory to decompress chunk."); + } + png_memcpy(text + prefix_size, png_ptr->zbuf, + text_size - prefix_size); + png_memcpy(text, chunkdata, prefix_size); + *(text + text_size) = 0x00; + } + else + { + png_charp tmp; + + tmp = text; + text = (png_charp)png_malloc_warn(png_ptr, + (png_uint_32)(text_size + + png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1)); + if (text == NULL) + { + png_free(png_ptr, tmp); + png_free(png_ptr, chunkdata); + png_error(png_ptr,"Not enough memory to decompress chunk.."); + } + png_memcpy(text, tmp, text_size); + png_free(png_ptr, tmp); + png_memcpy(text + text_size, png_ptr->zbuf, + (png_ptr->zbuf_size - png_ptr->zstream.avail_out)); + text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out; + *(text + text_size) = 0x00; + } + if (ret == Z_STREAM_END) + break; + else + { + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + } + } + } + if (ret != Z_STREAM_END) + { +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + char umsg[50]; + + if (ret == Z_BUF_ERROR) + sprintf(umsg,"Buffer error in compressed datastream in %s chunk", + png_ptr->chunk_name); + else if (ret == Z_DATA_ERROR) + sprintf(umsg,"Data error in compressed datastream in %s chunk", + png_ptr->chunk_name); + else + sprintf(umsg,"Incomplete compressed datastream in %s chunk", + png_ptr->chunk_name); + png_warning(png_ptr, umsg); +#else + png_warning(png_ptr, + "Incomplete compressed datastream in chunk other than IDAT"); +#endif + text_size=prefix_size; + if (text == NULL) + { + text = (png_charp)png_malloc_warn(png_ptr, text_size+1); + if (text == NULL) + { + png_free(png_ptr, chunkdata); + png_error(png_ptr,"Not enough memory for text."); + } + png_memcpy(text, chunkdata, prefix_size); + } + *(text + text_size) = 0x00; + } + + inflateReset(&png_ptr->zstream); + png_ptr->zstream.avail_in = 0; + + png_free(png_ptr, chunkdata); + chunkdata = text; + *newlength=text_size; + } + else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */ + { +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + char umsg[50]; + + sprintf(umsg, "Unknown zTXt compression type %d", comp_type); + png_warning(png_ptr, umsg); +#else + png_warning(png_ptr, "Unknown zTXt compression type"); +#endif + + *(chunkdata + prefix_size) = 0x00; + *newlength=prefix_size; + } + + return chunkdata; +} +#endif + +/* read and check the IDHR chunk */ +void /* PRIVATE */ +png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_byte buf[13]; + png_uint_32 width, height; + int bit_depth, color_type, compression_type, filter_type; + int interlace_type; + + png_debug(1, "in png_handle_IHDR\n"); + + if (png_ptr->mode & PNG_HAVE_IHDR) + png_error(png_ptr, "Out of place IHDR"); + + /* check the length */ + if (length != 13) + png_error(png_ptr, "Invalid IHDR chunk"); + + png_ptr->mode |= PNG_HAVE_IHDR; + + png_crc_read(png_ptr, buf, 13); + png_crc_finish(png_ptr, 0); + + width = png_get_uint_31(png_ptr, buf); + height = png_get_uint_31(png_ptr, buf + 4); + bit_depth = buf[8]; + color_type = buf[9]; + compression_type = buf[10]; + filter_type = buf[11]; + interlace_type = buf[12]; + + /* set internal variables */ + png_ptr->width = width; + png_ptr->height = height; + png_ptr->bit_depth = (png_byte)bit_depth; + png_ptr->interlaced = (png_byte)interlace_type; + png_ptr->color_type = (png_byte)color_type; +#if defined(PNG_MNG_FEATURES_SUPPORTED) + png_ptr->filter_type = (png_byte)filter_type; +#endif + png_ptr->compression_type = (png_byte)compression_type; + + /* find number of channels */ + switch (png_ptr->color_type) + { + case PNG_COLOR_TYPE_GRAY: + case PNG_COLOR_TYPE_PALETTE: + png_ptr->channels = 1; + break; + case PNG_COLOR_TYPE_RGB: + png_ptr->channels = 3; + break; + case PNG_COLOR_TYPE_GRAY_ALPHA: + png_ptr->channels = 2; + break; + case PNG_COLOR_TYPE_RGB_ALPHA: + png_ptr->channels = 4; + break; + } + + /* set up other useful info */ + png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * + png_ptr->channels); + png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width); + png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth); + png_debug1(3,"channels = %d\n", png_ptr->channels); + png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes); + png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, + color_type, interlace_type, compression_type, filter_type); +} + +/* read and check the palette */ +void /* PRIVATE */ +png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_color palette[PNG_MAX_PALETTE_LENGTH]; + int num, i; +#ifndef PNG_NO_POINTER_INDEXING + png_colorp pal_ptr; +#endif + + png_debug(1, "in png_handle_PLTE\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before PLTE"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid PLTE after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (png_ptr->mode & PNG_HAVE_PLTE) + png_error(png_ptr, "Duplicate PLTE chunk"); + + png_ptr->mode |= PNG_HAVE_PLTE; + + if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR)) + { + png_warning(png_ptr, + "Ignoring PLTE chunk in grayscale PNG"); + png_crc_finish(png_ptr, length); + return; + } +#if !defined(PNG_READ_OPT_PLTE_SUPPORTED) + if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) + { + png_crc_finish(png_ptr, length); + return; + } +#endif + + if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3) + { + if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) + { + png_warning(png_ptr, "Invalid palette chunk"); + png_crc_finish(png_ptr, length); + return; + } + else + { + png_error(png_ptr, "Invalid palette chunk"); + } + } + + num = (int)length / 3; + +#ifndef PNG_NO_POINTER_INDEXING + for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++) + { + png_byte buf[3]; + + png_crc_read(png_ptr, buf, 3); + pal_ptr->red = buf[0]; + pal_ptr->green = buf[1]; + pal_ptr->blue = buf[2]; + } +#else + for (i = 0; i < num; i++) + { + png_byte buf[3]; + + png_crc_read(png_ptr, buf, 3); + /* don't depend upon png_color being any order */ + palette[i].red = buf[0]; + palette[i].green = buf[1]; + palette[i].blue = buf[2]; + } +#endif + + /* If we actually NEED the PLTE chunk (ie for a paletted image), we do + whatever the normal CRC configuration tells us. However, if we + have an RGB image, the PLTE can be considered ancillary, so + we will act as though it is. */ +#if !defined(PNG_READ_OPT_PLTE_SUPPORTED) + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) +#endif + { + png_crc_finish(png_ptr, 0); + } +#if !defined(PNG_READ_OPT_PLTE_SUPPORTED) + else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */ + { + /* If we don't want to use the data from an ancillary chunk, + we have two options: an error abort, or a warning and we + ignore the data in this chunk (which should be OK, since + it's considered ancillary for a RGB or RGBA image). */ + if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE)) + { + if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) + { + png_chunk_error(png_ptr, "CRC error"); + } + else + { + png_chunk_warning(png_ptr, "CRC error"); + return; + } + } + /* Otherwise, we (optionally) emit a warning and use the chunk. */ + else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) + { + png_chunk_warning(png_ptr, "CRC error"); + } + } +#endif + + png_set_PLTE(png_ptr, info_ptr, palette, num); + +#if defined(PNG_READ_tRNS_SUPPORTED) + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS)) + { + if (png_ptr->num_trans > (png_uint_16)num) + { + png_warning(png_ptr, "Truncating incorrect tRNS chunk length"); + png_ptr->num_trans = (png_uint_16)num; + } + if (info_ptr->num_trans > (png_uint_16)num) + { + png_warning(png_ptr, "Truncating incorrect info tRNS chunk length"); + info_ptr->num_trans = (png_uint_16)num; + } + } + } +#endif + +} + +void /* PRIVATE */ +png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_debug(1, "in png_handle_IEND\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT)) + { + png_error(png_ptr, "No image in file"); + } + + png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND); + + if (length != 0) + { + png_warning(png_ptr, "Incorrect IEND chunk length"); + } + png_crc_finish(png_ptr, length); + + if (&info_ptr == NULL) /* quiet compiler warnings about unused info_ptr */ + return; +} + +#if defined(PNG_READ_gAMA_SUPPORTED) +void /* PRIVATE */ +png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_fixed_point igamma; +#ifdef PNG_FLOATING_POINT_SUPPORTED + float file_gamma; +#endif + png_byte buf[4]; + + png_debug(1, "in png_handle_gAMA\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before gAMA"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid gAMA after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (png_ptr->mode & PNG_HAVE_PLTE) + /* Should be an error, but we can cope with it */ + png_warning(png_ptr, "Out of place gAMA chunk"); + + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA) +#if defined(PNG_READ_sRGB_SUPPORTED) + && !(info_ptr->valid & PNG_INFO_sRGB) +#endif + ) + { + png_warning(png_ptr, "Duplicate gAMA chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (length != 4) + { + png_warning(png_ptr, "Incorrect gAMA chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, 4); + if (png_crc_finish(png_ptr, 0)) + return; + + igamma = (png_fixed_point)png_get_uint_32(buf); + /* check for zero gamma */ + if (igamma == 0) + { + png_warning(png_ptr, + "Ignoring gAMA chunk with gamma=0"); + return; + } + +#if defined(PNG_READ_sRGB_SUPPORTED) + if (info_ptr->valid & PNG_INFO_sRGB) + if (PNG_OUT_OF_RANGE(igamma, 45500L, 500)) + { + png_warning(png_ptr, + "Ignoring incorrect gAMA value when sRGB is also present"); +#ifndef PNG_NO_CONSOLE_IO + fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma); +#endif + return; + } +#endif /* PNG_READ_sRGB_SUPPORTED */ + +#ifdef PNG_FLOATING_POINT_SUPPORTED + file_gamma = (float)igamma / (float)100000.0; +# ifdef PNG_READ_GAMMA_SUPPORTED + png_ptr->gamma = file_gamma; +# endif + png_set_gAMA(png_ptr, info_ptr, file_gamma); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED + png_set_gAMA_fixed(png_ptr, info_ptr, igamma); +#endif +} +#endif + +#if defined(PNG_READ_sBIT_SUPPORTED) +void /* PRIVATE */ +png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_size_t truelen; + png_byte buf[4]; + + png_debug(1, "in png_handle_sBIT\n"); + + buf[0] = buf[1] = buf[2] = buf[3] = 0; + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before sBIT"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid sBIT after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (png_ptr->mode & PNG_HAVE_PLTE) + { + /* Should be an error, but we can cope with it */ + png_warning(png_ptr, "Out of place sBIT chunk"); + } + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)) + { + png_warning(png_ptr, "Duplicate sBIT chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + truelen = 3; + else + truelen = (png_size_t)png_ptr->channels; + + if (length != truelen || length > 4) + { + png_warning(png_ptr, "Incorrect sBIT chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, truelen); + if (png_crc_finish(png_ptr, 0)) + return; + + if (png_ptr->color_type & PNG_COLOR_MASK_COLOR) + { + png_ptr->sig_bit.red = buf[0]; + png_ptr->sig_bit.green = buf[1]; + png_ptr->sig_bit.blue = buf[2]; + png_ptr->sig_bit.alpha = buf[3]; + } + else + { + png_ptr->sig_bit.gray = buf[0]; + png_ptr->sig_bit.red = buf[0]; + png_ptr->sig_bit.green = buf[0]; + png_ptr->sig_bit.blue = buf[0]; + png_ptr->sig_bit.alpha = buf[1]; + } + png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit)); +} +#endif + +#if defined(PNG_READ_cHRM_SUPPORTED) +void /* PRIVATE */ +png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_byte buf[4]; +#ifdef PNG_FLOATING_POINT_SUPPORTED + float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y; +#endif + png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green, + int_y_green, int_x_blue, int_y_blue; + + png_uint_32 uint_x, uint_y; + + png_debug(1, "in png_handle_cHRM\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before cHRM"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid cHRM after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (png_ptr->mode & PNG_HAVE_PLTE) + /* Should be an error, but we can cope with it */ + png_warning(png_ptr, "Missing PLTE before cHRM"); + + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM) +#if defined(PNG_READ_sRGB_SUPPORTED) + && !(info_ptr->valid & PNG_INFO_sRGB) +#endif + ) + { + png_warning(png_ptr, "Duplicate cHRM chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (length != 32) + { + png_warning(png_ptr, "Incorrect cHRM chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, 4); + uint_x = png_get_uint_32(buf); + + png_crc_read(png_ptr, buf, 4); + uint_y = png_get_uint_32(buf); + + if (uint_x > 80000L || uint_y > 80000L || + uint_x + uint_y > 100000L) + { + png_warning(png_ptr, "Invalid cHRM white point"); + png_crc_finish(png_ptr, 24); + return; + } + int_x_white = (png_fixed_point)uint_x; + int_y_white = (png_fixed_point)uint_y; + + png_crc_read(png_ptr, buf, 4); + uint_x = png_get_uint_32(buf); + + png_crc_read(png_ptr, buf, 4); + uint_y = png_get_uint_32(buf); + + if (uint_x > 80000L || uint_y > 80000L || + uint_x + uint_y > 100000L) + { + png_warning(png_ptr, "Invalid cHRM red point"); + png_crc_finish(png_ptr, 16); + return; + } + int_x_red = (png_fixed_point)uint_x; + int_y_red = (png_fixed_point)uint_y; + + png_crc_read(png_ptr, buf, 4); + uint_x = png_get_uint_32(buf); + + png_crc_read(png_ptr, buf, 4); + uint_y = png_get_uint_32(buf); + + if (uint_x > 80000L || uint_y > 80000L || + uint_x + uint_y > 100000L) + { + png_warning(png_ptr, "Invalid cHRM green point"); + png_crc_finish(png_ptr, 8); + return; + } + int_x_green = (png_fixed_point)uint_x; + int_y_green = (png_fixed_point)uint_y; + + png_crc_read(png_ptr, buf, 4); + uint_x = png_get_uint_32(buf); + + png_crc_read(png_ptr, buf, 4); + uint_y = png_get_uint_32(buf); + + if (uint_x > 80000L || uint_y > 80000L || + uint_x + uint_y > 100000L) + { + png_warning(png_ptr, "Invalid cHRM blue point"); + png_crc_finish(png_ptr, 0); + return; + } + int_x_blue = (png_fixed_point)uint_x; + int_y_blue = (png_fixed_point)uint_y; + +#ifdef PNG_FLOATING_POINT_SUPPORTED + white_x = (float)int_x_white / (float)100000.0; + white_y = (float)int_y_white / (float)100000.0; + red_x = (float)int_x_red / (float)100000.0; + red_y = (float)int_y_red / (float)100000.0; + green_x = (float)int_x_green / (float)100000.0; + green_y = (float)int_y_green / (float)100000.0; + blue_x = (float)int_x_blue / (float)100000.0; + blue_y = (float)int_y_blue / (float)100000.0; +#endif + +#if defined(PNG_READ_sRGB_SUPPORTED) + if (info_ptr->valid & PNG_INFO_sRGB) + { + if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) || + PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) || + PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) || + PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) || + PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) || + PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) || + PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) || + PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000)) + { + + png_warning(png_ptr, + "Ignoring incorrect cHRM value when sRGB is also present"); +#ifndef PNG_NO_CONSOLE_IO +#ifdef PNG_FLOATING_POINT_SUPPORTED + fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n", + white_x, white_y, red_x, red_y); + fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n", + green_x, green_y, blue_x, blue_y); +#else + fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n", + int_x_white, int_y_white, int_x_red, int_y_red); + fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n", + int_x_green, int_y_green, int_x_blue, int_y_blue); +#endif +#endif /* PNG_NO_CONSOLE_IO */ + } + png_crc_finish(png_ptr, 0); + return; + } +#endif /* PNG_READ_sRGB_SUPPORTED */ + +#ifdef PNG_FLOATING_POINT_SUPPORTED + png_set_cHRM(png_ptr, info_ptr, + white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED + png_set_cHRM_fixed(png_ptr, info_ptr, + int_x_white, int_y_white, int_x_red, int_y_red, int_x_green, + int_y_green, int_x_blue, int_y_blue); +#endif + if (png_crc_finish(png_ptr, 0)) + return; +} +#endif + +#if defined(PNG_READ_sRGB_SUPPORTED) +void /* PRIVATE */ +png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + int intent; + png_byte buf[1]; + + png_debug(1, "in png_handle_sRGB\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before sRGB"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid sRGB after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (png_ptr->mode & PNG_HAVE_PLTE) + /* Should be an error, but we can cope with it */ + png_warning(png_ptr, "Out of place sRGB chunk"); + + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)) + { + png_warning(png_ptr, "Duplicate sRGB chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (length != 1) + { + png_warning(png_ptr, "Incorrect sRGB chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, 1); + if (png_crc_finish(png_ptr, 0)) + return; + + intent = buf[0]; + /* check for bad intent */ + if (intent >= PNG_sRGB_INTENT_LAST) + { + png_warning(png_ptr, "Unknown sRGB intent"); + return; + } + +#if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED) + if ((info_ptr->valid & PNG_INFO_gAMA)) + { + png_fixed_point igamma; +#ifdef PNG_FIXED_POINT_SUPPORTED + igamma=info_ptr->int_gamma; +#else +# ifdef PNG_FLOATING_POINT_SUPPORTED + igamma=(png_fixed_point)(info_ptr->gamma * 100000.); +# endif +#endif + if (PNG_OUT_OF_RANGE(igamma, 45500L, 500)) + { + png_warning(png_ptr, + "Ignoring incorrect gAMA value when sRGB is also present"); +#ifndef PNG_NO_CONSOLE_IO +# ifdef PNG_FIXED_POINT_SUPPORTED + fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma); +# else +# ifdef PNG_FLOATING_POINT_SUPPORTED + fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma); +# endif +# endif +#endif + } + } +#endif /* PNG_READ_gAMA_SUPPORTED */ + +#ifdef PNG_READ_cHRM_SUPPORTED +#ifdef PNG_FIXED_POINT_SUPPORTED + if (info_ptr->valid & PNG_INFO_cHRM) + if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) || + PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) || + PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) || + PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) || + PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) || + PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) || + PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) || + PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000)) + { + png_warning(png_ptr, + "Ignoring incorrect cHRM value when sRGB is also present"); + } +#endif /* PNG_FIXED_POINT_SUPPORTED */ +#endif /* PNG_READ_cHRM_SUPPORTED */ + + png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent); +} +#endif /* PNG_READ_sRGB_SUPPORTED */ + +#if defined(PNG_READ_iCCP_SUPPORTED) +void /* PRIVATE */ +png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +/* Note: this does not properly handle chunks that are > 64K under DOS */ +{ + png_charp chunkdata; + png_byte compression_type; + png_bytep pC; + png_charp profile; + png_uint_32 skip = 0; + png_uint_32 profile_size, profile_length; + png_size_t slength, prefix_length, data_length; + + png_debug(1, "in png_handle_iCCP\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before iCCP"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid iCCP after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (png_ptr->mode & PNG_HAVE_PLTE) + /* Should be an error, but we can cope with it */ + png_warning(png_ptr, "Out of place iCCP chunk"); + + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)) + { + png_warning(png_ptr, "Duplicate iCCP chunk"); + png_crc_finish(png_ptr, length); + return; + } + +#ifdef PNG_MAX_MALLOC_64K + if (length > (png_uint_32)65535L) + { + png_warning(png_ptr, "iCCP chunk too large to fit in memory"); + skip = length - (png_uint_32)65535L; + length = (png_uint_32)65535L; + } +#endif + + chunkdata = (png_charp)png_malloc(png_ptr, length + 1); + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)chunkdata, slength); + + if (png_crc_finish(png_ptr, skip)) + { + png_free(png_ptr, chunkdata); + return; + } + + chunkdata[slength] = 0x00; + + for (profile = chunkdata; *profile; profile++) + /* empty loop to find end of name */ ; + + ++profile; + + /* there should be at least one zero (the compression type byte) + following the separator, and we should be on it */ + if ( profile >= chunkdata + slength) + { + png_free(png_ptr, chunkdata); + png_warning(png_ptr, "Malformed iCCP chunk"); + return; + } + + /* compression_type should always be zero */ + compression_type = *profile++; + if (compression_type) + { + png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk"); + compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8 + wrote nonzero) */ + } + + prefix_length = profile - chunkdata; + chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata, + slength, prefix_length, &data_length); + + profile_length = data_length - prefix_length; + + if ( prefix_length > data_length || profile_length < 4) + { + png_free(png_ptr, chunkdata); + png_warning(png_ptr, "Profile size field missing from iCCP chunk"); + return; + } + + /* Check the profile_size recorded in the first 32 bits of the ICC profile */ + pC = (png_bytep)(chunkdata+prefix_length); + profile_size = ((*(pC ))<<24) | + ((*(pC+1))<<16) | + ((*(pC+2))<< 8) | + ((*(pC+3)) ); + + if(profile_size < profile_length) + profile_length = profile_size; + + if(profile_size > profile_length) + { + png_free(png_ptr, chunkdata); + png_warning(png_ptr, "Ignoring truncated iCCP profile.\n"); + return; + } + + png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type, + chunkdata + prefix_length, profile_length); + png_free(png_ptr, chunkdata); +} +#endif /* PNG_READ_iCCP_SUPPORTED */ + +#if defined(PNG_READ_sPLT_SUPPORTED) +void /* PRIVATE */ +png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +/* Note: this does not properly handle chunks that are > 64K under DOS */ +{ + png_bytep chunkdata; + png_bytep entry_start; + png_sPLT_t new_palette; +#ifdef PNG_NO_POINTER_INDEXING + png_sPLT_entryp pp; +#endif + int data_length, entry_size, i; + png_uint_32 skip = 0; + png_size_t slength; + + png_debug(1, "in png_handle_sPLT\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before sPLT"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid sPLT after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + +#ifdef PNG_MAX_MALLOC_64K + if (length > (png_uint_32)65535L) + { + png_warning(png_ptr, "sPLT chunk too large to fit in memory"); + skip = length - (png_uint_32)65535L; + length = (png_uint_32)65535L; + } +#endif + + chunkdata = (png_bytep)png_malloc(png_ptr, length + 1); + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)chunkdata, slength); + + if (png_crc_finish(png_ptr, skip)) + { + png_free(png_ptr, chunkdata); + return; + } + + chunkdata[slength] = 0x00; + + for (entry_start = chunkdata; *entry_start; entry_start++) + /* empty loop to find end of name */ ; + ++entry_start; + + /* a sample depth should follow the separator, and we should be on it */ + if (entry_start > chunkdata + slength) + { + png_free(png_ptr, chunkdata); + png_warning(png_ptr, "malformed sPLT chunk"); + return; + } + + new_palette.depth = *entry_start++; + entry_size = (new_palette.depth == 8 ? 6 : 10); + data_length = (slength - (entry_start - chunkdata)); + + /* integrity-check the data length */ + if (data_length % entry_size) + { + png_free(png_ptr, chunkdata); + png_warning(png_ptr, "sPLT chunk has bad length"); + return; + } + + new_palette.nentries = (png_uint_32) (data_length / entry_size); + if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX / + png_sizeof(png_sPLT_entry))) + { + png_warning(png_ptr, "sPLT chunk too long"); + return; + } + new_palette.entries = (png_sPLT_entryp)png_malloc_warn( + png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry)); + if (new_palette.entries == NULL) + { + png_warning(png_ptr, "sPLT chunk requires too much memory"); + return; + } + +#ifndef PNG_NO_POINTER_INDEXING + for (i = 0; i < new_palette.nentries; i++) + { + png_sPLT_entryp pp = new_palette.entries + i; + + if (new_palette.depth == 8) + { + pp->red = *entry_start++; + pp->green = *entry_start++; + pp->blue = *entry_start++; + pp->alpha = *entry_start++; + } + else + { + pp->red = png_get_uint_16(entry_start); entry_start += 2; + pp->green = png_get_uint_16(entry_start); entry_start += 2; + pp->blue = png_get_uint_16(entry_start); entry_start += 2; + pp->alpha = png_get_uint_16(entry_start); entry_start += 2; + } + pp->frequency = png_get_uint_16(entry_start); entry_start += 2; + } +#else + pp = new_palette.entries; + for (i = 0; i < new_palette.nentries; i++) + { + + if (new_palette.depth == 8) + { + pp[i].red = *entry_start++; + pp[i].green = *entry_start++; + pp[i].blue = *entry_start++; + pp[i].alpha = *entry_start++; + } + else + { + pp[i].red = png_get_uint_16(entry_start); entry_start += 2; + pp[i].green = png_get_uint_16(entry_start); entry_start += 2; + pp[i].blue = png_get_uint_16(entry_start); entry_start += 2; + pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2; + } + pp->frequency = png_get_uint_16(entry_start); entry_start += 2; + } +#endif + + /* discard all chunk data except the name and stash that */ + new_palette.name = (png_charp)chunkdata; + + png_set_sPLT(png_ptr, info_ptr, &new_palette, 1); + + png_free(png_ptr, chunkdata); + png_free(png_ptr, new_palette.entries); +} +#endif /* PNG_READ_sPLT_SUPPORTED */ + +#if defined(PNG_READ_tRNS_SUPPORTED) +void /* PRIVATE */ +png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_byte readbuf[PNG_MAX_PALETTE_LENGTH]; + + png_debug(1, "in png_handle_tRNS\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before tRNS"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid tRNS after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS)) + { + png_warning(png_ptr, "Duplicate tRNS chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) + { + png_byte buf[2]; + + if (length != 2) + { + png_warning(png_ptr, "Incorrect tRNS chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, 2); + png_ptr->num_trans = 1; + png_ptr->trans_values.gray = png_get_uint_16(buf); + } + else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) + { + png_byte buf[6]; + + if (length != 6) + { + png_warning(png_ptr, "Incorrect tRNS chunk length"); + png_crc_finish(png_ptr, length); + return; + } + png_crc_read(png_ptr, buf, (png_size_t)length); + png_ptr->num_trans = 1; + png_ptr->trans_values.red = png_get_uint_16(buf); + png_ptr->trans_values.green = png_get_uint_16(buf + 2); + png_ptr->trans_values.blue = png_get_uint_16(buf + 4); + } + else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + if (!(png_ptr->mode & PNG_HAVE_PLTE)) + { + /* Should be an error, but we can cope with it. */ + png_warning(png_ptr, "Missing PLTE before tRNS"); + } + if (length > (png_uint_32)png_ptr->num_palette || + length > PNG_MAX_PALETTE_LENGTH) + { + png_warning(png_ptr, "Incorrect tRNS chunk length"); + png_crc_finish(png_ptr, length); + return; + } + if (length == 0) + { + png_warning(png_ptr, "Zero length tRNS chunk"); + png_crc_finish(png_ptr, length); + return; + } + png_crc_read(png_ptr, readbuf, (png_size_t)length); + png_ptr->num_trans = (png_uint_16)length; + } + else + { + png_warning(png_ptr, "tRNS chunk not allowed with alpha channel"); + png_crc_finish(png_ptr, length); + return; + } + + if (png_crc_finish(png_ptr, 0)) + return; + + png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans, + &(png_ptr->trans_values)); +} +#endif + +#if defined(PNG_READ_bKGD_SUPPORTED) +void /* PRIVATE */ +png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_size_t truelen; + png_byte buf[6]; + + png_debug(1, "in png_handle_bKGD\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before bKGD"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid bKGD after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && + !(png_ptr->mode & PNG_HAVE_PLTE)) + { + png_warning(png_ptr, "Missing PLTE before bKGD"); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)) + { + png_warning(png_ptr, "Duplicate bKGD chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + truelen = 1; + else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR) + truelen = 6; + else + truelen = 2; + + if (length != truelen) + { + png_warning(png_ptr, "Incorrect bKGD chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, truelen); + if (png_crc_finish(png_ptr, 0)) + return; + + /* We convert the index value into RGB components so that we can allow + * arbitrary RGB values for background when we have transparency, and + * so it is easy to determine the RGB values of the background color + * from the info_ptr struct. */ + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + png_ptr->background.index = buf[0]; + if(info_ptr->num_palette) + { + if(buf[0] > info_ptr->num_palette) + { + png_warning(png_ptr, "Incorrect bKGD chunk index value"); + return; + } + png_ptr->background.red = + (png_uint_16)png_ptr->palette[buf[0]].red; + png_ptr->background.green = + (png_uint_16)png_ptr->palette[buf[0]].green; + png_ptr->background.blue = + (png_uint_16)png_ptr->palette[buf[0]].blue; + } + } + else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */ + { + png_ptr->background.red = + png_ptr->background.green = + png_ptr->background.blue = + png_ptr->background.gray = png_get_uint_16(buf); + } + else + { + png_ptr->background.red = png_get_uint_16(buf); + png_ptr->background.green = png_get_uint_16(buf + 2); + png_ptr->background.blue = png_get_uint_16(buf + 4); + } + + png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background)); +} +#endif + +#if defined(PNG_READ_hIST_SUPPORTED) +void /* PRIVATE */ +png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + unsigned int num, i; + png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH]; + + png_debug(1, "in png_handle_hIST\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before hIST"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid hIST after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (!(png_ptr->mode & PNG_HAVE_PLTE)) + { + png_warning(png_ptr, "Missing PLTE before hIST"); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)) + { + png_warning(png_ptr, "Duplicate hIST chunk"); + png_crc_finish(png_ptr, length); + return; + } + + num = length / 2 ; + if (num != (unsigned int) png_ptr->num_palette || num > + (unsigned int) PNG_MAX_PALETTE_LENGTH) + { + png_warning(png_ptr, "Incorrect hIST chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + for (i = 0; i < num; i++) + { + png_byte buf[2]; + + png_crc_read(png_ptr, buf, 2); + readbuf[i] = png_get_uint_16(buf); + } + + if (png_crc_finish(png_ptr, 0)) + return; + + png_set_hIST(png_ptr, info_ptr, readbuf); +} +#endif + +#if defined(PNG_READ_pHYs_SUPPORTED) +void /* PRIVATE */ +png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_byte buf[9]; + png_uint_32 res_x, res_y; + int unit_type; + + png_debug(1, "in png_handle_pHYs\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before pHYs"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid pHYs after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs)) + { + png_warning(png_ptr, "Duplicate pHYs chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (length != 9) + { + png_warning(png_ptr, "Incorrect pHYs chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, 9); + if (png_crc_finish(png_ptr, 0)) + return; + + res_x = png_get_uint_32(buf); + res_y = png_get_uint_32(buf + 4); + unit_type = buf[8]; + png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type); +} +#endif + +#if defined(PNG_READ_oFFs_SUPPORTED) +void /* PRIVATE */ +png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_byte buf[9]; + png_int_32 offset_x, offset_y; + int unit_type; + + png_debug(1, "in png_handle_oFFs\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before oFFs"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid oFFs after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)) + { + png_warning(png_ptr, "Duplicate oFFs chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (length != 9) + { + png_warning(png_ptr, "Incorrect oFFs chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, 9); + if (png_crc_finish(png_ptr, 0)) + return; + + offset_x = png_get_int_32(buf); + offset_y = png_get_int_32(buf + 4); + unit_type = buf[8]; + png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type); +} +#endif + +#if defined(PNG_READ_pCAL_SUPPORTED) +/* read the pCAL chunk (described in the PNG Extensions document) */ +void /* PRIVATE */ +png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_charp purpose; + png_int_32 X0, X1; + png_byte type, nparams; + png_charp buf, units, endptr; + png_charpp params; + png_size_t slength; + int i; + + png_debug(1, "in png_handle_pCAL\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before pCAL"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid pCAL after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)) + { + png_warning(png_ptr, "Duplicate pCAL chunk"); + png_crc_finish(png_ptr, length); + return; + } + + png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n", + length + 1); + purpose = (png_charp)png_malloc_warn(png_ptr, length + 1); + if (purpose == NULL) + { + png_warning(png_ptr, "No memory for pCAL purpose."); + return; + } + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)purpose, slength); + + if (png_crc_finish(png_ptr, 0)) + { + png_free(png_ptr, purpose); + return; + } + + purpose[slength] = 0x00; /* null terminate the last string */ + + png_debug(3, "Finding end of pCAL purpose string\n"); + for (buf = purpose; *buf; buf++) + /* empty loop */ ; + + endptr = purpose + slength; + + /* We need to have at least 12 bytes after the purpose string + in order to get the parameter information. */ + if (endptr <= buf + 12) + { + png_warning(png_ptr, "Invalid pCAL data"); + png_free(png_ptr, purpose); + return; + } + + png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n"); + X0 = png_get_int_32((png_bytep)buf+1); + X1 = png_get_int_32((png_bytep)buf+5); + type = buf[9]; + nparams = buf[10]; + units = buf + 11; + + png_debug(3, "Checking pCAL equation type and number of parameters\n"); + /* Check that we have the right number of parameters for known + equation types. */ + if ((type == PNG_EQUATION_LINEAR && nparams != 2) || + (type == PNG_EQUATION_BASE_E && nparams != 3) || + (type == PNG_EQUATION_ARBITRARY && nparams != 3) || + (type == PNG_EQUATION_HYPERBOLIC && nparams != 4)) + { + png_warning(png_ptr, "Invalid pCAL parameters for equation type"); + png_free(png_ptr, purpose); + return; + } + else if (type >= PNG_EQUATION_LAST) + { + png_warning(png_ptr, "Unrecognized equation type for pCAL chunk"); + } + + for (buf = units; *buf; buf++) + /* Empty loop to move past the units string. */ ; + + png_debug(3, "Allocating pCAL parameters array\n"); + params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams + *png_sizeof(png_charp))) ; + if (params == NULL) + { + png_free(png_ptr, purpose); + png_warning(png_ptr, "No memory for pCAL params."); + return; + } + + /* Get pointers to the start of each parameter string. */ + for (i = 0; i < (int)nparams; i++) + { + buf++; /* Skip the null string terminator from previous parameter. */ + + png_debug1(3, "Reading pCAL parameter %d\n", i); + for (params[i] = buf; *buf != 0x00 && buf <= endptr; buf++) + /* Empty loop to move past each parameter string */ ; + + /* Make sure we haven't run out of data yet */ + if (buf > endptr) + { + png_warning(png_ptr, "Invalid pCAL data"); + png_free(png_ptr, purpose); + png_free(png_ptr, params); + return; + } + } + + png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams, + units, params); + + png_free(png_ptr, purpose); + png_free(png_ptr, params); +} +#endif + +#if defined(PNG_READ_sCAL_SUPPORTED) +/* read the sCAL chunk */ +void /* PRIVATE */ +png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_charp buffer, ep; +#ifdef PNG_FLOATING_POINT_SUPPORTED + double width, height; + png_charp vp; +#else +#ifdef PNG_FIXED_POINT_SUPPORTED + png_charp swidth, sheight; +#endif +#endif + png_size_t slength; + + png_debug(1, "in png_handle_sCAL\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before sCAL"); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, "Invalid sCAL after IDAT"); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL)) + { + png_warning(png_ptr, "Duplicate sCAL chunk"); + png_crc_finish(png_ptr, length); + return; + } + + png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n", + length + 1); + buffer = (png_charp)png_malloc_warn(png_ptr, length + 1); + if (buffer == NULL) + { + png_warning(png_ptr, "Out of memory while processing sCAL chunk"); + return; + } + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)buffer, slength); + + if (png_crc_finish(png_ptr, 0)) + { + png_free(png_ptr, buffer); + return; + } + + buffer[slength] = 0x00; /* null terminate the last string */ + + ep = buffer + 1; /* skip unit byte */ + +#ifdef PNG_FLOATING_POINT_SUPPORTED + width = strtod(ep, &vp); + if (*vp) + { + png_warning(png_ptr, "malformed width string in sCAL chunk"); + return; + } +#else +#ifdef PNG_FIXED_POINT_SUPPORTED + swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1); + if (swidth == NULL) + { + png_warning(png_ptr, "Out of memory while processing sCAL chunk width"); + return; + } + png_memcpy(swidth, ep, (png_size_t)png_strlen(ep)); +#endif +#endif + + for (ep = buffer; *ep; ep++) + /* empty loop */ ; + ep++; + +#ifdef PNG_FLOATING_POINT_SUPPORTED + height = strtod(ep, &vp); + if (*vp) + { + png_warning(png_ptr, "malformed height string in sCAL chunk"); + return; + } +#else +#ifdef PNG_FIXED_POINT_SUPPORTED + sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1); + if (swidth == NULL) + { + png_warning(png_ptr, "Out of memory while processing sCAL chunk height"); + return; + } + png_memcpy(sheight, ep, (png_size_t)png_strlen(ep)); +#endif +#endif + + if (buffer + slength < ep +#ifdef PNG_FLOATING_POINT_SUPPORTED + || width <= 0. || height <= 0. +#endif + ) + { + png_warning(png_ptr, "Invalid sCAL data"); + png_free(png_ptr, buffer); +#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED) + png_free(png_ptr, swidth); + png_free(png_ptr, sheight); +#endif + return; + } + + +#ifdef PNG_FLOATING_POINT_SUPPORTED + png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height); +#else +#ifdef PNG_FIXED_POINT_SUPPORTED + png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight); +#endif +#endif + + png_free(png_ptr, buffer); +#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED) + png_free(png_ptr, swidth); + png_free(png_ptr, sheight); +#endif +} +#endif + +#if defined(PNG_READ_tIME_SUPPORTED) +void /* PRIVATE */ +png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_byte buf[7]; + png_time mod_time; + + png_debug(1, "in png_handle_tIME\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Out of place tIME chunk"); + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)) + { + png_warning(png_ptr, "Duplicate tIME chunk"); + png_crc_finish(png_ptr, length); + return; + } + + if (png_ptr->mode & PNG_HAVE_IDAT) + png_ptr->mode |= PNG_AFTER_IDAT; + + if (length != 7) + { + png_warning(png_ptr, "Incorrect tIME chunk length"); + png_crc_finish(png_ptr, length); + return; + } + + png_crc_read(png_ptr, buf, 7); + if (png_crc_finish(png_ptr, 0)) + return; + + mod_time.second = buf[6]; + mod_time.minute = buf[5]; + mod_time.hour = buf[4]; + mod_time.day = buf[3]; + mod_time.month = buf[2]; + mod_time.year = png_get_uint_16(buf); + + png_set_tIME(png_ptr, info_ptr, &mod_time); +} +#endif + +#if defined(PNG_READ_tEXt_SUPPORTED) +/* Note: this does not properly handle chunks that are > 64K under DOS */ +void /* PRIVATE */ +png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_textp text_ptr; + png_charp key; + png_charp text; + png_uint_32 skip = 0; + png_size_t slength; + int ret; + + png_debug(1, "in png_handle_tEXt\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before tEXt"); + + if (png_ptr->mode & PNG_HAVE_IDAT) + png_ptr->mode |= PNG_AFTER_IDAT; + +#ifdef PNG_MAX_MALLOC_64K + if (length > (png_uint_32)65535L) + { + png_warning(png_ptr, "tEXt chunk too large to fit in memory"); + skip = length - (png_uint_32)65535L; + length = (png_uint_32)65535L; + } +#endif + + key = (png_charp)png_malloc_warn(png_ptr, length + 1); + if (key == NULL) + { + png_warning(png_ptr, "No memory to process text chunk."); + return; + } + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)key, slength); + + if (png_crc_finish(png_ptr, skip)) + { + png_free(png_ptr, key); + return; + } + + key[slength] = 0x00; + + for (text = key; *text; text++) + /* empty loop to find end of key */ ; + + if (text != key + slength) + text++; + + text_ptr = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)png_sizeof(png_text)); + if (text_ptr == NULL) + { + png_warning(png_ptr, "Not enough memory to process text chunk."); + png_free(png_ptr, key); + return; + } + text_ptr->compression = PNG_TEXT_COMPRESSION_NONE; + text_ptr->key = key; +#ifdef PNG_iTXt_SUPPORTED + text_ptr->lang = NULL; + text_ptr->lang_key = NULL; + text_ptr->itxt_length = 0; +#endif + text_ptr->text = text; + text_ptr->text_length = png_strlen(text); + + ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1); + + png_free(png_ptr, key); + png_free(png_ptr, text_ptr); + if (ret) + png_warning(png_ptr, "Insufficient memory to process text chunk."); +} +#endif + +#if defined(PNG_READ_zTXt_SUPPORTED) +/* note: this does not correctly handle chunks that are > 64K under DOS */ +void /* PRIVATE */ +png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_textp text_ptr; + png_charp chunkdata; + png_charp text; + int comp_type; + int ret; + png_size_t slength, prefix_len, data_len; + + png_debug(1, "in png_handle_zTXt\n"); + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before zTXt"); + + if (png_ptr->mode & PNG_HAVE_IDAT) + png_ptr->mode |= PNG_AFTER_IDAT; + +#ifdef PNG_MAX_MALLOC_64K + /* We will no doubt have problems with chunks even half this size, but + there is no hard and fast rule to tell us where to stop. */ + if (length > (png_uint_32)65535L) + { + png_warning(png_ptr,"zTXt chunk too large to fit in memory"); + png_crc_finish(png_ptr, length); + return; + } +#endif + + chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); + if (chunkdata == NULL) + { + png_warning(png_ptr,"Out of memory processing zTXt chunk."); + return; + } + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)chunkdata, slength); + if (png_crc_finish(png_ptr, 0)) + { + png_free(png_ptr, chunkdata); + return; + } + + chunkdata[slength] = 0x00; + + for (text = chunkdata; *text; text++) + /* empty loop */ ; + + /* zTXt must have some text after the chunkdataword */ + if (text == chunkdata + slength) + { + comp_type = PNG_TEXT_COMPRESSION_NONE; + png_warning(png_ptr, "Zero length zTXt chunk"); + } + else + { + comp_type = *(++text); + if (comp_type != PNG_TEXT_COMPRESSION_zTXt) + { + png_warning(png_ptr, "Unknown compression type in zTXt chunk"); + comp_type = PNG_TEXT_COMPRESSION_zTXt; + } + text++; /* skip the compression_method byte */ + } + prefix_len = text - chunkdata; + + chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata, + (png_size_t)length, prefix_len, &data_len); + + text_ptr = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)png_sizeof(png_text)); + if (text_ptr == NULL) + { + png_warning(png_ptr,"Not enough memory to process zTXt chunk."); + png_free(png_ptr, chunkdata); + return; + } + text_ptr->compression = comp_type; + text_ptr->key = chunkdata; +#ifdef PNG_iTXt_SUPPORTED + text_ptr->lang = NULL; + text_ptr->lang_key = NULL; + text_ptr->itxt_length = 0; +#endif + text_ptr->text = chunkdata + prefix_len; + text_ptr->text_length = data_len; + + ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1); + + png_free(png_ptr, text_ptr); + png_free(png_ptr, chunkdata); + if (ret) + png_error(png_ptr, "Insufficient memory to store zTXt chunk."); +} +#endif + +#if defined(PNG_READ_iTXt_SUPPORTED) +/* note: this does not correctly handle chunks that are > 64K under DOS */ +void /* PRIVATE */ +png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_textp text_ptr; + png_charp chunkdata; + png_charp key, lang, text, lang_key; + int comp_flag; + int comp_type = 0; + int ret; + png_size_t slength, prefix_len, data_len; + + png_debug(1, "in png_handle_iTXt\n"); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, "Missing IHDR before iTXt"); + + if (png_ptr->mode & PNG_HAVE_IDAT) + png_ptr->mode |= PNG_AFTER_IDAT; + +#ifdef PNG_MAX_MALLOC_64K + /* We will no doubt have problems with chunks even half this size, but + there is no hard and fast rule to tell us where to stop. */ + if (length > (png_uint_32)65535L) + { + png_warning(png_ptr,"iTXt chunk too large to fit in memory"); + png_crc_finish(png_ptr, length); + return; + } +#endif + + chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); + if (chunkdata == NULL) + { + png_warning(png_ptr, "No memory to process iTXt chunk."); + return; + } + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)chunkdata, slength); + if (png_crc_finish(png_ptr, 0)) + { + png_free(png_ptr, chunkdata); + return; + } + + chunkdata[slength] = 0x00; + + for (lang = chunkdata; *lang; lang++) + /* empty loop */ ; + lang++; /* skip NUL separator */ + + /* iTXt must have a language tag (possibly empty), two compression bytes, + translated keyword (possibly empty), and possibly some text after the + keyword */ + + if (lang >= chunkdata + slength) + { + comp_flag = PNG_TEXT_COMPRESSION_NONE; + png_warning(png_ptr, "Zero length iTXt chunk"); + } + else + { + comp_flag = *lang++; + comp_type = *lang++; + } + + for (lang_key = lang; *lang_key; lang_key++) + /* empty loop */ ; + lang_key++; /* skip NUL separator */ + + for (text = lang_key; *text; text++) + /* empty loop */ ; + text++; /* skip NUL separator */ + + prefix_len = text - chunkdata; + + key=chunkdata; + if (comp_flag) + chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata, + (size_t)length, prefix_len, &data_len); + else + data_len=png_strlen(chunkdata + prefix_len); + text_ptr = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)png_sizeof(png_text)); + if (text_ptr == NULL) + { + png_warning(png_ptr,"Not enough memory to process iTXt chunk."); + png_free(png_ptr, chunkdata); + return; + } + text_ptr->compression = (int)comp_flag + 1; + text_ptr->lang_key = chunkdata+(lang_key-key); + text_ptr->lang = chunkdata+(lang-key); + text_ptr->itxt_length = data_len; + text_ptr->text_length = 0; + text_ptr->key = chunkdata; + text_ptr->text = chunkdata + prefix_len; + + ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1); + + png_free(png_ptr, text_ptr); + png_free(png_ptr, chunkdata); + if (ret) + png_error(png_ptr, "Insufficient memory to store iTXt chunk."); +} +#endif + +/* This function is called when we haven't found a handler for a + chunk. If there isn't a problem with the chunk itself (ie bad + chunk name, CRC, or a critical chunk), the chunk is silently ignored + -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which + case it will be saved away to be written out later. */ +void /* PRIVATE */ +png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_uint_32 skip = 0; + + png_debug(1, "in png_handle_unknown\n"); + + if (png_ptr->mode & PNG_HAVE_IDAT) + { +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IDAT; +#endif + if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */ + png_ptr->mode |= PNG_AFTER_IDAT; + } + + png_check_chunk_name(png_ptr, png_ptr->chunk_name); + + if (!(png_ptr->chunk_name[0] & 0x20)) + { +#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) + if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) != + PNG_HANDLE_CHUNK_ALWAYS +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED) + && png_ptr->read_user_chunk_fn == NULL +#endif + ) +#endif + png_chunk_error(png_ptr, "unknown critical chunk"); + } + +#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) + if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) + { + png_unknown_chunk chunk; + +#ifdef PNG_MAX_MALLOC_64K + if (length > (png_uint_32)65535L) + { + png_warning(png_ptr, "unknown chunk too large to fit in memory"); + skip = length - (png_uint_32)65535L; + length = (png_uint_32)65535L; + } +#endif + png_strcpy((png_charp)chunk.name, (png_charp)png_ptr->chunk_name); + chunk.data = (png_bytep)png_malloc(png_ptr, length); + chunk.size = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)chunk.data, length); +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED) + if(png_ptr->read_user_chunk_fn != NULL) + { + /* callback to user unknown chunk handler */ + if ((*(png_ptr->read_user_chunk_fn)) (png_ptr, &chunk) <= 0) + { + if (!(png_ptr->chunk_name[0] & 0x20)) + if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) != + PNG_HANDLE_CHUNK_ALWAYS) + { + png_free(png_ptr, chunk.data); + png_chunk_error(png_ptr, "unknown critical chunk"); + } + png_set_unknown_chunks(png_ptr, info_ptr, &chunk, 1); + } + } + else +#endif + png_set_unknown_chunks(png_ptr, info_ptr, &chunk, 1); + png_free(png_ptr, chunk.data); + } + else +#endif + skip = length; + + png_crc_finish(png_ptr, skip); + +#if !defined(PNG_READ_USER_CHUNKS_SUPPORTED) + if (&info_ptr == NULL) /* quiet compiler warnings about unused info_ptr */ + return; +#endif +} + +/* This function is called to verify that a chunk name is valid. + This function can't have the "critical chunk check" incorporated + into it, since in the future we will need to be able to call user + functions to handle unknown critical chunks after we check that + the chunk name itself is valid. */ + +#define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97)) + +void /* PRIVATE */ +png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name) +{ + png_debug(1, "in png_check_chunk_name\n"); + if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) || + isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3])) + { + png_chunk_error(png_ptr, "invalid chunk type"); + } +} + +/* Combines the row recently read in with the existing pixels in the + row. This routine takes care of alpha and transparency if requested. + This routine also handles the two methods of progressive display + of interlaced images, depending on the mask value. + The mask value describes which pixels are to be combined with + the row. The pattern always repeats every 8 pixels, so just 8 + bits are needed. A one indicates the pixel is to be combined, + a zero indicates the pixel is to be skipped. This is in addition + to any alpha or transparency value associated with the pixel. If + you want all pixels to be combined, pass 0xff (255) in mask. */ +#ifndef PNG_HAVE_ASSEMBLER_COMBINE_ROW +void /* PRIVATE */ +png_combine_row(png_structp png_ptr, png_bytep row, int mask) +{ + png_debug(1,"in png_combine_row\n"); + if (mask == 0xff) + { + png_memcpy(row, png_ptr->row_buf + 1, + PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width)); + } + else + { + switch (png_ptr->row_info.pixel_depth) + { + case 1: + { + png_bytep sp = png_ptr->row_buf + 1; + png_bytep dp = row; + int s_inc, s_start, s_end; + int m = 0x80; + int shift; + png_uint_32 i; + png_uint_32 row_width = png_ptr->width; + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 7; + s_inc = 1; + } + else +#endif + { + s_start = 7; + s_end = 0; + s_inc = -1; + } + + shift = s_start; + + for (i = 0; i < row_width; i++) + { + if (m & mask) + { + int value; + + value = (*sp >> shift) & 0x01; + *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + case 2: + { + png_bytep sp = png_ptr->row_buf + 1; + png_bytep dp = row; + int s_start, s_end, s_inc; + int m = 0x80; + int shift; + png_uint_32 i; + png_uint_32 row_width = png_ptr->width; + int value; + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 6; + s_inc = 2; + } + else +#endif + { + s_start = 6; + s_end = 0; + s_inc = -2; + } + + shift = s_start; + + for (i = 0; i < row_width; i++) + { + if (m & mask) + { + value = (*sp >> shift) & 0x03; + *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + case 4: + { + png_bytep sp = png_ptr->row_buf + 1; + png_bytep dp = row; + int s_start, s_end, s_inc; + int m = 0x80; + int shift; + png_uint_32 i; + png_uint_32 row_width = png_ptr->width; + int value; + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 4; + s_inc = 4; + } + else +#endif + { + s_start = 4; + s_end = 0; + s_inc = -4; + } + shift = s_start; + + for (i = 0; i < row_width; i++) + { + if (m & mask) + { + value = (*sp >> shift) & 0xf; + *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + default: + { + png_bytep sp = png_ptr->row_buf + 1; + png_bytep dp = row; + png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3); + png_uint_32 i; + png_uint_32 row_width = png_ptr->width; + png_byte m = 0x80; + + + for (i = 0; i < row_width; i++) + { + if (m & mask) + { + png_memcpy(dp, sp, pixel_bytes); + } + + sp += pixel_bytes; + dp += pixel_bytes; + + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + } + } +} +#endif /* !PNG_HAVE_ASSEMBLER_COMBINE_ROW */ + +#ifdef PNG_READ_INTERLACING_SUPPORTED +#ifndef PNG_HAVE_ASSEMBLER_READ_INTERLACE /* else in pngvcrd.c, pnggccrd.c */ +/* OLD pre-1.0.9 interface: +void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass, + png_uint_32 transformations) + */ +void /* PRIVATE */ +png_do_read_interlace(png_structp png_ptr) +{ + png_row_infop row_info = &(png_ptr->row_info); + png_bytep row = png_ptr->row_buf + 1; + int pass = png_ptr->pass; + png_uint_32 transformations = png_ptr->transformations; +#ifdef PNG_USE_LOCAL_ARRAYS + /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ + /* offset to next interlace block */ + const int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; +#endif + + png_debug(1,"in png_do_read_interlace (stock C version)\n"); + if (row != NULL && row_info != NULL) + { + png_uint_32 final_width; + + final_width = row_info->width * png_pass_inc[pass]; + + switch (row_info->pixel_depth) + { + case 1: + { + png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3); + png_bytep dp = row + (png_size_t)((final_width - 1) >> 3); + int sshift, dshift; + int s_start, s_end, s_inc; + int jstop = png_pass_inc[pass]; + png_byte v; + png_uint_32 i; + int j; + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (int)((row_info->width + 7) & 0x07); + dshift = (int)((final_width + 7) & 0x07); + s_start = 7; + s_end = 0; + s_inc = -1; + } + else +#endif + { + sshift = 7 - (int)((row_info->width + 7) & 0x07); + dshift = 7 - (int)((final_width + 7) & 0x07); + s_start = 0; + s_end = 7; + s_inc = 1; + } + + for (i = 0; i < row_info->width; i++) + { + v = (png_byte)((*sp >> sshift) & 0x01); + for (j = 0; j < jstop; j++) + { + *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + case 2: + { + png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2); + png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2); + int sshift, dshift; + int s_start, s_end, s_inc; + int jstop = png_pass_inc[pass]; + png_uint_32 i; + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (int)(((row_info->width + 3) & 0x03) << 1); + dshift = (int)(((final_width + 3) & 0x03) << 1); + s_start = 6; + s_end = 0; + s_inc = -2; + } + else +#endif + { + sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1); + dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1); + s_start = 0; + s_end = 6; + s_inc = 2; + } + + for (i = 0; i < row_info->width; i++) + { + png_byte v; + int j; + + v = (png_byte)((*sp >> sshift) & 0x03); + for (j = 0; j < jstop; j++) + { + *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + case 4: + { + png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1); + png_bytep dp = row + (png_size_t)((final_width - 1) >> 1); + int sshift, dshift; + int s_start, s_end, s_inc; + png_uint_32 i; + int jstop = png_pass_inc[pass]; + +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (int)(((row_info->width + 1) & 0x01) << 2); + dshift = (int)(((final_width + 1) & 0x01) << 2); + s_start = 4; + s_end = 0; + s_inc = -4; + } + else +#endif + { + sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2); + dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2); + s_start = 0; + s_end = 4; + s_inc = 4; + } + + for (i = 0; i < row_info->width; i++) + { + png_byte v = (png_byte)((*sp >> sshift) & 0xf); + int j; + + for (j = 0; j < jstop; j++) + { + *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + default: + { + png_size_t pixel_bytes = (row_info->pixel_depth >> 3); + png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes; + png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes; + + int jstop = png_pass_inc[pass]; + png_uint_32 i; + + for (i = 0; i < row_info->width; i++) + { + png_byte v[8]; + int j; + + png_memcpy(v, sp, pixel_bytes); + for (j = 0; j < jstop; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sp -= pixel_bytes; + } + break; + } + } + row_info->width = final_width; + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width); + } +#if !defined(PNG_READ_PACKSWAP_SUPPORTED) + if (&transformations == NULL) /* silence compiler warning */ + return; +#endif +} +#endif /* !PNG_HAVE_ASSEMBLER_READ_INTERLACE */ +#endif /* PNG_READ_INTERLACING_SUPPORTED */ + +#ifndef PNG_HAVE_ASSEMBLER_READ_FILTER_ROW +void /* PRIVATE */ +png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row, + png_bytep prev_row, int filter) +{ + png_debug(1, "in png_read_filter_row\n"); + png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter); + switch (filter) + { + case PNG_FILTER_VALUE_NONE: + break; + case PNG_FILTER_VALUE_SUB: + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_bytep rp = row + bpp; + png_bytep lp = row; + + for (i = bpp; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_UP: + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_bytep rp = row; + png_bytep pp = prev_row; + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_AVG: + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop = row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + + ((int)(*pp++) / 2 )) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + + (int)(*pp++ + *lp++) / 2 ) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_PAETH: + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_bytep cp = prev_row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop=row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) /* use leftover rp,pp */ + { + int a, b, c, pa, pb, pc, p; + + a = *lp++; + b = *pp++; + c = *cp++; + + p = b - c; + pc = a - c; + +#ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +#else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +#endif + + /* + if (pa <= pb && pa <= pc) + p = a; + else if (pb <= pc) + p = b; + else + p = c; + */ + + p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c; + + *rp = (png_byte)(((int)(*rp) + p) & 0xff); + rp++; + } + break; + } + default: + png_warning(png_ptr, "Ignoring bad adaptive filter type"); + *row=0; + break; + } +} +#endif /* !PNG_HAVE_ASSEMBLER_READ_FILTER_ROW */ + +void /* PRIVATE */ +png_read_finish_row(png_structp png_ptr) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ + + /* start of interlace block */ + const int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + + /* offset to next interlace block */ + const int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + + /* start of interlace block in the y direction */ + const int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; + + /* offset to next interlace block in the y direction */ + const int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; +#endif + + png_debug(1, "in png_read_finish_row\n"); + png_ptr->row_number++; + if (png_ptr->row_number < png_ptr->num_rows) + return; + + if (png_ptr->interlaced) + { + png_ptr->row_number = 0; + png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1); + do + { + png_ptr->pass++; + if (png_ptr->pass >= 7) + break; + png_ptr->iwidth = (png_ptr->width + + png_pass_inc[png_ptr->pass] - 1 - + png_pass_start[png_ptr->pass]) / + png_pass_inc[png_ptr->pass]; + + png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, + png_ptr->iwidth) + 1; + + if (!(png_ptr->transformations & PNG_INTERLACE)) + { + png_ptr->num_rows = (png_ptr->height + + png_pass_yinc[png_ptr->pass] - 1 - + png_pass_ystart[png_ptr->pass]) / + png_pass_yinc[png_ptr->pass]; + if (!(png_ptr->num_rows)) + continue; + } + else /* if (png_ptr->transformations & PNG_INTERLACE) */ + break; + } while (png_ptr->iwidth == 0); + + if (png_ptr->pass < 7) + return; + } + + if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED)) + { +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IDAT; +#endif + char extra; + int ret; + + png_ptr->zstream.next_out = (Byte *)&extra; + png_ptr->zstream.avail_out = (uInt)1; + for(;;) + { + if (!(png_ptr->zstream.avail_in)) + { + while (!png_ptr->idat_size) + { + png_byte chunk_length[4]; + + png_crc_finish(png_ptr, 0); + + png_read_data(png_ptr, chunk_length, 4); + png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length); + png_reset_crc(png_ptr); + png_crc_read(png_ptr, png_ptr->chunk_name, 4); + if (png_memcmp(png_ptr->chunk_name, (png_bytep)png_IDAT, 4)) + png_error(png_ptr, "Not enough image data"); + + } + png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size; + png_ptr->zstream.next_in = png_ptr->zbuf; + if (png_ptr->zbuf_size > png_ptr->idat_size) + png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size; + png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in); + png_ptr->idat_size -= png_ptr->zstream.avail_in; + } + ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH); + if (ret == Z_STREAM_END) + { + if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in || + png_ptr->idat_size) + png_warning(png_ptr, "Extra compressed data"); + png_ptr->mode |= PNG_AFTER_IDAT; + png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; + break; + } + if (ret != Z_OK) + png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg : + "Decompression Error"); + + if (!(png_ptr->zstream.avail_out)) + { + png_warning(png_ptr, "Extra compressed data."); + png_ptr->mode |= PNG_AFTER_IDAT; + png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; + break; + } + + } + png_ptr->zstream.avail_out = 0; + } + + if (png_ptr->idat_size || png_ptr->zstream.avail_in) + png_warning(png_ptr, "Extra compression data"); + + inflateReset(&png_ptr->zstream); + + png_ptr->mode |= PNG_AFTER_IDAT; +} + +void /* PRIVATE */ +png_read_start_row(png_structp png_ptr) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ + + /* start of interlace block */ + const int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + + /* offset to next interlace block */ + const int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + + /* start of interlace block in the y direction */ + const int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; + + /* offset to next interlace block in the y direction */ + const int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; +#endif + + int max_pixel_depth; + png_uint_32 row_bytes; + + png_debug(1, "in png_read_start_row\n"); + png_ptr->zstream.avail_in = 0; + png_init_read_transformations(png_ptr); + if (png_ptr->interlaced) + { + if (!(png_ptr->transformations & PNG_INTERLACE)) + png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - + png_pass_ystart[0]) / png_pass_yinc[0]; + else + png_ptr->num_rows = png_ptr->height; + + png_ptr->iwidth = (png_ptr->width + + png_pass_inc[png_ptr->pass] - 1 - + png_pass_start[png_ptr->pass]) / + png_pass_inc[png_ptr->pass]; + + row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1; + + png_ptr->irowbytes = (png_size_t)row_bytes; + if((png_uint_32)png_ptr->irowbytes != row_bytes) + png_error(png_ptr, "Rowbytes overflow in png_read_start_row"); + } + else + { + png_ptr->num_rows = png_ptr->height; + png_ptr->iwidth = png_ptr->width; + png_ptr->irowbytes = png_ptr->rowbytes + 1; + } + max_pixel_depth = png_ptr->pixel_depth; + +#if defined(PNG_READ_PACK_SUPPORTED) + if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8) + max_pixel_depth = 8; +#endif + +#if defined(PNG_READ_EXPAND_SUPPORTED) + if (png_ptr->transformations & PNG_EXPAND) + { + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + if (png_ptr->num_trans) + max_pixel_depth = 32; + else + max_pixel_depth = 24; + } + else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) + { + if (max_pixel_depth < 8) + max_pixel_depth = 8; + if (png_ptr->num_trans) + max_pixel_depth *= 2; + } + else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) + { + if (png_ptr->num_trans) + { + max_pixel_depth *= 4; + max_pixel_depth /= 3; + } + } + } +#endif + +#if defined(PNG_READ_FILLER_SUPPORTED) + if (png_ptr->transformations & (PNG_FILLER)) + { + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + max_pixel_depth = 32; + else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) + { + if (max_pixel_depth <= 8) + max_pixel_depth = 16; + else + max_pixel_depth = 32; + } + else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) + { + if (max_pixel_depth <= 32) + max_pixel_depth = 32; + else + max_pixel_depth = 64; + } + } +#endif + +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) + if (png_ptr->transformations & PNG_GRAY_TO_RGB) + { + if ( +#if defined(PNG_READ_EXPAND_SUPPORTED) + (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) || +#endif +#if defined(PNG_READ_FILLER_SUPPORTED) + (png_ptr->transformations & (PNG_FILLER)) || +#endif + png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + { + if (max_pixel_depth <= 16) + max_pixel_depth = 32; + else + max_pixel_depth = 64; + } + else + { + if (max_pixel_depth <= 8) + { + if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + max_pixel_depth = 32; + else + max_pixel_depth = 24; + } + else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + max_pixel_depth = 64; + else + max_pixel_depth = 48; + } + } +#endif + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \ +defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) + if(png_ptr->transformations & PNG_USER_TRANSFORM) + { + int user_pixel_depth=png_ptr->user_transform_depth* + png_ptr->user_transform_channels; + if(user_pixel_depth > max_pixel_depth) + max_pixel_depth=user_pixel_depth; + } +#endif + + /* align the width on the next larger 8 pixels. Mainly used + for interlacing */ + row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7)); + /* calculate the maximum bytes needed, adding a byte and a pixel + for safety's sake */ + row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) + + 1 + ((max_pixel_depth + 7) >> 3); +#ifdef PNG_MAX_MALLOC_64K + if (row_bytes > (png_uint_32)65536L) + png_error(png_ptr, "This image requires a row greater than 64KB"); +#endif + png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64); + png_ptr->row_buf = png_ptr->big_row_buf+32; +#if defined(PNG_DEBUG) && defined(PNG_USE_PNGGCCRD) + png_ptr->row_buf_size = row_bytes; +#endif + +#ifdef PNG_MAX_MALLOC_64K + if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L) + png_error(png_ptr, "This image requires a row greater than 64KB"); +#endif + if ((png_uint_32)png_ptr->rowbytes + 1 > PNG_SIZE_MAX) + png_error(png_ptr, "Row has too many bytes to allocate in memory."); + png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)( + png_ptr->rowbytes + 1)); + + png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1); + + png_debug1(3, "width = %lu,\n", png_ptr->width); + png_debug1(3, "height = %lu,\n", png_ptr->height); + png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth); + png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows); + png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes); + png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes); + + png_ptr->flags |= PNG_FLAG_ROW_INIT; +} diff --git a/SlnkDWFImpl/CxImage/png/pngset.c b/SlnkDWFImpl/CxImage/png/pngset.c new file mode 100644 index 0000000..30b9166 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngset.c @@ -0,0 +1,1219 @@ + +/* pngset.c - storage of image information into info struct + * + * libpng 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * The functions here are used during reads to store data from the file + * into the info struct, and during writes to store application data + * into the info struct for writing into the file. This abstracts the + * info struct and allows us to change the structure in the future. + */ + +#define PNG_INTERNAL +#include "png.h" + +#if defined(PNG_bKGD_SUPPORTED) +void PNGAPI +png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background) +{ + png_debug1(1, "in %s storage function\n", "bKGD"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16)); + info_ptr->valid |= PNG_INFO_bKGD; +} +#endif + +#if defined(PNG_cHRM_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +void PNGAPI +png_set_cHRM(png_structp png_ptr, png_infop info_ptr, + double white_x, double white_y, double red_x, double red_y, + double green_x, double green_y, double blue_x, double blue_y) +{ + png_debug1(1, "in %s storage function\n", "cHRM"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + if (white_x < 0.0 || white_y < 0.0 || + red_x < 0.0 || red_y < 0.0 || + green_x < 0.0 || green_y < 0.0 || + blue_x < 0.0 || blue_y < 0.0) + { + png_warning(png_ptr, + "Ignoring attempt to set negative chromaticity value"); + return; + } + if (white_x > 21474.83 || white_y > 21474.83 || + red_x > 21474.83 || red_y > 21474.83 || + green_x > 21474.83 || green_y > 21474.83 || + blue_x > 21474.83 || blue_y > 21474.83) + { + png_warning(png_ptr, + "Ignoring attempt to set chromaticity value exceeding 21474.83"); + return; + } + + info_ptr->x_white = (float)white_x; + info_ptr->y_white = (float)white_y; + info_ptr->x_red = (float)red_x; + info_ptr->y_red = (float)red_y; + info_ptr->x_green = (float)green_x; + info_ptr->y_green = (float)green_y; + info_ptr->x_blue = (float)blue_x; + info_ptr->y_blue = (float)blue_y; +#ifdef PNG_FIXED_POINT_SUPPORTED + info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5); + info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5); + info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5); + info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5); + info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5); + info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5); + info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5); + info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5); +#endif + info_ptr->valid |= PNG_INFO_cHRM; +} +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +void PNGAPI +png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr, + png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x, + png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y, + png_fixed_point blue_x, png_fixed_point blue_y) +{ + png_debug1(1, "in %s storage function\n", "cHRM"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + if (white_x < 0 || white_y < 0 || + red_x < 0 || red_y < 0 || + green_x < 0 || green_y < 0 || + blue_x < 0 || blue_y < 0) + { + png_warning(png_ptr, + "Ignoring attempt to set negative chromaticity value"); + return; + } + if (white_x > (double) PNG_UINT_31_MAX || + white_y > (double) PNG_UINT_31_MAX || + red_x > (double) PNG_UINT_31_MAX || + red_y > (double) PNG_UINT_31_MAX || + green_x > (double) PNG_UINT_31_MAX || + green_y > (double) PNG_UINT_31_MAX || + blue_x > (double) PNG_UINT_31_MAX || + blue_y > (double) PNG_UINT_31_MAX) + { + png_warning(png_ptr, + "Ignoring attempt to set chromaticity value exceeding 21474.83"); + return; + } + info_ptr->int_x_white = white_x; + info_ptr->int_y_white = white_y; + info_ptr->int_x_red = red_x; + info_ptr->int_y_red = red_y; + info_ptr->int_x_green = green_x; + info_ptr->int_y_green = green_y; + info_ptr->int_x_blue = blue_x; + info_ptr->int_y_blue = blue_y; +#ifdef PNG_FLOATING_POINT_SUPPORTED + info_ptr->x_white = (float)(white_x/100000.); + info_ptr->y_white = (float)(white_y/100000.); + info_ptr->x_red = (float)( red_x/100000.); + info_ptr->y_red = (float)( red_y/100000.); + info_ptr->x_green = (float)(green_x/100000.); + info_ptr->y_green = (float)(green_y/100000.); + info_ptr->x_blue = (float)( blue_x/100000.); + info_ptr->y_blue = (float)( blue_y/100000.); +#endif + info_ptr->valid |= PNG_INFO_cHRM; +} +#endif +#endif + +#if defined(PNG_gAMA_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +void PNGAPI +png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma) +{ + double gamma; + png_debug1(1, "in %s storage function\n", "gAMA"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + /* Check for overflow */ + if (file_gamma > 21474.83) + { + png_warning(png_ptr, "Limiting gamma to 21474.83"); + gamma=21474.83; + } + else + gamma=file_gamma; + info_ptr->gamma = (float)gamma; +#ifdef PNG_FIXED_POINT_SUPPORTED + info_ptr->int_gamma = (int)(gamma*100000.+.5); +#endif + info_ptr->valid |= PNG_INFO_gAMA; + if(gamma == 0.0) + png_warning(png_ptr, "Setting gamma=0"); +} +#endif +void PNGAPI +png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point + int_gamma) +{ + png_fixed_point gamma; + + png_debug1(1, "in %s storage function\n", "gAMA"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX) + { + png_warning(png_ptr, "Limiting gamma to 21474.83"); + gamma=PNG_UINT_31_MAX; + } + else + { + if (int_gamma < 0) + { + png_warning(png_ptr, "Setting negative gamma to zero"); + gamma=0; + } + else + gamma=int_gamma; + } +#ifdef PNG_FLOATING_POINT_SUPPORTED + info_ptr->gamma = (float)(gamma/100000.); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED + info_ptr->int_gamma = gamma; +#endif + info_ptr->valid |= PNG_INFO_gAMA; + if(gamma == 0) + png_warning(png_ptr, "Setting gamma=0"); +} +#endif + +#if defined(PNG_hIST_SUPPORTED) +void PNGAPI +png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist) +{ + int i; + + png_debug1(1, "in %s storage function\n", "hIST"); + if (png_ptr == NULL || info_ptr == NULL) + return; + if (info_ptr->num_palette == 0) + { + png_warning(png_ptr, + "Palette size 0, hIST allocation skipped."); + return; + } + +#ifdef PNG_FREE_ME_SUPPORTED + png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0); +#endif + /* Changed from info->num_palette to 256 in version 1.2.1 */ + png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr, + (png_uint_32)(256 * png_sizeof (png_uint_16))); + if (png_ptr->hist == NULL) + { + png_warning(png_ptr, "Insufficient memory for hIST chunk data."); + return; + } + + for (i = 0; i < info_ptr->num_palette; i++) + png_ptr->hist[i] = hist[i]; + info_ptr->hist = png_ptr->hist; + info_ptr->valid |= PNG_INFO_hIST; + +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_HIST; +#else + png_ptr->flags |= PNG_FLAG_FREE_HIST; +#endif +} +#endif + +void PNGAPI +png_set_IHDR(png_structp png_ptr, png_infop info_ptr, + png_uint_32 width, png_uint_32 height, int bit_depth, + int color_type, int interlace_type, int compression_type, + int filter_type) +{ + png_debug1(1, "in %s storage function\n", "IHDR"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + /* check for width and height valid values */ + if (width == 0 || height == 0) + png_error(png_ptr, "Image width or height is zero in IHDR"); +#ifdef PNG_SET_USER_LIMITS_SUPPORTED + if (width > png_ptr->user_width_max || height > png_ptr->user_height_max) + png_error(png_ptr, "image size exceeds user limits in IHDR"); +#else + if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX) + png_error(png_ptr, "image size exceeds user limits in IHDR"); +#endif + if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX) + png_error(png_ptr, "Invalid image size in IHDR"); + if ( width > (PNG_UINT_32_MAX + >> 3) /* 8-byte RGBA pixels */ + - 64 /* bigrowbuf hack */ + - 1 /* filter byte */ + - 7*8 /* rounding of width to multiple of 8 pixels */ + - 8) /* extra max_pixel_depth pad */ + png_warning(png_ptr, "Width is too large for libpng to process pixels"); + + /* check other values */ + if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 && + bit_depth != 8 && bit_depth != 16) + png_error(png_ptr, "Invalid bit depth in IHDR"); + + if (color_type < 0 || color_type == 1 || + color_type == 5 || color_type > 6) + png_error(png_ptr, "Invalid color type in IHDR"); + + if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) || + ((color_type == PNG_COLOR_TYPE_RGB || + color_type == PNG_COLOR_TYPE_GRAY_ALPHA || + color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8)) + png_error(png_ptr, "Invalid color type/bit depth combination in IHDR"); + + if (interlace_type >= PNG_INTERLACE_LAST) + png_error(png_ptr, "Unknown interlace method in IHDR"); + + if (compression_type != PNG_COMPRESSION_TYPE_BASE) + png_error(png_ptr, "Unknown compression method in IHDR"); + +#if defined(PNG_MNG_FEATURES_SUPPORTED) + /* Accept filter_method 64 (intrapixel differencing) only if + * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and + * 2. Libpng did not read a PNG signature (this filter_method is only + * used in PNG datastreams that are embedded in MNG datastreams) and + * 3. The application called png_permit_mng_features with a mask that + * included PNG_FLAG_MNG_FILTER_64 and + * 4. The filter_method is 64 and + * 5. The color_type is RGB or RGBA + */ + if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted) + png_warning(png_ptr,"MNG features are not allowed in a PNG datastream\n"); + if(filter_type != PNG_FILTER_TYPE_BASE) + { + if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && + (filter_type == PNG_INTRAPIXEL_DIFFERENCING) && + ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) && + (color_type == PNG_COLOR_TYPE_RGB || + color_type == PNG_COLOR_TYPE_RGB_ALPHA))) + png_error(png_ptr, "Unknown filter method in IHDR"); + if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) + png_warning(png_ptr, "Invalid filter method in IHDR"); + } +#else + if(filter_type != PNG_FILTER_TYPE_BASE) + png_error(png_ptr, "Unknown filter method in IHDR"); +#endif + + info_ptr->width = width; + info_ptr->height = height; + info_ptr->bit_depth = (png_byte)bit_depth; + info_ptr->color_type =(png_byte) color_type; + info_ptr->compression_type = (png_byte)compression_type; + info_ptr->filter_type = (png_byte)filter_type; + info_ptr->interlace_type = (png_byte)interlace_type; + if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + info_ptr->channels = 1; + else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) + info_ptr->channels = 3; + else + info_ptr->channels = 1; + if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) + info_ptr->channels++; + info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); + + /* check for potential overflow */ + if ( width > (PNG_UINT_32_MAX + >> 3) /* 8-byte RGBA pixels */ + - 64 /* bigrowbuf hack */ + - 1 /* filter byte */ + - 7*8 /* rounding of width to multiple of 8 pixels */ + - 8) /* extra max_pixel_depth pad */ + info_ptr->rowbytes = (png_size_t)0; + else + info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width); +} + +#if defined(PNG_oFFs_SUPPORTED) +void PNGAPI +png_set_oFFs(png_structp png_ptr, png_infop info_ptr, + png_int_32 offset_x, png_int_32 offset_y, int unit_type) +{ + png_debug1(1, "in %s storage function\n", "oFFs"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + info_ptr->x_offset = offset_x; + info_ptr->y_offset = offset_y; + info_ptr->offset_unit_type = (png_byte)unit_type; + info_ptr->valid |= PNG_INFO_oFFs; +} +#endif + +#if defined(PNG_pCAL_SUPPORTED) +void PNGAPI +png_set_pCAL(png_structp png_ptr, png_infop info_ptr, + png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams, + png_charp units, png_charpp params) +{ + png_uint_32 length; + int i; + + png_debug1(1, "in %s storage function\n", "pCAL"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + length = png_strlen(purpose) + 1; + png_debug1(3, "allocating purpose for info (%lu bytes)\n", length); + info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length); + if (info_ptr->pcal_purpose == NULL) + { + png_warning(png_ptr, "Insufficient memory for pCAL purpose."); + return; + } + png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length); + + png_debug(3, "storing X0, X1, type, and nparams in info\n"); + info_ptr->pcal_X0 = X0; + info_ptr->pcal_X1 = X1; + info_ptr->pcal_type = (png_byte)type; + info_ptr->pcal_nparams = (png_byte)nparams; + + length = png_strlen(units) + 1; + png_debug1(3, "allocating units for info (%lu bytes)\n", length); + info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length); + if (info_ptr->pcal_units == NULL) + { + png_warning(png_ptr, "Insufficient memory for pCAL units."); + return; + } + png_memcpy(info_ptr->pcal_units, units, (png_size_t)length); + + info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr, + (png_uint_32)((nparams + 1) * png_sizeof(png_charp))); + if (info_ptr->pcal_params == NULL) + { + png_warning(png_ptr, "Insufficient memory for pCAL params."); + return; + } + + info_ptr->pcal_params[nparams] = NULL; + + for (i = 0; i < nparams; i++) + { + length = png_strlen(params[i]) + 1; + png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length); + info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length); + if (info_ptr->pcal_params[i] == NULL) + { + png_warning(png_ptr, "Insufficient memory for pCAL parameter."); + return; + } + png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length); + } + + info_ptr->valid |= PNG_INFO_pCAL; +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_PCAL; +#endif +} +#endif + +#if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED +void PNGAPI +png_set_sCAL(png_structp png_ptr, png_infop info_ptr, + int unit, double width, double height) +{ + png_debug1(1, "in %s storage function\n", "sCAL"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + info_ptr->scal_unit = (png_byte)unit; + info_ptr->scal_pixel_width = width; + info_ptr->scal_pixel_height = height; + + info_ptr->valid |= PNG_INFO_sCAL; +} +#else +#ifdef PNG_FIXED_POINT_SUPPORTED +void PNGAPI +png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr, + int unit, png_charp swidth, png_charp sheight) +{ + png_uint_32 length; + + png_debug1(1, "in %s storage function\n", "sCAL"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + info_ptr->scal_unit = (png_byte)unit; + + length = png_strlen(swidth) + 1; + png_debug1(3, "allocating unit for info (%d bytes)\n", length); + info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length); + if (info_ptr->scal_s_width == NULL) + { + png_warning(png_ptr, "Memory allocation failed while processing sCAL."); + } + png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length); + + length = png_strlen(sheight) + 1; + png_debug1(3, "allocating unit for info (%d bytes)\n", length); + info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length); + if (info_ptr->scal_s_height == NULL) + { + png_free (png_ptr, info_ptr->scal_s_width); + png_warning(png_ptr, "Memory allocation failed while processing sCAL."); + } + png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length); + + info_ptr->valid |= PNG_INFO_sCAL; +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_SCAL; +#endif +} +#endif +#endif +#endif + +#if defined(PNG_pHYs_SUPPORTED) +void PNGAPI +png_set_pHYs(png_structp png_ptr, png_infop info_ptr, + png_uint_32 res_x, png_uint_32 res_y, int unit_type) +{ + png_debug1(1, "in %s storage function\n", "pHYs"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + info_ptr->x_pixels_per_unit = res_x; + info_ptr->y_pixels_per_unit = res_y; + info_ptr->phys_unit_type = (png_byte)unit_type; + info_ptr->valid |= PNG_INFO_pHYs; +} +#endif + +void PNGAPI +png_set_PLTE(png_structp png_ptr, png_infop info_ptr, + png_colorp palette, int num_palette) +{ + + png_debug1(1, "in %s storage function\n", "PLTE"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + /* + * It may not actually be necessary to set png_ptr->palette here; + * we do it for backward compatibility with the way the png_handle_tRNS + * function used to do the allocation. + */ +#ifdef PNG_FREE_ME_SUPPORTED + png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); +#endif + + /* Changed in libpng-1.2.1 to allocate 256 instead of num_palette entries, + in case of an invalid PNG file that has too-large sample values. */ + png_ptr->palette = (png_colorp)png_malloc(png_ptr, + 256 * png_sizeof(png_color)); + png_memset(png_ptr->palette, 0, 256 * png_sizeof(png_color)); + png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color)); + info_ptr->palette = png_ptr->palette; + info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; + +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_PLTE; +#else + png_ptr->flags |= PNG_FLAG_FREE_PLTE; +#endif + + info_ptr->valid |= PNG_INFO_PLTE; +} + +#if defined(PNG_sBIT_SUPPORTED) +void PNGAPI +png_set_sBIT(png_structp png_ptr, png_infop info_ptr, + png_color_8p sig_bit) +{ + png_debug1(1, "in %s storage function\n", "sBIT"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8)); + info_ptr->valid |= PNG_INFO_sBIT; +} +#endif + +#if defined(PNG_sRGB_SUPPORTED) +void PNGAPI +png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent) +{ + png_debug1(1, "in %s storage function\n", "sRGB"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + info_ptr->srgb_intent = (png_byte)intent; + info_ptr->valid |= PNG_INFO_sRGB; +} + +void PNGAPI +png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr, + int intent) +{ +#if defined(PNG_gAMA_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED + float file_gamma; +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED + png_fixed_point int_file_gamma; +#endif +#endif +#if defined(PNG_cHRM_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED + float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y; +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED + png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, + int_green_y, int_blue_x, int_blue_y; +#endif +#endif + png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + png_set_sRGB(png_ptr, info_ptr, intent); + +#if defined(PNG_gAMA_SUPPORTED) +#ifdef PNG_FLOATING_POINT_SUPPORTED + file_gamma = (float).45455; + png_set_gAMA(png_ptr, info_ptr, file_gamma); +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED + int_file_gamma = 45455L; + png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma); +#endif +#endif + +#if defined(PNG_cHRM_SUPPORTED) +#ifdef PNG_FIXED_POINT_SUPPORTED + int_white_x = 31270L; + int_white_y = 32900L; + int_red_x = 64000L; + int_red_y = 33000L; + int_green_x = 30000L; + int_green_y = 60000L; + int_blue_x = 15000L; + int_blue_y = 6000L; + + png_set_cHRM_fixed(png_ptr, info_ptr, + int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y, + int_blue_x, int_blue_y); +#endif +#ifdef PNG_FLOATING_POINT_SUPPORTED + white_x = (float).3127; + white_y = (float).3290; + red_x = (float).64; + red_y = (float).33; + green_x = (float).30; + green_y = (float).60; + blue_x = (float).15; + blue_y = (float).06; + + png_set_cHRM(png_ptr, info_ptr, + white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y); +#endif +#endif +} +#endif + + +#if defined(PNG_iCCP_SUPPORTED) +void PNGAPI +png_set_iCCP(png_structp png_ptr, png_infop info_ptr, + png_charp name, int compression_type, + png_charp profile, png_uint_32 proflen) +{ + png_charp new_iccp_name; + png_charp new_iccp_profile; + + png_debug1(1, "in %s storage function\n", "iCCP"); + if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL) + return; + + new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1); + if (new_iccp_name == NULL) + { + png_warning(png_ptr, "Insufficient memory to process iCCP chunk."); + return; + } + png_strcpy(new_iccp_name, name); + new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen); + if (new_iccp_profile == NULL) + { + png_free (png_ptr, new_iccp_name); + png_warning(png_ptr, "Insufficient memory to process iCCP profile."); + return; + } + png_memcpy(new_iccp_profile, profile, (png_size_t)proflen); + + png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0); + + info_ptr->iccp_proflen = proflen; + info_ptr->iccp_name = new_iccp_name; + info_ptr->iccp_profile = new_iccp_profile; + /* Compression is always zero but is here so the API and info structure + * does not have to change if we introduce multiple compression types */ + info_ptr->iccp_compression = (png_byte)compression_type; +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_ICCP; +#endif + info_ptr->valid |= PNG_INFO_iCCP; +} +#endif + +#if defined(PNG_TEXT_SUPPORTED) +void PNGAPI +png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr, + int num_text) +{ + int ret; + ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text); + if (ret) + png_error(png_ptr, "Insufficient memory to store text"); +} + +int /* PRIVATE */ +png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr, + int num_text) +{ + int i; + + png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ? + "text" : (png_const_charp)png_ptr->chunk_name)); + + if (png_ptr == NULL || info_ptr == NULL || num_text == 0) + return(0); + + /* Make sure we have enough space in the "text" array in info_struct + * to hold all of the incoming text_ptr objects. + */ + if (info_ptr->num_text + num_text > info_ptr->max_text) + { + if (info_ptr->text != NULL) + { + png_textp old_text; + int old_max; + + old_max = info_ptr->max_text; + info_ptr->max_text = info_ptr->num_text + num_text + 8; + old_text = info_ptr->text; + info_ptr->text = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)(info_ptr->max_text * png_sizeof (png_text))); + if (info_ptr->text == NULL) + { + png_free(png_ptr, old_text); + return(1); + } + png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max * + png_sizeof(png_text))); + png_free(png_ptr, old_text); + } + else + { + info_ptr->max_text = num_text + 8; + info_ptr->num_text = 0; + info_ptr->text = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)(info_ptr->max_text * png_sizeof (png_text))); + if (info_ptr->text == NULL) + return(1); +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_TEXT; +#endif + } + png_debug1(3, "allocated %d entries for info_ptr->text\n", + info_ptr->max_text); + } + for (i = 0; i < num_text; i++) + { + png_size_t text_length,key_len; + png_size_t lang_len,lang_key_len; + png_textp textp = &(info_ptr->text[info_ptr->num_text]); + + if (text_ptr[i].key == NULL) + continue; + + key_len = png_strlen(text_ptr[i].key); + + if(text_ptr[i].compression <= 0) + { + lang_len = 0; + lang_key_len = 0; + } + else +#ifdef PNG_iTXt_SUPPORTED + { + /* set iTXt data */ + if (text_ptr[i].lang != NULL) + lang_len = png_strlen(text_ptr[i].lang); + else + lang_len = 0; + if (text_ptr[i].lang_key != NULL) + lang_key_len = png_strlen(text_ptr[i].lang_key); + else + lang_key_len = 0; + } +#else + { + png_warning(png_ptr, "iTXt chunk not supported."); + continue; + } +#endif + + if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0') + { + text_length = 0; +#ifdef PNG_iTXt_SUPPORTED + if(text_ptr[i].compression > 0) + textp->compression = PNG_ITXT_COMPRESSION_NONE; + else +#endif + textp->compression = PNG_TEXT_COMPRESSION_NONE; + } + else + { + text_length = png_strlen(text_ptr[i].text); + textp->compression = text_ptr[i].compression; + } + + textp->key = (png_charp)png_malloc_warn(png_ptr, + (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4)); + if (textp->key == NULL) + return(1); + png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n", + (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4), + (int)textp->key); + + png_memcpy(textp->key, text_ptr[i].key, + (png_size_t)(key_len)); + *(textp->key+key_len) = '\0'; +#ifdef PNG_iTXt_SUPPORTED + if (text_ptr[i].compression > 0) + { + textp->lang=textp->key + key_len + 1; + png_memcpy(textp->lang, text_ptr[i].lang, lang_len); + *(textp->lang+lang_len) = '\0'; + textp->lang_key=textp->lang + lang_len + 1; + png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len); + *(textp->lang_key+lang_key_len) = '\0'; + textp->text=textp->lang_key + lang_key_len + 1; + } + else +#endif + { +#ifdef PNG_iTXt_SUPPORTED + textp->lang=NULL; + textp->lang_key=NULL; +#endif + textp->text=textp->key + key_len + 1; + } + if(text_length) + png_memcpy(textp->text, text_ptr[i].text, + (png_size_t)(text_length)); + *(textp->text+text_length) = '\0'; + +#ifdef PNG_iTXt_SUPPORTED + if(textp->compression > 0) + { + textp->text_length = 0; + textp->itxt_length = text_length; + } + else +#endif + { + textp->text_length = text_length; +#ifdef PNG_iTXt_SUPPORTED + textp->itxt_length = 0; +#endif + } + info_ptr->text[info_ptr->num_text]= *textp; + info_ptr->num_text++; + png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text); + } + return(0); +} +#endif + +#if defined(PNG_tIME_SUPPORTED) +void PNGAPI +png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time) +{ + png_debug1(1, "in %s storage function\n", "tIME"); + if (png_ptr == NULL || info_ptr == NULL || + (png_ptr->mode & PNG_WROTE_tIME)) + return; + + png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time)); + info_ptr->valid |= PNG_INFO_tIME; +} +#endif + +#if defined(PNG_tRNS_SUPPORTED) +void PNGAPI +png_set_tRNS(png_structp png_ptr, png_infop info_ptr, + png_bytep trans, int num_trans, png_color_16p trans_values) +{ + png_debug1(1, "in %s storage function\n", "tRNS"); + if (png_ptr == NULL || info_ptr == NULL) + return; + + if (trans != NULL) + { + /* + * It may not actually be necessary to set png_ptr->trans here; + * we do it for backward compatibility with the way the png_handle_tRNS + * function used to do the allocation. + */ +#ifdef PNG_FREE_ME_SUPPORTED + png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0); +#endif + /* Changed from num_trans to 256 in version 1.2.1 */ + png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr, + (png_uint_32)256); + png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans); +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_TRNS; +#else + png_ptr->flags |= PNG_FLAG_FREE_TRNS; +#endif + } + + if (trans_values != NULL) + { + png_memcpy(&(info_ptr->trans_values), trans_values, + png_sizeof(png_color_16)); + if (num_trans == 0) + num_trans = 1; + } + info_ptr->num_trans = (png_uint_16)num_trans; + info_ptr->valid |= PNG_INFO_tRNS; +} +#endif + +#if defined(PNG_sPLT_SUPPORTED) +void PNGAPI +png_set_sPLT(png_structp png_ptr, + png_infop info_ptr, png_sPLT_tp entries, int nentries) +{ + png_sPLT_tp np; + int i; + + np = (png_sPLT_tp)png_malloc_warn(png_ptr, + (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t)); + if (np == NULL) + { + png_warning(png_ptr, "No memory for sPLT palettes."); + return; + } + + png_memcpy(np, info_ptr->splt_palettes, + info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t)); + png_free(png_ptr, info_ptr->splt_palettes); + info_ptr->splt_palettes=NULL; + + for (i = 0; i < nentries; i++) + { + png_sPLT_tp to = np + info_ptr->splt_palettes_num + i; + png_sPLT_tp from = entries + i; + + to->name = (png_charp)png_malloc(png_ptr, + png_strlen(from->name) + 1); + /* TODO: use png_malloc_warn */ + png_strcpy(to->name, from->name); + to->entries = (png_sPLT_entryp)png_malloc(png_ptr, + from->nentries * png_sizeof(png_sPLT_t)); + /* TODO: use png_malloc_warn */ + png_memcpy(to->entries, from->entries, + from->nentries * png_sizeof(png_sPLT_t)); + to->nentries = from->nentries; + to->depth = from->depth; + } + + info_ptr->splt_palettes = np; + info_ptr->splt_palettes_num += nentries; + info_ptr->valid |= PNG_INFO_sPLT; +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_SPLT; +#endif +} +#endif /* PNG_sPLT_SUPPORTED */ + +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) +void PNGAPI +png_set_unknown_chunks(png_structp png_ptr, + png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns) +{ + png_unknown_chunkp np; + int i; + + if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0) + return; + + np = (png_unknown_chunkp)png_malloc_warn(png_ptr, + (info_ptr->unknown_chunks_num + num_unknowns) * + png_sizeof(png_unknown_chunk)); + if (np == NULL) + { + png_warning(png_ptr, "Out of memory while processing unknown chunk."); + return; + } + + png_memcpy(np, info_ptr->unknown_chunks, + info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk)); + png_free(png_ptr, info_ptr->unknown_chunks); + info_ptr->unknown_chunks=NULL; + + for (i = 0; i < num_unknowns; i++) + { + png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i; + png_unknown_chunkp from = unknowns + i; + + png_strncpy((png_charp)to->name, (png_charp)from->name, 5); + to->data = (png_bytep)png_malloc_warn(png_ptr, from->size); + if (to->data == NULL) + { + png_warning(png_ptr, "Out of memory processing unknown chunk."); + } + else + { + png_memcpy(to->data, from->data, from->size); + to->size = from->size; + + /* note our location in the read or write sequence */ + to->location = (png_byte)(png_ptr->mode & 0xff); + } + } + + info_ptr->unknown_chunks = np; + info_ptr->unknown_chunks_num += num_unknowns; +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_UNKN; +#endif +} +void PNGAPI +png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr, + int chunk, int location) +{ + if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk < + (int)info_ptr->unknown_chunks_num) + info_ptr->unknown_chunks[chunk].location = (png_byte)location; +} +#endif + +#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) +void PNGAPI +png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted) +{ + /* This function is deprecated in favor of png_permit_mng_features() + and will be removed from libpng-2.0.0 */ + png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n"); + if (png_ptr == NULL) + return; + png_ptr->mng_features_permitted = (png_byte) + ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) | + ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE))); +} +#endif + +#if defined(PNG_MNG_FEATURES_SUPPORTED) +png_uint_32 PNGAPI +png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features) +{ + png_debug(1, "in png_permit_mng_features\n"); + if (png_ptr == NULL) + return (png_uint_32)0; + png_ptr->mng_features_permitted = + (png_byte)(mng_features & PNG_ALL_MNG_FEATURES); + return (png_uint_32)png_ptr->mng_features_permitted; +} +#endif + +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) +void PNGAPI +png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep + chunk_list, int num_chunks) +{ + png_bytep new_list, p; + int i, old_num_chunks; + if (num_chunks == 0) + { + if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE) + png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS; + else + png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS; + + if(keep == PNG_HANDLE_CHUNK_ALWAYS) + png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS; + else + png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS; + return; + } + if (chunk_list == NULL) + return; + old_num_chunks=png_ptr->num_chunk_list; + new_list=(png_bytep)png_malloc(png_ptr, + (png_uint_32)(5*(num_chunks+old_num_chunks))); + if(png_ptr->chunk_list != NULL) + { + png_memcpy(new_list, png_ptr->chunk_list, + (png_size_t)(5*old_num_chunks)); + png_free(png_ptr, png_ptr->chunk_list); + png_ptr->chunk_list=NULL; + } + png_memcpy(new_list+5*old_num_chunks, chunk_list, + (png_size_t)(5*num_chunks)); + for (p=new_list+5*old_num_chunks+4, i=0; inum_chunk_list=old_num_chunks+num_chunks; + png_ptr->chunk_list=new_list; +#ifdef PNG_FREE_ME_SUPPORTED + png_ptr->free_me |= PNG_FREE_LIST; +#endif +} +#endif + +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED) +void PNGAPI +png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr, + png_user_chunk_ptr read_user_chunk_fn) +{ + png_debug(1, "in png_set_read_user_chunk_fn\n"); + png_ptr->read_user_chunk_fn = read_user_chunk_fn; + png_ptr->user_chunk_ptr = user_chunk_ptr; +} +#endif + +#if defined(PNG_INFO_IMAGE_SUPPORTED) +void PNGAPI +png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers) +{ + png_debug1(1, "in %s storage function\n", "rows"); + + if (png_ptr == NULL || info_ptr == NULL) + return; + + if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers)) + png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0); + info_ptr->row_pointers = row_pointers; + if(row_pointers) + info_ptr->valid |= PNG_INFO_IDAT; +} +#endif + +#ifdef PNG_WRITE_SUPPORTED +void PNGAPI +png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size) +{ + if(png_ptr->zbuf) + png_free(png_ptr, png_ptr->zbuf); + png_ptr->zbuf_size = (png_size_t)size; + png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size); + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; +} +#endif + +void PNGAPI +png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask) +{ + if (png_ptr && info_ptr) + info_ptr->valid &= ~(mask); +} + + +#ifndef PNG_1_0_X +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED +/* this function was added to libpng 1.2.0 and should always exist by default */ +void PNGAPI +png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags) +{ + png_uint_32 settable_asm_flags; + png_uint_32 settable_mmx_flags; + + settable_mmx_flags = +#ifdef PNG_HAVE_ASSEMBLER_COMBINE_ROW + PNG_ASM_FLAG_MMX_READ_COMBINE_ROW | +#endif +#ifdef PNG_HAVE_ASSEMBLER_READ_INTERLACE + PNG_ASM_FLAG_MMX_READ_INTERLACE | +#endif +#ifdef PNG_HAVE_ASSEMBLER_READ_FILTER_ROW + PNG_ASM_FLAG_MMX_READ_FILTER_SUB | + PNG_ASM_FLAG_MMX_READ_FILTER_UP | + PNG_ASM_FLAG_MMX_READ_FILTER_AVG | + PNG_ASM_FLAG_MMX_READ_FILTER_PAETH | +#endif + 0; + + /* could be some non-MMX ones in the future, but not currently: */ + settable_asm_flags = settable_mmx_flags; + + if (!(png_ptr->asm_flags & PNG_ASM_FLAG_MMX_SUPPORT_COMPILED) || + !(png_ptr->asm_flags & PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU)) + { + /* clear all MMX flags if MMX isn't supported */ + settable_asm_flags &= ~settable_mmx_flags; + png_ptr->asm_flags &= ~settable_mmx_flags; + } + + /* we're replacing the settable bits with those passed in by the user, + * so first zero them out of the master copy, then logical-OR in the + * allowed subset that was requested */ + + png_ptr->asm_flags &= ~settable_asm_flags; /* zero them */ + png_ptr->asm_flags |= (asm_flags & settable_asm_flags); /* set them */ +} +#endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */ + +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED +/* this function was added to libpng 1.2.0 */ +void PNGAPI +png_set_mmx_thresholds (png_structp png_ptr, + png_byte mmx_bitdepth_threshold, + png_uint_32 mmx_rowbytes_threshold) +{ + png_ptr->mmx_bitdepth_threshold = mmx_bitdepth_threshold; + png_ptr->mmx_rowbytes_threshold = mmx_rowbytes_threshold; +} +#endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */ + +#ifdef PNG_SET_USER_LIMITS_SUPPORTED +/* this function was added to libpng 1.2.6 */ +void PNGAPI +png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max, + png_uint_32 user_height_max) +{ + /* Images with dimensions larger than these limits will be + * rejected by png_set_IHDR(). To accept any PNG datastream + * regardless of dimensions, set both limits to 0x7ffffffL. + */ + png_ptr->user_width_max = user_width_max; + png_ptr->user_height_max = user_height_max; +} +#endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */ + +#endif /* ?PNG_1_0_X */ diff --git a/SlnkDWFImpl/CxImage/png/pngtrans.c b/SlnkDWFImpl/CxImage/png/pngtrans.c new file mode 100644 index 0000000..05324ec --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngtrans.c @@ -0,0 +1,644 @@ + +/* pngtrans.c - transforms the data in a row (used by both readers and writers) + * + * libpng 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + */ + +#define PNG_INTERNAL +#include "png.h" + +#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) +/* turn on BGR-to-RGB mapping */ +void PNGAPI +png_set_bgr(png_structp png_ptr) +{ + png_debug(1, "in png_set_bgr\n"); + png_ptr->transformations |= PNG_BGR; +} +#endif + +#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) +/* turn on 16 bit byte swapping */ +void PNGAPI +png_set_swap(png_structp png_ptr) +{ + png_debug(1, "in png_set_swap\n"); + if (png_ptr->bit_depth == 16) + png_ptr->transformations |= PNG_SWAP_BYTES; +} +#endif + +#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) +/* turn on pixel packing */ +void PNGAPI +png_set_packing(png_structp png_ptr) +{ + png_debug(1, "in png_set_packing\n"); + if (png_ptr->bit_depth < 8) + { + png_ptr->transformations |= PNG_PACK; + png_ptr->usr_bit_depth = 8; + } +} +#endif + +#if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED) +/* turn on packed pixel swapping */ +void PNGAPI +png_set_packswap(png_structp png_ptr) +{ + png_debug(1, "in png_set_packswap\n"); + if (png_ptr->bit_depth < 8) + png_ptr->transformations |= PNG_PACKSWAP; +} +#endif + +#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED) +void PNGAPI +png_set_shift(png_structp png_ptr, png_color_8p true_bits) +{ + png_debug(1, "in png_set_shift\n"); + png_ptr->transformations |= PNG_SHIFT; + png_ptr->shift = *true_bits; +} +#endif + +#if defined(PNG_READ_INTERLACING_SUPPORTED) || \ + defined(PNG_WRITE_INTERLACING_SUPPORTED) +int PNGAPI +png_set_interlace_handling(png_structp png_ptr) +{ + png_debug(1, "in png_set_interlace handling\n"); + if (png_ptr->interlaced) + { + png_ptr->transformations |= PNG_INTERLACE; + return (7); + } + + return (1); +} +#endif + +#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED) +/* Add a filler byte on read, or remove a filler or alpha byte on write. + * The filler type has changed in v0.95 to allow future 2-byte fillers + * for 48-bit input data, as well as to avoid problems with some compilers + * that don't like bytes as parameters. + */ +void PNGAPI +png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc) +{ + png_debug(1, "in png_set_filler\n"); + png_ptr->transformations |= PNG_FILLER; + png_ptr->filler = (png_byte)filler; + if (filler_loc == PNG_FILLER_AFTER) + png_ptr->flags |= PNG_FLAG_FILLER_AFTER; + else + png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER; + + /* This should probably go in the "do_read_filler" routine. + * I attempted to do that in libpng-1.0.1a but that caused problems + * so I restored it in libpng-1.0.2a + */ + + if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) + { + png_ptr->usr_channels = 4; + } + + /* Also I added this in libpng-1.0.2a (what happens when we expand + * a less-than-8-bit grayscale to GA? */ + + if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8) + { + png_ptr->usr_channels = 2; + } +} + +#if !defined(PNG_1_0_X) +/* Added to libpng-1.2.7 */ +void PNGAPI +png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc) +{ + png_debug(1, "in png_set_add_alpha\n"); + png_set_filler(png_ptr, filler, filler_loc); + png_ptr->transformations |= PNG_ADD_ALPHA; +} +#endif + +#endif + +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \ + defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) +void PNGAPI +png_set_swap_alpha(png_structp png_ptr) +{ + png_debug(1, "in png_set_swap_alpha\n"); + png_ptr->transformations |= PNG_SWAP_ALPHA; +} +#endif + +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \ + defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) +void PNGAPI +png_set_invert_alpha(png_structp png_ptr) +{ + png_debug(1, "in png_set_invert_alpha\n"); + png_ptr->transformations |= PNG_INVERT_ALPHA; +} +#endif + +#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED) +void PNGAPI +png_set_invert_mono(png_structp png_ptr) +{ + png_debug(1, "in png_set_invert_mono\n"); + png_ptr->transformations |= PNG_INVERT_MONO; +} + +/* invert monochrome grayscale data */ +void /* PRIVATE */ +png_do_invert(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_invert\n"); + /* This test removed from libpng version 1.0.13 and 1.2.0: + * if (row_info->bit_depth == 1 && + */ +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row == NULL || row_info == NULL) + return; +#endif + if (row_info->color_type == PNG_COLOR_TYPE_GRAY) + { + png_bytep rp = row; + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(~(*rp)); + rp++; + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA && + row_info->bit_depth == 8) + { + png_bytep rp = row; + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + + for (i = 0; i < istop; i+=2) + { + *rp = (png_byte)(~(*rp)); + rp+=2; + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA && + row_info->bit_depth == 16) + { + png_bytep rp = row; + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + + for (i = 0; i < istop; i+=4) + { + *rp = (png_byte)(~(*rp)); + *(rp+1) = (png_byte)(~(*(rp+1))); + rp+=4; + } + } +} +#endif + +#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) +/* swaps byte order on 16 bit depth images */ +void /* PRIVATE */ +png_do_swap(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_swap\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + row_info->bit_depth == 16) + { + png_bytep rp = row; + png_uint_32 i; + png_uint_32 istop= row_info->width * row_info->channels; + + for (i = 0; i < istop; i++, rp += 2) + { + png_byte t = *rp; + *rp = *(rp + 1); + *(rp + 1) = t; + } + } +} +#endif + +#if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED) +static png_byte onebppswaptable[256] = { + 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, + 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, + 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, + 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, + 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, + 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, + 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, + 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, + 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, + 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, + 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, + 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, + 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, + 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, + 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, + 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, + 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, + 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, + 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, + 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, + 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, + 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, + 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, + 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, + 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, + 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, + 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, + 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, + 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, + 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, + 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, + 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF +}; + +static png_byte twobppswaptable[256] = { + 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0, + 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0, + 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4, + 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4, + 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8, + 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8, + 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC, + 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC, + 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1, + 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1, + 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5, + 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5, + 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9, + 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9, + 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD, + 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD, + 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2, + 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2, + 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6, + 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6, + 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA, + 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA, + 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE, + 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE, + 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3, + 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3, + 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7, + 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7, + 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB, + 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB, + 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF, + 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF +}; + +static png_byte fourbppswaptable[256] = { + 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, + 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, + 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71, + 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1, + 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, + 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2, + 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73, + 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3, + 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74, + 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4, + 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75, + 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5, + 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76, + 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6, + 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77, + 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7, + 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78, + 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8, + 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79, + 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9, + 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A, + 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA, + 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B, + 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB, + 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C, + 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC, + 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D, + 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD, + 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E, + 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE, + 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F, + 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF +}; + +/* swaps pixel packing order within bytes */ +void /* PRIVATE */ +png_do_packswap(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_packswap\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + row_info->bit_depth < 8) + { + png_bytep rp, end, table; + + end = row + row_info->rowbytes; + + if (row_info->bit_depth == 1) + table = onebppswaptable; + else if (row_info->bit_depth == 2) + table = twobppswaptable; + else if (row_info->bit_depth == 4) + table = fourbppswaptable; + else + return; + + for (rp = row; rp < end; rp++) + *rp = table[*rp]; + } +} +#endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */ + +#if defined(PNG_WRITE_FILLER_SUPPORTED) || \ + defined(PNG_READ_STRIP_ALPHA_SUPPORTED) +/* remove filler or alpha byte(s) */ +void /* PRIVATE */ +png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags) +{ + png_debug(1, "in png_do_strip_filler\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL) +#endif + { + png_bytep sp=row; + png_bytep dp=row; + png_uint_32 row_width=row_info->width; + png_uint_32 i; + + if (row_info->color_type == PNG_COLOR_TYPE_RGB && + row_info->channels == 4) + { + if (row_info->bit_depth == 8) + { + /* This converts from RGBX or RGBA to RGB */ + if (flags & PNG_FLAG_FILLER_AFTER) + { + dp+=3; sp+=4; + for (i = 1; i < row_width; i++) + { + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + sp++; + } + } + /* This converts from XRGB or ARGB to RGB */ + else + { + for (i = 0; i < row_width; i++) + { + sp++; + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + } + } + row_info->pixel_depth = 24; + row_info->rowbytes = row_width * 3; + } + else /* if (row_info->bit_depth == 16) */ + { + if (flags & PNG_FLAG_FILLER_AFTER) + { + /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */ + sp += 8; dp += 6; + for (i = 1; i < row_width; i++) + { + /* This could be (although png_memcpy is probably slower): + png_memcpy(dp, sp, 6); + sp += 8; + dp += 6; + */ + + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + sp += 2; + } + } + else + { + /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */ + for (i = 0; i < row_width; i++) + { + /* This could be (although png_memcpy is probably slower): + png_memcpy(dp, sp, 6); + sp += 8; + dp += 6; + */ + + sp+=2; + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + *dp++ = *sp++; + } + } + row_info->pixel_depth = 48; + row_info->rowbytes = row_width * 6; + } + row_info->channels = 3; + } + else if (row_info->color_type == PNG_COLOR_TYPE_GRAY && + row_info->channels == 2) + { + if (row_info->bit_depth == 8) + { + /* This converts from GX or GA to G */ + if (flags & PNG_FLAG_FILLER_AFTER) + { + for (i = 0; i < row_width; i++) + { + *dp++ = *sp++; + sp++; + } + } + /* This converts from XG or AG to G */ + else + { + for (i = 0; i < row_width; i++) + { + sp++; + *dp++ = *sp++; + } + } + row_info->pixel_depth = 8; + row_info->rowbytes = row_width; + } + else /* if (row_info->bit_depth == 16) */ + { + if (flags & PNG_FLAG_FILLER_AFTER) + { + /* This converts from GGXX or GGAA to GG */ + sp += 4; dp += 2; + for (i = 1; i < row_width; i++) + { + *dp++ = *sp++; + *dp++ = *sp++; + sp += 2; + } + } + else + { + /* This converts from XXGG or AAGG to GG */ + for (i = 0; i < row_width; i++) + { + sp += 2; + *dp++ = *sp++; + *dp++ = *sp++; + } + } + row_info->pixel_depth = 16; + row_info->rowbytes = row_width * 2; + } + row_info->channels = 1; + } + } +} +#endif + +#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) +/* swaps red and blue bytes within a pixel */ +void /* PRIVATE */ +png_do_bgr(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_bgr\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + (row_info->color_type & PNG_COLOR_MASK_COLOR)) + { + png_uint_32 row_width = row_info->width; + if (row_info->bit_depth == 8) + { + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + { + png_bytep rp; + png_uint_32 i; + + for (i = 0, rp = row; i < row_width; i++, rp += 3) + { + png_byte save = *rp; + *rp = *(rp + 2); + *(rp + 2) = save; + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + { + png_bytep rp; + png_uint_32 i; + + for (i = 0, rp = row; i < row_width; i++, rp += 4) + { + png_byte save = *rp; + *rp = *(rp + 2); + *(rp + 2) = save; + } + } + } + else if (row_info->bit_depth == 16) + { + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + { + png_bytep rp; + png_uint_32 i; + + for (i = 0, rp = row; i < row_width; i++, rp += 6) + { + png_byte save = *rp; + *rp = *(rp + 4); + *(rp + 4) = save; + save = *(rp + 1); + *(rp + 1) = *(rp + 5); + *(rp + 5) = save; + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + { + png_bytep rp; + png_uint_32 i; + + for (i = 0, rp = row; i < row_width; i++, rp += 8) + { + png_byte save = *rp; + *rp = *(rp + 4); + *(rp + 4) = save; + save = *(rp + 1); + *(rp + 1) = *(rp + 5); + *(rp + 5) = save; + } + } + } + } +} +#endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */ + +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \ + defined(PNG_LEGACY_SUPPORTED) +void PNGAPI +png_set_user_transform_info(png_structp png_ptr, png_voidp + user_transform_ptr, int user_transform_depth, int user_transform_channels) +{ + png_debug(1, "in png_set_user_transform_info\n"); +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) + png_ptr->user_transform_ptr = user_transform_ptr; + png_ptr->user_transform_depth = (png_byte)user_transform_depth; + png_ptr->user_transform_channels = (png_byte)user_transform_channels; +#else + if(user_transform_ptr || user_transform_depth || user_transform_channels) + png_warning(png_ptr, + "This version of libpng does not support user transform info"); +#endif +} +#endif + +/* This function returns a pointer to the user_transform_ptr associated with + * the user transform functions. The application should free any memory + * associated with this pointer before png_write_destroy and png_read_destroy + * are called. + */ +png_voidp PNGAPI +png_get_user_transform_ptr(png_structp png_ptr) +{ +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) + return ((png_voidp)png_ptr->user_transform_ptr); +#else + if(png_ptr) + return (NULL); + return (NULL); +#endif +} diff --git a/SlnkDWFImpl/CxImage/png/pngvcrd.c b/SlnkDWFImpl/CxImage/png/pngvcrd.c new file mode 100644 index 0000000..6e6e735 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngvcrd.c @@ -0,0 +1,3903 @@ +/* pngvcrd.c - mixed C/assembler version of utilities to read a PNG file + * + * For Intel x86 CPU and Microsoft Visual C++ compiler + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * Copyright (c) 1998, Intel Corporation + * + * Contributed by Nirav Chhatrapati, Intel Corporation, 1998 + * Interface to libpng contributed by Gilles Vollant, 1999 + * + * + * In png_do_read_interlace() in libpng versions 1.0.3a through 1.0.4d, + * a sign error in the post-MMX cleanup code for each pixel_depth resulted + * in bad pixels at the beginning of some rows of some images, and also + * (due to out-of-range memory reads and writes) caused heap corruption + * when compiled with MSVC 6.0. The error was fixed in version 1.0.4e. + * + * [png_read_filter_row_mmx_avg() bpp == 2 bugfix, GRR 20000916] + * + * [runtime MMX configuration, GRR 20010102] + * + */ + +#define PNG_INTERNAL +#include "png.h" + +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && defined(PNG_USE_PNGVCRD) + +static int mmx_supported=2; + + +int PNGAPI +png_mmx_support(void) +{ + int mmx_supported_local = 0; + _asm { + push ebx //CPUID will trash these + push ecx + push edx + + pushfd //Save Eflag to stack + pop eax //Get Eflag from stack into eax + mov ecx, eax //Make another copy of Eflag in ecx + xor eax, 0x200000 //Toggle ID bit in Eflag [i.e. bit(21)] + push eax //Save modified Eflag back to stack + + popfd //Restored modified value back to Eflag reg + pushfd //Save Eflag to stack + pop eax //Get Eflag from stack + push ecx // save original Eflag to stack + popfd // restore original Eflag + xor eax, ecx //Compare the new Eflag with the original Eflag + jz NOT_SUPPORTED //If the same, CPUID instruction is not supported, + //skip following instructions and jump to + //NOT_SUPPORTED label + + xor eax, eax //Set eax to zero + + _asm _emit 0x0f //CPUID instruction (two bytes opcode) + _asm _emit 0xa2 + + cmp eax, 1 //make sure eax return non-zero value + jl NOT_SUPPORTED //If eax is zero, mmx not supported + + xor eax, eax //set eax to zero + inc eax //Now increment eax to 1. This instruction is + //faster than the instruction "mov eax, 1" + + _asm _emit 0x0f //CPUID instruction + _asm _emit 0xa2 + + and edx, 0x00800000 //mask out all bits but mmx bit(24) + cmp edx, 0 // 0 = mmx not supported + jz NOT_SUPPORTED // non-zero = Yes, mmx IS supported + + mov mmx_supported_local, 1 //set return value to 1 + +NOT_SUPPORTED: + mov eax, mmx_supported_local //move return value to eax + pop edx //CPUID trashed these + pop ecx + pop ebx + } + + //mmx_supported_local=0; // test code for force don't support MMX + //printf("MMX : %u (1=MMX supported)\n",mmx_supported_local); + + mmx_supported = mmx_supported_local; + return mmx_supported_local; +} + +/* Combines the row recently read in with the previous row. + This routine takes care of alpha and transparency if requested. + This routine also handles the two methods of progressive display + of interlaced images, depending on the mask value. + The mask value describes which pixels are to be combined with + the row. The pattern always repeats every 8 pixels, so just 8 + bits are needed. A one indicates the pixel is to be combined; a + zero indicates the pixel is to be skipped. This is in addition + to any alpha or transparency value associated with the pixel. If + you want all pixels to be combined, pass 0xff (255) in mask. */ + +/* Use this routine for x86 platform - uses faster MMX routine if machine + supports MMX */ + +void /* PRIVATE */ +png_combine_row(png_structp png_ptr, png_bytep row, int mask) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + const int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; +#endif + + png_debug(1,"in png_combine_row_asm\n"); + + if (mmx_supported == 2) { +#if !defined(PNG_1_0_X) + /* this should have happened in png_init_mmx_flags() already */ + png_warning(png_ptr, "asm_flags may not have been initialized"); +#endif + png_mmx_support(); + } + + if (mask == 0xff) + { + png_memcpy(row, png_ptr->row_buf + 1, + (png_size_t)PNG_ROWBYTES(png_ptr->row_info.pixel_depth, + png_ptr->width)); + } + /* GRR: add "else if (mask == 0)" case? + * or does png_combine_row() not even get called in that case? */ + else + { + switch (png_ptr->row_info.pixel_depth) + { + case 1: + { + png_bytep sp; + png_bytep dp; + int s_inc, s_start, s_end; + int m; + int shift; + png_uint_32 i; + + sp = png_ptr->row_buf + 1; + dp = row; + m = 0x80; +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 7; + s_inc = 1; + } + else +#endif + { + s_start = 7; + s_end = 0; + s_inc = -1; + } + + shift = s_start; + + for (i = 0; i < png_ptr->width; i++) + { + if (m & mask) + { + int value; + + value = (*sp >> shift) & 0x1; + *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + + case 2: + { + png_bytep sp; + png_bytep dp; + int s_start, s_end, s_inc; + int m; + int shift; + png_uint_32 i; + int value; + + sp = png_ptr->row_buf + 1; + dp = row; + m = 0x80; +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 6; + s_inc = 2; + } + else +#endif + { + s_start = 6; + s_end = 0; + s_inc = -2; + } + + shift = s_start; + + for (i = 0; i < png_ptr->width; i++) + { + if (m & mask) + { + value = (*sp >> shift) & 0x3; + *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + + case 4: + { + png_bytep sp; + png_bytep dp; + int s_start, s_end, s_inc; + int m; + int shift; + png_uint_32 i; + int value; + + sp = png_ptr->row_buf + 1; + dp = row; + m = 0x80; +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + { + s_start = 0; + s_end = 4; + s_inc = 4; + } + else +#endif + { + s_start = 4; + s_end = 0; + s_inc = -4; + } + shift = s_start; + + for (i = 0; i < png_ptr->width; i++) + { + if (m & mask) + { + value = (*sp >> shift) & 0xf; + *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); + *dp |= (png_byte)(value << shift); + } + + if (shift == s_end) + { + shift = s_start; + sp++; + dp++; + } + else + shift += s_inc; + if (m == 1) + m = 0x80; + else + m >>= 1; + } + break; + } + + case 8: + { + png_bytep srcptr; + png_bytep dstptr; + png_uint_32 len; + int m; + int diff, unmask; + + __int64 mask0=0x0102040810204080; + +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && mmx_supported */ ) +#else + if (mmx_supported) +#endif + { + srcptr = png_ptr->row_buf + 1; + dstptr = row; + m = 0x80; + unmask = ~mask; + len = png_ptr->width &~7; //reduce to multiple of 8 + diff = png_ptr->width & 7; //amount lost + + _asm + { + movd mm7, unmask //load bit pattern + psubb mm6,mm6 //zero mm6 + punpcklbw mm7,mm7 + punpcklwd mm7,mm7 + punpckldq mm7,mm7 //fill register with 8 masks + + movq mm0,mask0 + + pand mm0,mm7 //nonzero if keep byte + pcmpeqb mm0,mm6 //zeros->1s, v versa + + mov ecx,len //load length of line (pixels) + mov esi,srcptr //load source + mov ebx,dstptr //load dest + cmp ecx,0 //lcr + je mainloop8end + +mainloop8: + movq mm4,[esi] + pand mm4,mm0 + movq mm6,mm0 + pandn mm6,[ebx] + por mm4,mm6 + movq [ebx],mm4 + + add esi,8 //inc by 8 bytes processed + add ebx,8 + sub ecx,8 //dec by 8 pixels processed + + ja mainloop8 +mainloop8end: + + mov ecx,diff + cmp ecx,0 + jz end8 + + mov edx,mask + sal edx,24 //make low byte the high byte + +secondloop8: + sal edx,1 //move high bit to CF + jnc skip8 //if CF = 0 + mov al,[esi] + mov [ebx],al +skip8: + inc esi + inc ebx + + dec ecx + jnz secondloop8 +end8: + emms + } + } + else /* mmx not supported - use modified C routine */ + { + register unsigned int incr1, initial_val, final_val; + png_size_t pixel_bytes; + png_uint_32 i; + register int disp = png_pass_inc[png_ptr->pass]; + int offset_table[7] = {0, 4, 0, 2, 0, 1, 0}; + + pixel_bytes = (png_ptr->row_info.pixel_depth >> 3); + srcptr = png_ptr->row_buf + 1 + offset_table[png_ptr->pass]* + pixel_bytes; + dstptr = row + offset_table[png_ptr->pass]*pixel_bytes; + initial_val = offset_table[png_ptr->pass]*pixel_bytes; + final_val = png_ptr->width*pixel_bytes; + incr1 = (disp)*pixel_bytes; + for (i = initial_val; i < final_val; i += incr1) + { + png_memcpy(dstptr, srcptr, pixel_bytes); + srcptr += incr1; + dstptr += incr1; + } + } /* end of else */ + + break; + } // end 8 bpp + + case 16: + { + png_bytep srcptr; + png_bytep dstptr; + png_uint_32 len; + int unmask, diff; + __int64 mask1=0x0101020204040808, + mask0=0x1010202040408080; + +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && mmx_supported */ ) +#else + if (mmx_supported) +#endif + { + srcptr = png_ptr->row_buf + 1; + dstptr = row; + + unmask = ~mask; + len = (png_ptr->width)&~7; + diff = (png_ptr->width)&7; + _asm + { + movd mm7, unmask //load bit pattern + psubb mm6,mm6 //zero mm6 + punpcklbw mm7,mm7 + punpcklwd mm7,mm7 + punpckldq mm7,mm7 //fill register with 8 masks + + movq mm0,mask0 + movq mm1,mask1 + + pand mm0,mm7 + pand mm1,mm7 + + pcmpeqb mm0,mm6 + pcmpeqb mm1,mm6 + + mov ecx,len //load length of line + mov esi,srcptr //load source + mov ebx,dstptr //load dest + cmp ecx,0 //lcr + jz mainloop16end + +mainloop16: + movq mm4,[esi] + pand mm4,mm0 + movq mm6,mm0 + movq mm7,[ebx] + pandn mm6,mm7 + por mm4,mm6 + movq [ebx],mm4 + + movq mm5,[esi+8] + pand mm5,mm1 + movq mm7,mm1 + movq mm6,[ebx+8] + pandn mm7,mm6 + por mm5,mm7 + movq [ebx+8],mm5 + + add esi,16 //inc by 16 bytes processed + add ebx,16 + sub ecx,8 //dec by 8 pixels processed + + ja mainloop16 + +mainloop16end: + mov ecx,diff + cmp ecx,0 + jz end16 + + mov edx,mask + sal edx,24 //make low byte the high byte +secondloop16: + sal edx,1 //move high bit to CF + jnc skip16 //if CF = 0 + mov ax,[esi] + mov [ebx],ax +skip16: + add esi,2 + add ebx,2 + + dec ecx + jnz secondloop16 +end16: + emms + } + } + else /* mmx not supported - use modified C routine */ + { + register unsigned int incr1, initial_val, final_val; + png_size_t pixel_bytes; + png_uint_32 i; + register int disp = png_pass_inc[png_ptr->pass]; + int offset_table[7] = {0, 4, 0, 2, 0, 1, 0}; + + pixel_bytes = (png_ptr->row_info.pixel_depth >> 3); + srcptr = png_ptr->row_buf + 1 + offset_table[png_ptr->pass]* + pixel_bytes; + dstptr = row + offset_table[png_ptr->pass]*pixel_bytes; + initial_val = offset_table[png_ptr->pass]*pixel_bytes; + final_val = png_ptr->width*pixel_bytes; + incr1 = (disp)*pixel_bytes; + for (i = initial_val; i < final_val; i += incr1) + { + png_memcpy(dstptr, srcptr, pixel_bytes); + srcptr += incr1; + dstptr += incr1; + } + } /* end of else */ + + break; + } // end 16 bpp + + case 24: + { + png_bytep srcptr; + png_bytep dstptr; + png_uint_32 len; + int unmask, diff; + + __int64 mask2=0x0101010202020404, //24bpp + mask1=0x0408080810101020, + mask0=0x2020404040808080; + + srcptr = png_ptr->row_buf + 1; + dstptr = row; + + unmask = ~mask; + len = (png_ptr->width)&~7; + diff = (png_ptr->width)&7; + +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && mmx_supported */ ) +#else + if (mmx_supported) +#endif + { + _asm + { + movd mm7, unmask //load bit pattern + psubb mm6,mm6 //zero mm6 + punpcklbw mm7,mm7 + punpcklwd mm7,mm7 + punpckldq mm7,mm7 //fill register with 8 masks + + movq mm0,mask0 + movq mm1,mask1 + movq mm2,mask2 + + pand mm0,mm7 + pand mm1,mm7 + pand mm2,mm7 + + pcmpeqb mm0,mm6 + pcmpeqb mm1,mm6 + pcmpeqb mm2,mm6 + + mov ecx,len //load length of line + mov esi,srcptr //load source + mov ebx,dstptr //load dest + cmp ecx,0 + jz mainloop24end + +mainloop24: + movq mm4,[esi] + pand mm4,mm0 + movq mm6,mm0 + movq mm7,[ebx] + pandn mm6,mm7 + por mm4,mm6 + movq [ebx],mm4 + + + movq mm5,[esi+8] + pand mm5,mm1 + movq mm7,mm1 + movq mm6,[ebx+8] + pandn mm7,mm6 + por mm5,mm7 + movq [ebx+8],mm5 + + movq mm6,[esi+16] + pand mm6,mm2 + movq mm4,mm2 + movq mm7,[ebx+16] + pandn mm4,mm7 + por mm6,mm4 + movq [ebx+16],mm6 + + add esi,24 //inc by 24 bytes processed + add ebx,24 + sub ecx,8 //dec by 8 pixels processed + + ja mainloop24 + +mainloop24end: + mov ecx,diff + cmp ecx,0 + jz end24 + + mov edx,mask + sal edx,24 //make low byte the high byte +secondloop24: + sal edx,1 //move high bit to CF + jnc skip24 //if CF = 0 + mov ax,[esi] + mov [ebx],ax + xor eax,eax + mov al,[esi+2] + mov [ebx+2],al +skip24: + add esi,3 + add ebx,3 + + dec ecx + jnz secondloop24 + +end24: + emms + } + } + else /* mmx not supported - use modified C routine */ + { + register unsigned int incr1, initial_val, final_val; + png_size_t pixel_bytes; + png_uint_32 i; + register int disp = png_pass_inc[png_ptr->pass]; + int offset_table[7] = {0, 4, 0, 2, 0, 1, 0}; + + pixel_bytes = (png_ptr->row_info.pixel_depth >> 3); + srcptr = png_ptr->row_buf + 1 + offset_table[png_ptr->pass]* + pixel_bytes; + dstptr = row + offset_table[png_ptr->pass]*pixel_bytes; + initial_val = offset_table[png_ptr->pass]*pixel_bytes; + final_val = png_ptr->width*pixel_bytes; + incr1 = (disp)*pixel_bytes; + for (i = initial_val; i < final_val; i += incr1) + { + png_memcpy(dstptr, srcptr, pixel_bytes); + srcptr += incr1; + dstptr += incr1; + } + } /* end of else */ + + break; + } // end 24 bpp + + case 32: + { + png_bytep srcptr; + png_bytep dstptr; + png_uint_32 len; + int unmask, diff; + + __int64 mask3=0x0101010102020202, //32bpp + mask2=0x0404040408080808, + mask1=0x1010101020202020, + mask0=0x4040404080808080; + + srcptr = png_ptr->row_buf + 1; + dstptr = row; + + unmask = ~mask; + len = (png_ptr->width)&~7; + diff = (png_ptr->width)&7; + +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && mmx_supported */ ) +#else + if (mmx_supported) +#endif + { + _asm + { + movd mm7, unmask //load bit pattern + psubb mm6,mm6 //zero mm6 + punpcklbw mm7,mm7 + punpcklwd mm7,mm7 + punpckldq mm7,mm7 //fill register with 8 masks + + movq mm0,mask0 + movq mm1,mask1 + movq mm2,mask2 + movq mm3,mask3 + + pand mm0,mm7 + pand mm1,mm7 + pand mm2,mm7 + pand mm3,mm7 + + pcmpeqb mm0,mm6 + pcmpeqb mm1,mm6 + pcmpeqb mm2,mm6 + pcmpeqb mm3,mm6 + + mov ecx,len //load length of line + mov esi,srcptr //load source + mov ebx,dstptr //load dest + + cmp ecx,0 //lcr + jz mainloop32end + +mainloop32: + movq mm4,[esi] + pand mm4,mm0 + movq mm6,mm0 + movq mm7,[ebx] + pandn mm6,mm7 + por mm4,mm6 + movq [ebx],mm4 + + movq mm5,[esi+8] + pand mm5,mm1 + movq mm7,mm1 + movq mm6,[ebx+8] + pandn mm7,mm6 + por mm5,mm7 + movq [ebx+8],mm5 + + movq mm6,[esi+16] + pand mm6,mm2 + movq mm4,mm2 + movq mm7,[ebx+16] + pandn mm4,mm7 + por mm6,mm4 + movq [ebx+16],mm6 + + movq mm7,[esi+24] + pand mm7,mm3 + movq mm5,mm3 + movq mm4,[ebx+24] + pandn mm5,mm4 + por mm7,mm5 + movq [ebx+24],mm7 + + add esi,32 //inc by 32 bytes processed + add ebx,32 + sub ecx,8 //dec by 8 pixels processed + + ja mainloop32 + +mainloop32end: + mov ecx,diff + cmp ecx,0 + jz end32 + + mov edx,mask + sal edx,24 //make low byte the high byte +secondloop32: + sal edx,1 //move high bit to CF + jnc skip32 //if CF = 0 + mov eax,[esi] + mov [ebx],eax +skip32: + add esi,4 + add ebx,4 + + dec ecx + jnz secondloop32 + +end32: + emms + } + } + else /* mmx _not supported - Use modified C routine */ + { + register unsigned int incr1, initial_val, final_val; + png_size_t pixel_bytes; + png_uint_32 i; + register int disp = png_pass_inc[png_ptr->pass]; + int offset_table[7] = {0, 4, 0, 2, 0, 1, 0}; + + pixel_bytes = (png_ptr->row_info.pixel_depth >> 3); + srcptr = png_ptr->row_buf + 1 + offset_table[png_ptr->pass]* + pixel_bytes; + dstptr = row + offset_table[png_ptr->pass]*pixel_bytes; + initial_val = offset_table[png_ptr->pass]*pixel_bytes; + final_val = png_ptr->width*pixel_bytes; + incr1 = (disp)*pixel_bytes; + for (i = initial_val; i < final_val; i += incr1) + { + png_memcpy(dstptr, srcptr, pixel_bytes); + srcptr += incr1; + dstptr += incr1; + } + } /* end of else */ + + break; + } // end 32 bpp + + case 48: + { + png_bytep srcptr; + png_bytep dstptr; + png_uint_32 len; + int unmask, diff; + + __int64 mask5=0x0101010101010202, + mask4=0x0202020204040404, + mask3=0x0404080808080808, + mask2=0x1010101010102020, + mask1=0x2020202040404040, + mask0=0x4040808080808080; + +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) + /* && mmx_supported */ ) +#else + if (mmx_supported) +#endif + { + srcptr = png_ptr->row_buf + 1; + dstptr = row; + + unmask = ~mask; + len = (png_ptr->width)&~7; + diff = (png_ptr->width)&7; + _asm + { + movd mm7, unmask //load bit pattern + psubb mm6,mm6 //zero mm6 + punpcklbw mm7,mm7 + punpcklwd mm7,mm7 + punpckldq mm7,mm7 //fill register with 8 masks + + movq mm0,mask0 + movq mm1,mask1 + movq mm2,mask2 + movq mm3,mask3 + movq mm4,mask4 + movq mm5,mask5 + + pand mm0,mm7 + pand mm1,mm7 + pand mm2,mm7 + pand mm3,mm7 + pand mm4,mm7 + pand mm5,mm7 + + pcmpeqb mm0,mm6 + pcmpeqb mm1,mm6 + pcmpeqb mm2,mm6 + pcmpeqb mm3,mm6 + pcmpeqb mm4,mm6 + pcmpeqb mm5,mm6 + + mov ecx,len //load length of line + mov esi,srcptr //load source + mov ebx,dstptr //load dest + + cmp ecx,0 + jz mainloop48end + +mainloop48: + movq mm7,[esi] + pand mm7,mm0 + movq mm6,mm0 + pandn mm6,[ebx] + por mm7,mm6 + movq [ebx],mm7 + + movq mm6,[esi+8] + pand mm6,mm1 + movq mm7,mm1 + pandn mm7,[ebx+8] + por mm6,mm7 + movq [ebx+8],mm6 + + movq mm6,[esi+16] + pand mm6,mm2 + movq mm7,mm2 + pandn mm7,[ebx+16] + por mm6,mm7 + movq [ebx+16],mm6 + + movq mm7,[esi+24] + pand mm7,mm3 + movq mm6,mm3 + pandn mm6,[ebx+24] + por mm7,mm6 + movq [ebx+24],mm7 + + movq mm6,[esi+32] + pand mm6,mm4 + movq mm7,mm4 + pandn mm7,[ebx+32] + por mm6,mm7 + movq [ebx+32],mm6 + + movq mm7,[esi+40] + pand mm7,mm5 + movq mm6,mm5 + pandn mm6,[ebx+40] + por mm7,mm6 + movq [ebx+40],mm7 + + add esi,48 //inc by 32 bytes processed + add ebx,48 + sub ecx,8 //dec by 8 pixels processed + + ja mainloop48 +mainloop48end: + + mov ecx,diff + cmp ecx,0 + jz end48 + + mov edx,mask + sal edx,24 //make low byte the high byte + +secondloop48: + sal edx,1 //move high bit to CF + jnc skip48 //if CF = 0 + mov eax,[esi] + mov [ebx],eax +skip48: + add esi,4 + add ebx,4 + + dec ecx + jnz secondloop48 + +end48: + emms + } + } + else /* mmx _not supported - Use modified C routine */ + { + register unsigned int incr1, initial_val, final_val; + png_size_t pixel_bytes; + png_uint_32 i; + register int disp = png_pass_inc[png_ptr->pass]; + int offset_table[7] = {0, 4, 0, 2, 0, 1, 0}; + + pixel_bytes = (png_ptr->row_info.pixel_depth >> 3); + srcptr = png_ptr->row_buf + 1 + offset_table[png_ptr->pass]* + pixel_bytes; + dstptr = row + offset_table[png_ptr->pass]*pixel_bytes; + initial_val = offset_table[png_ptr->pass]*pixel_bytes; + final_val = png_ptr->width*pixel_bytes; + incr1 = (disp)*pixel_bytes; + for (i = initial_val; i < final_val; i += incr1) + { + png_memcpy(dstptr, srcptr, pixel_bytes); + srcptr += incr1; + dstptr += incr1; + } + } /* end of else */ + + break; + } // end 48 bpp + + default: + { + png_bytep sptr; + png_bytep dp; + png_size_t pixel_bytes; + int offset_table[7] = {0, 4, 0, 2, 0, 1, 0}; + unsigned int i; + register int disp = png_pass_inc[png_ptr->pass]; // get the offset + register unsigned int incr1, initial_val, final_val; + + pixel_bytes = (png_ptr->row_info.pixel_depth >> 3); + sptr = png_ptr->row_buf + 1 + offset_table[png_ptr->pass]* + pixel_bytes; + dp = row + offset_table[png_ptr->pass]*pixel_bytes; + initial_val = offset_table[png_ptr->pass]*pixel_bytes; + final_val = png_ptr->width*pixel_bytes; + incr1 = (disp)*pixel_bytes; + for (i = initial_val; i < final_val; i += incr1) + { + png_memcpy(dp, sptr, pixel_bytes); + sptr += incr1; + dp += incr1; + } + break; + } + } /* end switch (png_ptr->row_info.pixel_depth) */ + } /* end if (non-trivial mask) */ + +} /* end png_combine_row() */ + + +#if defined(PNG_READ_INTERLACING_SUPPORTED) + +void /* PRIVATE */ +png_do_read_interlace(png_structp png_ptr) +{ + png_row_infop row_info = &(png_ptr->row_info); + png_bytep row = png_ptr->row_buf + 1; + int pass = png_ptr->pass; + png_uint_32 transformations = png_ptr->transformations; +#ifdef PNG_USE_LOCAL_ARRAYS + const int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; +#endif + + png_debug(1,"in png_do_read_interlace\n"); + + if (mmx_supported == 2) { +#if !defined(PNG_1_0_X) + /* this should have happened in png_init_mmx_flags() already */ + png_warning(png_ptr, "asm_flags may not have been initialized"); +#endif + png_mmx_support(); + } + + if (row != NULL && row_info != NULL) + { + png_uint_32 final_width; + + final_width = row_info->width * png_pass_inc[pass]; + + switch (row_info->pixel_depth) + { + case 1: + { + png_bytep sp, dp; + int sshift, dshift; + int s_start, s_end, s_inc; + png_byte v; + png_uint_32 i; + int j; + + sp = row + (png_size_t)((row_info->width - 1) >> 3); + dp = row + (png_size_t)((final_width - 1) >> 3); +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (int)((row_info->width + 7) & 7); + dshift = (int)((final_width + 7) & 7); + s_start = 7; + s_end = 0; + s_inc = -1; + } + else +#endif + { + sshift = 7 - (int)((row_info->width + 7) & 7); + dshift = 7 - (int)((final_width + 7) & 7); + s_start = 0; + s_end = 7; + s_inc = 1; + } + + for (i = row_info->width; i; i--) + { + v = (png_byte)((*sp >> sshift) & 0x1); + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + + case 2: + { + png_bytep sp, dp; + int sshift, dshift; + int s_start, s_end, s_inc; + png_uint_32 i; + + sp = row + (png_size_t)((row_info->width - 1) >> 2); + dp = row + (png_size_t)((final_width - 1) >> 2); +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (png_size_t)(((row_info->width + 3) & 3) << 1); + dshift = (png_size_t)(((final_width + 3) & 3) << 1); + s_start = 6; + s_end = 0; + s_inc = -2; + } + else +#endif + { + sshift = (png_size_t)((3 - ((row_info->width + 3) & 3)) << 1); + dshift = (png_size_t)((3 - ((final_width + 3) & 3)) << 1); + s_start = 0; + s_end = 6; + s_inc = 2; + } + + for (i = row_info->width; i; i--) + { + png_byte v; + int j; + + v = (png_byte)((*sp >> sshift) & 0x3); + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + + case 4: + { + png_bytep sp, dp; + int sshift, dshift; + int s_start, s_end, s_inc; + png_uint_32 i; + + sp = row + (png_size_t)((row_info->width - 1) >> 1); + dp = row + (png_size_t)((final_width - 1) >> 1); +#if defined(PNG_READ_PACKSWAP_SUPPORTED) + if (transformations & PNG_PACKSWAP) + { + sshift = (png_size_t)(((row_info->width + 1) & 1) << 2); + dshift = (png_size_t)(((final_width + 1) & 1) << 2); + s_start = 4; + s_end = 0; + s_inc = -4; + } + else +#endif + { + sshift = (png_size_t)((1 - ((row_info->width + 1) & 1)) << 2); + dshift = (png_size_t)((1 - ((final_width + 1) & 1)) << 2); + s_start = 0; + s_end = 4; + s_inc = 4; + } + + for (i = row_info->width; i; i--) + { + png_byte v; + int j; + + v = (png_byte)((*sp >> sshift) & 0xf); + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff); + *dp |= (png_byte)(v << dshift); + if (dshift == s_end) + { + dshift = s_start; + dp--; + } + else + dshift += s_inc; + } + if (sshift == s_end) + { + sshift = s_start; + sp--; + } + else + sshift += s_inc; + } + break; + } + + default: // This is the place where the routine is modified + { + __int64 const4 = 0x0000000000FFFFFF; + // __int64 const5 = 0x000000FFFFFF0000; // unused... + __int64 const6 = 0x00000000000000FF; + png_bytep sptr, dp; + png_uint_32 i; + png_size_t pixel_bytes; + int width = row_info->width; + + pixel_bytes = (row_info->pixel_depth >> 3); + + sptr = row + (width - 1) * pixel_bytes; + dp = row + (final_width - 1) * pixel_bytes; + // New code by Nirav Chhatrapati - Intel Corporation + // sign fix by GRR + // NOTE: there is NO MMX code for 48-bit and 64-bit images + + // use MMX routine if machine supports it +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_INTERLACE) + /* && mmx_supported */ ) +#else + if (mmx_supported) +#endif + { + if (pixel_bytes == 3) + { + if (((pass == 0) || (pass == 1)) && width) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width + sub edi, 21 // (png_pass_inc[pass] - 1)*pixel_bytes +loop_pass0: + movd mm0, [esi] ; X X X X X v2 v1 v0 + pand mm0, const4 ; 0 0 0 0 0 v2 v1 v0 + movq mm1, mm0 ; 0 0 0 0 0 v2 v1 v0 + psllq mm0, 16 ; 0 0 0 v2 v1 v0 0 0 + movq mm2, mm0 ; 0 0 0 v2 v1 v0 0 0 + psllq mm0, 24 ; v2 v1 v0 0 0 0 0 0 + psrlq mm1, 8 ; 0 0 0 0 0 0 v2 v1 + por mm0, mm2 ; v2 v1 v0 v2 v1 v0 0 0 + por mm0, mm1 ; v2 v1 v0 v2 v1 v0 v2 v1 + movq mm3, mm0 ; v2 v1 v0 v2 v1 v0 v2 v1 + psllq mm0, 16 ; v0 v2 v1 v0 v2 v1 0 0 + movq mm4, mm3 ; v2 v1 v0 v2 v1 v0 v2 v1 + punpckhdq mm3, mm0 ; v0 v2 v1 v0 v2 v1 v0 v2 + movq [edi+16] , mm4 + psrlq mm0, 32 ; 0 0 0 0 v0 v2 v1 v0 + movq [edi+8] , mm3 + punpckldq mm0, mm4 ; v1 v0 v2 v1 v0 v2 v1 v0 + sub esi, 3 + movq [edi], mm0 + sub edi, 24 + //sub esi, 3 + dec ecx + jnz loop_pass0 + EMMS + } + } + else if (((pass == 2) || (pass == 3)) && width) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width + sub edi, 9 // (png_pass_inc[pass] - 1)*pixel_bytes +loop_pass2: + movd mm0, [esi] ; X X X X X v2 v1 v0 + pand mm0, const4 ; 0 0 0 0 0 v2 v1 v0 + movq mm1, mm0 ; 0 0 0 0 0 v2 v1 v0 + psllq mm0, 16 ; 0 0 0 v2 v1 v0 0 0 + movq mm2, mm0 ; 0 0 0 v2 v1 v0 0 0 + psllq mm0, 24 ; v2 v1 v0 0 0 0 0 0 + psrlq mm1, 8 ; 0 0 0 0 0 0 v2 v1 + por mm0, mm2 ; v2 v1 v0 v2 v1 v0 0 0 + por mm0, mm1 ; v2 v1 v0 v2 v1 v0 v2 v1 + movq [edi+4], mm0 ; move to memory + psrlq mm0, 16 ; 0 0 v2 v1 v0 v2 v1 v0 + movd [edi], mm0 ; move to memory + sub esi, 3 + sub edi, 12 + dec ecx + jnz loop_pass2 + EMMS + } + } + else if (width) /* && ((pass == 4) || (pass == 5)) */ + { + int width_mmx = ((width >> 1) << 1) - 8; + if (width_mmx < 0) + width_mmx = 0; + width -= width_mmx; // 8 or 9 pix, 24 or 27 bytes + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub esi, 3 + sub edi, 9 +loop_pass4: + movq mm0, [esi] ; X X v2 v1 v0 v5 v4 v3 + movq mm7, mm0 ; X X v2 v1 v0 v5 v4 v3 + movq mm6, mm0 ; X X v2 v1 v0 v5 v4 v3 + psllq mm0, 24 ; v1 v0 v5 v4 v3 0 0 0 + pand mm7, const4 ; 0 0 0 0 0 v5 v4 v3 + psrlq mm6, 24 ; 0 0 0 X X v2 v1 v0 + por mm0, mm7 ; v1 v0 v5 v4 v3 v5 v4 v3 + movq mm5, mm6 ; 0 0 0 X X v2 v1 v0 + psllq mm6, 8 ; 0 0 X X v2 v1 v0 0 + movq [edi], mm0 ; move quad to memory + psrlq mm5, 16 ; 0 0 0 0 0 X X v2 + pand mm5, const6 ; 0 0 0 0 0 0 0 v2 + por mm6, mm5 ; 0 0 X X v2 v1 v0 v2 + movd [edi+8], mm6 ; move double to memory + sub esi, 6 + sub edi, 12 + sub ecx, 2 + jnz loop_pass4 + EMMS + } + } + + sptr -= width_mmx*3; + dp -= width_mmx*6; + for (i = width; i; i--) + { + png_byte v[8]; + int j; + + png_memcpy(v, sptr, 3); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, 3); + dp -= 3; + } + sptr -= 3; + } + } + } /* end of pixel_bytes == 3 */ + + else if (pixel_bytes == 1) + { + if (((pass == 0) || (pass == 1)) && width) + { + int width_mmx = ((width >> 2) << 2); + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub edi, 31 + sub esi, 3 +loop1_pass0: + movd mm0, [esi] ; X X X X v0 v1 v2 v3 + movq mm1, mm0 ; X X X X v0 v1 v2 v3 + punpcklbw mm0, mm0 ; v0 v0 v1 v1 v2 v2 v3 v3 + movq mm2, mm0 ; v0 v0 v1 v1 v2 v2 v3 v3 + punpcklwd mm0, mm0 ; v2 v2 v2 v2 v3 v3 v3 v3 + movq mm3, mm0 ; v2 v2 v2 v2 v3 v3 v3 v3 + punpckldq mm0, mm0 ; v3 v3 v3 v3 v3 v3 v3 v3 + punpckhdq mm3, mm3 ; v2 v2 v2 v2 v2 v2 v2 v2 + movq [edi], mm0 ; move to memory v3 + punpckhwd mm2, mm2 ; v0 v0 v0 v0 v1 v1 v1 v1 + movq [edi+8], mm3 ; move to memory v2 + movq mm4, mm2 ; v0 v0 v0 v0 v1 v1 v1 v1 + punpckldq mm2, mm2 ; v1 v1 v1 v1 v1 v1 v1 v1 + punpckhdq mm4, mm4 ; v0 v0 v0 v0 v0 v0 v0 v0 + movq [edi+16], mm2 ; move to memory v1 + movq [edi+24], mm4 ; move to memory v0 + sub esi, 4 + sub edi, 32 + sub ecx, 4 + jnz loop1_pass0 + EMMS + } + } + + sptr -= width_mmx; + dp -= width_mmx*8; + for (i = width; i; i--) + { + int j; + + /* I simplified this part in version 1.0.4e + * here and in several other instances where + * pixel_bytes == 1 -- GR-P + * + * Original code: + * + * png_byte v[8]; + * png_memcpy(v, sptr, pixel_bytes); + * for (j = 0; j < png_pass_inc[pass]; j++) + * { + * png_memcpy(dp, v, pixel_bytes); + * dp -= pixel_bytes; + * } + * sptr -= pixel_bytes; + * + * Replacement code is in the next three lines: + */ + + for (j = 0; j < png_pass_inc[pass]; j++) + *dp-- = *sptr; + sptr--; + } + } + else if (((pass == 2) || (pass == 3)) && width) + { + int width_mmx = ((width >> 2) << 2); + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub edi, 15 + sub esi, 3 +loop1_pass2: + movd mm0, [esi] ; X X X X v0 v1 v2 v3 + punpcklbw mm0, mm0 ; v0 v0 v1 v1 v2 v2 v3 v3 + movq mm1, mm0 ; v0 v0 v1 v1 v2 v2 v3 v3 + punpcklwd mm0, mm0 ; v2 v2 v2 v2 v3 v3 v3 v3 + punpckhwd mm1, mm1 ; v0 v0 v0 v0 v1 v1 v1 v1 + movq [edi], mm0 ; move to memory v2 and v3 + sub esi, 4 + movq [edi+8], mm1 ; move to memory v1 and v0 + sub edi, 16 + sub ecx, 4 + jnz loop1_pass2 + EMMS + } + } + + sptr -= width_mmx; + dp -= width_mmx*4; + for (i = width; i; i--) + { + int j; + + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp-- = *sptr; + } + sptr --; + } + } + else if (width) /* && ((pass == 4) || (pass == 5))) */ + { + int width_mmx = ((width >> 3) << 3); + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub edi, 15 + sub esi, 7 +loop1_pass4: + movq mm0, [esi] ; v0 v1 v2 v3 v4 v5 v6 v7 + movq mm1, mm0 ; v0 v1 v2 v3 v4 v5 v6 v7 + punpcklbw mm0, mm0 ; v4 v4 v5 v5 v6 v6 v7 v7 + //movq mm1, mm0 ; v0 v0 v1 v1 v2 v2 v3 v3 + punpckhbw mm1, mm1 ;v0 v0 v1 v1 v2 v2 v3 v3 + movq [edi+8], mm1 ; move to memory v0 v1 v2 and v3 + sub esi, 8 + movq [edi], mm0 ; move to memory v4 v5 v6 and v7 + //sub esi, 4 + sub edi, 16 + sub ecx, 8 + jnz loop1_pass4 + EMMS + } + } + + sptr -= width_mmx; + dp -= width_mmx*2; + for (i = width; i; i--) + { + int j; + + for (j = 0; j < png_pass_inc[pass]; j++) + { + *dp-- = *sptr; + } + sptr --; + } + } + } /* end of pixel_bytes == 1 */ + + else if (pixel_bytes == 2) + { + if (((pass == 0) || (pass == 1)) && width) + { + int width_mmx = ((width >> 1) << 1); + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub esi, 2 + sub edi, 30 +loop2_pass0: + movd mm0, [esi] ; X X X X v1 v0 v3 v2 + punpcklwd mm0, mm0 ; v1 v0 v1 v0 v3 v2 v3 v2 + movq mm1, mm0 ; v1 v0 v1 v0 v3 v2 v3 v2 + punpckldq mm0, mm0 ; v3 v2 v3 v2 v3 v2 v3 v2 + punpckhdq mm1, mm1 ; v1 v0 v1 v0 v1 v0 v1 v0 + movq [edi], mm0 + movq [edi + 8], mm0 + movq [edi + 16], mm1 + movq [edi + 24], mm1 + sub esi, 4 + sub edi, 32 + sub ecx, 2 + jnz loop2_pass0 + EMMS + } + } + + sptr -= (width_mmx*2 - 2); // sign fixed + dp -= (width_mmx*16 - 2); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 2; + png_memcpy(v, sptr, 2); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 2; + png_memcpy(dp, v, 2); + } + } + } + else if (((pass == 2) || (pass == 3)) && width) + { + int width_mmx = ((width >> 1) << 1) ; + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub esi, 2 + sub edi, 14 +loop2_pass2: + movd mm0, [esi] ; X X X X v1 v0 v3 v2 + punpcklwd mm0, mm0 ; v1 v0 v1 v0 v3 v2 v3 v2 + movq mm1, mm0 ; v1 v0 v1 v0 v3 v2 v3 v2 + punpckldq mm0, mm0 ; v3 v2 v3 v2 v3 v2 v3 v2 + punpckhdq mm1, mm1 ; v1 v0 v1 v0 v1 v0 v1 v0 + movq [edi], mm0 + sub esi, 4 + movq [edi + 8], mm1 + //sub esi, 4 + sub edi, 16 + sub ecx, 2 + jnz loop2_pass2 + EMMS + } + } + + sptr -= (width_mmx*2 - 2); // sign fixed + dp -= (width_mmx*8 - 2); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 2; + png_memcpy(v, sptr, 2); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 2; + png_memcpy(dp, v, 2); + } + } + } + else if (width) // pass == 4 or 5 + { + int width_mmx = ((width >> 1) << 1) ; + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub esi, 2 + sub edi, 6 +loop2_pass4: + movd mm0, [esi] ; X X X X v1 v0 v3 v2 + punpcklwd mm0, mm0 ; v1 v0 v1 v0 v3 v2 v3 v2 + sub esi, 4 + movq [edi], mm0 + sub edi, 8 + sub ecx, 2 + jnz loop2_pass4 + EMMS + } + } + + sptr -= (width_mmx*2 - 2); // sign fixed + dp -= (width_mmx*4 - 2); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 2; + png_memcpy(v, sptr, 2); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 2; + png_memcpy(dp, v, 2); + } + } + } + } /* end of pixel_bytes == 2 */ + + else if (pixel_bytes == 4) + { + if (((pass == 0) || (pass == 1)) && width) + { + int width_mmx = ((width >> 1) << 1) ; + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub esi, 4 + sub edi, 60 +loop4_pass0: + movq mm0, [esi] ; v3 v2 v1 v0 v7 v6 v5 v4 + movq mm1, mm0 ; v3 v2 v1 v0 v7 v6 v5 v4 + punpckldq mm0, mm0 ; v7 v6 v5 v4 v7 v6 v5 v4 + punpckhdq mm1, mm1 ; v3 v2 v1 v0 v3 v2 v1 v0 + movq [edi], mm0 + movq [edi + 8], mm0 + movq [edi + 16], mm0 + movq [edi + 24], mm0 + movq [edi+32], mm1 + movq [edi + 40], mm1 + movq [edi+ 48], mm1 + sub esi, 8 + movq [edi + 56], mm1 + sub edi, 64 + sub ecx, 2 + jnz loop4_pass0 + EMMS + } + } + + sptr -= (width_mmx*4 - 4); // sign fixed + dp -= (width_mmx*32 - 4); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 4; + png_memcpy(v, sptr, 4); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 4; + png_memcpy(dp, v, 4); + } + } + } + else if (((pass == 2) || (pass == 3)) && width) + { + int width_mmx = ((width >> 1) << 1) ; + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub esi, 4 + sub edi, 28 +loop4_pass2: + movq mm0, [esi] ; v3 v2 v1 v0 v7 v6 v5 v4 + movq mm1, mm0 ; v3 v2 v1 v0 v7 v6 v5 v4 + punpckldq mm0, mm0 ; v7 v6 v5 v4 v7 v6 v5 v4 + punpckhdq mm1, mm1 ; v3 v2 v1 v0 v3 v2 v1 v0 + movq [edi], mm0 + movq [edi + 8], mm0 + movq [edi+16], mm1 + movq [edi + 24], mm1 + sub esi, 8 + sub edi, 32 + sub ecx, 2 + jnz loop4_pass2 + EMMS + } + } + + sptr -= (width_mmx*4 - 4); // sign fixed + dp -= (width_mmx*16 - 4); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 4; + png_memcpy(v, sptr, 4); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 4; + png_memcpy(dp, v, 4); + } + } + } + else if (width) // pass == 4 or 5 + { + int width_mmx = ((width >> 1) << 1) ; + width -= width_mmx; + if (width_mmx) + { + _asm + { + mov esi, sptr + mov edi, dp + mov ecx, width_mmx + sub esi, 4 + sub edi, 12 +loop4_pass4: + movq mm0, [esi] ; v3 v2 v1 v0 v7 v6 v5 v4 + movq mm1, mm0 ; v3 v2 v1 v0 v7 v6 v5 v4 + punpckldq mm0, mm0 ; v7 v6 v5 v4 v7 v6 v5 v4 + punpckhdq mm1, mm1 ; v3 v2 v1 v0 v3 v2 v1 v0 + movq [edi], mm0 + sub esi, 8 + movq [edi + 8], mm1 + sub edi, 16 + sub ecx, 2 + jnz loop4_pass4 + EMMS + } + } + + sptr -= (width_mmx*4 - 4); // sign fixed + dp -= (width_mmx*8 - 4); // sign fixed + for (i = width; i; i--) + { + png_byte v[8]; + int j; + sptr -= 4; + png_memcpy(v, sptr, 4); + for (j = 0; j < png_pass_inc[pass]; j++) + { + dp -= 4; + png_memcpy(dp, v, 4); + } + } + } + + } /* end of pixel_bytes == 4 */ + + else if (pixel_bytes == 6) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, 6); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, 6); + dp -= 6; + } + sptr -= 6; + } + } /* end of pixel_bytes == 6 */ + + else + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, pixel_bytes); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sptr-= pixel_bytes; + } + } + } /* end of mmx_supported */ + + else /* MMX not supported: use modified C code - takes advantage + * of inlining of memcpy for a constant */ + { + if (pixel_bytes == 1) + { + for (i = width; i; i--) + { + int j; + for (j = 0; j < png_pass_inc[pass]; j++) + *dp-- = *sptr; + sptr--; + } + } + else if (pixel_bytes == 3) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, pixel_bytes); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sptr -= pixel_bytes; + } + } + else if (pixel_bytes == 2) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, pixel_bytes); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sptr -= pixel_bytes; + } + } + else if (pixel_bytes == 4) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, pixel_bytes); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sptr -= pixel_bytes; + } + } + else if (pixel_bytes == 6) + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, pixel_bytes); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sptr -= pixel_bytes; + } + } + else + { + for (i = width; i; i--) + { + png_byte v[8]; + int j; + png_memcpy(v, sptr, pixel_bytes); + for (j = 0; j < png_pass_inc[pass]; j++) + { + png_memcpy(dp, v, pixel_bytes); + dp -= pixel_bytes; + } + sptr -= pixel_bytes; + } + } + + } /* end of MMX not supported */ + break; + } + } /* end switch (row_info->pixel_depth) */ + + row_info->width = final_width; + + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width); + } + +} + +#endif /* PNG_READ_INTERLACING_SUPPORTED */ + + +// These variables are utilized in the functions below. They are declared +// globally here to ensure alignment on 8-byte boundaries. + +union uAll { + __int64 use; + double align; +} LBCarryMask = {0x0101010101010101}, + HBClearMask = {0x7f7f7f7f7f7f7f7f}, + ActiveMask, ActiveMask2, ActiveMaskEnd, ShiftBpp, ShiftRem; + + +// Optimized code for PNG Average filter decoder +void /* PRIVATE */ +png_read_filter_row_mmx_avg(png_row_infop row_info, png_bytep row + , png_bytep prev_row) +{ + int bpp; + png_uint_32 FullLength; + png_uint_32 MMXLength; + //png_uint_32 len; + int diff; + + bpp = (row_info->pixel_depth + 7) >> 3; // Get # bytes per pixel + FullLength = row_info->rowbytes; // # of bytes to filter + _asm { + // Init address pointers and offset + mov edi, row // edi ==> Avg(x) + xor ebx, ebx // ebx ==> x + mov edx, edi + mov esi, prev_row // esi ==> Prior(x) + sub edx, bpp // edx ==> Raw(x-bpp) + + xor eax, eax + // Compute the Raw value for the first bpp bytes + // Raw(x) = Avg(x) + (Prior(x)/2) +davgrlp: + mov al, [esi + ebx] // Load al with Prior(x) + inc ebx + shr al, 1 // divide by 2 + add al, [edi+ebx-1] // Add Avg(x); -1 to offset inc ebx + cmp ebx, bpp + mov [edi+ebx-1], al // Write back Raw(x); + // mov does not affect flags; -1 to offset inc ebx + jb davgrlp + // get # of bytes to alignment + mov diff, edi // take start of row + add diff, ebx // add bpp + add diff, 0xf // add 7 + 8 to incr past alignment boundary + and diff, 0xfffffff8 // mask to alignment boundary + sub diff, edi // subtract from start ==> value ebx at alignment + jz davggo + // fix alignment + // Compute the Raw value for the bytes upto the alignment boundary + // Raw(x) = Avg(x) + ((Raw(x-bpp) + Prior(x))/2) + xor ecx, ecx +davglp1: + xor eax, eax + mov cl, [esi + ebx] // load cl with Prior(x) + mov al, [edx + ebx] // load al with Raw(x-bpp) + add ax, cx + inc ebx + shr ax, 1 // divide by 2 + add al, [edi+ebx-1] // Add Avg(x); -1 to offset inc ebx + cmp ebx, diff // Check if at alignment boundary + mov [edi+ebx-1], al // Write back Raw(x); + // mov does not affect flags; -1 to offset inc ebx + jb davglp1 // Repeat until at alignment boundary +davggo: + mov eax, FullLength + mov ecx, eax + sub eax, ebx // subtract alignment fix + and eax, 0x00000007 // calc bytes over mult of 8 + sub ecx, eax // drop over bytes from original length + mov MMXLength, ecx + } // end _asm block + // Now do the math for the rest of the row + switch ( bpp ) + { + case 3: + { + ActiveMask.use = 0x0000000000ffffff; + ShiftBpp.use = 24; // == 3 * 8 + ShiftRem.use = 40; // == 64 - 24 + _asm { + // Re-init address pointers and offset + movq mm7, ActiveMask + mov ebx, diff // ebx ==> x = offset to alignment boundary + movq mm5, LBCarryMask + mov edi, row // edi ==> Avg(x) + movq mm4, HBClearMask + mov esi, prev_row // esi ==> Prior(x) + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm2, [edi + ebx - 8] // Load previous aligned 8 bytes + // (we correct position in loop below) +davg3lp: + movq mm0, [edi + ebx] // Load mm0 with Avg(x) + // Add (Prev_row/2) to Average + movq mm3, mm5 + psrlq mm2, ShiftRem // Correct position Raw(x-bpp) data + movq mm1, [esi + ebx] // Load mm1 with Prior(x) + movq mm6, mm7 + pand mm3, mm1 // get lsb for each prev_row byte + psrlq mm1, 1 // divide prev_row bytes by 2 + pand mm1, mm4 // clear invalid bit 7 of each byte + paddb mm0, mm1 // add (Prev_row/2) to Avg for each byte + // Add 1st active group (Raw(x-bpp)/2) to Average with LBCarry + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm6 // Leave only Active Group 1 bytes to add to Avg + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active + // byte + // Add 2nd active group (Raw(x-bpp)/2) to Average with LBCarry + psllq mm6, ShiftBpp // shift the mm6 mask to cover bytes 3-5 + movq mm2, mm0 // mov updated Raws to mm2 + psllq mm2, ShiftBpp // shift data to position correctly + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm6 // Leave only Active Group 2 bytes to add to Avg + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active + // byte + + // Add 3rd active group (Raw(x-bpp)/2) to Average with LBCarry + psllq mm6, ShiftBpp // shift the mm6 mask to cover the last two + // bytes + movq mm2, mm0 // mov updated Raws to mm2 + psllq mm2, ShiftBpp // shift data to position correctly + // Data only needs to be shifted once here to + // get the correct x-bpp offset. + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm6 // Leave only Active Group 2 bytes to add to Avg + add ebx, 8 + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active + // byte + + // Now ready to write back to memory + movq [edi + ebx - 8], mm0 + // Move updated Raw(x) to use as Raw(x-bpp) for next loop + cmp ebx, MMXLength + movq mm2, mm0 // mov updated Raw(x) to mm2 + jb davg3lp + } // end _asm block + } + break; + + case 6: + case 4: + case 7: + case 5: + { + ActiveMask.use = 0xffffffffffffffff; // use shift below to clear + // appropriate inactive bytes + ShiftBpp.use = bpp << 3; + ShiftRem.use = 64 - ShiftBpp.use; + _asm { + movq mm4, HBClearMask + // Re-init address pointers and offset + mov ebx, diff // ebx ==> x = offset to alignment boundary + // Load ActiveMask and clear all bytes except for 1st active group + movq mm7, ActiveMask + mov edi, row // edi ==> Avg(x) + psrlq mm7, ShiftRem + mov esi, prev_row // esi ==> Prior(x) + movq mm6, mm7 + movq mm5, LBCarryMask + psllq mm6, ShiftBpp // Create mask for 2nd active group + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm2, [edi + ebx - 8] // Load previous aligned 8 bytes + // (we correct position in loop below) +davg4lp: + movq mm0, [edi + ebx] + psrlq mm2, ShiftRem // shift data to position correctly + movq mm1, [esi + ebx] + // Add (Prev_row/2) to Average + movq mm3, mm5 + pand mm3, mm1 // get lsb for each prev_row byte + psrlq mm1, 1 // divide prev_row bytes by 2 + pand mm1, mm4 // clear invalid bit 7 of each byte + paddb mm0, mm1 // add (Prev_row/2) to Avg for each byte + // Add 1st active group (Raw(x-bpp)/2) to Average with LBCarry + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm7 // Leave only Active Group 1 bytes to add to Avg + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active + // byte + // Add 2nd active group (Raw(x-bpp)/2) to Average with LBCarry + movq mm2, mm0 // mov updated Raws to mm2 + psllq mm2, ShiftBpp // shift data to position correctly + add ebx, 8 + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm6 // Leave only Active Group 2 bytes to add to Avg + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active + // byte + cmp ebx, MMXLength + // Now ready to write back to memory + movq [edi + ebx - 8], mm0 + // Prep Raw(x-bpp) for next loop + movq mm2, mm0 // mov updated Raws to mm2 + jb davg4lp + } // end _asm block + } + break; + case 2: + { + ActiveMask.use = 0x000000000000ffff; + ShiftBpp.use = 16; // == 2 * 8 [BUGFIX] + ShiftRem.use = 48; // == 64 - 16 [BUGFIX] + _asm { + // Load ActiveMask + movq mm7, ActiveMask + // Re-init address pointers and offset + mov ebx, diff // ebx ==> x = offset to alignment boundary + movq mm5, LBCarryMask + mov edi, row // edi ==> Avg(x) + movq mm4, HBClearMask + mov esi, prev_row // esi ==> Prior(x) + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm2, [edi + ebx - 8] // Load previous aligned 8 bytes + // (we correct position in loop below) +davg2lp: + movq mm0, [edi + ebx] + psrlq mm2, ShiftRem // shift data to position correctly [BUGFIX] + movq mm1, [esi + ebx] + // Add (Prev_row/2) to Average + movq mm3, mm5 + pand mm3, mm1 // get lsb for each prev_row byte + psrlq mm1, 1 // divide prev_row bytes by 2 + pand mm1, mm4 // clear invalid bit 7 of each byte + movq mm6, mm7 + paddb mm0, mm1 // add (Prev_row/2) to Avg for each byte + // Add 1st active group (Raw(x-bpp)/2) to Average with LBCarry + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm6 // Leave only Active Group 1 bytes to add to Avg + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active byte + // Add 2nd active group (Raw(x-bpp)/2) to Average with LBCarry + psllq mm6, ShiftBpp // shift the mm6 mask to cover bytes 2 & 3 + movq mm2, mm0 // mov updated Raws to mm2 + psllq mm2, ShiftBpp // shift data to position correctly + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm6 // Leave only Active Group 2 bytes to add to Avg + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active byte + + // Add rdd active group (Raw(x-bpp)/2) to Average with LBCarry + psllq mm6, ShiftBpp // shift the mm6 mask to cover bytes 4 & 5 + movq mm2, mm0 // mov updated Raws to mm2 + psllq mm2, ShiftBpp // shift data to position correctly + // Data only needs to be shifted once here to + // get the correct x-bpp offset. + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm6 // Leave only Active Group 2 bytes to add to Avg + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active byte + + // Add 4th active group (Raw(x-bpp)/2) to Average with LBCarry + psllq mm6, ShiftBpp // shift the mm6 mask to cover bytes 6 & 7 + movq mm2, mm0 // mov updated Raws to mm2 + psllq mm2, ShiftBpp // shift data to position correctly + // Data only needs to be shifted once here to + // get the correct x-bpp offset. + add ebx, 8 + movq mm1, mm3 // now use mm1 for getting LBCarrys + pand mm1, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 (Only valid for active group) + psrlq mm2, 1 // divide raw bytes by 2 + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm2, mm1 // add LBCarrys to (Raw(x-bpp)/2) for each byte + pand mm2, mm6 // Leave only Active Group 2 bytes to add to Avg + paddb mm0, mm2 // add (Raw/2) + LBCarrys to Avg for each Active byte + + cmp ebx, MMXLength + // Now ready to write back to memory + movq [edi + ebx - 8], mm0 + // Prep Raw(x-bpp) for next loop + movq mm2, mm0 // mov updated Raws to mm2 + jb davg2lp + } // end _asm block + } + break; + + case 1: // bpp == 1 + { + _asm { + // Re-init address pointers and offset + mov ebx, diff // ebx ==> x = offset to alignment boundary + mov edi, row // edi ==> Avg(x) + cmp ebx, FullLength // Test if offset at end of array + jnb davg1end + // Do Paeth decode for remaining bytes + mov esi, prev_row // esi ==> Prior(x) + mov edx, edi + xor ecx, ecx // zero ecx before using cl & cx in loop below + sub edx, bpp // edx ==> Raw(x-bpp) +davg1lp: + // Raw(x) = Avg(x) + ((Raw(x-bpp) + Prior(x))/2) + xor eax, eax + mov cl, [esi + ebx] // load cl with Prior(x) + mov al, [edx + ebx] // load al with Raw(x-bpp) + add ax, cx + inc ebx + shr ax, 1 // divide by 2 + add al, [edi+ebx-1] // Add Avg(x); -1 to offset inc ebx + cmp ebx, FullLength // Check if at end of array + mov [edi+ebx-1], al // Write back Raw(x); + // mov does not affect flags; -1 to offset inc ebx + jb davg1lp +davg1end: + } // end _asm block + } + return; + + case 8: // bpp == 8 + { + _asm { + // Re-init address pointers and offset + mov ebx, diff // ebx ==> x = offset to alignment boundary + movq mm5, LBCarryMask + mov edi, row // edi ==> Avg(x) + movq mm4, HBClearMask + mov esi, prev_row // esi ==> Prior(x) + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm2, [edi + ebx - 8] // Load previous aligned 8 bytes + // (NO NEED to correct position in loop below) +davg8lp: + movq mm0, [edi + ebx] + movq mm3, mm5 + movq mm1, [esi + ebx] + add ebx, 8 + pand mm3, mm1 // get lsb for each prev_row byte + psrlq mm1, 1 // divide prev_row bytes by 2 + pand mm3, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 + psrlq mm2, 1 // divide raw bytes by 2 + pand mm1, mm4 // clear invalid bit 7 of each byte + paddb mm0, mm3 // add LBCarrys to Avg for each byte + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm0, mm1 // add (Prev_row/2) to Avg for each byte + paddb mm0, mm2 // add (Raw/2) to Avg for each byte + cmp ebx, MMXLength + movq [edi + ebx - 8], mm0 + movq mm2, mm0 // reuse as Raw(x-bpp) + jb davg8lp + } // end _asm block + } + break; + default: // bpp greater than 8 + { + _asm { + movq mm5, LBCarryMask + // Re-init address pointers and offset + mov ebx, diff // ebx ==> x = offset to alignment boundary + mov edi, row // edi ==> Avg(x) + movq mm4, HBClearMask + mov edx, edi + mov esi, prev_row // esi ==> Prior(x) + sub edx, bpp // edx ==> Raw(x-bpp) +davgAlp: + movq mm0, [edi + ebx] + movq mm3, mm5 + movq mm1, [esi + ebx] + pand mm3, mm1 // get lsb for each prev_row byte + movq mm2, [edx + ebx] + psrlq mm1, 1 // divide prev_row bytes by 2 + pand mm3, mm2 // get LBCarrys for each byte where both + // lsb's were == 1 + psrlq mm2, 1 // divide raw bytes by 2 + pand mm1, mm4 // clear invalid bit 7 of each byte + paddb mm0, mm3 // add LBCarrys to Avg for each byte + pand mm2, mm4 // clear invalid bit 7 of each byte + paddb mm0, mm1 // add (Prev_row/2) to Avg for each byte + add ebx, 8 + paddb mm0, mm2 // add (Raw/2) to Avg for each byte + cmp ebx, MMXLength + movq [edi + ebx - 8], mm0 + jb davgAlp + } // end _asm block + } + break; + } // end switch ( bpp ) + + _asm { + // MMX acceleration complete now do clean-up + // Check if any remaining bytes left to decode + mov ebx, MMXLength // ebx ==> x = offset bytes remaining after MMX + mov edi, row // edi ==> Avg(x) + cmp ebx, FullLength // Test if offset at end of array + jnb davgend + // Do Paeth decode for remaining bytes + mov esi, prev_row // esi ==> Prior(x) + mov edx, edi + xor ecx, ecx // zero ecx before using cl & cx in loop below + sub edx, bpp // edx ==> Raw(x-bpp) +davglp2: + // Raw(x) = Avg(x) + ((Raw(x-bpp) + Prior(x))/2) + xor eax, eax + mov cl, [esi + ebx] // load cl with Prior(x) + mov al, [edx + ebx] // load al with Raw(x-bpp) + add ax, cx + inc ebx + shr ax, 1 // divide by 2 + add al, [edi+ebx-1] // Add Avg(x); -1 to offset inc ebx + cmp ebx, FullLength // Check if at end of array + mov [edi+ebx-1], al // Write back Raw(x); + // mov does not affect flags; -1 to offset inc ebx + jb davglp2 +davgend: + emms // End MMX instructions; prep for possible FP instrs. + } // end _asm block +} + +// Optimized code for PNG Paeth filter decoder +void /* PRIVATE */ +png_read_filter_row_mmx_paeth(png_row_infop row_info, png_bytep row, + png_bytep prev_row) +{ + png_uint_32 FullLength; + png_uint_32 MMXLength; + //png_uint_32 len; + int bpp; + int diff; + //int ptemp; + int patemp, pbtemp, pctemp; + + bpp = (row_info->pixel_depth + 7) >> 3; // Get # bytes per pixel + FullLength = row_info->rowbytes; // # of bytes to filter + _asm + { + xor ebx, ebx // ebx ==> x offset + mov edi, row + xor edx, edx // edx ==> x-bpp offset + mov esi, prev_row + xor eax, eax + + // Compute the Raw value for the first bpp bytes + // Note: the formula works out to be always + // Paeth(x) = Raw(x) + Prior(x) where x < bpp +dpthrlp: + mov al, [edi + ebx] + add al, [esi + ebx] + inc ebx + cmp ebx, bpp + mov [edi + ebx - 1], al + jb dpthrlp + // get # of bytes to alignment + mov diff, edi // take start of row + add diff, ebx // add bpp + xor ecx, ecx + add diff, 0xf // add 7 + 8 to incr past alignment boundary + and diff, 0xfffffff8 // mask to alignment boundary + sub diff, edi // subtract from start ==> value ebx at alignment + jz dpthgo + // fix alignment +dpthlp1: + xor eax, eax + // pav = p - a = (a + b - c) - a = b - c + mov al, [esi + ebx] // load Prior(x) into al + mov cl, [esi + edx] // load Prior(x-bpp) into cl + sub eax, ecx // subtract Prior(x-bpp) + mov patemp, eax // Save pav for later use + xor eax, eax + // pbv = p - b = (a + b - c) - b = a - c + mov al, [edi + edx] // load Raw(x-bpp) into al + sub eax, ecx // subtract Prior(x-bpp) + mov ecx, eax + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + add eax, patemp // pcv = pav + pbv + // pc = abs(pcv) + test eax, 0x80000000 + jz dpthpca + neg eax // reverse sign of neg values +dpthpca: + mov pctemp, eax // save pc for later use + // pb = abs(pbv) + test ecx, 0x80000000 + jz dpthpba + neg ecx // reverse sign of neg values +dpthpba: + mov pbtemp, ecx // save pb for later use + // pa = abs(pav) + mov eax, patemp + test eax, 0x80000000 + jz dpthpaa + neg eax // reverse sign of neg values +dpthpaa: + mov patemp, eax // save pa for later use + // test if pa <= pb + cmp eax, ecx + jna dpthabb + // pa > pb; now test if pb <= pc + cmp ecx, pctemp + jna dpthbbc + // pb > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + mov cl, [esi + edx] // load Prior(x-bpp) into cl + jmp dpthpaeth +dpthbbc: + // pb <= pc; Raw(x) = Paeth(x) + Prior(x) + mov cl, [esi + ebx] // load Prior(x) into cl + jmp dpthpaeth +dpthabb: + // pa <= pb; now test if pa <= pc + cmp eax, pctemp + jna dpthabc + // pa > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + mov cl, [esi + edx] // load Prior(x-bpp) into cl + jmp dpthpaeth +dpthabc: + // pa <= pc; Raw(x) = Paeth(x) + Raw(x-bpp) + mov cl, [edi + edx] // load Raw(x-bpp) into cl +dpthpaeth: + inc ebx + inc edx + // Raw(x) = (Paeth(x) + Paeth_Predictor( a, b, c )) mod 256 + add [edi + ebx - 1], cl + cmp ebx, diff + jb dpthlp1 +dpthgo: + mov ecx, FullLength + mov eax, ecx + sub eax, ebx // subtract alignment fix + and eax, 0x00000007 // calc bytes over mult of 8 + sub ecx, eax // drop over bytes from original length + mov MMXLength, ecx + } // end _asm block + // Now do the math for the rest of the row + switch ( bpp ) + { + case 3: + { + ActiveMask.use = 0x0000000000ffffff; + ActiveMaskEnd.use = 0xffff000000000000; + ShiftBpp.use = 24; // == bpp(3) * 8 + ShiftRem.use = 40; // == 64 - 24 + _asm + { + mov ebx, diff + mov edi, row + mov esi, prev_row + pxor mm0, mm0 + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm1, [edi+ebx-8] +dpth3lp: + psrlq mm1, ShiftRem // shift last 3 bytes to 1st 3 bytes + movq mm2, [esi + ebx] // load b=Prior(x) + punpcklbw mm1, mm0 // Unpack High bytes of a + movq mm3, [esi+ebx-8] // Prep c=Prior(x-bpp) bytes + punpcklbw mm2, mm0 // Unpack High bytes of b + psrlq mm3, ShiftRem // shift last 3 bytes to 1st 3 bytes + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + punpcklbw mm3, mm0 // Unpack High bytes of c + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + psubw mm4, mm3 + pxor mm7, mm7 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + movq mm6, mm4 + psubw mm5, mm3 + + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm4 // Create mask pav bytes < 0 + paddw mm6, mm5 + pand mm0, mm4 // Only pav bytes < 0 in mm7 + pcmpgtw mm7, mm5 // Create mask pbv bytes < 0 + psubw mm4, mm0 + pand mm7, mm5 // Only pbv bytes < 0 in mm0 + psubw mm4, mm0 + psubw mm5, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm5, mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + pandn mm7, mm4 + pandn mm0, mm1 + paddw mm7, mm5 + paddw mm0, mm2 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + pxor mm1, mm1 + pand mm3, mm7 + pandn mm7, mm0 + paddw mm7, mm3 + pxor mm0, mm0 + packuswb mm7, mm1 + movq mm3, [esi + ebx] // load c=Prior(x-bpp) + pand mm7, ActiveMask + movq mm2, mm3 // load b=Prior(x) step 1 + paddb mm7, [edi + ebx] // add Paeth predictor with Raw(x) + punpcklbw mm3, mm0 // Unpack High bytes of c + movq [edi + ebx], mm7 // write back updated value + movq mm1, mm7 // Now mm1 will be used as Raw(x-bpp) + // Now do Paeth for 2nd set of bytes (3-5) + psrlq mm2, ShiftBpp // load b=Prior(x) step 2 + punpcklbw mm1, mm0 // Unpack High bytes of a + pxor mm7, mm7 + punpcklbw mm2, mm0 // Unpack High bytes of b + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + psubw mm5, mm3 + psubw mm4, mm3 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = + // pav + pbv = pbv + pav + movq mm6, mm5 + paddw mm6, mm4 + + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm5 // Create mask pbv bytes < 0 + pcmpgtw mm7, mm4 // Create mask pav bytes < 0 + pand mm0, mm5 // Only pbv bytes < 0 in mm0 + pand mm7, mm4 // Only pav bytes < 0 in mm7 + psubw mm5, mm0 + psubw mm4, mm7 + psubw mm5, mm0 + psubw mm4, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + pandn mm7, mm4 + pandn mm0, mm1 + paddw mm7, mm5 + paddw mm0, mm2 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + movq mm2, [esi + ebx] // load b=Prior(x) + pand mm3, mm7 + pandn mm7, mm0 + pxor mm1, mm1 + paddw mm7, mm3 + pxor mm0, mm0 + packuswb mm7, mm1 + movq mm3, mm2 // load c=Prior(x-bpp) step 1 + pand mm7, ActiveMask + punpckhbw mm2, mm0 // Unpack High bytes of b + psllq mm7, ShiftBpp // Shift bytes to 2nd group of 3 bytes + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + paddb mm7, [edi + ebx] // add Paeth predictor with Raw(x) + psllq mm3, ShiftBpp // load c=Prior(x-bpp) step 2 + movq [edi + ebx], mm7 // write back updated value + movq mm1, mm7 + punpckhbw mm3, mm0 // Unpack High bytes of c + psllq mm1, ShiftBpp // Shift bytes + // Now mm1 will be used as Raw(x-bpp) + // Now do Paeth for 3rd, and final, set of bytes (6-7) + pxor mm7, mm7 + punpckhbw mm1, mm0 // Unpack High bytes of a + psubw mm4, mm3 + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + movq mm6, mm4 + psubw mm5, mm3 + pxor mm0, mm0 + paddw mm6, mm5 + + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm4 // Create mask pav bytes < 0 + pcmpgtw mm7, mm5 // Create mask pbv bytes < 0 + pand mm0, mm4 // Only pav bytes < 0 in mm7 + pand mm7, mm5 // Only pbv bytes < 0 in mm0 + psubw mm4, mm0 + psubw mm5, mm7 + psubw mm4, mm0 + psubw mm5, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + pandn mm0, mm1 + pandn mm7, mm4 + paddw mm0, mm2 + paddw mm7, mm5 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + pand mm3, mm7 + pandn mm7, mm0 + paddw mm7, mm3 + pxor mm1, mm1 + packuswb mm1, mm7 + // Step ebx to next set of 8 bytes and repeat loop til done + add ebx, 8 + pand mm1, ActiveMaskEnd + paddb mm1, [edi + ebx - 8] // add Paeth predictor with Raw(x) + + cmp ebx, MMXLength + pxor mm0, mm0 // pxor does not affect flags + movq [edi + ebx - 8], mm1 // write back updated value + // mm1 will be used as Raw(x-bpp) next loop + // mm3 ready to be used as Prior(x-bpp) next loop + jb dpth3lp + } // end _asm block + } + break; + + case 6: + case 7: + case 5: + { + ActiveMask.use = 0x00000000ffffffff; + ActiveMask2.use = 0xffffffff00000000; + ShiftBpp.use = bpp << 3; // == bpp * 8 + ShiftRem.use = 64 - ShiftBpp.use; + _asm + { + mov ebx, diff + mov edi, row + mov esi, prev_row + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm1, [edi+ebx-8] + pxor mm0, mm0 +dpth6lp: + // Must shift to position Raw(x-bpp) data + psrlq mm1, ShiftRem + // Do first set of 4 bytes + movq mm3, [esi+ebx-8] // read c=Prior(x-bpp) bytes + punpcklbw mm1, mm0 // Unpack Low bytes of a + movq mm2, [esi + ebx] // load b=Prior(x) + punpcklbw mm2, mm0 // Unpack Low bytes of b + // Must shift to position Prior(x-bpp) data + psrlq mm3, ShiftRem + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + punpcklbw mm3, mm0 // Unpack Low bytes of c + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + psubw mm4, mm3 + pxor mm7, mm7 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + movq mm6, mm4 + psubw mm5, mm3 + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm4 // Create mask pav bytes < 0 + paddw mm6, mm5 + pand mm0, mm4 // Only pav bytes < 0 in mm7 + pcmpgtw mm7, mm5 // Create mask pbv bytes < 0 + psubw mm4, mm0 + pand mm7, mm5 // Only pbv bytes < 0 in mm0 + psubw mm4, mm0 + psubw mm5, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm5, mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + pandn mm7, mm4 + pandn mm0, mm1 + paddw mm7, mm5 + paddw mm0, mm2 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + pxor mm1, mm1 + pand mm3, mm7 + pandn mm7, mm0 + paddw mm7, mm3 + pxor mm0, mm0 + packuswb mm7, mm1 + movq mm3, [esi + ebx - 8] // load c=Prior(x-bpp) + pand mm7, ActiveMask + psrlq mm3, ShiftRem + movq mm2, [esi + ebx] // load b=Prior(x) step 1 + paddb mm7, [edi + ebx] // add Paeth predictor with Raw(x) + movq mm6, mm2 + movq [edi + ebx], mm7 // write back updated value + movq mm1, [edi+ebx-8] + psllq mm6, ShiftBpp + movq mm5, mm7 + psrlq mm1, ShiftRem + por mm3, mm6 + psllq mm5, ShiftBpp + punpckhbw mm3, mm0 // Unpack High bytes of c + por mm1, mm5 + // Do second set of 4 bytes + punpckhbw mm2, mm0 // Unpack High bytes of b + punpckhbw mm1, mm0 // Unpack High bytes of a + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + psubw mm4, mm3 + pxor mm7, mm7 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + movq mm6, mm4 + psubw mm5, mm3 + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm4 // Create mask pav bytes < 0 + paddw mm6, mm5 + pand mm0, mm4 // Only pav bytes < 0 in mm7 + pcmpgtw mm7, mm5 // Create mask pbv bytes < 0 + psubw mm4, mm0 + pand mm7, mm5 // Only pbv bytes < 0 in mm0 + psubw mm4, mm0 + psubw mm5, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm5, mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + pandn mm7, mm4 + pandn mm0, mm1 + paddw mm7, mm5 + paddw mm0, mm2 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + pxor mm1, mm1 + pand mm3, mm7 + pandn mm7, mm0 + pxor mm1, mm1 + paddw mm7, mm3 + pxor mm0, mm0 + // Step ex to next set of 8 bytes and repeat loop til done + add ebx, 8 + packuswb mm1, mm7 + paddb mm1, [edi + ebx - 8] // add Paeth predictor with Raw(x) + cmp ebx, MMXLength + movq [edi + ebx - 8], mm1 // write back updated value + // mm1 will be used as Raw(x-bpp) next loop + jb dpth6lp + } // end _asm block + } + break; + + case 4: + { + ActiveMask.use = 0x00000000ffffffff; + _asm { + mov ebx, diff + mov edi, row + mov esi, prev_row + pxor mm0, mm0 + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm1, [edi+ebx-8] // Only time should need to read + // a=Raw(x-bpp) bytes +dpth4lp: + // Do first set of 4 bytes + movq mm3, [esi+ebx-8] // read c=Prior(x-bpp) bytes + punpckhbw mm1, mm0 // Unpack Low bytes of a + movq mm2, [esi + ebx] // load b=Prior(x) + punpcklbw mm2, mm0 // Unpack High bytes of b + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + punpckhbw mm3, mm0 // Unpack High bytes of c + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + psubw mm4, mm3 + pxor mm7, mm7 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + movq mm6, mm4 + psubw mm5, mm3 + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm4 // Create mask pav bytes < 0 + paddw mm6, mm5 + pand mm0, mm4 // Only pav bytes < 0 in mm7 + pcmpgtw mm7, mm5 // Create mask pbv bytes < 0 + psubw mm4, mm0 + pand mm7, mm5 // Only pbv bytes < 0 in mm0 + psubw mm4, mm0 + psubw mm5, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm5, mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + pandn mm7, mm4 + pandn mm0, mm1 + paddw mm7, mm5 + paddw mm0, mm2 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + pxor mm1, mm1 + pand mm3, mm7 + pandn mm7, mm0 + paddw mm7, mm3 + pxor mm0, mm0 + packuswb mm7, mm1 + movq mm3, [esi + ebx] // load c=Prior(x-bpp) + pand mm7, ActiveMask + movq mm2, mm3 // load b=Prior(x) step 1 + paddb mm7, [edi + ebx] // add Paeth predictor with Raw(x) + punpcklbw mm3, mm0 // Unpack High bytes of c + movq [edi + ebx], mm7 // write back updated value + movq mm1, mm7 // Now mm1 will be used as Raw(x-bpp) + // Do second set of 4 bytes + punpckhbw mm2, mm0 // Unpack Low bytes of b + punpcklbw mm1, mm0 // Unpack Low bytes of a + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + psubw mm4, mm3 + pxor mm7, mm7 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + movq mm6, mm4 + psubw mm5, mm3 + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm4 // Create mask pav bytes < 0 + paddw mm6, mm5 + pand mm0, mm4 // Only pav bytes < 0 in mm7 + pcmpgtw mm7, mm5 // Create mask pbv bytes < 0 + psubw mm4, mm0 + pand mm7, mm5 // Only pbv bytes < 0 in mm0 + psubw mm4, mm0 + psubw mm5, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm5, mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + pandn mm7, mm4 + pandn mm0, mm1 + paddw mm7, mm5 + paddw mm0, mm2 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + pxor mm1, mm1 + pand mm3, mm7 + pandn mm7, mm0 + pxor mm1, mm1 + paddw mm7, mm3 + pxor mm0, mm0 + // Step ex to next set of 8 bytes and repeat loop til done + add ebx, 8 + packuswb mm1, mm7 + paddb mm1, [edi + ebx - 8] // add Paeth predictor with Raw(x) + cmp ebx, MMXLength + movq [edi + ebx - 8], mm1 // write back updated value + // mm1 will be used as Raw(x-bpp) next loop + jb dpth4lp + } // end _asm block + } + break; + case 8: // bpp == 8 + { + ActiveMask.use = 0x00000000ffffffff; + _asm { + mov ebx, diff + mov edi, row + mov esi, prev_row + pxor mm0, mm0 + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm1, [edi+ebx-8] // Only time should need to read + // a=Raw(x-bpp) bytes +dpth8lp: + // Do first set of 4 bytes + movq mm3, [esi+ebx-8] // read c=Prior(x-bpp) bytes + punpcklbw mm1, mm0 // Unpack Low bytes of a + movq mm2, [esi + ebx] // load b=Prior(x) + punpcklbw mm2, mm0 // Unpack Low bytes of b + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + punpcklbw mm3, mm0 // Unpack Low bytes of c + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + psubw mm4, mm3 + pxor mm7, mm7 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + movq mm6, mm4 + psubw mm5, mm3 + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm4 // Create mask pav bytes < 0 + paddw mm6, mm5 + pand mm0, mm4 // Only pav bytes < 0 in mm7 + pcmpgtw mm7, mm5 // Create mask pbv bytes < 0 + psubw mm4, mm0 + pand mm7, mm5 // Only pbv bytes < 0 in mm0 + psubw mm4, mm0 + psubw mm5, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm5, mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + pandn mm7, mm4 + pandn mm0, mm1 + paddw mm7, mm5 + paddw mm0, mm2 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + pxor mm1, mm1 + pand mm3, mm7 + pandn mm7, mm0 + paddw mm7, mm3 + pxor mm0, mm0 + packuswb mm7, mm1 + movq mm3, [esi+ebx-8] // read c=Prior(x-bpp) bytes + pand mm7, ActiveMask + movq mm2, [esi + ebx] // load b=Prior(x) + paddb mm7, [edi + ebx] // add Paeth predictor with Raw(x) + punpckhbw mm3, mm0 // Unpack High bytes of c + movq [edi + ebx], mm7 // write back updated value + movq mm1, [edi+ebx-8] // read a=Raw(x-bpp) bytes + + // Do second set of 4 bytes + punpckhbw mm2, mm0 // Unpack High bytes of b + punpckhbw mm1, mm0 // Unpack High bytes of a + // pav = p - a = (a + b - c) - a = b - c + movq mm4, mm2 + // pbv = p - b = (a + b - c) - b = a - c + movq mm5, mm1 + psubw mm4, mm3 + pxor mm7, mm7 + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + movq mm6, mm4 + psubw mm5, mm3 + // pa = abs(p-a) = abs(pav) + // pb = abs(p-b) = abs(pbv) + // pc = abs(p-c) = abs(pcv) + pcmpgtw mm0, mm4 // Create mask pav bytes < 0 + paddw mm6, mm5 + pand mm0, mm4 // Only pav bytes < 0 in mm7 + pcmpgtw mm7, mm5 // Create mask pbv bytes < 0 + psubw mm4, mm0 + pand mm7, mm5 // Only pbv bytes < 0 in mm0 + psubw mm4, mm0 + psubw mm5, mm7 + pxor mm0, mm0 + pcmpgtw mm0, mm6 // Create mask pcv bytes < 0 + pand mm0, mm6 // Only pav bytes < 0 in mm7 + psubw mm5, mm7 + psubw mm6, mm0 + // test pa <= pb + movq mm7, mm4 + psubw mm6, mm0 + pcmpgtw mm7, mm5 // pa > pb? + movq mm0, mm7 + // use mm7 mask to merge pa & pb + pand mm5, mm7 + // use mm0 mask copy to merge a & b + pand mm2, mm0 + pandn mm7, mm4 + pandn mm0, mm1 + paddw mm7, mm5 + paddw mm0, mm2 + // test ((pa <= pb)? pa:pb) <= pc + pcmpgtw mm7, mm6 // pab > pc? + pxor mm1, mm1 + pand mm3, mm7 + pandn mm7, mm0 + pxor mm1, mm1 + paddw mm7, mm3 + pxor mm0, mm0 + // Step ex to next set of 8 bytes and repeat loop til done + add ebx, 8 + packuswb mm1, mm7 + paddb mm1, [edi + ebx - 8] // add Paeth predictor with Raw(x) + cmp ebx, MMXLength + movq [edi + ebx - 8], mm1 // write back updated value + // mm1 will be used as Raw(x-bpp) next loop + jb dpth8lp + } // end _asm block + } + break; + + case 1: // bpp = 1 + case 2: // bpp = 2 + default: // bpp > 8 + { + _asm { + mov ebx, diff + cmp ebx, FullLength + jnb dpthdend + mov edi, row + mov esi, prev_row + // Do Paeth decode for remaining bytes + mov edx, ebx + xor ecx, ecx // zero ecx before using cl & cx in loop below + sub edx, bpp // Set edx = ebx - bpp +dpthdlp: + xor eax, eax + // pav = p - a = (a + b - c) - a = b - c + mov al, [esi + ebx] // load Prior(x) into al + mov cl, [esi + edx] // load Prior(x-bpp) into cl + sub eax, ecx // subtract Prior(x-bpp) + mov patemp, eax // Save pav for later use + xor eax, eax + // pbv = p - b = (a + b - c) - b = a - c + mov al, [edi + edx] // load Raw(x-bpp) into al + sub eax, ecx // subtract Prior(x-bpp) + mov ecx, eax + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + add eax, patemp // pcv = pav + pbv + // pc = abs(pcv) + test eax, 0x80000000 + jz dpthdpca + neg eax // reverse sign of neg values +dpthdpca: + mov pctemp, eax // save pc for later use + // pb = abs(pbv) + test ecx, 0x80000000 + jz dpthdpba + neg ecx // reverse sign of neg values +dpthdpba: + mov pbtemp, ecx // save pb for later use + // pa = abs(pav) + mov eax, patemp + test eax, 0x80000000 + jz dpthdpaa + neg eax // reverse sign of neg values +dpthdpaa: + mov patemp, eax // save pa for later use + // test if pa <= pb + cmp eax, ecx + jna dpthdabb + // pa > pb; now test if pb <= pc + cmp ecx, pctemp + jna dpthdbbc + // pb > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + mov cl, [esi + edx] // load Prior(x-bpp) into cl + jmp dpthdpaeth +dpthdbbc: + // pb <= pc; Raw(x) = Paeth(x) + Prior(x) + mov cl, [esi + ebx] // load Prior(x) into cl + jmp dpthdpaeth +dpthdabb: + // pa <= pb; now test if pa <= pc + cmp eax, pctemp + jna dpthdabc + // pa > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + mov cl, [esi + edx] // load Prior(x-bpp) into cl + jmp dpthdpaeth +dpthdabc: + // pa <= pc; Raw(x) = Paeth(x) + Raw(x-bpp) + mov cl, [edi + edx] // load Raw(x-bpp) into cl +dpthdpaeth: + inc ebx + inc edx + // Raw(x) = (Paeth(x) + Paeth_Predictor( a, b, c )) mod 256 + add [edi + ebx - 1], cl + cmp ebx, FullLength + jb dpthdlp +dpthdend: + } // end _asm block + } + return; // No need to go further with this one + } // end switch ( bpp ) + _asm + { + // MMX acceleration complete now do clean-up + // Check if any remaining bytes left to decode + mov ebx, MMXLength + cmp ebx, FullLength + jnb dpthend + mov edi, row + mov esi, prev_row + // Do Paeth decode for remaining bytes + mov edx, ebx + xor ecx, ecx // zero ecx before using cl & cx in loop below + sub edx, bpp // Set edx = ebx - bpp +dpthlp2: + xor eax, eax + // pav = p - a = (a + b - c) - a = b - c + mov al, [esi + ebx] // load Prior(x) into al + mov cl, [esi + edx] // load Prior(x-bpp) into cl + sub eax, ecx // subtract Prior(x-bpp) + mov patemp, eax // Save pav for later use + xor eax, eax + // pbv = p - b = (a + b - c) - b = a - c + mov al, [edi + edx] // load Raw(x-bpp) into al + sub eax, ecx // subtract Prior(x-bpp) + mov ecx, eax + // pcv = p - c = (a + b - c) -c = (a - c) + (b - c) = pav + pbv + add eax, patemp // pcv = pav + pbv + // pc = abs(pcv) + test eax, 0x80000000 + jz dpthpca2 + neg eax // reverse sign of neg values +dpthpca2: + mov pctemp, eax // save pc for later use + // pb = abs(pbv) + test ecx, 0x80000000 + jz dpthpba2 + neg ecx // reverse sign of neg values +dpthpba2: + mov pbtemp, ecx // save pb for later use + // pa = abs(pav) + mov eax, patemp + test eax, 0x80000000 + jz dpthpaa2 + neg eax // reverse sign of neg values +dpthpaa2: + mov patemp, eax // save pa for later use + // test if pa <= pb + cmp eax, ecx + jna dpthabb2 + // pa > pb; now test if pb <= pc + cmp ecx, pctemp + jna dpthbbc2 + // pb > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + mov cl, [esi + edx] // load Prior(x-bpp) into cl + jmp dpthpaeth2 +dpthbbc2: + // pb <= pc; Raw(x) = Paeth(x) + Prior(x) + mov cl, [esi + ebx] // load Prior(x) into cl + jmp dpthpaeth2 +dpthabb2: + // pa <= pb; now test if pa <= pc + cmp eax, pctemp + jna dpthabc2 + // pa > pc; Raw(x) = Paeth(x) + Prior(x-bpp) + mov cl, [esi + edx] // load Prior(x-bpp) into cl + jmp dpthpaeth2 +dpthabc2: + // pa <= pc; Raw(x) = Paeth(x) + Raw(x-bpp) + mov cl, [edi + edx] // load Raw(x-bpp) into cl +dpthpaeth2: + inc ebx + inc edx + // Raw(x) = (Paeth(x) + Paeth_Predictor( a, b, c )) mod 256 + add [edi + ebx - 1], cl + cmp ebx, FullLength + jb dpthlp2 +dpthend: + emms // End MMX instructions; prep for possible FP instrs. + } // end _asm block +} + +// Optimized code for PNG Sub filter decoder +void /* PRIVATE */ +png_read_filter_row_mmx_sub(png_row_infop row_info, png_bytep row) +{ + //int test; + int bpp; + png_uint_32 FullLength; + png_uint_32 MMXLength; + int diff; + + bpp = (row_info->pixel_depth + 7) >> 3; // Get # bytes per pixel + FullLength = row_info->rowbytes - bpp; // # of bytes to filter + _asm { + mov edi, row + mov esi, edi // lp = row + add edi, bpp // rp = row + bpp + xor eax, eax + // get # of bytes to alignment + mov diff, edi // take start of row + add diff, 0xf // add 7 + 8 to incr past + // alignment boundary + xor ebx, ebx + and diff, 0xfffffff8 // mask to alignment boundary + sub diff, edi // subtract from start ==> value + // ebx at alignment + jz dsubgo + // fix alignment +dsublp1: + mov al, [esi+ebx] + add [edi+ebx], al + inc ebx + cmp ebx, diff + jb dsublp1 +dsubgo: + mov ecx, FullLength + mov edx, ecx + sub edx, ebx // subtract alignment fix + and edx, 0x00000007 // calc bytes over mult of 8 + sub ecx, edx // drop over bytes from length + mov MMXLength, ecx + } // end _asm block + + // Now do the math for the rest of the row + switch ( bpp ) + { + case 3: + { + ActiveMask.use = 0x0000ffffff000000; + ShiftBpp.use = 24; // == 3 * 8 + ShiftRem.use = 40; // == 64 - 24 + _asm { + mov edi, row + movq mm7, ActiveMask // Load ActiveMask for 2nd active byte group + mov esi, edi // lp = row + add edi, bpp // rp = row + bpp + movq mm6, mm7 + mov ebx, diff + psllq mm6, ShiftBpp // Move mask in mm6 to cover 3rd active + // byte group + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm1, [edi+ebx-8] +dsub3lp: + psrlq mm1, ShiftRem // Shift data for adding 1st bpp bytes + // no need for mask; shift clears inactive bytes + // Add 1st active group + movq mm0, [edi+ebx] + paddb mm0, mm1 + // Add 2nd active group + movq mm1, mm0 // mov updated Raws to mm1 + psllq mm1, ShiftBpp // shift data to position correctly + pand mm1, mm7 // mask to use only 2nd active group + paddb mm0, mm1 + // Add 3rd active group + movq mm1, mm0 // mov updated Raws to mm1 + psllq mm1, ShiftBpp // shift data to position correctly + pand mm1, mm6 // mask to use only 3rd active group + add ebx, 8 + paddb mm0, mm1 + cmp ebx, MMXLength + movq [edi+ebx-8], mm0 // Write updated Raws back to array + // Prep for doing 1st add at top of loop + movq mm1, mm0 + jb dsub3lp + } // end _asm block + } + break; + + case 1: + { + // Placed here just in case this is a duplicate of the + // non-MMX code for the SUB filter in png_read_filter_row below + // + // png_bytep rp; + // png_bytep lp; + // png_uint_32 i; + // bpp = (row_info->pixel_depth + 7) >> 3; + // for (i = (png_uint_32)bpp, rp = row + bpp, lp = row; + // i < row_info->rowbytes; i++, rp++, lp++) + // { + // *rp = (png_byte)(((int)(*rp) + (int)(*lp)) & 0xff); + // } + _asm { + mov ebx, diff + mov edi, row + cmp ebx, FullLength + jnb dsub1end + mov esi, edi // lp = row + xor eax, eax + add edi, bpp // rp = row + bpp +dsub1lp: + mov al, [esi+ebx] + add [edi+ebx], al + inc ebx + cmp ebx, FullLength + jb dsub1lp +dsub1end: + } // end _asm block + } + return; + + case 6: + case 7: + case 4: + case 5: + { + ShiftBpp.use = bpp << 3; + ShiftRem.use = 64 - ShiftBpp.use; + _asm { + mov edi, row + mov ebx, diff + mov esi, edi // lp = row + add edi, bpp // rp = row + bpp + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm1, [edi+ebx-8] +dsub4lp: + psrlq mm1, ShiftRem // Shift data for adding 1st bpp bytes + // no need for mask; shift clears inactive bytes + movq mm0, [edi+ebx] + paddb mm0, mm1 + // Add 2nd active group + movq mm1, mm0 // mov updated Raws to mm1 + psllq mm1, ShiftBpp // shift data to position correctly + // there is no need for any mask + // since shift clears inactive bits/bytes + add ebx, 8 + paddb mm0, mm1 + cmp ebx, MMXLength + movq [edi+ebx-8], mm0 + movq mm1, mm0 // Prep for doing 1st add at top of loop + jb dsub4lp + } // end _asm block + } + break; + + case 2: + { + ActiveMask.use = 0x00000000ffff0000; + ShiftBpp.use = 16; // == 2 * 8 + ShiftRem.use = 48; // == 64 - 16 + _asm { + movq mm7, ActiveMask // Load ActiveMask for 2nd active byte group + mov ebx, diff + movq mm6, mm7 + mov edi, row + psllq mm6, ShiftBpp // Move mask in mm6 to cover 3rd active + // byte group + mov esi, edi // lp = row + movq mm5, mm6 + add edi, bpp // rp = row + bpp + psllq mm5, ShiftBpp // Move mask in mm5 to cover 4th active + // byte group + // PRIME the pump (load the first Raw(x-bpp) data set + movq mm1, [edi+ebx-8] +dsub2lp: + // Add 1st active group + psrlq mm1, ShiftRem // Shift data for adding 1st bpp bytes + // no need for mask; shift clears inactive + // bytes + movq mm0, [edi+ebx] + paddb mm0, mm1 + // Add 2nd active group + movq mm1, mm0 // mov updated Raws to mm1 + psllq mm1, ShiftBpp // shift data to position correctly + pand mm1, mm7 // mask to use only 2nd active group + paddb mm0, mm1 + // Add 3rd active group + movq mm1, mm0 // mov updated Raws to mm1 + psllq mm1, ShiftBpp // shift data to position correctly + pand mm1, mm6 // mask to use only 3rd active group + paddb mm0, mm1 + // Add 4th active group + movq mm1, mm0 // mov updated Raws to mm1 + psllq mm1, ShiftBpp // shift data to position correctly + pand mm1, mm5 // mask to use only 4th active group + add ebx, 8 + paddb mm0, mm1 + cmp ebx, MMXLength + movq [edi+ebx-8], mm0 // Write updated Raws back to array + movq mm1, mm0 // Prep for doing 1st add at top of loop + jb dsub2lp + } // end _asm block + } + break; + case 8: + { + _asm { + mov edi, row + mov ebx, diff + mov esi, edi // lp = row + add edi, bpp // rp = row + bpp + mov ecx, MMXLength + movq mm7, [edi+ebx-8] // PRIME the pump (load the first + // Raw(x-bpp) data set + and ecx, 0x0000003f // calc bytes over mult of 64 +dsub8lp: + movq mm0, [edi+ebx] // Load Sub(x) for 1st 8 bytes + paddb mm0, mm7 + movq mm1, [edi+ebx+8] // Load Sub(x) for 2nd 8 bytes + movq [edi+ebx], mm0 // Write Raw(x) for 1st 8 bytes + // Now mm0 will be used as Raw(x-bpp) for + // the 2nd group of 8 bytes. This will be + // repeated for each group of 8 bytes with + // the 8th group being used as the Raw(x-bpp) + // for the 1st group of the next loop. + paddb mm1, mm0 + movq mm2, [edi+ebx+16] // Load Sub(x) for 3rd 8 bytes + movq [edi+ebx+8], mm1 // Write Raw(x) for 2nd 8 bytes + paddb mm2, mm1 + movq mm3, [edi+ebx+24] // Load Sub(x) for 4th 8 bytes + movq [edi+ebx+16], mm2 // Write Raw(x) for 3rd 8 bytes + paddb mm3, mm2 + movq mm4, [edi+ebx+32] // Load Sub(x) for 5th 8 bytes + movq [edi+ebx+24], mm3 // Write Raw(x) for 4th 8 bytes + paddb mm4, mm3 + movq mm5, [edi+ebx+40] // Load Sub(x) for 6th 8 bytes + movq [edi+ebx+32], mm4 // Write Raw(x) for 5th 8 bytes + paddb mm5, mm4 + movq mm6, [edi+ebx+48] // Load Sub(x) for 7th 8 bytes + movq [edi+ebx+40], mm5 // Write Raw(x) for 6th 8 bytes + paddb mm6, mm5 + movq mm7, [edi+ebx+56] // Load Sub(x) for 8th 8 bytes + movq [edi+ebx+48], mm6 // Write Raw(x) for 7th 8 bytes + add ebx, 64 + paddb mm7, mm6 + cmp ebx, ecx + movq [edi+ebx-8], mm7 // Write Raw(x) for 8th 8 bytes + jb dsub8lp + cmp ebx, MMXLength + jnb dsub8lt8 +dsub8lpA: + movq mm0, [edi+ebx] + add ebx, 8 + paddb mm0, mm7 + cmp ebx, MMXLength + movq [edi+ebx-8], mm0 // use -8 to offset early add to ebx + movq mm7, mm0 // Move calculated Raw(x) data to mm1 to + // be the new Raw(x-bpp) for the next loop + jb dsub8lpA +dsub8lt8: + } // end _asm block + } + break; + + default: // bpp greater than 8 bytes + { + _asm { + mov ebx, diff + mov edi, row + mov esi, edi // lp = row + add edi, bpp // rp = row + bpp +dsubAlp: + movq mm0, [edi+ebx] + movq mm1, [esi+ebx] + add ebx, 8 + paddb mm0, mm1 + cmp ebx, MMXLength + movq [edi+ebx-8], mm0 // mov does not affect flags; -8 to offset + // add ebx + jb dsubAlp + } // end _asm block + } + break; + + } // end switch ( bpp ) + + _asm { + mov ebx, MMXLength + mov edi, row + cmp ebx, FullLength + jnb dsubend + mov esi, edi // lp = row + xor eax, eax + add edi, bpp // rp = row + bpp +dsublp2: + mov al, [esi+ebx] + add [edi+ebx], al + inc ebx + cmp ebx, FullLength + jb dsublp2 +dsubend: + emms // End MMX instructions; prep for possible FP instrs. + } // end _asm block +} + +// Optimized code for PNG Up filter decoder +void /* PRIVATE */ +png_read_filter_row_mmx_up(png_row_infop row_info, png_bytep row, + png_bytep prev_row) +{ + png_uint_32 len; + len = row_info->rowbytes; // # of bytes to filter + _asm { + mov edi, row + // get # of bytes to alignment + mov ecx, edi + xor ebx, ebx + add ecx, 0x7 + xor eax, eax + and ecx, 0xfffffff8 + mov esi, prev_row + sub ecx, edi + jz dupgo + // fix alignment +duplp1: + mov al, [edi+ebx] + add al, [esi+ebx] + inc ebx + cmp ebx, ecx + mov [edi + ebx-1], al // mov does not affect flags; -1 to offset inc ebx + jb duplp1 +dupgo: + mov ecx, len + mov edx, ecx + sub edx, ebx // subtract alignment fix + and edx, 0x0000003f // calc bytes over mult of 64 + sub ecx, edx // drop over bytes from length + // Unrolled loop - use all MMX registers and interleave to reduce + // number of branch instructions (loops) and reduce partial stalls +duploop: + movq mm1, [esi+ebx] + movq mm0, [edi+ebx] + movq mm3, [esi+ebx+8] + paddb mm0, mm1 + movq mm2, [edi+ebx+8] + movq [edi+ebx], mm0 + paddb mm2, mm3 + movq mm5, [esi+ebx+16] + movq [edi+ebx+8], mm2 + movq mm4, [edi+ebx+16] + movq mm7, [esi+ebx+24] + paddb mm4, mm5 + movq mm6, [edi+ebx+24] + movq [edi+ebx+16], mm4 + paddb mm6, mm7 + movq mm1, [esi+ebx+32] + movq [edi+ebx+24], mm6 + movq mm0, [edi+ebx+32] + movq mm3, [esi+ebx+40] + paddb mm0, mm1 + movq mm2, [edi+ebx+40] + movq [edi+ebx+32], mm0 + paddb mm2, mm3 + movq mm5, [esi+ebx+48] + movq [edi+ebx+40], mm2 + movq mm4, [edi+ebx+48] + movq mm7, [esi+ebx+56] + paddb mm4, mm5 + movq mm6, [edi+ebx+56] + movq [edi+ebx+48], mm4 + add ebx, 64 + paddb mm6, mm7 + cmp ebx, ecx + movq [edi+ebx-8], mm6 // (+56)movq does not affect flags; + // -8 to offset add ebx + jb duploop + + cmp edx, 0 // Test for bytes over mult of 64 + jz dupend + + + // 2 lines added by lcreeve@netins.net + // (mail 11 Jul 98 in png-implement list) + cmp edx, 8 //test for less than 8 bytes + jb duplt8 + + + add ecx, edx + and edx, 0x00000007 // calc bytes over mult of 8 + sub ecx, edx // drop over bytes from length + jz duplt8 + // Loop using MMX registers mm0 & mm1 to update 8 bytes simultaneously +duplpA: + movq mm1, [esi+ebx] + movq mm0, [edi+ebx] + add ebx, 8 + paddb mm0, mm1 + cmp ebx, ecx + movq [edi+ebx-8], mm0 // movq does not affect flags; -8 to offset add ebx + jb duplpA + cmp edx, 0 // Test for bytes over mult of 8 + jz dupend +duplt8: + xor eax, eax + add ecx, edx // move over byte count into counter + // Loop using x86 registers to update remaining bytes +duplp2: + mov al, [edi + ebx] + add al, [esi + ebx] + inc ebx + cmp ebx, ecx + mov [edi + ebx-1], al // mov does not affect flags; -1 to offset inc ebx + jb duplp2 +dupend: + // Conversion of filtered row completed + emms // End MMX instructions; prep for possible FP instrs. + } // end _asm block +} + + +// Optimized png_read_filter_row routines +void /* PRIVATE */ +png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep + row, png_bytep prev_row, int filter) +{ +#ifdef PNG_DEBUG + char filnm[10]; +#endif + + if (mmx_supported == 2) { +#if !defined(PNG_1_0_X) + /* this should have happened in png_init_mmx_flags() already */ + png_warning(png_ptr, "asm_flags may not have been initialized"); +#endif + png_mmx_support(); + } + +#ifdef PNG_DEBUG + png_debug(1, "in png_read_filter_row\n"); + switch (filter) + { + case 0: sprintf(filnm, "none"); + break; +#if !defined(PNG_1_0_X) + case 1: sprintf(filnm, "sub-%s", + (png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_SUB)? "MMX" : "x86"); + break; + case 2: sprintf(filnm, "up-%s", + (png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_UP)? "MMX" : "x86"); + break; + case 3: sprintf(filnm, "avg-%s", + (png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_AVG)? "MMX" : "x86"); + break; + case 4: sprintf(filnm, "Paeth-%s", + (png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_PAETH)? "MMX":"x86"); + break; +#else + case 1: sprintf(filnm, "sub"); + break; + case 2: sprintf(filnm, "up"); + break; + case 3: sprintf(filnm, "avg"); + break; + case 4: sprintf(filnm, "Paeth"); + break; +#endif + default: sprintf(filnm, "unknw"); + break; + } + png_debug2(0,"row=%5d, %s, ", png_ptr->row_number, filnm); + png_debug2(0, "pd=%2d, b=%d, ", (int)row_info->pixel_depth, + (int)((row_info->pixel_depth + 7) >> 3)); + png_debug1(0,"len=%8d, ", row_info->rowbytes); +#endif /* PNG_DEBUG */ + + switch (filter) + { + case PNG_FILTER_VALUE_NONE: + break; + + case PNG_FILTER_VALUE_SUB: + { +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_SUB) && + (row_info->pixel_depth >= png_ptr->mmx_bitdepth_threshold) && + (row_info->rowbytes >= png_ptr->mmx_rowbytes_threshold)) +#else + if (mmx_supported) +#endif + { + png_read_filter_row_mmx_sub(row_info, row); + } + else + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_bytep rp = row + bpp; + png_bytep lp = row; + + for (i = bpp; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff); + rp++; + } + } + break; + } + + case PNG_FILTER_VALUE_UP: + { +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_UP) && + (row_info->pixel_depth >= png_ptr->mmx_bitdepth_threshold) && + (row_info->rowbytes >= png_ptr->mmx_rowbytes_threshold)) +#else + if (mmx_supported) +#endif + { + png_read_filter_row_mmx_up(row_info, row, prev_row); + } + else + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_bytep rp = row; + png_bytep pp = prev_row; + + for (i = 0; i < istop; ++i) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + } + break; + } + + case PNG_FILTER_VALUE_AVG: + { +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_AVG) && + (row_info->pixel_depth >= png_ptr->mmx_bitdepth_threshold) && + (row_info->rowbytes >= png_ptr->mmx_rowbytes_threshold)) +#else + if (mmx_supported) +#endif + { + png_read_filter_row_mmx_avg(row_info, row, prev_row); + } + else + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop = row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + + ((int)(*pp++) >> 1)) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + + ((int)(*pp++ + *lp++) >> 1)) & 0xff); + rp++; + } + } + break; + } + + case PNG_FILTER_VALUE_PAETH: + { +#if !defined(PNG_1_0_X) + if ((png_ptr->asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_PAETH) && + (row_info->pixel_depth >= png_ptr->mmx_bitdepth_threshold) && + (row_info->rowbytes >= png_ptr->mmx_rowbytes_threshold)) +#else + if (mmx_supported) +#endif + { + png_read_filter_row_mmx_paeth(row_info, row, prev_row); + } + else + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_bytep cp = prev_row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop=row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) // use leftover rp,pp + { + int a, b, c, pa, pb, pc, p; + + a = *lp++; + b = *pp++; + c = *cp++; + + p = b - c; + pc = a - c; + +#ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +#else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +#endif + + /* + if (pa <= pb && pa <= pc) + p = a; + else if (pb <= pc) + p = b; + else + p = c; + */ + + p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c; + + *rp = (png_byte)(((int)(*rp) + p) & 0xff); + rp++; + } + } + break; + } + + default: + png_warning(png_ptr, "Ignoring bad row filter type"); + *row=0; + break; + } +} + +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED && PNG_USE_PNGVCRD */ diff --git a/SlnkDWFImpl/CxImage/png/pngwio.c b/SlnkDWFImpl/CxImage/png/pngwio.c new file mode 100644 index 0000000..cb3ac78 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngwio.c @@ -0,0 +1,228 @@ + +/* pngwio.c - functions for data output + * + * libpng 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * + * This file provides a location for all output. Users who need + * special handling are expected to write functions that have the same + * arguments as these and perform similar functions, but that possibly + * use different output methods. Note that you shouldn't change these + * functions, but rather write replacement functions and then change + * them at run time with png_set_write_fn(...). + */ + +#define PNG_INTERNAL +#include "png.h" +#ifdef PNG_WRITE_SUPPORTED + +/* Write the data to whatever output you are using. The default routine + writes to a file pointer. Note that this routine sometimes gets called + with very small lengths, so you should implement some kind of simple + buffering if you are using unbuffered writes. This should never be asked + to write more than 64K on a 16 bit machine. */ + +void /* PRIVATE */ +png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) +{ + if (png_ptr->write_data_fn != NULL ) + (*(png_ptr->write_data_fn))(png_ptr, data, length); + else + png_error(png_ptr, "Call to NULL write function"); +} + +#if !defined(PNG_NO_STDIO) +/* This is the function that does the actual writing of data. If you are + not writing to a standard C stream, you should create a replacement + write_data function and use it at run time with png_set_write_fn(), rather + than changing the library. */ +#ifndef USE_FAR_KEYWORD +void PNGAPI +png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length) +{ + png_uint_32 check; + +#if defined(_WIN32_WCE) + if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) ) + check = 0; +#else + check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr)); +#endif + if (check != length) + png_error(png_ptr, "Write Error"); +} +#else +/* this is the model-independent version. Since the standard I/O library + can't handle far buffers in the medium and small models, we have to copy + the data. +*/ + +#define NEAR_BUF_SIZE 1024 +#define MIN(a,b) (a <= b ? a : b) + +void PNGAPI +png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length) +{ + png_uint_32 check; + png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */ + png_FILE_p io_ptr; + + /* Check if data really is near. If so, use usual code. */ + near_data = (png_byte *)CVT_PTR_NOCHECK(data); + io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr); + if ((png_bytep)near_data == data) + { +#if defined(_WIN32_WCE) + if ( !WriteFile(io_ptr, near_data, length, &check, NULL) ) + check = 0; +#else + check = fwrite(near_data, 1, length, io_ptr); +#endif + } + else + { + png_byte buf[NEAR_BUF_SIZE]; + png_size_t written, remaining, err; + check = 0; + remaining = length; + do + { + written = MIN(NEAR_BUF_SIZE, remaining); + png_memcpy(buf, data, written); /* copy far buffer to near buffer */ +#if defined(_WIN32_WCE) + if ( !WriteFile(io_ptr, buf, written, &err, NULL) ) + err = 0; +#else + err = fwrite(buf, 1, written, io_ptr); +#endif + if (err != written) + break; + else + check += err; + data += written; + remaining -= written; + } + while (remaining != 0); + } + if (check != length) + png_error(png_ptr, "Write Error"); +} + +#endif +#endif + +/* This function is called to output any data pending writing (normally + to disk). After png_flush is called, there should be no data pending + writing in any buffers. */ +#if defined(PNG_WRITE_FLUSH_SUPPORTED) +void /* PRIVATE */ +png_flush(png_structp png_ptr) +{ + if (png_ptr->output_flush_fn != NULL) + (*(png_ptr->output_flush_fn))(png_ptr); +} + +#if !defined(PNG_NO_STDIO) +void PNGAPI +png_default_flush(png_structp png_ptr) +{ +#if !defined(_WIN32_WCE) + png_FILE_p io_ptr; + io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr)); + if (io_ptr != NULL) + fflush(io_ptr); +#endif +} +#endif +#endif + +/* This function allows the application to supply new output functions for + libpng if standard C streams aren't being used. + + This function takes as its arguments: + png_ptr - pointer to a png output data structure + io_ptr - pointer to user supplied structure containing info about + the output functions. May be NULL. + write_data_fn - pointer to a new output function that takes as its + arguments a pointer to a png_struct, a pointer to + data to be written, and a 32-bit unsigned int that is + the number of bytes to be written. The new write + function should call png_error(png_ptr, "Error msg") + to exit and output any fatal error messages. + flush_data_fn - pointer to a new flush function that takes as its + arguments a pointer to a png_struct. After a call to + the flush function, there should be no data in any buffers + or pending transmission. If the output method doesn't do + any buffering of ouput, a function prototype must still be + supplied although it doesn't have to do anything. If + PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile + time, output_flush_fn will be ignored, although it must be + supplied for compatibility. */ +void PNGAPI +png_set_write_fn(png_structp png_ptr, png_voidp io_ptr, + png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn) +{ + png_ptr->io_ptr = io_ptr; + +#if !defined(PNG_NO_STDIO) + if (write_data_fn != NULL) + png_ptr->write_data_fn = write_data_fn; + else + png_ptr->write_data_fn = png_default_write_data; +#else + png_ptr->write_data_fn = write_data_fn; +#endif + +#if defined(PNG_WRITE_FLUSH_SUPPORTED) +#if !defined(PNG_NO_STDIO) + if (output_flush_fn != NULL) + png_ptr->output_flush_fn = output_flush_fn; + else + png_ptr->output_flush_fn = png_default_flush; +#else + png_ptr->output_flush_fn = output_flush_fn; +#endif +#endif /* PNG_WRITE_FLUSH_SUPPORTED */ + + /* It is an error to read while writing a png file */ + if (png_ptr->read_data_fn != NULL) + { + png_ptr->read_data_fn = NULL; + png_warning(png_ptr, + "Attempted to set both read_data_fn and write_data_fn in"); + png_warning(png_ptr, + "the same structure. Resetting read_data_fn to NULL."); + } +} + +#if defined(USE_FAR_KEYWORD) +#if defined(_MSC_VER) +void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check) +{ + void *near_ptr; + void FAR *far_ptr; + FP_OFF(near_ptr) = FP_OFF(ptr); + far_ptr = (void FAR *)near_ptr; + if(check != 0) + if(FP_SEG(ptr) != FP_SEG(far_ptr)) + png_error(png_ptr,"segment lost in conversion"); + return(near_ptr); +} +# else +void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check) +{ + void *near_ptr; + void FAR *far_ptr; + near_ptr = (void FAR *)ptr; + far_ptr = (void FAR *)near_ptr; + if(check != 0) + if(far_ptr != ptr) + png_error(png_ptr,"segment lost in conversion"); + return(near_ptr); +} +# endif +# endif +#endif /* PNG_WRITE_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/png/pngwrite.c b/SlnkDWFImpl/CxImage/png/pngwrite.c new file mode 100644 index 0000000..fad5f56 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngwrite.c @@ -0,0 +1,1464 @@ + +/* pngwrite.c - general routines to write a PNG file + * + * libpng 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + */ + +/* get internal access to png.h */ +#define PNG_INTERNAL +#include "png.h" +#ifdef PNG_WRITE_SUPPORTED + +/* Writes all the PNG information. This is the suggested way to use the + * library. If you have a new chunk to add, make a function to write it, + * and put it in the correct location here. If you want the chunk written + * after the image data, put it in png_write_end(). I strongly encourage + * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing + * the chunk, as that will keep the code from breaking if you want to just + * write a plain PNG file. If you have long comments, I suggest writing + * them in png_write_end(), and compressing them. + */ +void PNGAPI +png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr) +{ + png_debug(1, "in png_write_info_before_PLTE\n"); + if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE)) + { + png_write_sig(png_ptr); /* write PNG signature */ +#if defined(PNG_MNG_FEATURES_SUPPORTED) + if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted)) + { + png_warning(png_ptr,"MNG features are not allowed in a PNG datastream\n"); + png_ptr->mng_features_permitted=0; + } +#endif + /* write IHDR information. */ + png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height, + info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type, + info_ptr->filter_type, +#if defined(PNG_WRITE_INTERLACING_SUPPORTED) + info_ptr->interlace_type); +#else + 0); +#endif + /* the rest of these check to see if the valid field has the appropriate + flag set, and if it does, writes the chunk. */ +#if defined(PNG_WRITE_gAMA_SUPPORTED) + if (info_ptr->valid & PNG_INFO_gAMA) + { +# ifdef PNG_FLOATING_POINT_SUPPORTED + png_write_gAMA(png_ptr, info_ptr->gamma); +#else +#ifdef PNG_FIXED_POINT_SUPPORTED + png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma); +# endif +#endif + } +#endif +#if defined(PNG_WRITE_sRGB_SUPPORTED) + if (info_ptr->valid & PNG_INFO_sRGB) + png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent); +#endif +#if defined(PNG_WRITE_iCCP_SUPPORTED) + if (info_ptr->valid & PNG_INFO_iCCP) + png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE, + info_ptr->iccp_profile, (int)info_ptr->iccp_proflen); +#endif +#if defined(PNG_WRITE_sBIT_SUPPORTED) + if (info_ptr->valid & PNG_INFO_sBIT) + png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type); +#endif +#if defined(PNG_WRITE_cHRM_SUPPORTED) + if (info_ptr->valid & PNG_INFO_cHRM) + { +#ifdef PNG_FLOATING_POINT_SUPPORTED + png_write_cHRM(png_ptr, + info_ptr->x_white, info_ptr->y_white, + info_ptr->x_red, info_ptr->y_red, + info_ptr->x_green, info_ptr->y_green, + info_ptr->x_blue, info_ptr->y_blue); +#else +# ifdef PNG_FIXED_POINT_SUPPORTED + png_write_cHRM_fixed(png_ptr, + info_ptr->int_x_white, info_ptr->int_y_white, + info_ptr->int_x_red, info_ptr->int_y_red, + info_ptr->int_x_green, info_ptr->int_y_green, + info_ptr->int_x_blue, info_ptr->int_y_blue); +# endif +#endif + } +#endif +#if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED) + if (info_ptr->unknown_chunks_num) + { + png_unknown_chunk *up; + + png_debug(5, "writing extra chunks\n"); + + for (up = info_ptr->unknown_chunks; + up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num; + up++) + { + int keep=png_handle_as_unknown(png_ptr, up->name); + if (keep != PNG_HANDLE_CHUNK_NEVER && + up->location && !(up->location & PNG_HAVE_PLTE) && + !(up->location & PNG_HAVE_IDAT) && + ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS || + (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS))) + { + png_write_chunk(png_ptr, up->name, up->data, up->size); + } + } + } +#endif + png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE; + } +} + +void PNGAPI +png_write_info(png_structp png_ptr, png_infop info_ptr) +{ +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED) + int i; +#endif + + png_debug(1, "in png_write_info\n"); + + png_write_info_before_PLTE(png_ptr, info_ptr); + + if (info_ptr->valid & PNG_INFO_PLTE) + png_write_PLTE(png_ptr, info_ptr->palette, + (png_uint_32)info_ptr->num_palette); + else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + png_error(png_ptr, "Valid palette required for paletted images\n"); + +#if defined(PNG_WRITE_tRNS_SUPPORTED) + if (info_ptr->valid & PNG_INFO_tRNS) + { +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) + /* invert the alpha channel (in tRNS) */ + if ((png_ptr->transformations & PNG_INVERT_ALPHA) && + info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + int j; + for (j=0; j<(int)info_ptr->num_trans; j++) + info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]); + } +#endif + png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values), + info_ptr->num_trans, info_ptr->color_type); + } +#endif +#if defined(PNG_WRITE_bKGD_SUPPORTED) + if (info_ptr->valid & PNG_INFO_bKGD) + png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type); +#endif +#if defined(PNG_WRITE_hIST_SUPPORTED) + if (info_ptr->valid & PNG_INFO_hIST) + png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette); +#endif +#if defined(PNG_WRITE_oFFs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_oFFs) + png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset, + info_ptr->offset_unit_type); +#endif +#if defined(PNG_WRITE_pCAL_SUPPORTED) + if (info_ptr->valid & PNG_INFO_pCAL) + png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0, + info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams, + info_ptr->pcal_units, info_ptr->pcal_params); +#endif +#if defined(PNG_WRITE_sCAL_SUPPORTED) + if (info_ptr->valid & PNG_INFO_sCAL) +#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO) + png_write_sCAL(png_ptr, (int)info_ptr->scal_unit, + info_ptr->scal_pixel_width, info_ptr->scal_pixel_height); +#else +#ifdef PNG_FIXED_POINT_SUPPORTED + png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit, + info_ptr->scal_s_width, info_ptr->scal_s_height); +#else + png_warning(png_ptr, + "png_write_sCAL not supported; sCAL chunk not written.\n"); +#endif +#endif +#endif +#if defined(PNG_WRITE_pHYs_SUPPORTED) + if (info_ptr->valid & PNG_INFO_pHYs) + png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit, + info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type); +#endif +#if defined(PNG_WRITE_tIME_SUPPORTED) + if (info_ptr->valid & PNG_INFO_tIME) + { + png_write_tIME(png_ptr, &(info_ptr->mod_time)); + png_ptr->mode |= PNG_WROTE_tIME; + } +#endif +#if defined(PNG_WRITE_sPLT_SUPPORTED) + if (info_ptr->valid & PNG_INFO_sPLT) + for (i = 0; i < (int)info_ptr->splt_palettes_num; i++) + png_write_sPLT(png_ptr, info_ptr->splt_palettes + i); +#endif +#if defined(PNG_WRITE_TEXT_SUPPORTED) + /* Check to see if we need to write text chunks */ + for (i = 0; i < info_ptr->num_text; i++) + { + png_debug2(2, "Writing header text chunk %d, type %d\n", i, + info_ptr->text[i].compression); + /* an internationalized chunk? */ + if (info_ptr->text[i].compression > 0) + { +#if defined(PNG_WRITE_iTXt_SUPPORTED) + /* write international chunk */ + png_write_iTXt(png_ptr, + info_ptr->text[i].compression, + info_ptr->text[i].key, + info_ptr->text[i].lang, + info_ptr->text[i].lang_key, + info_ptr->text[i].text); +#else + png_warning(png_ptr, "Unable to write international text\n"); +#endif + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; + } + /* If we want a compressed text chunk */ + else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt) + { +#if defined(PNG_WRITE_zTXt_SUPPORTED) + /* write compressed chunk */ + png_write_zTXt(png_ptr, info_ptr->text[i].key, + info_ptr->text[i].text, 0, + info_ptr->text[i].compression); +#else + png_warning(png_ptr, "Unable to write compressed text\n"); +#endif + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; + } + else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE) + { +#if defined(PNG_WRITE_tEXt_SUPPORTED) + /* write uncompressed chunk */ + png_write_tEXt(png_ptr, info_ptr->text[i].key, + info_ptr->text[i].text, + 0); +#else + png_warning(png_ptr, "Unable to write uncompressed text\n"); +#endif + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; + } + } +#endif +#if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED) + if (info_ptr->unknown_chunks_num) + { + png_unknown_chunk *up; + + png_debug(5, "writing extra chunks\n"); + + for (up = info_ptr->unknown_chunks; + up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num; + up++) + { + int keep=png_handle_as_unknown(png_ptr, up->name); + if (keep != PNG_HANDLE_CHUNK_NEVER && + up->location && (up->location & PNG_HAVE_PLTE) && + !(up->location & PNG_HAVE_IDAT) && + ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS || + (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS))) + { + png_write_chunk(png_ptr, up->name, up->data, up->size); + } + } + } +#endif +} + +/* Writes the end of the PNG file. If you don't want to write comments or + * time information, you can pass NULL for info. If you already wrote these + * in png_write_info(), do not write them again here. If you have long + * comments, I suggest writing them here, and compressing them. + */ +void PNGAPI +png_write_end(png_structp png_ptr, png_infop info_ptr) +{ + png_debug(1, "in png_write_end\n"); + if (!(png_ptr->mode & PNG_HAVE_IDAT)) + png_error(png_ptr, "No IDATs written into file"); + + /* see if user wants us to write information chunks */ + if (info_ptr != NULL) + { +#if defined(PNG_WRITE_TEXT_SUPPORTED) + int i; /* local index variable */ +#endif +#if defined(PNG_WRITE_tIME_SUPPORTED) + /* check to see if user has supplied a time chunk */ + if ((info_ptr->valid & PNG_INFO_tIME) && + !(png_ptr->mode & PNG_WROTE_tIME)) + png_write_tIME(png_ptr, &(info_ptr->mod_time)); +#endif +#if defined(PNG_WRITE_TEXT_SUPPORTED) + /* loop through comment chunks */ + for (i = 0; i < info_ptr->num_text; i++) + { + png_debug2(2, "Writing trailer text chunk %d, type %d\n", i, + info_ptr->text[i].compression); + /* an internationalized chunk? */ + if (info_ptr->text[i].compression > 0) + { +#if defined(PNG_WRITE_iTXt_SUPPORTED) + /* write international chunk */ + png_write_iTXt(png_ptr, + info_ptr->text[i].compression, + info_ptr->text[i].key, + info_ptr->text[i].lang, + info_ptr->text[i].lang_key, + info_ptr->text[i].text); +#else + png_warning(png_ptr, "Unable to write international text\n"); +#endif + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; + } + else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt) + { +#if defined(PNG_WRITE_zTXt_SUPPORTED) + /* write compressed chunk */ + png_write_zTXt(png_ptr, info_ptr->text[i].key, + info_ptr->text[i].text, 0, + info_ptr->text[i].compression); +#else + png_warning(png_ptr, "Unable to write compressed text\n"); +#endif + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; + } + else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE) + { +#if defined(PNG_WRITE_tEXt_SUPPORTED) + /* write uncompressed chunk */ + png_write_tEXt(png_ptr, info_ptr->text[i].key, + info_ptr->text[i].text, 0); +#else + png_warning(png_ptr, "Unable to write uncompressed text\n"); +#endif + + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; + } + } +#endif +#if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED) + if (info_ptr->unknown_chunks_num) + { + png_unknown_chunk *up; + + png_debug(5, "writing extra chunks\n"); + + for (up = info_ptr->unknown_chunks; + up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num; + up++) + { + int keep=png_handle_as_unknown(png_ptr, up->name); + if (keep != PNG_HANDLE_CHUNK_NEVER && + up->location && (up->location & PNG_AFTER_IDAT) && + ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS || + (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS))) + { + png_write_chunk(png_ptr, up->name, up->data, up->size); + } + } + } +#endif + } + + png_ptr->mode |= PNG_AFTER_IDAT; + + /* write end of PNG file */ + png_write_IEND(png_ptr); +#if 0 +/* This flush, added in libpng-1.0.8, causes some applications to crash + because they do not set png_ptr->output_flush_fn */ + png_flush(png_ptr); +#endif +} + +#if defined(PNG_WRITE_tIME_SUPPORTED) +#if !defined(_WIN32_WCE) +/* "time.h" functions are not supported on WindowsCE */ +void PNGAPI +png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime) +{ + png_debug(1, "in png_convert_from_struct_tm\n"); + ptime->year = (png_uint_16)(1900 + ttime->tm_year); + ptime->month = (png_byte)(ttime->tm_mon + 1); + ptime->day = (png_byte)ttime->tm_mday; + ptime->hour = (png_byte)ttime->tm_hour; + ptime->minute = (png_byte)ttime->tm_min; + ptime->second = (png_byte)ttime->tm_sec; +} + +void PNGAPI +png_convert_from_time_t(png_timep ptime, time_t ttime) +{ + struct tm *tbuf; + + png_debug(1, "in png_convert_from_time_t\n"); + tbuf = gmtime(&ttime); + png_convert_from_struct_tm(ptime, tbuf); +} +#endif +#endif + +/* Initialize png_ptr structure, and allocate any memory needed */ +png_structp PNGAPI +png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warn_fn) +{ +#ifdef PNG_USER_MEM_SUPPORTED + return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn, + warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL)); +} + +/* Alternate initialize png_ptr structure, and allocate any memory needed */ +png_structp PNGAPI +png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr, + png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, + png_malloc_ptr malloc_fn, png_free_ptr free_fn) +{ +#endif /* PNG_USER_MEM_SUPPORTED */ + png_structp png_ptr; +#ifdef PNG_SETJMP_SUPPORTED +#ifdef USE_FAR_KEYWORD + jmp_buf jmpbuf; +#endif +#endif + int i; + png_debug(1, "in png_create_write_struct\n"); +#ifdef PNG_USER_MEM_SUPPORTED + png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG, + (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr); +#else + png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); +#endif /* PNG_USER_MEM_SUPPORTED */ + if (png_ptr == NULL) + return (NULL); + +#if !defined(PNG_1_0_X) +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED + png_init_mmx_flags(png_ptr); /* 1.2.0 addition */ +#endif +#endif /* PNG_1_0_X */ + + /* added at libpng-1.2.6 */ +#ifdef PNG_SET_USER_LIMITS_SUPPORTED + png_ptr->user_width_max=PNG_USER_WIDTH_MAX; + png_ptr->user_height_max=PNG_USER_HEIGHT_MAX; +#endif + +#ifdef PNG_SETJMP_SUPPORTED +#ifdef USE_FAR_KEYWORD + if (setjmp(jmpbuf)) +#else + if (setjmp(png_ptr->jmpbuf)) +#endif + { + png_free(png_ptr, png_ptr->zbuf); + png_ptr->zbuf=NULL; + png_destroy_struct(png_ptr); + return (NULL); + } +#ifdef USE_FAR_KEYWORD + png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf)); +#endif +#endif + +#ifdef PNG_USER_MEM_SUPPORTED + png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn); +#endif /* PNG_USER_MEM_SUPPORTED */ + png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn); + + i=0; + do + { + if(user_png_ver[i] != png_libpng_ver[i]) + png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; + } while (png_libpng_ver[i++]); + + if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) + { + /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so + * we must recompile any applications that use any older library version. + * For versions after libpng 1.0, we will be compatible, so we need + * only check the first digit. + */ + if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] || + (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) || + (user_png_ver[0] == '0' && user_png_ver[2] < '9')) + { +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + char msg[80]; + if (user_png_ver) + { + sprintf(msg, "Application was compiled with png.h from libpng-%.20s", + user_png_ver); + png_warning(png_ptr, msg); + } + sprintf(msg, "Application is running with png.c from libpng-%.20s", + png_libpng_ver); + png_warning(png_ptr, msg); +#endif +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + png_ptr->flags=0; +#endif + png_error(png_ptr, + "Incompatible libpng version in application and library"); + } + } + + /* initialize zbuf - compression buffer */ + png_ptr->zbuf_size = PNG_ZBUF_SIZE; + png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, + (png_uint_32)png_ptr->zbuf_size); + + png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL, + png_flush_ptr_NULL); + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT, + 1, png_doublep_NULL, png_doublep_NULL); +#endif + +#ifdef PNG_SETJMP_SUPPORTED +/* Applications that neglect to set up their own setjmp() and then encounter + a png_error() will longjmp here. Since the jmpbuf is then meaningless we + abort instead of returning. */ +#ifdef USE_FAR_KEYWORD + if (setjmp(jmpbuf)) + PNG_ABORT(); + png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf)); +#else + if (setjmp(png_ptr->jmpbuf)) + PNG_ABORT(); +#endif +#endif + return (png_ptr); +} + +/* Initialize png_ptr structure, and allocate any memory needed */ +#undef png_write_init +void PNGAPI +png_write_init(png_structp png_ptr) +{ + /* We only come here via pre-1.0.7-compiled applications */ + png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0); +} + +void PNGAPI +png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver, + png_size_t png_struct_size, png_size_t png_info_size) +{ + /* We only come here via pre-1.0.12-compiled applications */ +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + if(png_sizeof(png_struct) > png_struct_size || + png_sizeof(png_info) > png_info_size) + { + char msg[80]; + png_ptr->warning_fn=NULL; + if (user_png_ver) + { + sprintf(msg, "Application was compiled with png.h from libpng-%.20s", + user_png_ver); + png_warning(png_ptr, msg); + } + sprintf(msg, "Application is running with png.c from libpng-%.20s", + png_libpng_ver); + png_warning(png_ptr, msg); + } +#endif + if(png_sizeof(png_struct) > png_struct_size) + { + png_ptr->error_fn=NULL; +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + png_ptr->flags=0; +#endif + png_error(png_ptr, + "The png struct allocated by the application for writing is too small."); + } + if(png_sizeof(png_info) > png_info_size) + { + png_ptr->error_fn=NULL; +#ifdef PNG_ERROR_NUMBERS_SUPPORTED + png_ptr->flags=0; +#endif + png_error(png_ptr, + "The info struct allocated by the application for writing is too small."); + } + png_write_init_3(&png_ptr, user_png_ver, png_struct_size); +} + + +void PNGAPI +png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, + png_size_t png_struct_size) +{ + png_structp png_ptr=*ptr_ptr; +#ifdef PNG_SETJMP_SUPPORTED + jmp_buf tmp_jmp; /* to save current jump buffer */ +#endif + int i = 0; + do + { + if (user_png_ver[i] != png_libpng_ver[i]) + { +#ifdef PNG_LEGACY_SUPPORTED + png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; +#else + png_ptr->warning_fn=NULL; + png_warning(png_ptr, + "Application uses deprecated png_write_init() and should be recompiled."); + break; +#endif + } + } while (png_libpng_ver[i++]); + + png_debug(1, "in png_write_init_3\n"); + +#ifdef PNG_SETJMP_SUPPORTED + /* save jump buffer and error functions */ + png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf)); +#endif + + if (png_sizeof(png_struct) > png_struct_size) + { + png_destroy_struct(png_ptr); + png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); + *ptr_ptr = png_ptr; + } + + /* reset all variables to 0 */ + png_memset(png_ptr, 0, png_sizeof (png_struct)); + + /* added at libpng-1.2.6 */ +#ifdef PNG_SET_USER_LIMITS_SUPPORTED + png_ptr->user_width_max=PNG_USER_WIDTH_MAX; + png_ptr->user_height_max=PNG_USER_HEIGHT_MAX; +#endif + +#if !defined(PNG_1_0_X) +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED + png_init_mmx_flags(png_ptr); /* 1.2.0 addition */ +#endif +#endif /* PNG_1_0_X */ + +#ifdef PNG_SETJMP_SUPPORTED + /* restore jump buffer */ + png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf)); +#endif + + png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL, + png_flush_ptr_NULL); + + /* initialize zbuf - compression buffer */ + png_ptr->zbuf_size = PNG_ZBUF_SIZE; + png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, + (png_uint_32)png_ptr->zbuf_size); + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT, + 1, png_doublep_NULL, png_doublep_NULL); +#endif +} + +/* Write a few rows of image data. If the image is interlaced, + * either you will have to write the 7 sub images, or, if you + * have called png_set_interlace_handling(), you will have to + * "write" the image seven times. + */ +void PNGAPI +png_write_rows(png_structp png_ptr, png_bytepp row, + png_uint_32 num_rows) +{ + png_uint_32 i; /* row counter */ + png_bytepp rp; /* row pointer */ + + png_debug(1, "in png_write_rows\n"); + /* loop through the rows */ + for (i = 0, rp = row; i < num_rows; i++, rp++) + { + png_write_row(png_ptr, *rp); + } +} + +/* Write the image. You only need to call this function once, even + * if you are writing an interlaced image. + */ +void PNGAPI +png_write_image(png_structp png_ptr, png_bytepp image) +{ + png_uint_32 i; /* row index */ + int pass, num_pass; /* pass variables */ + png_bytepp rp; /* points to current row */ + + png_debug(1, "in png_write_image\n"); +#if defined(PNG_WRITE_INTERLACING_SUPPORTED) + /* intialize interlace handling. If image is not interlaced, + this will set pass to 1 */ + num_pass = png_set_interlace_handling(png_ptr); +#else + num_pass = 1; +#endif + /* loop through passes */ + for (pass = 0; pass < num_pass; pass++) + { + /* loop through image */ + for (i = 0, rp = image; i < png_ptr->height; i++, rp++) + { + png_write_row(png_ptr, *rp); + } + } +} + +/* called by user to write a row of image data */ +void PNGAPI +png_write_row(png_structp png_ptr, png_bytep row) +{ + png_debug2(1, "in png_write_row (row %ld, pass %d)\n", + png_ptr->row_number, png_ptr->pass); + /* initialize transformations and other stuff if first time */ + if (png_ptr->row_number == 0 && png_ptr->pass == 0) + { + /* make sure we wrote the header info */ + if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE)) + png_error(png_ptr, + "png_write_info was never called before png_write_row."); + + /* check for transforms that have been set but were defined out */ +#if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED) + if (png_ptr->transformations & PNG_INVERT_MONO) + png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined."); +#endif +#if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED) + if (png_ptr->transformations & PNG_FILLER) + png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined."); +#endif +#if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined."); +#endif +#if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED) + if (png_ptr->transformations & PNG_PACK) + png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined."); +#endif +#if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED) + if (png_ptr->transformations & PNG_SHIFT) + png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined."); +#endif +#if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED) + if (png_ptr->transformations & PNG_BGR) + png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined."); +#endif +#if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED) + if (png_ptr->transformations & PNG_SWAP_BYTES) + png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined."); +#endif + + png_write_start_row(png_ptr); + } + +#if defined(PNG_WRITE_INTERLACING_SUPPORTED) + /* if interlaced and not interested in row, return */ + if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) + { + switch (png_ptr->pass) + { + case 0: + if (png_ptr->row_number & 0x07) + { + png_write_finish_row(png_ptr); + return; + } + break; + case 1: + if ((png_ptr->row_number & 0x07) || png_ptr->width < 5) + { + png_write_finish_row(png_ptr); + return; + } + break; + case 2: + if ((png_ptr->row_number & 0x07) != 4) + { + png_write_finish_row(png_ptr); + return; + } + break; + case 3: + if ((png_ptr->row_number & 0x03) || png_ptr->width < 3) + { + png_write_finish_row(png_ptr); + return; + } + break; + case 4: + if ((png_ptr->row_number & 0x03) != 2) + { + png_write_finish_row(png_ptr); + return; + } + break; + case 5: + if ((png_ptr->row_number & 0x01) || png_ptr->width < 2) + { + png_write_finish_row(png_ptr); + return; + } + break; + case 6: + if (!(png_ptr->row_number & 0x01)) + { + png_write_finish_row(png_ptr); + return; + } + break; + } + } +#endif + + /* set up row info for transformations */ + png_ptr->row_info.color_type = png_ptr->color_type; + png_ptr->row_info.width = png_ptr->usr_width; + png_ptr->row_info.channels = png_ptr->usr_channels; + png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth; + png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth * + png_ptr->row_info.channels); + + png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, + png_ptr->row_info.width); + + png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type); + png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width); + png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels); + png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth); + png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth); + png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes); + + /* Copy user's row into buffer, leaving room for filter byte. */ + png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row, + png_ptr->row_info.rowbytes); + +#if defined(PNG_WRITE_INTERLACING_SUPPORTED) + /* handle interlacing */ + if (png_ptr->interlaced && png_ptr->pass < 6 && + (png_ptr->transformations & PNG_INTERLACE)) + { + png_do_write_interlace(&(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->pass); + /* this should always get caught above, but still ... */ + if (!(png_ptr->row_info.width)) + { + png_write_finish_row(png_ptr); + return; + } + } +#endif + + /* handle other transformations */ + if (png_ptr->transformations) + png_do_write_transformations(png_ptr); + +#if defined(PNG_MNG_FEATURES_SUPPORTED) + /* Write filter_method 64 (intrapixel differencing) only if + * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and + * 2. Libpng did not write a PNG signature (this filter_method is only + * used in PNG datastreams that are embedded in MNG datastreams) and + * 3. The application called png_permit_mng_features with a mask that + * included PNG_FLAG_MNG_FILTER_64 and + * 4. The filter_method is 64 and + * 5. The color_type is RGB or RGBA + */ + if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && + (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING)) + { + /* Intrapixel differencing */ + png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1); + } +#endif + + /* Find a filter if necessary, filter the row and write it out. */ + png_write_find_filter(png_ptr, &(png_ptr->row_info)); + + if (png_ptr->write_row_fn != NULL) + (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass); +} + +#if defined(PNG_WRITE_FLUSH_SUPPORTED) +/* Set the automatic flush interval or 0 to turn flushing off */ +void PNGAPI +png_set_flush(png_structp png_ptr, int nrows) +{ + png_debug(1, "in png_set_flush\n"); + png_ptr->flush_dist = (nrows < 0 ? 0 : nrows); +} + +/* flush the current output buffers now */ +void PNGAPI +png_write_flush(png_structp png_ptr) +{ + int wrote_IDAT; + + png_debug(1, "in png_write_flush\n"); + /* We have already written out all of the data */ + if (png_ptr->row_number >= png_ptr->num_rows) + return; + + do + { + int ret; + + /* compress the data */ + ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH); + wrote_IDAT = 0; + + /* check for compression errors */ + if (ret != Z_OK) + { + if (png_ptr->zstream.msg != NULL) + png_error(png_ptr, png_ptr->zstream.msg); + else + png_error(png_ptr, "zlib error"); + } + + if (!(png_ptr->zstream.avail_out)) + { + /* write the IDAT and reset the zlib output buffer */ + png_write_IDAT(png_ptr, png_ptr->zbuf, + png_ptr->zbuf_size); + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + wrote_IDAT = 1; + } + } while(wrote_IDAT == 1); + + /* If there is any data left to be output, write it into a new IDAT */ + if (png_ptr->zbuf_size != png_ptr->zstream.avail_out) + { + /* write the IDAT and reset the zlib output buffer */ + png_write_IDAT(png_ptr, png_ptr->zbuf, + png_ptr->zbuf_size - png_ptr->zstream.avail_out); + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + } + png_ptr->flush_rows = 0; + png_flush(png_ptr); +} +#endif /* PNG_WRITE_FLUSH_SUPPORTED */ + +/* free all memory used by the write */ +void PNGAPI +png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr) +{ + png_structp png_ptr = NULL; + png_infop info_ptr = NULL; +#ifdef PNG_USER_MEM_SUPPORTED + png_free_ptr free_fn = NULL; + png_voidp mem_ptr = NULL; +#endif + + png_debug(1, "in png_destroy_write_struct\n"); + if (png_ptr_ptr != NULL) + { + png_ptr = *png_ptr_ptr; +#ifdef PNG_USER_MEM_SUPPORTED + free_fn = png_ptr->free_fn; + mem_ptr = png_ptr->mem_ptr; +#endif + } + + if (info_ptr_ptr != NULL) + info_ptr = *info_ptr_ptr; + + if (info_ptr != NULL) + { + png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1); + +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) + if (png_ptr->num_chunk_list) + { + png_free(png_ptr, png_ptr->chunk_list); + png_ptr->chunk_list=NULL; + png_ptr->num_chunk_list=0; + } +#endif + +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn, + (png_voidp)mem_ptr); +#else + png_destroy_struct((png_voidp)info_ptr); +#endif + *info_ptr_ptr = NULL; + } + + if (png_ptr != NULL) + { + png_write_destroy(png_ptr); +#ifdef PNG_USER_MEM_SUPPORTED + png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn, + (png_voidp)mem_ptr); +#else + png_destroy_struct((png_voidp)png_ptr); +#endif + *png_ptr_ptr = NULL; + } +} + + +/* Free any memory used in png_ptr struct (old method) */ +void /* PRIVATE */ +png_write_destroy(png_structp png_ptr) +{ +#ifdef PNG_SETJMP_SUPPORTED + jmp_buf tmp_jmp; /* save jump buffer */ +#endif + png_error_ptr error_fn; + png_error_ptr warning_fn; + png_voidp error_ptr; +#ifdef PNG_USER_MEM_SUPPORTED + png_free_ptr free_fn; +#endif + + png_debug(1, "in png_write_destroy\n"); + /* free any memory zlib uses */ + deflateEnd(&png_ptr->zstream); + + /* free our memory. png_free checks NULL for us. */ + png_free(png_ptr, png_ptr->zbuf); + png_free(png_ptr, png_ptr->row_buf); + png_free(png_ptr, png_ptr->prev_row); + png_free(png_ptr, png_ptr->sub_row); + png_free(png_ptr, png_ptr->up_row); + png_free(png_ptr, png_ptr->avg_row); + png_free(png_ptr, png_ptr->paeth_row); + +#if defined(PNG_TIME_RFC1123_SUPPORTED) + png_free(png_ptr, png_ptr->time_buffer); +#endif + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + png_free(png_ptr, png_ptr->prev_filters); + png_free(png_ptr, png_ptr->filter_weights); + png_free(png_ptr, png_ptr->inv_filter_weights); + png_free(png_ptr, png_ptr->filter_costs); + png_free(png_ptr, png_ptr->inv_filter_costs); +#endif + +#ifdef PNG_SETJMP_SUPPORTED + /* reset structure */ + png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf)); +#endif + + error_fn = png_ptr->error_fn; + warning_fn = png_ptr->warning_fn; + error_ptr = png_ptr->error_ptr; +#ifdef PNG_USER_MEM_SUPPORTED + free_fn = png_ptr->free_fn; +#endif + + png_memset(png_ptr, 0, png_sizeof (png_struct)); + + png_ptr->error_fn = error_fn; + png_ptr->warning_fn = warning_fn; + png_ptr->error_ptr = error_ptr; +#ifdef PNG_USER_MEM_SUPPORTED + png_ptr->free_fn = free_fn; +#endif + +#ifdef PNG_SETJMP_SUPPORTED + png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf)); +#endif +} + +/* Allow the application to select one or more row filters to use. */ +void PNGAPI +png_set_filter(png_structp png_ptr, int method, int filters) +{ + png_debug(1, "in png_set_filter\n"); +#if defined(PNG_MNG_FEATURES_SUPPORTED) + if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && + (method == PNG_INTRAPIXEL_DIFFERENCING)) + method = PNG_FILTER_TYPE_BASE; +#endif + if (method == PNG_FILTER_TYPE_BASE) + { + switch (filters & (PNG_ALL_FILTERS | 0x07)) + { + case 5: + case 6: + case 7: png_warning(png_ptr, "Unknown row filter for method 0"); + case PNG_FILTER_VALUE_NONE: png_ptr->do_filter=PNG_FILTER_NONE; break; + case PNG_FILTER_VALUE_SUB: png_ptr->do_filter=PNG_FILTER_SUB; break; + case PNG_FILTER_VALUE_UP: png_ptr->do_filter=PNG_FILTER_UP; break; + case PNG_FILTER_VALUE_AVG: png_ptr->do_filter=PNG_FILTER_AVG; break; + case PNG_FILTER_VALUE_PAETH: png_ptr->do_filter=PNG_FILTER_PAETH;break; + default: png_ptr->do_filter = (png_byte)filters; break; + } + + /* If we have allocated the row_buf, this means we have already started + * with the image and we should have allocated all of the filter buffers + * that have been selected. If prev_row isn't already allocated, then + * it is too late to start using the filters that need it, since we + * will be missing the data in the previous row. If an application + * wants to start and stop using particular filters during compression, + * it should start out with all of the filters, and then add and + * remove them after the start of compression. + */ + if (png_ptr->row_buf != NULL) + { + if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL) + { + png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, + (png_ptr->rowbytes + 1)); + png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB; + } + + if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL) + { + if (png_ptr->prev_row == NULL) + { + png_warning(png_ptr, "Can't add Up filter after starting"); + png_ptr->do_filter &= ~PNG_FILTER_UP; + } + else + { + png_ptr->up_row = (png_bytep)png_malloc(png_ptr, + (png_ptr->rowbytes + 1)); + png_ptr->up_row[0] = PNG_FILTER_VALUE_UP; + } + } + + if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL) + { + if (png_ptr->prev_row == NULL) + { + png_warning(png_ptr, "Can't add Average filter after starting"); + png_ptr->do_filter &= ~PNG_FILTER_AVG; + } + else + { + png_ptr->avg_row = (png_bytep)png_malloc(png_ptr, + (png_ptr->rowbytes + 1)); + png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG; + } + } + + if ((png_ptr->do_filter & PNG_FILTER_PAETH) && + png_ptr->paeth_row == NULL) + { + if (png_ptr->prev_row == NULL) + { + png_warning(png_ptr, "Can't add Paeth filter after starting"); + png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH); + } + else + { + png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr, + (png_ptr->rowbytes + 1)); + png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH; + } + } + + if (png_ptr->do_filter == PNG_NO_FILTERS) + png_ptr->do_filter = PNG_FILTER_NONE; + } + } + else + png_error(png_ptr, "Unknown custom filter method"); +} + +/* This allows us to influence the way in which libpng chooses the "best" + * filter for the current scanline. While the "minimum-sum-of-absolute- + * differences metric is relatively fast and effective, there is some + * question as to whether it can be improved upon by trying to keep the + * filtered data going to zlib more consistent, hopefully resulting in + * better compression. + */ +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */ +void PNGAPI +png_set_filter_heuristics(png_structp png_ptr, int heuristic_method, + int num_weights, png_doublep filter_weights, + png_doublep filter_costs) +{ + int i; + + png_debug(1, "in png_set_filter_heuristics\n"); + if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST) + { + png_warning(png_ptr, "Unknown filter heuristic method"); + return; + } + + if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT) + { + heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED; + } + + if (num_weights < 0 || filter_weights == NULL || + heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED) + { + num_weights = 0; + } + + png_ptr->num_prev_filters = (png_byte)num_weights; + png_ptr->heuristic_method = (png_byte)heuristic_method; + + if (num_weights > 0) + { + if (png_ptr->prev_filters == NULL) + { + png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr, + (png_uint_32)(png_sizeof(png_byte) * num_weights)); + + /* To make sure that the weighting starts out fairly */ + for (i = 0; i < num_weights; i++) + { + png_ptr->prev_filters[i] = 255; + } + } + + if (png_ptr->filter_weights == NULL) + { + png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr, + (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); + + png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr, + (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); + for (i = 0; i < num_weights; i++) + { + png_ptr->inv_filter_weights[i] = + png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR; + } + } + + for (i = 0; i < num_weights; i++) + { + if (filter_weights[i] < 0.0) + { + png_ptr->inv_filter_weights[i] = + png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR; + } + else + { + png_ptr->inv_filter_weights[i] = + (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5); + png_ptr->filter_weights[i] = + (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5); + } + } + } + + /* If, in the future, there are other filter methods, this would + * need to be based on png_ptr->filter. + */ + if (png_ptr->filter_costs == NULL) + { + png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr, + (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); + + png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr, + (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); + + for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) + { + png_ptr->inv_filter_costs[i] = + png_ptr->filter_costs[i] = PNG_COST_FACTOR; + } + } + + /* Here is where we set the relative costs of the different filters. We + * should take the desired compression level into account when setting + * the costs, so that Paeth, for instance, has a high relative cost at low + * compression levels, while it has a lower relative cost at higher + * compression settings. The filter types are in order of increasing + * relative cost, so it would be possible to do this with an algorithm. + */ + for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) + { + if (filter_costs == NULL || filter_costs[i] < 0.0) + { + png_ptr->inv_filter_costs[i] = + png_ptr->filter_costs[i] = PNG_COST_FACTOR; + } + else if (filter_costs[i] >= 1.0) + { + png_ptr->inv_filter_costs[i] = + (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5); + png_ptr->filter_costs[i] = + (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5); + } + } +} +#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */ + +void PNGAPI +png_set_compression_level(png_structp png_ptr, int level) +{ + png_debug(1, "in png_set_compression_level\n"); + png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL; + png_ptr->zlib_level = level; +} + +void PNGAPI +png_set_compression_mem_level(png_structp png_ptr, int mem_level) +{ + png_debug(1, "in png_set_compression_mem_level\n"); + png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL; + png_ptr->zlib_mem_level = mem_level; +} + +void PNGAPI +png_set_compression_strategy(png_structp png_ptr, int strategy) +{ + png_debug(1, "in png_set_compression_strategy\n"); + png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY; + png_ptr->zlib_strategy = strategy; +} + +void PNGAPI +png_set_compression_window_bits(png_structp png_ptr, int window_bits) +{ + if (window_bits > 15) + png_warning(png_ptr, "Only compression windows <= 32k supported by PNG"); + else if (window_bits < 8) + png_warning(png_ptr, "Only compression windows >= 256 supported by PNG"); +#ifndef WBITS_8_OK + /* avoid libpng bug with 256-byte windows */ + if (window_bits == 8) + { + png_warning(png_ptr, "Compression window is being reset to 512"); + window_bits=9; + } +#endif + png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS; + png_ptr->zlib_window_bits = window_bits; +} + +void PNGAPI +png_set_compression_method(png_structp png_ptr, int method) +{ + png_debug(1, "in png_set_compression_method\n"); + if (method != 8) + png_warning(png_ptr, "Only compression method 8 is supported by PNG"); + png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD; + png_ptr->zlib_method = method; +} + +void PNGAPI +png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn) +{ + png_ptr->write_row_fn = write_row_fn; +} + +#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) +void PNGAPI +png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr + write_user_transform_fn) +{ + png_debug(1, "in png_set_write_user_transform_fn\n"); + png_ptr->transformations |= PNG_USER_TRANSFORM; + png_ptr->write_user_transform_fn = write_user_transform_fn; +} +#endif + + +#if defined(PNG_INFO_IMAGE_SUPPORTED) +void PNGAPI +png_write_png(png_structp png_ptr, png_infop info_ptr, + int transforms, voidp params) +{ +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) + /* invert the alpha channel from opacity to transparency */ + if (transforms & PNG_TRANSFORM_INVERT_ALPHA) + png_set_invert_alpha(png_ptr); +#endif + + /* Write the file header information. */ + png_write_info(png_ptr, info_ptr); + + /* ------ these transformations don't touch the info structure ------- */ + +#if defined(PNG_WRITE_INVERT_SUPPORTED) + /* invert monochrome pixels */ + if (transforms & PNG_TRANSFORM_INVERT_MONO) + png_set_invert_mono(png_ptr); +#endif + +#if defined(PNG_WRITE_SHIFT_SUPPORTED) + /* Shift the pixels up to a legal bit depth and fill in + * as appropriate to correctly scale the image. + */ + if ((transforms & PNG_TRANSFORM_SHIFT) + && (info_ptr->valid & PNG_INFO_sBIT)) + png_set_shift(png_ptr, &info_ptr->sig_bit); +#endif + +#if defined(PNG_WRITE_PACK_SUPPORTED) + /* pack pixels into bytes */ + if (transforms & PNG_TRANSFORM_PACKING) + png_set_packing(png_ptr); +#endif + +#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) + /* swap location of alpha bytes from ARGB to RGBA */ + if (transforms & PNG_TRANSFORM_SWAP_ALPHA) + png_set_swap_alpha(png_ptr); +#endif + +#if defined(PNG_WRITE_FILLER_SUPPORTED) + /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into + * RGB (4 channels -> 3 channels). The second parameter is not used. + */ + if (transforms & PNG_TRANSFORM_STRIP_FILLER) + png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE); +#endif + +#if defined(PNG_WRITE_BGR_SUPPORTED) + /* flip BGR pixels to RGB */ + if (transforms & PNG_TRANSFORM_BGR) + png_set_bgr(png_ptr); +#endif + +#if defined(PNG_WRITE_SWAP_SUPPORTED) + /* swap bytes of 16-bit files to most significant byte first */ + if (transforms & PNG_TRANSFORM_SWAP_ENDIAN) + png_set_swap(png_ptr); +#endif + +#if defined(PNG_WRITE_PACKSWAP_SUPPORTED) + /* swap bits of 1, 2, 4 bit packed pixel formats */ + if (transforms & PNG_TRANSFORM_PACKSWAP) + png_set_packswap(png_ptr); +#endif + + /* ----------------------- end of transformations ------------------- */ + + /* write the bits */ + if (info_ptr->valid & PNG_INFO_IDAT) + png_write_image(png_ptr, info_ptr->row_pointers); + + /* It is REQUIRED to call this to finish writing the rest of the file */ + png_write_end(png_ptr, info_ptr); + + if(transforms == 0 || params == NULL) + /* quiet compiler warnings */ return; +} +#endif +#endif /* PNG_WRITE_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/png/pngwtran.c b/SlnkDWFImpl/CxImage/png/pngwtran.c new file mode 100644 index 0000000..f841021 --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngwtran.c @@ -0,0 +1,563 @@ + +/* pngwtran.c - transforms the data in a row for PNG writers + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + */ + +#define PNG_INTERNAL +#include "png.h" +#ifdef PNG_WRITE_SUPPORTED + +/* Transform the data according to the user's wishes. The order of + * transformations is significant. + */ +void /* PRIVATE */ +png_do_write_transformations(png_structp png_ptr) +{ + png_debug(1, "in png_do_write_transformations\n"); + + if (png_ptr == NULL) + return; + +#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) + if (png_ptr->transformations & PNG_USER_TRANSFORM) + if(png_ptr->write_user_transform_fn != NULL) + (*(png_ptr->write_user_transform_fn)) /* user write transform function */ + (png_ptr, /* png_ptr */ + &(png_ptr->row_info), /* row_info: */ + /* png_uint_32 width; width of row */ + /* png_uint_32 rowbytes; number of bytes in row */ + /* png_byte color_type; color type of pixels */ + /* png_byte bit_depth; bit depth of samples */ + /* png_byte channels; number of channels (1-4) */ + /* png_byte pixel_depth; bits per pixel (depth*channels) */ + png_ptr->row_buf + 1); /* start of pixel data for row */ +#endif +#if defined(PNG_WRITE_FILLER_SUPPORTED) + if (png_ptr->transformations & PNG_FILLER) + png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1, + png_ptr->flags); +#endif +#if defined(PNG_WRITE_PACKSWAP_SUPPORTED) + if (png_ptr->transformations & PNG_PACKSWAP) + png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif +#if defined(PNG_WRITE_PACK_SUPPORTED) + if (png_ptr->transformations & PNG_PACK) + png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1, + (png_uint_32)png_ptr->bit_depth); +#endif +#if defined(PNG_WRITE_SWAP_SUPPORTED) + if (png_ptr->transformations & PNG_SWAP_BYTES) + png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif +#if defined(PNG_WRITE_SHIFT_SUPPORTED) + if (png_ptr->transformations & PNG_SHIFT) + png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1, + &(png_ptr->shift)); +#endif +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) + if (png_ptr->transformations & PNG_INVERT_ALPHA) + png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif +#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) + if (png_ptr->transformations & PNG_SWAP_ALPHA) + png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif +#if defined(PNG_WRITE_BGR_SUPPORTED) + if (png_ptr->transformations & PNG_BGR) + png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif +#if defined(PNG_WRITE_INVERT_SUPPORTED) + if (png_ptr->transformations & PNG_INVERT_MONO) + png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1); +#endif +} + +#if defined(PNG_WRITE_PACK_SUPPORTED) +/* Pack pixels into bytes. Pass the true bit depth in bit_depth. The + * row_info bit depth should be 8 (one pixel per byte). The channels + * should be 1 (this only happens on grayscale and paletted images). + */ +void /* PRIVATE */ +png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth) +{ + png_debug(1, "in png_do_pack\n"); + if (row_info->bit_depth == 8 && +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + row_info->channels == 1) + { + switch ((int)bit_depth) + { + case 1: + { + png_bytep sp, dp; + int mask, v; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + sp = row; + dp = row; + mask = 0x80; + v = 0; + + for (i = 0; i < row_width; i++) + { + if (*sp != 0) + v |= mask; + sp++; + if (mask > 1) + mask >>= 1; + else + { + mask = 0x80; + *dp = (png_byte)v; + dp++; + v = 0; + } + } + if (mask != 0x80) + *dp = (png_byte)v; + break; + } + case 2: + { + png_bytep sp, dp; + int shift, v; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + sp = row; + dp = row; + shift = 6; + v = 0; + for (i = 0; i < row_width; i++) + { + png_byte value; + + value = (png_byte)(*sp & 0x03); + v |= (value << shift); + if (shift == 0) + { + shift = 6; + *dp = (png_byte)v; + dp++; + v = 0; + } + else + shift -= 2; + sp++; + } + if (shift != 6) + *dp = (png_byte)v; + break; + } + case 4: + { + png_bytep sp, dp; + int shift, v; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + sp = row; + dp = row; + shift = 4; + v = 0; + for (i = 0; i < row_width; i++) + { + png_byte value; + + value = (png_byte)(*sp & 0x0f); + v |= (value << shift); + + if (shift == 0) + { + shift = 4; + *dp = (png_byte)v; + dp++; + v = 0; + } + else + shift -= 4; + + sp++; + } + if (shift != 4) + *dp = (png_byte)v; + break; + } + } + row_info->bit_depth = (png_byte)bit_depth; + row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels); + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, + row_info->width); + } +} +#endif + +#if defined(PNG_WRITE_SHIFT_SUPPORTED) +/* Shift pixel values to take advantage of whole range. Pass the + * true number of bits in bit_depth. The row should be packed + * according to row_info->bit_depth. Thus, if you had a row of + * bit depth 4, but the pixels only had values from 0 to 7, you + * would pass 3 as bit_depth, and this routine would translate the + * data to 0 to 15. + */ +void /* PRIVATE */ +png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth) +{ + png_debug(1, "in png_do_shift\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL && +#else + if ( +#endif + row_info->color_type != PNG_COLOR_TYPE_PALETTE) + { + int shift_start[4], shift_dec[4]; + int channels = 0; + + if (row_info->color_type & PNG_COLOR_MASK_COLOR) + { + shift_start[channels] = row_info->bit_depth - bit_depth->red; + shift_dec[channels] = bit_depth->red; + channels++; + shift_start[channels] = row_info->bit_depth - bit_depth->green; + shift_dec[channels] = bit_depth->green; + channels++; + shift_start[channels] = row_info->bit_depth - bit_depth->blue; + shift_dec[channels] = bit_depth->blue; + channels++; + } + else + { + shift_start[channels] = row_info->bit_depth - bit_depth->gray; + shift_dec[channels] = bit_depth->gray; + channels++; + } + if (row_info->color_type & PNG_COLOR_MASK_ALPHA) + { + shift_start[channels] = row_info->bit_depth - bit_depth->alpha; + shift_dec[channels] = bit_depth->alpha; + channels++; + } + + /* with low row depths, could only be grayscale, so one channel */ + if (row_info->bit_depth < 8) + { + png_bytep bp = row; + png_uint_32 i; + png_byte mask; + png_uint_32 row_bytes = row_info->rowbytes; + + if (bit_depth->gray == 1 && row_info->bit_depth == 2) + mask = 0x55; + else if (row_info->bit_depth == 4 && bit_depth->gray == 3) + mask = 0x11; + else + mask = 0xff; + + for (i = 0; i < row_bytes; i++, bp++) + { + png_uint_16 v; + int j; + + v = *bp; + *bp = 0; + for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0]) + { + if (j > 0) + *bp |= (png_byte)((v << j) & 0xff); + else + *bp |= (png_byte)((v >> (-j)) & mask); + } + } + } + else if (row_info->bit_depth == 8) + { + png_bytep bp = row; + png_uint_32 i; + png_uint_32 istop = channels * row_info->width; + + for (i = 0; i < istop; i++, bp++) + { + + png_uint_16 v; + int j; + int c = (int)(i%channels); + + v = *bp; + *bp = 0; + for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c]) + { + if (j > 0) + *bp |= (png_byte)((v << j) & 0xff); + else + *bp |= (png_byte)((v >> (-j)) & 0xff); + } + } + } + else + { + png_bytep bp; + png_uint_32 i; + png_uint_32 istop = channels * row_info->width; + + for (bp = row, i = 0; i < istop; i++) + { + int c = (int)(i%channels); + png_uint_16 value, v; + int j; + + v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1)); + value = 0; + for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c]) + { + if (j > 0) + value |= (png_uint_16)((v << j) & (png_uint_16)0xffff); + else + value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff); + } + *bp++ = (png_byte)(value >> 8); + *bp++ = (png_byte)(value & 0xff); + } + } + } +} +#endif + +#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) +void /* PRIVATE */ +png_do_write_swap_alpha(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_write_swap_alpha\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL) +#endif + { + if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + { + /* This converts from ARGB to RGBA */ + if (row_info->bit_depth == 8) + { + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + for (i = 0, sp = dp = row; i < row_width; i++) + { + png_byte save = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = save; + } + } + /* This converts from AARRGGBB to RRGGBBAA */ + else + { + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + for (i = 0, sp = dp = row; i < row_width; i++) + { + png_byte save[2]; + save[0] = *(sp++); + save[1] = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = save[0]; + *(dp++) = save[1]; + } + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + { + /* This converts from AG to GA */ + if (row_info->bit_depth == 8) + { + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + for (i = 0, sp = dp = row; i < row_width; i++) + { + png_byte save = *(sp++); + *(dp++) = *(sp++); + *(dp++) = save; + } + } + /* This converts from AAGG to GGAA */ + else + { + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + for (i = 0, sp = dp = row; i < row_width; i++) + { + png_byte save[2]; + save[0] = *(sp++); + save[1] = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = save[0]; + *(dp++) = save[1]; + } + } + } + } +} +#endif + +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) +void /* PRIVATE */ +png_do_write_invert_alpha(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_write_invert_alpha\n"); +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL) +#endif + { + if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + { + /* This inverts the alpha channel in RGBA */ + if (row_info->bit_depth == 8) + { + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + for (i = 0, sp = dp = row; i < row_width; i++) + { + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = (png_byte)(255 - *(sp++)); + } + } + /* This inverts the alpha channel in RRGGBBAA */ + else + { + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + for (i = 0, sp = dp = row; i < row_width; i++) + { + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = (png_byte)(255 - *(sp++)); + *(dp++) = (png_byte)(255 - *(sp++)); + } + } + } + else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + { + /* This inverts the alpha channel in GA */ + if (row_info->bit_depth == 8) + { + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + for (i = 0, sp = dp = row; i < row_width; i++) + { + *(dp++) = *(sp++); + *(dp++) = (png_byte)(255 - *(sp++)); + } + } + /* This inverts the alpha channel in GGAA */ + else + { + png_bytep sp, dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + for (i = 0, sp = dp = row; i < row_width; i++) + { + *(dp++) = *(sp++); + *(dp++) = *(sp++); + *(dp++) = (png_byte)(255 - *(sp++)); + *(dp++) = (png_byte)(255 - *(sp++)); + } + } + } + } +} +#endif + +#if defined(PNG_MNG_FEATURES_SUPPORTED) +/* undoes intrapixel differencing */ +void /* PRIVATE */ +png_do_write_intrapixel(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_write_intrapixel\n"); + if ( +#if defined(PNG_USELESS_TESTS_SUPPORTED) + row != NULL && row_info != NULL && +#endif + (row_info->color_type & PNG_COLOR_MASK_COLOR)) + { + int bytes_per_pixel; + png_uint_32 row_width = row_info->width; + if (row_info->bit_depth == 8) + { + png_bytep rp; + png_uint_32 i; + + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + bytes_per_pixel = 3; + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + bytes_per_pixel = 4; + else + return; + + for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) + { + *(rp) = (png_byte)((*rp - *(rp+1))&0xff); + *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff); + } + } + else if (row_info->bit_depth == 16) + { + png_bytep rp; + png_uint_32 i; + + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + bytes_per_pixel = 6; + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + bytes_per_pixel = 8; + else + return; + + for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) + { + png_uint_32 s0 = (*(rp ) << 8) | *(rp+1); + png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3); + png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5); + png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL); + png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL); + *(rp ) = (png_byte)((red >> 8) & 0xff); + *(rp+1) = (png_byte)(red & 0xff); + *(rp+4) = (png_byte)((blue >> 8) & 0xff); + *(rp+5) = (png_byte)(blue & 0xff); + } + } + } +} +#endif /* PNG_MNG_FEATURES_SUPPORTED */ +#endif /* PNG_WRITE_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/png/pngwutil.c b/SlnkDWFImpl/CxImage/png/pngwutil.c new file mode 100644 index 0000000..f9bc3fb --- /dev/null +++ b/SlnkDWFImpl/CxImage/png/pngwutil.c @@ -0,0 +1,2726 @@ + +/* pngwutil.c - utilities to write a PNG file + * + * libpng version 1.2.7 - September 12, 2004 + * For conditions of distribution and use, see copyright notice in png.h + * Copyright (c) 1998-2004 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + */ + +#define PNG_INTERNAL +#include "png.h" +#ifdef PNG_WRITE_SUPPORTED + +/* Place a 32-bit number into a buffer in PNG byte order. We work + * with unsigned numbers for convenience, although one supported + * ancillary chunk uses signed (two's complement) numbers. + */ +void /* PRIVATE */ +png_save_uint_32(png_bytep buf, png_uint_32 i) +{ + buf[0] = (png_byte)((i >> 24) & 0xff); + buf[1] = (png_byte)((i >> 16) & 0xff); + buf[2] = (png_byte)((i >> 8) & 0xff); + buf[3] = (png_byte)(i & 0xff); +} + +#if defined(PNG_WRITE_pCAL_SUPPORTED) || defined(PNG_WRITE_oFFs_SUPPORTED) +/* The png_save_int_32 function assumes integers are stored in two's + * complement format. If this isn't the case, then this routine needs to + * be modified to write data in two's complement format. + */ +void /* PRIVATE */ +png_save_int_32(png_bytep buf, png_int_32 i) +{ + buf[0] = (png_byte)((i >> 24) & 0xff); + buf[1] = (png_byte)((i >> 16) & 0xff); + buf[2] = (png_byte)((i >> 8) & 0xff); + buf[3] = (png_byte)(i & 0xff); +} +#endif + +/* Place a 16-bit number into a buffer in PNG byte order. + * The parameter is declared unsigned int, not png_uint_16, + * just to avoid potential problems on pre-ANSI C compilers. + */ +void /* PRIVATE */ +png_save_uint_16(png_bytep buf, unsigned int i) +{ + buf[0] = (png_byte)((i >> 8) & 0xff); + buf[1] = (png_byte)(i & 0xff); +} + +/* Write a PNG chunk all at once. The type is an array of ASCII characters + * representing the chunk name. The array must be at least 4 bytes in + * length, and does not need to be null terminated. To be safe, pass the + * pre-defined chunk names here, and if you need a new one, define it + * where the others are defined. The length is the length of the data. + * All the data must be present. If that is not possible, use the + * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end() + * functions instead. + */ +void PNGAPI +png_write_chunk(png_structp png_ptr, png_bytep chunk_name, + png_bytep data, png_size_t length) +{ + png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length); + png_write_chunk_data(png_ptr, data, length); + png_write_chunk_end(png_ptr); +} + +/* Write the start of a PNG chunk. The type is the chunk type. + * The total_length is the sum of the lengths of all the data you will be + * passing in png_write_chunk_data(). + */ +void PNGAPI +png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name, + png_uint_32 length) +{ + png_byte buf[4]; + png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length); + + /* write the length */ + png_save_uint_32(buf, length); + png_write_data(png_ptr, buf, (png_size_t)4); + + /* write the chunk name */ + png_write_data(png_ptr, chunk_name, (png_size_t)4); + /* reset the crc and run it over the chunk name */ + png_reset_crc(png_ptr); + png_calculate_crc(png_ptr, chunk_name, (png_size_t)4); +} + +/* Write the data of a PNG chunk started with png_write_chunk_start(). + * Note that multiple calls to this function are allowed, and that the + * sum of the lengths from these calls *must* add up to the total_length + * given to png_write_chunk_start(). + */ +void PNGAPI +png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length) +{ + /* write the data, and run the CRC over it */ + if (data != NULL && length > 0) + { + png_calculate_crc(png_ptr, data, length); + png_write_data(png_ptr, data, length); + } +} + +/* Finish a chunk started with png_write_chunk_start(). */ +void PNGAPI +png_write_chunk_end(png_structp png_ptr) +{ + png_byte buf[4]; + + /* write the crc */ + png_save_uint_32(buf, png_ptr->crc); + + png_write_data(png_ptr, buf, (png_size_t)4); +} + +/* Simple function to write the signature. If we have already written + * the magic bytes of the signature, or more likely, the PNG stream is + * being embedded into another stream and doesn't need its own signature, + * we should call png_set_sig_bytes() to tell libpng how many of the + * bytes have already been written. + */ +void /* PRIVATE */ +png_write_sig(png_structp png_ptr) +{ + png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10}; + /* write the rest of the 8 byte signature */ + png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes], + (png_size_t)8 - png_ptr->sig_bytes); + if(png_ptr->sig_bytes < 3) + png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE; +} + +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED) +/* + * This pair of functions encapsulates the operation of (a) compressing a + * text string, and (b) issuing it later as a series of chunk data writes. + * The compression_state structure is shared context for these functions + * set up by the caller in order to make the whole mess thread-safe. + */ + +typedef struct +{ + char *input; /* the uncompressed input data */ + int input_len; /* its length */ + int num_output_ptr; /* number of output pointers used */ + int max_output_ptr; /* size of output_ptr */ + png_charpp output_ptr; /* array of pointers to output */ +} compression_state; + +/* compress given text into storage in the png_ptr structure */ +static int /* PRIVATE */ +png_text_compress(png_structp png_ptr, + png_charp text, png_size_t text_len, int compression, + compression_state *comp) +{ + int ret; + + comp->num_output_ptr = comp->max_output_ptr = 0; + comp->output_ptr = NULL; + comp->input = NULL; + + /* we may just want to pass the text right through */ + if (compression == PNG_TEXT_COMPRESSION_NONE) + { + comp->input = text; + comp->input_len = text_len; + return((int)text_len); + } + + if (compression >= PNG_TEXT_COMPRESSION_LAST) + { +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + char msg[50]; + sprintf(msg, "Unknown compression type %d", compression); + png_warning(png_ptr, msg); +#else + png_warning(png_ptr, "Unknown compression type"); +#endif + } + + /* We can't write the chunk until we find out how much data we have, + * which means we need to run the compressor first and save the + * output. This shouldn't be a problem, as the vast majority of + * comments should be reasonable, but we will set up an array of + * malloc'd pointers to be sure. + * + * If we knew the application was well behaved, we could simplify this + * greatly by assuming we can always malloc an output buffer large + * enough to hold the compressed text ((1001 * text_len / 1000) + 12) + * and malloc this directly. The only time this would be a bad idea is + * if we can't malloc more than 64K and we have 64K of random input + * data, or if the input string is incredibly large (although this + * wouldn't cause a failure, just a slowdown due to swapping). + */ + + /* set up the compression buffers */ + png_ptr->zstream.avail_in = (uInt)text_len; + png_ptr->zstream.next_in = (Bytef *)text; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf; + + /* this is the same compression loop as in png_write_row() */ + do + { + /* compress the data */ + ret = deflate(&png_ptr->zstream, Z_NO_FLUSH); + if (ret != Z_OK) + { + /* error */ + if (png_ptr->zstream.msg != NULL) + png_error(png_ptr, png_ptr->zstream.msg); + else + png_error(png_ptr, "zlib error"); + } + /* check to see if we need more room */ + if (!png_ptr->zstream.avail_out && png_ptr->zstream.avail_in) + { + /* make sure the output array has room */ + if (comp->num_output_ptr >= comp->max_output_ptr) + { + int old_max; + + old_max = comp->max_output_ptr; + comp->max_output_ptr = comp->num_output_ptr + 4; + if (comp->output_ptr != NULL) + { + png_charpp old_ptr; + + old_ptr = comp->output_ptr; + comp->output_ptr = (png_charpp)png_malloc(png_ptr, + (png_uint_32)(comp->max_output_ptr * + png_sizeof (png_charpp))); + png_memcpy(comp->output_ptr, old_ptr, old_max + * png_sizeof (png_charp)); + png_free(png_ptr, old_ptr); + } + else + comp->output_ptr = (png_charpp)png_malloc(png_ptr, + (png_uint_32)(comp->max_output_ptr * + png_sizeof (png_charp))); + } + + /* save the data */ + comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr, + (png_uint_32)png_ptr->zbuf_size); + png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf, + png_ptr->zbuf_size); + comp->num_output_ptr++; + + /* and reset the buffer */ + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + png_ptr->zstream.next_out = png_ptr->zbuf; + } + /* continue until we don't have any more to compress */ + } while (png_ptr->zstream.avail_in); + + /* finish the compression */ + do + { + /* tell zlib we are finished */ + ret = deflate(&png_ptr->zstream, Z_FINISH); + + if (ret == Z_OK) + { + /* check to see if we need more room */ + if (!(png_ptr->zstream.avail_out)) + { + /* check to make sure our output array has room */ + if (comp->num_output_ptr >= comp->max_output_ptr) + { + int old_max; + + old_max = comp->max_output_ptr; + comp->max_output_ptr = comp->num_output_ptr + 4; + if (comp->output_ptr != NULL) + { + png_charpp old_ptr; + + old_ptr = comp->output_ptr; + /* This could be optimized to realloc() */ + comp->output_ptr = (png_charpp)png_malloc(png_ptr, + (png_uint_32)(comp->max_output_ptr * + png_sizeof (png_charpp))); + png_memcpy(comp->output_ptr, old_ptr, + old_max * png_sizeof (png_charp)); + png_free(png_ptr, old_ptr); + } + else + comp->output_ptr = (png_charpp)png_malloc(png_ptr, + (png_uint_32)(comp->max_output_ptr * + png_sizeof (png_charp))); + } + + /* save off the data */ + comp->output_ptr[comp->num_output_ptr] = + (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); + png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf, + png_ptr->zbuf_size); + comp->num_output_ptr++; + + /* and reset the buffer pointers */ + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + png_ptr->zstream.next_out = png_ptr->zbuf; + } + } + else if (ret != Z_STREAM_END) + { + /* we got an error */ + if (png_ptr->zstream.msg != NULL) + png_error(png_ptr, png_ptr->zstream.msg); + else + png_error(png_ptr, "zlib error"); + } + } while (ret != Z_STREAM_END); + + /* text length is number of buffers plus last buffer */ + text_len = png_ptr->zbuf_size * comp->num_output_ptr; + if (png_ptr->zstream.avail_out < png_ptr->zbuf_size) + text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out; + + return((int)text_len); +} + +/* ship the compressed text out via chunk writes */ +static void /* PRIVATE */ +png_write_compressed_data_out(png_structp png_ptr, compression_state *comp) +{ + int i; + + /* handle the no-compression case */ + if (comp->input) + { + png_write_chunk_data(png_ptr, (png_bytep)comp->input, + (png_size_t)comp->input_len); + return; + } + + /* write saved output buffers, if any */ + for (i = 0; i < comp->num_output_ptr; i++) + { + png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i], + png_ptr->zbuf_size); + png_free(png_ptr, comp->output_ptr[i]); + comp->output_ptr[i]=NULL; + } + if (comp->max_output_ptr != 0) + png_free(png_ptr, comp->output_ptr); + comp->output_ptr=NULL; + /* write anything left in zbuf */ + if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size) + png_write_chunk_data(png_ptr, png_ptr->zbuf, + png_ptr->zbuf_size - png_ptr->zstream.avail_out); + + /* reset zlib for another zTXt/iTXt or the image data */ + deflateReset(&png_ptr->zstream); + +} +#endif + +/* Write the IHDR chunk, and update the png_struct with the necessary + * information. Note that the rest of this code depends upon this + * information being correct. + */ +void /* PRIVATE */ +png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height, + int bit_depth, int color_type, int compression_type, int filter_type, + int interlace_type) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IHDR; +#endif + png_byte buf[13]; /* buffer to store the IHDR info */ + + png_debug(1, "in png_write_IHDR\n"); + /* Check that we have valid input data from the application info */ + switch (color_type) + { + case PNG_COLOR_TYPE_GRAY: + switch (bit_depth) + { + case 1: + case 2: + case 4: + case 8: + case 16: png_ptr->channels = 1; break; + default: png_error(png_ptr,"Invalid bit depth for grayscale image"); + } + break; + case PNG_COLOR_TYPE_RGB: + if (bit_depth != 8 && bit_depth != 16) + png_error(png_ptr, "Invalid bit depth for RGB image"); + png_ptr->channels = 3; + break; + case PNG_COLOR_TYPE_PALETTE: + switch (bit_depth) + { + case 1: + case 2: + case 4: + case 8: png_ptr->channels = 1; break; + default: png_error(png_ptr, "Invalid bit depth for paletted image"); + } + break; + case PNG_COLOR_TYPE_GRAY_ALPHA: + if (bit_depth != 8 && bit_depth != 16) + png_error(png_ptr, "Invalid bit depth for grayscale+alpha image"); + png_ptr->channels = 2; + break; + case PNG_COLOR_TYPE_RGB_ALPHA: + if (bit_depth != 8 && bit_depth != 16) + png_error(png_ptr, "Invalid bit depth for RGBA image"); + png_ptr->channels = 4; + break; + default: + png_error(png_ptr, "Invalid image color type specified"); + } + + if (compression_type != PNG_COMPRESSION_TYPE_BASE) + { + png_warning(png_ptr, "Invalid compression type specified"); + compression_type = PNG_COMPRESSION_TYPE_BASE; + } + + /* Write filter_method 64 (intrapixel differencing) only if + * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and + * 2. Libpng did not write a PNG signature (this filter_method is only + * used in PNG datastreams that are embedded in MNG datastreams) and + * 3. The application called png_permit_mng_features with a mask that + * included PNG_FLAG_MNG_FILTER_64 and + * 4. The filter_method is 64 and + * 5. The color_type is RGB or RGBA + */ + if ( +#if defined(PNG_MNG_FEATURES_SUPPORTED) + !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && + ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) && + (color_type == PNG_COLOR_TYPE_RGB || + color_type == PNG_COLOR_TYPE_RGB_ALPHA) && + (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) && +#endif + filter_type != PNG_FILTER_TYPE_BASE) + { + png_warning(png_ptr, "Invalid filter type specified"); + filter_type = PNG_FILTER_TYPE_BASE; + } + +#ifdef PNG_WRITE_INTERLACING_SUPPORTED + if (interlace_type != PNG_INTERLACE_NONE && + interlace_type != PNG_INTERLACE_ADAM7) + { + png_warning(png_ptr, "Invalid interlace type specified"); + interlace_type = PNG_INTERLACE_ADAM7; + } +#else + interlace_type=PNG_INTERLACE_NONE; +#endif + + /* save off the relevent information */ + png_ptr->bit_depth = (png_byte)bit_depth; + png_ptr->color_type = (png_byte)color_type; + png_ptr->interlaced = (png_byte)interlace_type; +#if defined(PNG_MNG_FEATURES_SUPPORTED) + png_ptr->filter_type = (png_byte)filter_type; +#endif + png_ptr->compression_type = (png_byte)compression_type; + png_ptr->width = width; + png_ptr->height = height; + + png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels); + png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width); + /* set the usr info, so any transformations can modify it */ + png_ptr->usr_width = png_ptr->width; + png_ptr->usr_bit_depth = png_ptr->bit_depth; + png_ptr->usr_channels = png_ptr->channels; + + /* pack the header information into the buffer */ + png_save_uint_32(buf, width); + png_save_uint_32(buf + 4, height); + buf[8] = (png_byte)bit_depth; + buf[9] = (png_byte)color_type; + buf[10] = (png_byte)compression_type; + buf[11] = (png_byte)filter_type; + buf[12] = (png_byte)interlace_type; + + /* write the chunk */ + png_write_chunk(png_ptr, (png_bytep)png_IHDR, buf, (png_size_t)13); + + /* initialize zlib with PNG info */ + png_ptr->zstream.zalloc = png_zalloc; + png_ptr->zstream.zfree = png_zfree; + png_ptr->zstream.opaque = (voidpf)png_ptr; + if (!(png_ptr->do_filter)) + { + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE || + png_ptr->bit_depth < 8) + png_ptr->do_filter = PNG_FILTER_NONE; + else + png_ptr->do_filter = PNG_ALL_FILTERS; + } + if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY)) + { + if (png_ptr->do_filter != PNG_FILTER_NONE) + png_ptr->zlib_strategy = Z_FILTERED; + else + png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY; + } + if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL)) + png_ptr->zlib_level = Z_DEFAULT_COMPRESSION; + if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL)) + png_ptr->zlib_mem_level = 8; + if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS)) + png_ptr->zlib_window_bits = 15; + if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD)) + png_ptr->zlib_method = 8; + deflateInit2(&png_ptr->zstream, png_ptr->zlib_level, + png_ptr->zlib_method, png_ptr->zlib_window_bits, + png_ptr->zlib_mem_level, png_ptr->zlib_strategy); + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + + png_ptr->mode = PNG_HAVE_IHDR; +} + +/* write the palette. We are careful not to trust png_color to be in the + * correct order for PNG, so people can redefine it to any convenient + * structure. + */ +void /* PRIVATE */ +png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_PLTE; +#endif + png_uint_32 i; + png_colorp pal_ptr; + png_byte buf[3]; + + png_debug(1, "in png_write_PLTE\n"); + if (( +#if defined(PNG_MNG_FEATURES_SUPPORTED) + !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) && +#endif + num_pal == 0) || num_pal > 256) + { + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + png_error(png_ptr, "Invalid number of colors in palette"); + } + else + { + png_warning(png_ptr, "Invalid number of colors in palette"); + return; + } + } + + if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR)) + { + png_warning(png_ptr, + "Ignoring request to write a PLTE chunk in grayscale PNG"); + return; + } + + png_ptr->num_palette = (png_uint_16)num_pal; + png_debug1(3, "num_palette = %d\n", png_ptr->num_palette); + + png_write_chunk_start(png_ptr, (png_bytep)png_PLTE, num_pal * 3); +#ifndef PNG_NO_POINTER_INDEXING + for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++) + { + buf[0] = pal_ptr->red; + buf[1] = pal_ptr->green; + buf[2] = pal_ptr->blue; + png_write_chunk_data(png_ptr, buf, (png_size_t)3); + } +#else + /* This is a little slower but some buggy compilers need to do this instead */ + pal_ptr=palette; + for (i = 0; i < num_pal; i++) + { + buf[0] = pal_ptr[i].red; + buf[1] = pal_ptr[i].green; + buf[2] = pal_ptr[i].blue; + png_write_chunk_data(png_ptr, buf, (png_size_t)3); + } +#endif + png_write_chunk_end(png_ptr); + png_ptr->mode |= PNG_HAVE_PLTE; +} + +/* write an IDAT chunk */ +void /* PRIVATE */ +png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IDAT; +#endif + png_debug(1, "in png_write_IDAT\n"); + + /* Optimize the CMF field in the zlib stream. */ + /* This hack of the zlib stream is compliant to the stream specification. */ + if (!(png_ptr->mode & PNG_HAVE_IDAT) && + png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE) + { + unsigned int z_cmf = data[0]; /* zlib compression method and flags */ + if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70) + { + /* Avoid memory underflows and multiplication overflows. */ + /* The conditions below are practically always satisfied; + however, they still must be checked. */ + if (length >= 2 && + png_ptr->height < 16384 && png_ptr->width < 16384) + { + png_uint_32 uncompressed_idat_size = png_ptr->height * + ((png_ptr->width * + png_ptr->channels * png_ptr->bit_depth + 15) >> 3); + unsigned int z_cinfo = z_cmf >> 4; + unsigned int half_z_window_size = 1 << (z_cinfo + 7); + while (uncompressed_idat_size <= half_z_window_size && + half_z_window_size >= 256) + { + z_cinfo--; + half_z_window_size >>= 1; + } + z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4); + if (data[0] != (png_byte)z_cmf) + { + data[0] = (png_byte)z_cmf; + data[1] &= 0xe0; + data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f); + } + } + } + else + png_error(png_ptr, + "Invalid zlib compression method or flags in IDAT"); + } + + png_write_chunk(png_ptr, (png_bytep)png_IDAT, data, length); + png_ptr->mode |= PNG_HAVE_IDAT; +} + +/* write an IEND chunk */ +void /* PRIVATE */ +png_write_IEND(png_structp png_ptr) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_IEND; +#endif + png_debug(1, "in png_write_IEND\n"); + png_write_chunk(png_ptr, (png_bytep)png_IEND, png_bytep_NULL, + (png_size_t)0); + png_ptr->mode |= PNG_HAVE_IEND; +} + +#if defined(PNG_WRITE_gAMA_SUPPORTED) +/* write a gAMA chunk */ +#ifdef PNG_FLOATING_POINT_SUPPORTED +void /* PRIVATE */ +png_write_gAMA(png_structp png_ptr, double file_gamma) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_gAMA; +#endif + png_uint_32 igamma; + png_byte buf[4]; + + png_debug(1, "in png_write_gAMA\n"); + /* file_gamma is saved in 1/100,000ths */ + igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5); + png_save_uint_32(buf, igamma); + png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4); +} +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +void /* PRIVATE */ +png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_gAMA; +#endif + png_byte buf[4]; + + png_debug(1, "in png_write_gAMA\n"); + /* file_gamma is saved in 1/100,000ths */ + png_save_uint_32(buf, (png_uint_32)file_gamma); + png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4); +} +#endif +#endif + +#if defined(PNG_WRITE_sRGB_SUPPORTED) +/* write a sRGB chunk */ +void /* PRIVATE */ +png_write_sRGB(png_structp png_ptr, int srgb_intent) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_sRGB; +#endif + png_byte buf[1]; + + png_debug(1, "in png_write_sRGB\n"); + if(srgb_intent >= PNG_sRGB_INTENT_LAST) + png_warning(png_ptr, + "Invalid sRGB rendering intent specified"); + buf[0]=(png_byte)srgb_intent; + png_write_chunk(png_ptr, (png_bytep)png_sRGB, buf, (png_size_t)1); +} +#endif + +#if defined(PNG_WRITE_iCCP_SUPPORTED) +/* write an iCCP chunk */ +void /* PRIVATE */ +png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type, + png_charp profile, int profile_len) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_iCCP; +#endif + png_size_t name_len; + png_charp new_name; + compression_state comp; + + png_debug(1, "in png_write_iCCP\n"); + if (name == NULL || (name_len = png_check_keyword(png_ptr, name, + &new_name)) == 0) + { + png_warning(png_ptr, "Empty keyword in iCCP chunk"); + return; + } + + if (compression_type != PNG_COMPRESSION_TYPE_BASE) + png_warning(png_ptr, "Unknown compression type in iCCP chunk"); + + if (profile == NULL) + profile_len = 0; + + if (profile_len) + profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len, + PNG_COMPRESSION_TYPE_BASE, &comp); + + /* make sure we include the NULL after the name and the compression type */ + png_write_chunk_start(png_ptr, (png_bytep)png_iCCP, + (png_uint_32)name_len+profile_len+2); + new_name[name_len+1]=0x00; + png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2); + + if (profile_len) + png_write_compressed_data_out(png_ptr, &comp); + + png_write_chunk_end(png_ptr); + png_free(png_ptr, new_name); +} +#endif + +#if defined(PNG_WRITE_sPLT_SUPPORTED) +/* write a sPLT chunk */ +void /* PRIVATE */ +png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_sPLT; +#endif + png_size_t name_len; + png_charp new_name; + png_byte entrybuf[10]; + int entry_size = (spalette->depth == 8 ? 6 : 10); + int palette_size = entry_size * spalette->nentries; + png_sPLT_entryp ep; +#ifdef PNG_NO_POINTER_INDEXING + int i; +#endif + + png_debug(1, "in png_write_sPLT\n"); + if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr, + spalette->name, &new_name))==0) + { + png_warning(png_ptr, "Empty keyword in sPLT chunk"); + return; + } + + /* make sure we include the NULL after the name */ + png_write_chunk_start(png_ptr, (png_bytep)png_sPLT, + (png_uint_32)(name_len + 2 + palette_size)); + png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1); + png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1); + + /* loop through each palette entry, writing appropriately */ +#ifndef PNG_NO_POINTER_INDEXING + for (ep = spalette->entries; epentries+spalette->nentries; ep++) + { + if (spalette->depth == 8) + { + entrybuf[0] = (png_byte)ep->red; + entrybuf[1] = (png_byte)ep->green; + entrybuf[2] = (png_byte)ep->blue; + entrybuf[3] = (png_byte)ep->alpha; + png_save_uint_16(entrybuf + 4, ep->frequency); + } + else + { + png_save_uint_16(entrybuf + 0, ep->red); + png_save_uint_16(entrybuf + 2, ep->green); + png_save_uint_16(entrybuf + 4, ep->blue); + png_save_uint_16(entrybuf + 6, ep->alpha); + png_save_uint_16(entrybuf + 8, ep->frequency); + } + png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size); + } +#else + ep=spalette->entries; + for (i=0; i>spalette->nentries; i++) + { + if (spalette->depth == 8) + { + entrybuf[0] = (png_byte)ep[i].red; + entrybuf[1] = (png_byte)ep[i].green; + entrybuf[2] = (png_byte)ep[i].blue; + entrybuf[3] = (png_byte)ep[i].alpha; + png_save_uint_16(entrybuf + 4, ep[i].frequency); + } + else + { + png_save_uint_16(entrybuf + 0, ep[i].red); + png_save_uint_16(entrybuf + 2, ep[i].green); + png_save_uint_16(entrybuf + 4, ep[i].blue); + png_save_uint_16(entrybuf + 6, ep[i].alpha); + png_save_uint_16(entrybuf + 8, ep[i].frequency); + } + png_write_chunk_data(png_ptr, entrybuf, entry_size); + } +#endif + + png_write_chunk_end(png_ptr); + png_free(png_ptr, new_name); +} +#endif + +#if defined(PNG_WRITE_sBIT_SUPPORTED) +/* write the sBIT chunk */ +void /* PRIVATE */ +png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_sBIT; +#endif + png_byte buf[4]; + png_size_t size; + + png_debug(1, "in png_write_sBIT\n"); + /* make sure we don't depend upon the order of PNG_COLOR_8 */ + if (color_type & PNG_COLOR_MASK_COLOR) + { + png_byte maxbits; + + maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 : + png_ptr->usr_bit_depth); + if (sbit->red == 0 || sbit->red > maxbits || + sbit->green == 0 || sbit->green > maxbits || + sbit->blue == 0 || sbit->blue > maxbits) + { + png_warning(png_ptr, "Invalid sBIT depth specified"); + return; + } + buf[0] = sbit->red; + buf[1] = sbit->green; + buf[2] = sbit->blue; + size = 3; + } + else + { + if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth) + { + png_warning(png_ptr, "Invalid sBIT depth specified"); + return; + } + buf[0] = sbit->gray; + size = 1; + } + + if (color_type & PNG_COLOR_MASK_ALPHA) + { + if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth) + { + png_warning(png_ptr, "Invalid sBIT depth specified"); + return; + } + buf[size++] = sbit->alpha; + } + + png_write_chunk(png_ptr, (png_bytep)png_sBIT, buf, size); +} +#endif + +#if defined(PNG_WRITE_cHRM_SUPPORTED) +/* write the cHRM chunk */ +#ifdef PNG_FLOATING_POINT_SUPPORTED +void /* PRIVATE */ +png_write_cHRM(png_structp png_ptr, double white_x, double white_y, + double red_x, double red_y, double green_x, double green_y, + double blue_x, double blue_y) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_cHRM; +#endif + png_byte buf[32]; + png_uint_32 itemp; + + png_debug(1, "in png_write_cHRM\n"); + /* each value is saved in 1/100,000ths */ + if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 || + white_x + white_y > 1.0) + { + png_warning(png_ptr, "Invalid cHRM white point specified"); +#if !defined(PNG_NO_CONSOLE_IO) + fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y); +#endif + return; + } + itemp = (png_uint_32)(white_x * 100000.0 + 0.5); + png_save_uint_32(buf, itemp); + itemp = (png_uint_32)(white_y * 100000.0 + 0.5); + png_save_uint_32(buf + 4, itemp); + + if (red_x < 0 || red_x > 0.8 || red_y < 0 || red_y > 0.8 || + red_x + red_y > 1.0) + { + png_warning(png_ptr, "Invalid cHRM red point specified"); + return; + } + itemp = (png_uint_32)(red_x * 100000.0 + 0.5); + png_save_uint_32(buf + 8, itemp); + itemp = (png_uint_32)(red_y * 100000.0 + 0.5); + png_save_uint_32(buf + 12, itemp); + + if (green_x < 0 || green_x > 0.8 || green_y < 0 || green_y > 0.8 || + green_x + green_y > 1.0) + { + png_warning(png_ptr, "Invalid cHRM green point specified"); + return; + } + itemp = (png_uint_32)(green_x * 100000.0 + 0.5); + png_save_uint_32(buf + 16, itemp); + itemp = (png_uint_32)(green_y * 100000.0 + 0.5); + png_save_uint_32(buf + 20, itemp); + + if (blue_x < 0 || blue_x > 0.8 || blue_y < 0 || blue_y > 0.8 || + blue_x + blue_y > 1.0) + { + png_warning(png_ptr, "Invalid cHRM blue point specified"); + return; + } + itemp = (png_uint_32)(blue_x * 100000.0 + 0.5); + png_save_uint_32(buf + 24, itemp); + itemp = (png_uint_32)(blue_y * 100000.0 + 0.5); + png_save_uint_32(buf + 28, itemp); + + png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32); +} +#endif +#ifdef PNG_FIXED_POINT_SUPPORTED +void /* PRIVATE */ +png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x, + png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y, + png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x, + png_fixed_point blue_y) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_cHRM; +#endif + png_byte buf[32]; + + png_debug(1, "in png_write_cHRM\n"); + /* each value is saved in 1/100,000ths */ + if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L) + { + png_warning(png_ptr, "Invalid fixed cHRM white point specified"); +#if !defined(PNG_NO_CONSOLE_IO) + fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y); +#endif + return; + } + png_save_uint_32(buf, (png_uint_32)white_x); + png_save_uint_32(buf + 4, (png_uint_32)white_y); + + if (red_x > 80000L || red_y > 80000L || red_x + red_y > 100000L) + { + png_warning(png_ptr, "Invalid cHRM fixed red point specified"); + return; + } + png_save_uint_32(buf + 8, (png_uint_32)red_x); + png_save_uint_32(buf + 12, (png_uint_32)red_y); + + if (green_x > 80000L || green_y > 80000L || green_x + green_y > 100000L) + { + png_warning(png_ptr, "Invalid fixed cHRM green point specified"); + return; + } + png_save_uint_32(buf + 16, (png_uint_32)green_x); + png_save_uint_32(buf + 20, (png_uint_32)green_y); + + if (blue_x > 80000L || blue_y > 80000L || blue_x + blue_y > 100000L) + { + png_warning(png_ptr, "Invalid fixed cHRM blue point specified"); + return; + } + png_save_uint_32(buf + 24, (png_uint_32)blue_x); + png_save_uint_32(buf + 28, (png_uint_32)blue_y); + + png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32); +} +#endif +#endif + +#if defined(PNG_WRITE_tRNS_SUPPORTED) +/* write the tRNS chunk */ +void /* PRIVATE */ +png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran, + int num_trans, int color_type) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_tRNS; +#endif + png_byte buf[6]; + + png_debug(1, "in png_write_tRNS\n"); + if (color_type == PNG_COLOR_TYPE_PALETTE) + { + if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette) + { + png_warning(png_ptr,"Invalid number of transparent colors specified"); + return; + } + /* write the chunk out as it is */ + png_write_chunk(png_ptr, (png_bytep)png_tRNS, trans, (png_size_t)num_trans); + } + else if (color_type == PNG_COLOR_TYPE_GRAY) + { + /* one 16 bit value */ + if(tran->gray >= (1 << png_ptr->bit_depth)) + { + png_warning(png_ptr, + "Ignoring attempt to write tRNS chunk out-of-range for bit_depth"); + return; + } + png_save_uint_16(buf, tran->gray); + png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)2); + } + else if (color_type == PNG_COLOR_TYPE_RGB) + { + /* three 16 bit values */ + png_save_uint_16(buf, tran->red); + png_save_uint_16(buf + 2, tran->green); + png_save_uint_16(buf + 4, tran->blue); + if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4])) + { + png_warning(png_ptr, + "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8"); + return; + } + png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)6); + } + else + { + png_warning(png_ptr, "Can't write tRNS with an alpha channel"); + } +} +#endif + +#if defined(PNG_WRITE_bKGD_SUPPORTED) +/* write the background chunk */ +void /* PRIVATE */ +png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_bKGD; +#endif + png_byte buf[6]; + + png_debug(1, "in png_write_bKGD\n"); + if (color_type == PNG_COLOR_TYPE_PALETTE) + { + if ( +#if defined(PNG_MNG_FEATURES_SUPPORTED) + (png_ptr->num_palette || + (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) && +#endif + back->index > png_ptr->num_palette) + { + png_warning(png_ptr, "Invalid background palette index"); + return; + } + buf[0] = back->index; + png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)1); + } + else if (color_type & PNG_COLOR_MASK_COLOR) + { + png_save_uint_16(buf, back->red); + png_save_uint_16(buf + 2, back->green); + png_save_uint_16(buf + 4, back->blue); + if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4])) + { + png_warning(png_ptr, + "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8"); + return; + } + png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)6); + } + else + { + if(back->gray >= (1 << png_ptr->bit_depth)) + { + png_warning(png_ptr, + "Ignoring attempt to write bKGD chunk out-of-range for bit_depth"); + return; + } + png_save_uint_16(buf, back->gray); + png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)2); + } +} +#endif + +#if defined(PNG_WRITE_hIST_SUPPORTED) +/* write the histogram */ +void /* PRIVATE */ +png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_hIST; +#endif + int i; + png_byte buf[3]; + + png_debug(1, "in png_write_hIST\n"); + if (num_hist > (int)png_ptr->num_palette) + { + png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist, + png_ptr->num_palette); + png_warning(png_ptr, "Invalid number of histogram entries specified"); + return; + } + + png_write_chunk_start(png_ptr, (png_bytep)png_hIST, (png_uint_32)(num_hist * 2)); + for (i = 0; i < num_hist; i++) + { + png_save_uint_16(buf, hist[i]); + png_write_chunk_data(png_ptr, buf, (png_size_t)2); + } + png_write_chunk_end(png_ptr); +} +#endif + +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \ + defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED) +/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification, + * and if invalid, correct the keyword rather than discarding the entire + * chunk. The PNG 1.0 specification requires keywords 1-79 characters in + * length, forbids leading or trailing whitespace, multiple internal spaces, + * and the non-break space (0x80) from ISO 8859-1. Returns keyword length. + * + * The new_key is allocated to hold the corrected keyword and must be freed + * by the calling routine. This avoids problems with trying to write to + * static keywords without having to have duplicate copies of the strings. + */ +png_size_t /* PRIVATE */ +png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key) +{ + png_size_t key_len; + png_charp kp, dp; + int kflag; + int kwarn=0; + + png_debug(1, "in png_check_keyword\n"); + *new_key = NULL; + + if (key == NULL || (key_len = png_strlen(key)) == 0) + { + png_warning(png_ptr, "zero length keyword"); + return ((png_size_t)0); + } + + png_debug1(2, "Keyword to be checked is '%s'\n", key); + + *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2)); + if (*new_key == NULL) + { + png_warning(png_ptr, "Out of memory while procesing keyword"); + return ((png_size_t)0); + } + + /* Replace non-printing characters with a blank and print a warning */ + for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++) + { + if (*kp < 0x20 || (*kp > 0x7E && (png_byte)*kp < 0xA1)) + { +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE) + char msg[40]; + + sprintf(msg, "invalid keyword character 0x%02X", *kp); + png_warning(png_ptr, msg); +#else + png_warning(png_ptr, "invalid character in keyword"); +#endif + *dp = ' '; + } + else + { + *dp = *kp; + } + } + *dp = '\0'; + + /* Remove any trailing white space. */ + kp = *new_key + key_len - 1; + if (*kp == ' ') + { + png_warning(png_ptr, "trailing spaces removed from keyword"); + + while (*kp == ' ') + { + *(kp--) = '\0'; + key_len--; + } + } + + /* Remove any leading white space. */ + kp = *new_key; + if (*kp == ' ') + { + png_warning(png_ptr, "leading spaces removed from keyword"); + + while (*kp == ' ') + { + kp++; + key_len--; + } + } + + png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp); + + /* Remove multiple internal spaces. */ + for (kflag = 0, dp = *new_key; *kp != '\0'; kp++) + { + if (*kp == ' ' && kflag == 0) + { + *(dp++) = *kp; + kflag = 1; + } + else if (*kp == ' ') + { + key_len--; + kwarn=1; + } + else + { + *(dp++) = *kp; + kflag = 0; + } + } + *dp = '\0'; + if(kwarn) + png_warning(png_ptr, "extra interior spaces removed from keyword"); + + if (key_len == 0) + { + png_free(png_ptr, *new_key); + *new_key=NULL; + png_warning(png_ptr, "Zero length keyword"); + } + + if (key_len > 79) + { + png_warning(png_ptr, "keyword length must be 1 - 79 characters"); + new_key[79] = '\0'; + key_len = 79; + } + + return (key_len); +} +#endif + +#if defined(PNG_WRITE_tEXt_SUPPORTED) +/* write a tEXt chunk */ +void /* PRIVATE */ +png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text, + png_size_t text_len) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_tEXt; +#endif + png_size_t key_len; + png_charp new_key; + + png_debug(1, "in png_write_tEXt\n"); + if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0) + { + png_warning(png_ptr, "Empty keyword in tEXt chunk"); + return; + } + + if (text == NULL || *text == '\0') + text_len = 0; + else + text_len = png_strlen(text); + + /* make sure we include the 0 after the key */ + png_write_chunk_start(png_ptr, (png_bytep)png_tEXt, (png_uint_32)key_len+text_len+1); + /* + * We leave it to the application to meet PNG-1.0 requirements on the + * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of + * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them. + * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG. + */ + png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1); + if (text_len) + png_write_chunk_data(png_ptr, (png_bytep)text, text_len); + + png_write_chunk_end(png_ptr); + png_free(png_ptr, new_key); +} +#endif + +#if defined(PNG_WRITE_zTXt_SUPPORTED) +/* write a compressed text chunk */ +void /* PRIVATE */ +png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text, + png_size_t text_len, int compression) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_zTXt; +#endif + png_size_t key_len; + char buf[1]; + png_charp new_key; + compression_state comp; + + png_debug(1, "in png_write_zTXt\n"); + + if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0) + { + png_warning(png_ptr, "Empty keyword in zTXt chunk"); + return; + } + + if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE) + { + png_write_tEXt(png_ptr, new_key, text, (png_size_t)0); + png_free(png_ptr, new_key); + return; + } + + text_len = png_strlen(text); + + png_free(png_ptr, new_key); + + /* compute the compressed data; do it now for the length */ + text_len = png_text_compress(png_ptr, text, text_len, compression, + &comp); + + /* write start of chunk */ + png_write_chunk_start(png_ptr, (png_bytep)png_zTXt, (png_uint_32) + (key_len+text_len+2)); + /* write key */ + png_write_chunk_data(png_ptr, (png_bytep)key, key_len + 1); + buf[0] = (png_byte)compression; + /* write compression */ + png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1); + /* write the compressed data */ + png_write_compressed_data_out(png_ptr, &comp); + + /* close the chunk */ + png_write_chunk_end(png_ptr); +} +#endif + +#if defined(PNG_WRITE_iTXt_SUPPORTED) +/* write an iTXt chunk */ +void /* PRIVATE */ +png_write_iTXt(png_structp png_ptr, int compression, png_charp key, + png_charp lang, png_charp lang_key, png_charp text) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_iTXt; +#endif + png_size_t lang_len, key_len, lang_key_len, text_len; + png_charp new_lang, new_key; + png_byte cbuf[2]; + compression_state comp; + + png_debug(1, "in png_write_iTXt\n"); + + if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0) + { + png_warning(png_ptr, "Empty keyword in iTXt chunk"); + return; + } + if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0) + { + png_warning(png_ptr, "Empty language field in iTXt chunk"); + new_lang = NULL; + lang_len = 0; + } + + if (lang_key == NULL) + lang_key_len = 0; + else + lang_key_len = png_strlen(lang_key); + + if (text == NULL) + text_len = 0; + else + text_len = png_strlen(text); + + /* compute the compressed data; do it now for the length */ + text_len = png_text_compress(png_ptr, text, text_len, compression-2, + &comp); + + + /* make sure we include the compression flag, the compression byte, + * and the NULs after the key, lang, and lang_key parts */ + + png_write_chunk_start(png_ptr, (png_bytep)png_iTXt, + (png_uint_32)( + 5 /* comp byte, comp flag, terminators for key, lang and lang_key */ + + key_len + + lang_len + + lang_key_len + + text_len)); + + /* + * We leave it to the application to meet PNG-1.0 requirements on the + * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of + * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them. + * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG. + */ + png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1); + + /* set the compression flag */ + if (compression == PNG_ITXT_COMPRESSION_NONE || \ + compression == PNG_TEXT_COMPRESSION_NONE) + cbuf[0] = 0; + else /* compression == PNG_ITXT_COMPRESSION_zTXt */ + cbuf[0] = 1; + /* set the compression method */ + cbuf[1] = 0; + png_write_chunk_data(png_ptr, cbuf, 2); + + cbuf[0] = 0; + png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1); + png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1); + png_write_compressed_data_out(png_ptr, &comp); + + png_write_chunk_end(png_ptr); + png_free(png_ptr, new_key); + if (new_lang) + png_free(png_ptr, new_lang); +} +#endif + +#if defined(PNG_WRITE_oFFs_SUPPORTED) +/* write the oFFs chunk */ +void /* PRIVATE */ +png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset, + int unit_type) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_oFFs; +#endif + png_byte buf[9]; + + png_debug(1, "in png_write_oFFs\n"); + if (unit_type >= PNG_OFFSET_LAST) + png_warning(png_ptr, "Unrecognized unit type for oFFs chunk"); + + png_save_int_32(buf, x_offset); + png_save_int_32(buf + 4, y_offset); + buf[8] = (png_byte)unit_type; + + png_write_chunk(png_ptr, (png_bytep)png_oFFs, buf, (png_size_t)9); +} +#endif + +#if defined(PNG_WRITE_pCAL_SUPPORTED) +/* write the pCAL chunk (described in the PNG extensions document) */ +void /* PRIVATE */ +png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0, + png_int_32 X1, int type, int nparams, png_charp units, png_charpp params) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_pCAL; +#endif + png_size_t purpose_len, units_len, total_len; + png_uint_32p params_len; + png_byte buf[10]; + png_charp new_purpose; + int i; + + png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams); + if (type >= PNG_EQUATION_LAST) + png_warning(png_ptr, "Unrecognized equation type for pCAL chunk"); + + purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1; + png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len); + units_len = png_strlen(units) + (nparams == 0 ? 0 : 1); + png_debug1(3, "pCAL units length = %d\n", (int)units_len); + total_len = purpose_len + units_len + 10; + + params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams + *png_sizeof(png_uint_32))); + + /* Find the length of each parameter, making sure we don't count the + null terminator for the last parameter. */ + for (i = 0; i < nparams; i++) + { + params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1); + png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]); + total_len += (png_size_t)params_len[i]; + } + + png_debug1(3, "pCAL total length = %d\n", (int)total_len); + png_write_chunk_start(png_ptr, (png_bytep)png_pCAL, (png_uint_32)total_len); + png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len); + png_save_int_32(buf, X0); + png_save_int_32(buf + 4, X1); + buf[8] = (png_byte)type; + buf[9] = (png_byte)nparams; + png_write_chunk_data(png_ptr, buf, (png_size_t)10); + png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len); + + png_free(png_ptr, new_purpose); + + for (i = 0; i < nparams; i++) + { + png_write_chunk_data(png_ptr, (png_bytep)params[i], + (png_size_t)params_len[i]); + } + + png_free(png_ptr, params_len); + png_write_chunk_end(png_ptr); +} +#endif + +#if defined(PNG_WRITE_sCAL_SUPPORTED) +/* write the sCAL chunk */ +#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO) +void /* PRIVATE */ +png_write_sCAL(png_structp png_ptr, int unit, double width,double height) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_sCAL; +#endif + png_size_t total_len; + char wbuf[32], hbuf[32]; + png_byte bunit = unit; + + png_debug(1, "in png_write_sCAL\n"); + +#if defined(_WIN32_WCE) +/* sprintf() function is not supported on WindowsCE */ + { + wchar_t wc_buf[32]; + swprintf(wc_buf, TEXT("%12.12e"), width); + WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, wbuf, 32, NULL, NULL); + swprintf(wc_buf, TEXT("%12.12e"), height); + WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, hbuf, 32, NULL, NULL); + } +#else + sprintf(wbuf, "%12.12e", width); + sprintf(hbuf, "%12.12e", height); +#endif + total_len = 1 + png_strlen(wbuf)+1 + png_strlen(hbuf); + + png_debug1(3, "sCAL total length = %d\n", (int)total_len); + png_write_chunk_start(png_ptr, (png_bytep)png_sCAL, (png_uint_32)total_len); + png_write_chunk_data(png_ptr, (png_bytep)&bunit, 1); + png_write_chunk_data(png_ptr, (png_bytep)wbuf, png_strlen(wbuf)+1); + png_write_chunk_data(png_ptr, (png_bytep)hbuf, png_strlen(hbuf)); + + png_write_chunk_end(png_ptr); +} +#else +#ifdef PNG_FIXED_POINT_SUPPORTED +void /* PRIVATE */ +png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width, + png_charp height) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_sCAL; +#endif + png_size_t total_len; + char wbuf[32], hbuf[32]; + png_byte bunit = unit; + + png_debug(1, "in png_write_sCAL_s\n"); + + png_strcpy(wbuf,(const char *)width); + png_strcpy(hbuf,(const char *)height); + total_len = 1 + png_strlen(wbuf)+1 + png_strlen(hbuf); + + png_debug1(3, "sCAL total length = %d\n", total_len); + png_write_chunk_start(png_ptr, (png_bytep)png_sCAL, (png_uint_32)total_len); + png_write_chunk_data(png_ptr, (png_bytep)&bunit, 1); + png_write_chunk_data(png_ptr, (png_bytep)wbuf, png_strlen(wbuf)+1); + png_write_chunk_data(png_ptr, (png_bytep)hbuf, png_strlen(hbuf)); + + png_write_chunk_end(png_ptr); +} +#endif +#endif +#endif + +#if defined(PNG_WRITE_pHYs_SUPPORTED) +/* write the pHYs chunk */ +void /* PRIVATE */ +png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit, + png_uint_32 y_pixels_per_unit, + int unit_type) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_pHYs; +#endif + png_byte buf[9]; + + png_debug(1, "in png_write_pHYs\n"); + if (unit_type >= PNG_RESOLUTION_LAST) + png_warning(png_ptr, "Unrecognized unit type for pHYs chunk"); + + png_save_uint_32(buf, x_pixels_per_unit); + png_save_uint_32(buf + 4, y_pixels_per_unit); + buf[8] = (png_byte)unit_type; + + png_write_chunk(png_ptr, (png_bytep)png_pHYs, buf, (png_size_t)9); +} +#endif + +#if defined(PNG_WRITE_tIME_SUPPORTED) +/* Write the tIME chunk. Use either png_convert_from_struct_tm() + * or png_convert_from_time_t(), or fill in the structure yourself. + */ +void /* PRIVATE */ +png_write_tIME(png_structp png_ptr, png_timep mod_time) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + PNG_tIME; +#endif + png_byte buf[7]; + + png_debug(1, "in png_write_tIME\n"); + if (mod_time->month > 12 || mod_time->month < 1 || + mod_time->day > 31 || mod_time->day < 1 || + mod_time->hour > 23 || mod_time->second > 60) + { + png_warning(png_ptr, "Invalid time specified for tIME chunk"); + return; + } + + png_save_uint_16(buf, mod_time->year); + buf[2] = mod_time->month; + buf[3] = mod_time->day; + buf[4] = mod_time->hour; + buf[5] = mod_time->minute; + buf[6] = mod_time->second; + + png_write_chunk(png_ptr, (png_bytep)png_tIME, buf, (png_size_t)7); +} +#endif + +/* initializes the row writing capability of libpng */ +void /* PRIVATE */ +png_write_start_row(png_structp png_ptr) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ + + /* start of interlace block */ + int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + + /* offset to next interlace block */ + int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + + /* start of interlace block in the y direction */ + int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; + + /* offset to next interlace block in the y direction */ + int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; +#endif + + png_size_t buf_size; + + png_debug(1, "in png_write_start_row\n"); + buf_size = (png_size_t)(PNG_ROWBYTES( + png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1); + + /* set up row buffer */ + png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size); + png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE; + + /* set up filtering buffer, if using this filter */ + if (png_ptr->do_filter & PNG_FILTER_SUB) + { + png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, + (png_ptr->rowbytes + 1)); + png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB; + } + + /* We only need to keep the previous row if we are using one of these. */ + if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) + { + /* set up previous row buffer */ + png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size); + png_memset(png_ptr->prev_row, 0, buf_size); + + if (png_ptr->do_filter & PNG_FILTER_UP) + { + png_ptr->up_row = (png_bytep )png_malloc(png_ptr, + (png_ptr->rowbytes + 1)); + png_ptr->up_row[0] = PNG_FILTER_VALUE_UP; + } + + if (png_ptr->do_filter & PNG_FILTER_AVG) + { + png_ptr->avg_row = (png_bytep)png_malloc(png_ptr, + (png_ptr->rowbytes + 1)); + png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG; + } + + if (png_ptr->do_filter & PNG_FILTER_PAETH) + { + png_ptr->paeth_row = (png_bytep )png_malloc(png_ptr, + (png_ptr->rowbytes + 1)); + png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH; + } + } + +#ifdef PNG_WRITE_INTERLACING_SUPPORTED + /* if interlaced, we need to set up width and height of pass */ + if (png_ptr->interlaced) + { + if (!(png_ptr->transformations & PNG_INTERLACE)) + { + png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - + png_pass_ystart[0]) / png_pass_yinc[0]; + png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 - + png_pass_start[0]) / png_pass_inc[0]; + } + else + { + png_ptr->num_rows = png_ptr->height; + png_ptr->usr_width = png_ptr->width; + } + } + else +#endif + { + png_ptr->num_rows = png_ptr->height; + png_ptr->usr_width = png_ptr->width; + } + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + png_ptr->zstream.next_out = png_ptr->zbuf; +} + +/* Internal use only. Called when finished processing a row of data. */ +void /* PRIVATE */ +png_write_finish_row(png_structp png_ptr) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ + + /* start of interlace block */ + int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + + /* offset to next interlace block */ + int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + + /* start of interlace block in the y direction */ + int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; + + /* offset to next interlace block in the y direction */ + int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; +#endif + + int ret; + + png_debug(1, "in png_write_finish_row\n"); + /* next row */ + png_ptr->row_number++; + + /* see if we are done */ + if (png_ptr->row_number < png_ptr->num_rows) + return; + +#ifdef PNG_WRITE_INTERLACING_SUPPORTED + /* if interlaced, go to next pass */ + if (png_ptr->interlaced) + { + png_ptr->row_number = 0; + if (png_ptr->transformations & PNG_INTERLACE) + { + png_ptr->pass++; + } + else + { + /* loop until we find a non-zero width or height pass */ + do + { + png_ptr->pass++; + if (png_ptr->pass >= 7) + break; + png_ptr->usr_width = (png_ptr->width + + png_pass_inc[png_ptr->pass] - 1 - + png_pass_start[png_ptr->pass]) / + png_pass_inc[png_ptr->pass]; + png_ptr->num_rows = (png_ptr->height + + png_pass_yinc[png_ptr->pass] - 1 - + png_pass_ystart[png_ptr->pass]) / + png_pass_yinc[png_ptr->pass]; + if (png_ptr->transformations & PNG_INTERLACE) + break; + } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0); + + } + + /* reset the row above the image for the next pass */ + if (png_ptr->pass < 7) + { + if (png_ptr->prev_row != NULL) + png_memset(png_ptr->prev_row, 0, + (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels* + png_ptr->usr_bit_depth,png_ptr->width))+1); + return; + } + } +#endif + + /* if we get here, we've just written the last row, so we need + to flush the compressor */ + do + { + /* tell the compressor we are done */ + ret = deflate(&png_ptr->zstream, Z_FINISH); + /* check for an error */ + if (ret == Z_OK) + { + /* check to see if we need more room */ + if (!(png_ptr->zstream.avail_out)) + { + png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + } + } + else if (ret != Z_STREAM_END) + { + if (png_ptr->zstream.msg != NULL) + png_error(png_ptr, png_ptr->zstream.msg); + else + png_error(png_ptr, "zlib error"); + } + } while (ret != Z_STREAM_END); + + /* write any extra space */ + if (png_ptr->zstream.avail_out < png_ptr->zbuf_size) + { + png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size - + png_ptr->zstream.avail_out); + } + + deflateReset(&png_ptr->zstream); +} + +#if defined(PNG_WRITE_INTERLACING_SUPPORTED) +/* Pick out the correct pixels for the interlace pass. + * The basic idea here is to go through the row with a source + * pointer and a destination pointer (sp and dp), and copy the + * correct pixels for the pass. As the row gets compacted, + * sp will always be >= dp, so we should never overwrite anything. + * See the default: case for the easiest code to understand. + */ +void /* PRIVATE */ +png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass) +{ +#ifdef PNG_USE_LOCAL_ARRAYS + /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */ + + /* start of interlace block */ + int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + + /* offset to next interlace block */ + int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; +#endif + + png_debug(1, "in png_do_write_interlace\n"); + /* we don't have to do anything on the last pass (6) */ +#if defined(PNG_USELESS_TESTS_SUPPORTED) + if (row != NULL && row_info != NULL && pass < 6) +#else + if (pass < 6) +#endif + { + /* each pixel depth is handled separately */ + switch (row_info->pixel_depth) + { + case 1: + { + png_bytep sp; + png_bytep dp; + int shift; + int d; + int value; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + dp = row; + d = 0; + shift = 7; + for (i = png_pass_start[pass]; i < row_width; + i += png_pass_inc[pass]) + { + sp = row + (png_size_t)(i >> 3); + value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01; + d |= (value << shift); + + if (shift == 0) + { + shift = 7; + *dp++ = (png_byte)d; + d = 0; + } + else + shift--; + + } + if (shift != 7) + *dp = (png_byte)d; + break; + } + case 2: + { + png_bytep sp; + png_bytep dp; + int shift; + int d; + int value; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + dp = row; + shift = 6; + d = 0; + for (i = png_pass_start[pass]; i < row_width; + i += png_pass_inc[pass]) + { + sp = row + (png_size_t)(i >> 2); + value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03; + d |= (value << shift); + + if (shift == 0) + { + shift = 6; + *dp++ = (png_byte)d; + d = 0; + } + else + shift -= 2; + } + if (shift != 6) + *dp = (png_byte)d; + break; + } + case 4: + { + png_bytep sp; + png_bytep dp; + int shift; + int d; + int value; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + + dp = row; + shift = 4; + d = 0; + for (i = png_pass_start[pass]; i < row_width; + i += png_pass_inc[pass]) + { + sp = row + (png_size_t)(i >> 1); + value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f; + d |= (value << shift); + + if (shift == 0) + { + shift = 4; + *dp++ = (png_byte)d; + d = 0; + } + else + shift -= 4; + } + if (shift != 4) + *dp = (png_byte)d; + break; + } + default: + { + png_bytep sp; + png_bytep dp; + png_uint_32 i; + png_uint_32 row_width = row_info->width; + png_size_t pixel_bytes; + + /* start at the beginning */ + dp = row; + /* find out how many bytes each pixel takes up */ + pixel_bytes = (row_info->pixel_depth >> 3); + /* loop through the row, only looking at the pixels that + matter */ + for (i = png_pass_start[pass]; i < row_width; + i += png_pass_inc[pass]) + { + /* find out where the original pixel is */ + sp = row + (png_size_t)i * pixel_bytes; + /* move the pixel */ + if (dp != sp) + png_memcpy(dp, sp, pixel_bytes); + /* next pixel */ + dp += pixel_bytes; + } + break; + } + } + /* set new row width */ + row_info->width = (row_info->width + + png_pass_inc[pass] - 1 - + png_pass_start[pass]) / + png_pass_inc[pass]; + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, + row_info->width); + } +} +#endif + +/* This filters the row, chooses which filter to use, if it has not already + * been specified by the application, and then writes the row out with the + * chosen filter. + */ +#define PNG_MAXSUM (~((png_uint_32)0) >> 1) +#define PNG_HISHIFT 10 +#define PNG_LOMASK ((png_uint_32)0xffffL) +#define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT)) +void /* PRIVATE */ +png_write_find_filter(png_structp png_ptr, png_row_infop row_info) +{ + png_bytep prev_row, best_row, row_buf; + png_uint_32 mins, bpp; + png_byte filter_to_do = png_ptr->do_filter; + png_uint_32 row_bytes = row_info->rowbytes; +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + int num_p_filters = (int)png_ptr->num_prev_filters; +#endif + + png_debug(1, "in png_write_find_filter\n"); + /* find out how many bytes offset each pixel is */ + bpp = (row_info->pixel_depth + 7) >> 3; + + prev_row = png_ptr->prev_row; + best_row = row_buf = png_ptr->row_buf; + mins = PNG_MAXSUM; + + /* The prediction method we use is to find which method provides the + * smallest value when summing the absolute values of the distances + * from zero, using anything >= 128 as negative numbers. This is known + * as the "minimum sum of absolute differences" heuristic. Other + * heuristics are the "weighted minimum sum of absolute differences" + * (experimental and can in theory improve compression), and the "zlib + * predictive" method (not implemented yet), which does test compressions + * of lines using different filter methods, and then chooses the + * (series of) filter(s) that give minimum compressed data size (VERY + * computationally expensive). + * + * GRR 980525: consider also + * (1) minimum sum of absolute differences from running average (i.e., + * keep running sum of non-absolute differences & count of bytes) + * [track dispersion, too? restart average if dispersion too large?] + * (1b) minimum sum of absolute differences from sliding average, probably + * with window size <= deflate window (usually 32K) + * (2) minimum sum of squared differences from zero or running average + * (i.e., ~ root-mean-square approach) + */ + + + /* We don't need to test the 'no filter' case if this is the only filter + * that has been chosen, as it doesn't actually do anything to the data. + */ + if ((filter_to_do & PNG_FILTER_NONE) && + filter_to_do != PNG_FILTER_NONE) + { + png_bytep rp; + png_uint_32 sum = 0; + png_uint_32 i; + int v; + + for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++) + { + v = *rp; + sum += (v < 128) ? v : 256 - v; + } + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + png_uint_32 sumhi, sumlo; + int j; + sumlo = sum & PNG_LOMASK; + sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */ + + /* Reduce the sum if we match any of the previous rows */ + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE) + { + sumlo = (sumlo * png_ptr->filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + sumhi = (sumhi * png_ptr->filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + /* Factor in the cost of this filter (this is here for completeness, + * but it makes no sense to have a "cost" for the NONE filter, as + * it has the minimum possible computational cost - none). + */ + sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >> + PNG_COST_SHIFT; + sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >> + PNG_COST_SHIFT; + + if (sumhi > PNG_HIMASK) + sum = PNG_MAXSUM; + else + sum = (sumhi << PNG_HISHIFT) + sumlo; + } +#endif + mins = sum; + } + + /* sub filter */ + if (filter_to_do == PNG_FILTER_SUB) + /* it's the only filter so no testing is needed */ + { + png_bytep rp, lp, dp; + png_uint_32 i; + for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp; + i++, rp++, dp++) + { + *dp = *rp; + } + for (lp = row_buf + 1; i < row_bytes; + i++, rp++, lp++, dp++) + { + *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff); + } + best_row = png_ptr->sub_row; + } + + else if (filter_to_do & PNG_FILTER_SUB) + { + png_bytep rp, dp, lp; + png_uint_32 sum = 0, lmins = mins; + png_uint_32 i; + int v; + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + /* We temporarily increase the "minimum sum" by the factor we + * would reduce the sum of this filter, so that we can do the + * early exit comparison without scaling the sum each time. + */ + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + int j; + png_uint_32 lmhi, lmlo; + lmlo = lmins & PNG_LOMASK; + lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK; + + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB) + { + lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >> + PNG_COST_SHIFT; + lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >> + PNG_COST_SHIFT; + + if (lmhi > PNG_HIMASK) + lmins = PNG_MAXSUM; + else + lmins = (lmhi << PNG_HISHIFT) + lmlo; + } +#endif + + for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp; + i++, rp++, dp++) + { + v = *dp = *rp; + + sum += (v < 128) ? v : 256 - v; + } + for (lp = row_buf + 1; i < row_bytes; + i++, rp++, lp++, dp++) + { + v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff); + + sum += (v < 128) ? v : 256 - v; + + if (sum > lmins) /* We are already worse, don't continue. */ + break; + } + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + int j; + png_uint_32 sumhi, sumlo; + sumlo = sum & PNG_LOMASK; + sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; + + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB) + { + sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >> + PNG_COST_SHIFT; + sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >> + PNG_COST_SHIFT; + + if (sumhi > PNG_HIMASK) + sum = PNG_MAXSUM; + else + sum = (sumhi << PNG_HISHIFT) + sumlo; + } +#endif + + if (sum < mins) + { + mins = sum; + best_row = png_ptr->sub_row; + } + } + + /* up filter */ + if (filter_to_do == PNG_FILTER_UP) + { + png_bytep rp, dp, pp; + png_uint_32 i; + + for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1, + pp = prev_row + 1; i < row_bytes; + i++, rp++, pp++, dp++) + { + *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff); + } + best_row = png_ptr->up_row; + } + + else if (filter_to_do & PNG_FILTER_UP) + { + png_bytep rp, dp, pp; + png_uint_32 sum = 0, lmins = mins; + png_uint_32 i; + int v; + + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + int j; + png_uint_32 lmhi, lmlo; + lmlo = lmins & PNG_LOMASK; + lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK; + + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP) + { + lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >> + PNG_COST_SHIFT; + lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >> + PNG_COST_SHIFT; + + if (lmhi > PNG_HIMASK) + lmins = PNG_MAXSUM; + else + lmins = (lmhi << PNG_HISHIFT) + lmlo; + } +#endif + + for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1, + pp = prev_row + 1; i < row_bytes; i++) + { + v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff); + + sum += (v < 128) ? v : 256 - v; + + if (sum > lmins) /* We are already worse, don't continue. */ + break; + } + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + int j; + png_uint_32 sumhi, sumlo; + sumlo = sum & PNG_LOMASK; + sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; + + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP) + { + sumlo = (sumlo * png_ptr->filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + sumhi = (sumhi * png_ptr->filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >> + PNG_COST_SHIFT; + sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >> + PNG_COST_SHIFT; + + if (sumhi > PNG_HIMASK) + sum = PNG_MAXSUM; + else + sum = (sumhi << PNG_HISHIFT) + sumlo; + } +#endif + + if (sum < mins) + { + mins = sum; + best_row = png_ptr->up_row; + } + } + + /* avg filter */ + if (filter_to_do == PNG_FILTER_AVG) + { + png_bytep rp, dp, pp, lp; + png_uint_32 i; + for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1, + pp = prev_row + 1; i < bpp; i++) + { + *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff); + } + for (lp = row_buf + 1; i < row_bytes; i++) + { + *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) + & 0xff); + } + best_row = png_ptr->avg_row; + } + + else if (filter_to_do & PNG_FILTER_AVG) + { + png_bytep rp, dp, pp, lp; + png_uint_32 sum = 0, lmins = mins; + png_uint_32 i; + int v; + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + int j; + png_uint_32 lmhi, lmlo; + lmlo = lmins & PNG_LOMASK; + lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK; + + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG) + { + lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >> + PNG_COST_SHIFT; + lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >> + PNG_COST_SHIFT; + + if (lmhi > PNG_HIMASK) + lmins = PNG_MAXSUM; + else + lmins = (lmhi << PNG_HISHIFT) + lmlo; + } +#endif + + for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1, + pp = prev_row + 1; i < bpp; i++) + { + v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff); + + sum += (v < 128) ? v : 256 - v; + } + for (lp = row_buf + 1; i < row_bytes; i++) + { + v = *dp++ = + (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff); + + sum += (v < 128) ? v : 256 - v; + + if (sum > lmins) /* We are already worse, don't continue. */ + break; + } + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + int j; + png_uint_32 sumhi, sumlo; + sumlo = sum & PNG_LOMASK; + sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; + + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE) + { + sumlo = (sumlo * png_ptr->filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + sumhi = (sumhi * png_ptr->filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >> + PNG_COST_SHIFT; + sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >> + PNG_COST_SHIFT; + + if (sumhi > PNG_HIMASK) + sum = PNG_MAXSUM; + else + sum = (sumhi << PNG_HISHIFT) + sumlo; + } +#endif + + if (sum < mins) + { + mins = sum; + best_row = png_ptr->avg_row; + } + } + + /* Paeth filter */ + if (filter_to_do == PNG_FILTER_PAETH) + { + png_bytep rp, dp, pp, cp, lp; + png_uint_32 i; + for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1, + pp = prev_row + 1; i < bpp; i++) + { + *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff); + } + + for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++) + { + int a, b, c, pa, pb, pc, p; + + b = *pp++; + c = *cp++; + a = *lp++; + + p = b - c; + pc = a - c; + +#ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +#else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +#endif + + p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c; + + *dp++ = (png_byte)(((int)*rp++ - p) & 0xff); + } + best_row = png_ptr->paeth_row; + } + + else if (filter_to_do & PNG_FILTER_PAETH) + { + png_bytep rp, dp, pp, cp, lp; + png_uint_32 sum = 0, lmins = mins; + png_uint_32 i; + int v; + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + int j; + png_uint_32 lmhi, lmlo; + lmlo = lmins & PNG_LOMASK; + lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK; + + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH) + { + lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >> + PNG_COST_SHIFT; + lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >> + PNG_COST_SHIFT; + + if (lmhi > PNG_HIMASK) + lmins = PNG_MAXSUM; + else + lmins = (lmhi << PNG_HISHIFT) + lmlo; + } +#endif + + for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1, + pp = prev_row + 1; i < bpp; i++) + { + v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff); + + sum += (v < 128) ? v : 256 - v; + } + + for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++) + { + int a, b, c, pa, pb, pc, p; + + b = *pp++; + c = *cp++; + a = *lp++; + +#ifndef PNG_SLOW_PAETH + p = b - c; + pc = a - c; +#ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +#else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +#endif + p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c; +#else /* PNG_SLOW_PAETH */ + p = a + b - c; + pa = abs(p - a); + pb = abs(p - b); + pc = abs(p - c); + if (pa <= pb && pa <= pc) + p = a; + else if (pb <= pc) + p = b; + else + p = c; +#endif /* PNG_SLOW_PAETH */ + + v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff); + + sum += (v < 128) ? v : 256 - v; + + if (sum > lmins) /* We are already worse, don't continue. */ + break; + } + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED) + { + int j; + png_uint_32 sumhi, sumlo; + sumlo = sum & PNG_LOMASK; + sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; + + for (j = 0; j < num_p_filters; j++) + { + if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH) + { + sumlo = (sumlo * png_ptr->filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + sumhi = (sumhi * png_ptr->filter_weights[j]) >> + PNG_WEIGHT_SHIFT; + } + } + + sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >> + PNG_COST_SHIFT; + sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >> + PNG_COST_SHIFT; + + if (sumhi > PNG_HIMASK) + sum = PNG_MAXSUM; + else + sum = (sumhi << PNG_HISHIFT) + sumlo; + } +#endif + + if (sum < mins) + { + best_row = png_ptr->paeth_row; + } + } + + /* Do the actual writing of the filtered row data from the chosen filter. */ + + png_write_filtered_row(png_ptr, best_row); + +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) + /* Save the type of filter we picked this time for future calculations */ + if (png_ptr->num_prev_filters > 0) + { + int j; + for (j = 1; j < num_p_filters; j++) + { + png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1]; + } + png_ptr->prev_filters[j] = best_row[0]; + } +#endif +} + + +/* Do the actual writing of a previously filtered row. */ +void /* PRIVATE */ +png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row) +{ + png_debug(1, "in png_write_filtered_row\n"); + png_debug1(2, "filter = %d\n", filtered_row[0]); + /* set up the zlib input buffer */ + + png_ptr->zstream.next_in = filtered_row; + png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1; + /* repeat until we have compressed all the data */ + do + { + int ret; /* return of zlib */ + + /* compress the data */ + ret = deflate(&png_ptr->zstream, Z_NO_FLUSH); + /* check for compression errors */ + if (ret != Z_OK) + { + if (png_ptr->zstream.msg != NULL) + png_error(png_ptr, png_ptr->zstream.msg); + else + png_error(png_ptr, "zlib error"); + } + + /* see if it is time to write another IDAT */ + if (!(png_ptr->zstream.avail_out)) + { + /* write the IDAT and reset the zlib output buffer */ + png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); + png_ptr->zstream.next_out = png_ptr->zbuf; + png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + } + /* repeat until all data has been compressed */ + } while (png_ptr->zstream.avail_in); + + /* swap the current and previous rows */ + if (png_ptr->prev_row != NULL) + { + png_bytep tptr; + + tptr = png_ptr->prev_row; + png_ptr->prev_row = png_ptr->row_buf; + png_ptr->row_buf = tptr; + } + + /* finish row - updates counters and flushes zlib if last row */ + png_write_finish_row(png_ptr); + +#if defined(PNG_WRITE_FLUSH_SUPPORTED) + png_ptr->flush_rows++; + + if (png_ptr->flush_dist > 0 && + png_ptr->flush_rows >= png_ptr->flush_dist) + { + png_write_flush(png_ptr); + } +#endif +} +#endif /* PNG_WRITE_SUPPORTED */ diff --git a/SlnkDWFImpl/CxImage/tiff/Tiff.dsp b/SlnkDWFImpl/CxImage/tiff/Tiff.dsp new file mode 100644 index 0000000..6161e26 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/Tiff.dsp @@ -0,0 +1,266 @@ +# Microsoft Developer Studio Project File - Name="tiff" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=Tiff - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Tiff.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Tiff.mak" CFG="Tiff - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "tiff - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "tiff - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName ""$/Tiff", MKAAAAAA" +# PROP Scc_LocalPath "." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "tiff - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O1 /I "..\zlib" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D "_AFXDLL" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "tiff - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\zlib" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D "_AFXDLL" /FD /GZ /c +# SUBTRACT CPP /Fr /YX +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "tiff - Win32 Release" +# Name "tiff - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\fax3sm_winnt.c +# End Source File +# Begin Source File + +SOURCE=.\tif_aux.c +# End Source File +# Begin Source File + +SOURCE=.\tif_close.c +# End Source File +# Begin Source File + +SOURCE=.\tif_codec.c +# End Source File +# Begin Source File + +SOURCE=.\tif_compress.c +# End Source File +# Begin Source File + +SOURCE=.\tif_dir.c +# End Source File +# Begin Source File + +SOURCE=.\tif_dirinfo.c +# End Source File +# Begin Source File + +SOURCE=.\tif_dirread.c +# End Source File +# Begin Source File + +SOURCE=.\tif_dirwrite.c +# End Source File +# Begin Source File + +SOURCE=.\tif_dumpmode.c +# End Source File +# Begin Source File + +SOURCE=.\tif_error.c +# End Source File +# Begin Source File + +SOURCE=.\tif_fax3.c +# End Source File +# Begin Source File + +SOURCE=.\tif_flush.c +# End Source File +# Begin Source File + +SOURCE=.\tif_getimage.c +# End Source File +# Begin Source File + +SOURCE=.\tif_jpeg.c +# End Source File +# Begin Source File + +SOURCE=.\tif_luv.c +# End Source File +# Begin Source File + +SOURCE=.\tif_lzw.c +# End Source File +# Begin Source File + +SOURCE=.\tif_next.c +# End Source File +# Begin Source File + +SOURCE=.\tif_ojpeg.c +# End Source File +# Begin Source File + +SOURCE=.\tif_open.c +# End Source File +# Begin Source File + +SOURCE=.\tif_packbits.c +# End Source File +# Begin Source File + +SOURCE=.\tif_pixarlog.c +# End Source File +# Begin Source File + +SOURCE=.\tif_predict.c +# End Source File +# Begin Source File + +SOURCE=.\tif_print.c +# End Source File +# Begin Source File + +SOURCE=.\tif_read.c +# End Source File +# Begin Source File + +SOURCE=.\tif_strip.c +# End Source File +# Begin Source File + +SOURCE=.\tif_swab.c +# End Source File +# Begin Source File + +SOURCE=.\tif_thunder.c +# End Source File +# Begin Source File + +SOURCE=.\tif_tile.c +# End Source File +# Begin Source File + +SOURCE=.\tif_version.c +# End Source File +# Begin Source File + +SOURCE=.\tif_warning.c +# End Source File +# Begin Source File + +SOURCE=.\tif_write.c +# End Source File +# Begin Source File + +SOURCE=.\tif_zip.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\t4.h +# End Source File +# Begin Source File + +SOURCE=.\tif_dir.h +# End Source File +# Begin Source File + +SOURCE=.\tif_fax3.h +# End Source File +# Begin Source File + +SOURCE=.\tif_predict.h +# End Source File +# Begin Source File + +SOURCE=.\tiff.h +# End Source File +# Begin Source File + +SOURCE=.\tiffcomp.h +# End Source File +# Begin Source File + +SOURCE=.\tiffconf.h +# End Source File +# Begin Source File + +SOURCE=.\tiffio.h +# End Source File +# Begin Source File + +SOURCE=.\tiffiop.h +# End Source File +# Begin Source File + +SOURCE=.\uvcode.h +# End Source File +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/tiff/Tiff.dsw b/SlnkDWFImpl/CxImage/tiff/Tiff.dsw new file mode 100644 index 0000000..13101aa --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/Tiff.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "tiff"=.\tiff.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/tiff/Tiff.sln b/SlnkDWFImpl/CxImage/tiff/Tiff.sln new file mode 100644 index 0000000..02e952e --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/Tiff.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 7.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tiff", "Tiff.vcproj", "{64511FB0-7999-4AFF-B213-984566326527}" +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + ConfigName.0 = Debug + ConfigName.1 = Release + EndGlobalSection + GlobalSection(ProjectDependencies) = postSolution + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {64511FB0-7999-4AFF-B213-984566326527}.Debug.ActiveCfg = Debug|Win32 + {64511FB0-7999-4AFF-B213-984566326527}.Debug.Build.0 = Debug|Win32 + {64511FB0-7999-4AFF-B213-984566326527}.Release.ActiveCfg = Release|Win32 + {64511FB0-7999-4AFF-B213-984566326527}.Release.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj b/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj new file mode 100644 index 0000000..5624de2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj @@ -0,0 +1,951 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj.7.00.old b/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj.7.00.old new file mode 100644 index 0000000..02264b0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj.7.00.old @@ -0,0 +1,246 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..f57b253 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/Tiff.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/tiff/fax3sm_winnt.c b/SlnkDWFImpl/CxImage/tiff/fax3sm_winnt.c new file mode 100644 index 0000000..1d0f34a --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/fax3sm_winnt.c @@ -0,0 +1,1046 @@ +/* WARNING, this file was automatically generated by the + mkg3states program */ +#include "tiff.h" +#include "tif_fax3.h" + const TIFFFaxTabEnt TIFFFaxMainTable[128] = { +12,7,0,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0,1,4,0,3,1,0,5,3,1,3,1,0, +2,3,0,3,1,0,4,3,1,3,1,0,5,6,2,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0, +1,4,0,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0,5,7,3,3,1,0,5,3,1,3,1,0, +2,3,0,3,1,0,4,3,1,3,1,0,1,4,0,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0, +4,6,2,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0,1,4,0,3,1,0,5,3,1,3,1,0, +2,3,0,3,1,0,4,3,1,3,1,0,6,7,0,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0, +1,4,0,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0,5,6,2,3,1,0,5,3,1,3,1,0, +2,3,0,3,1,0,4,3,1,3,1,0,1,4,0,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0, +4,7,3,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0,1,4,0,3,1,0,5,3,1,3,1,0, +2,3,0,3,1,0,4,3,1,3,1,0,4,6,2,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0, +1,4,0,3,1,0,5,3,1,3,1,0,2,3,0,3,1,0,4,3,1,3,1,0 +}; +const TIFFFaxTabEnt TIFFFaxWhiteTable[4096] = { +12,11,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6, +7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5, +7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1472,7,4,5,7,8,43,7,6,17,9,9,1216,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5, +7,8,41,7,6,16,9,9,960,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,704,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15, +9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,11,11,1792,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,832,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6, +7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1600,7,4,5, +7,8,44,7,6,17,9,9,1344,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14, +7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1088,7,4,6, +7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15, +7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1536,7,4,5,7,8,43,7,6,17,9,9,1280,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7, +7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,1024,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,768,7,4,6, +7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +11,11,1856,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,896,7,4,6, +7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5, +7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1728,7,4,5,7,8,44,7,6,17,9,9,1408,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5, +7,8,42,7,6,16,9,9,1152,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15, +9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6, +7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1472,7,4,5, +7,8,43,7,6,17,9,9,1216,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14, +7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,960,7,4,6, +7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,9,704,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,11,12,2112,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,40,7,6,16,9,9,832,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15, +7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1600,7,4,5,7,8,44,7,6,17,9,9,1344,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7, +7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1088,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6, +7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6, +7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5, +7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1536,7,4,5,7,8,43,7,6,17,9,9,1280,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5, +7,8,41,7,6,16,9,9,1024,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,768,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15, +9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,11,12,2368,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,896,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6, +7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1728,7,4,5, +7,8,44,7,6,17,9,9,1408,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14, +7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1152,7,4,6, +7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15, +7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1472,7,4,5,7,8,43,7,6,17,9,9,1216,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7, +7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,960,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,704,7,4,6, +7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +11,12,1984,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,832,7,4,6, +7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5, +7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1600,7,4,5,7,8,44,7,6,17,9,9,1344,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5, +7,8,42,7,6,16,9,9,1088,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15, +9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6, +7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1536,7,4,5, +7,8,43,7,6,17,9,9,1280,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14, +7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,1024,7,4,6, +7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,9,768,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,11,11,1920,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,40,7,6,16,9,9,896,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15, +7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1728,7,4,5,7,8,44,7,6,17,9,9,1408,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7, +7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1152,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6, +7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6, +7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5, +7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1472,7,4,5,7,8,43,7,6,17,9,9,1216,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5, +7,8,41,7,6,16,9,9,960,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,704,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15, +9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,11,12,2240,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,832,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6, +7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1600,7,4,5, +7,8,44,7,6,17,9,9,1344,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14, +7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1088,7,4,6, +7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15, +7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1536,7,4,5,7,8,43,7,6,17,9,9,1280,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7, +7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,1024,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,768,7,4,6, +7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +11,12,2496,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,896,7,4,6, +7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5, +7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1728,7,4,5,7,8,44,7,6,17,9,9,1408,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5, +7,8,42,7,6,16,9,9,1152,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15, +9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,12,11,0,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6, +7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1472,7,4,5, +7,8,43,7,6,17,9,9,1216,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14, +7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,960,7,4,6, +7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,9,704,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,11,11,1792,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,40,7,6,16,9,9,832,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15, +7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1600,7,4,5,7,8,44,7,6,17,9,9,1344,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7, +7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1088,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6, +7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6, +7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5, +7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1536,7,4,5,7,8,43,7,6,17,9,9,1280,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5, +7,8,41,7,6,16,9,9,1024,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,768,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15, +9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,11,11,1856,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,896,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6, +7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1728,7,4,5, +7,8,44,7,6,17,9,9,1408,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14, +7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1152,7,4,6, +7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15, +7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1472,7,4,5,7,8,43,7,6,17,9,9,1216,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7, +7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,960,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,704,7,4,6, +7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +11,12,2176,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,832,7,4,6, +7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5, +7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1600,7,4,5,7,8,44,7,6,17,9,9,1344,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5, +7,8,42,7,6,16,9,9,1088,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15, +9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6, +7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1536,7,4,5, +7,8,43,7,6,17,9,9,1280,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14, +7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,1024,7,4,6, +7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,9,768,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,11,12,2432,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,40,7,6,16,9,9,896,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15, +7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1728,7,4,5,7,8,44,7,6,17,9,9,1408,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7, +7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1152,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6, +7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6, +7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5, +7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1472,7,4,5,7,8,43,7,6,17,9,9,1216,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5, +7,8,41,7,6,16,9,9,960,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,704,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15, +9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,11,12,2048,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,832,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6, +7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1600,7,4,5, +7,8,44,7,6,17,9,9,1344,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14, +7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1088,7,4,6, +7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15, +7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1536,7,4,5,7,8,43,7,6,17,9,9,1280,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7, +7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,1024,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,768,7,4,6, +7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +11,11,1920,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,896,7,4,6, +7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5, +7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1728,7,4,5,7,8,44,7,6,17,9,9,1408,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5, +7,8,42,7,6,16,9,9,1152,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15, +9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,0,0,0,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6,7,7,19,7,5,8,7,8,55,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5,7,8,53,7,5,9,9,8,448,7,4,6, +7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1472,7,4,5, +7,8,43,7,6,17,9,9,1216,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,33,9,5,128,7,8,49,7,6,14, +7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5,7,8,41,7,6,16,9,9,960,7,4,6, +7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,9,704,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15,9,8,320,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,11,12,2304,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5, +7,8,40,7,6,16,9,9,832,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6,7,8,36,9,5,128,7,8,52,7,6,15, +7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1600,7,4,5,7,8,44,7,6,17,9,9,1344,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,30,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14,7,8,62,7,4,4,7,4,2,7,4,7, +7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1088,7,4,6,7,8,32,7,5,8,7,8,58,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,8,640,7,4,6, +7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5, +7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +0,0,0,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14, +7,7,28,7,4,4,7,4,2,7,4,7,7,7,23,7,4,3,7,7,27,7,4,5,7,8,39,7,6,16,9,8,576,7,4,6, +7,7,19,7,5,8,7,8,55,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,8,45,7,4,3,7,5,11,7,4,5, +7,8,53,7,5,9,9,8,448,7,4,6,7,8,35,9,5,128,7,8,51,7,6,15,7,8,63,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,9,9,1536,7,4,5,7,8,43,7,6,17,9,9,1280,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,29,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6, +7,8,33,9,5,128,7,8,49,7,6,14,7,8,61,7,4,4,7,4,2,7,4,7,7,8,47,7,4,3,7,8,59,7,4,5, +7,8,41,7,6,16,9,9,1024,7,4,6,7,8,31,7,5,8,7,8,57,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,7,22,7,4,3,7,5,11,7,4,5,7,7,26,7,5,9,9,9,768,7,4,6,7,8,37,9,5,128,7,7,25,7,6,15, +9,8,320,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6, +7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,11,12,2560,7,4,3,7,5,11,7,4,5, +7,6,12,7,5,9,9,6,1664,7,4,6,7,7,20,9,5,128,7,7,24,7,6,14,7,7,28,7,4,4,7,4,2,7,4,7, +7,7,23,7,4,3,7,7,27,7,4,5,7,8,40,7,6,16,9,9,896,7,4,6,7,7,19,7,5,8,7,8,56,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7,7,8,46,7,4,3,7,5,11,7,4,5,7,8,54,7,5,9,9,8,512,7,4,6, +7,8,36,9,5,128,7,8,52,7,6,15,7,8,0,7,4,4,7,4,2,7,4,7,7,6,13,7,4,3,9,9,1728,7,4,5, +7,8,44,7,6,17,9,9,1408,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7, +7,8,30,7,4,3,7,5,11,7,4,5,7,6,12,7,5,9,9,6,1664,7,4,6,7,8,34,9,5,128,7,8,50,7,6,14, +7,8,62,7,4,4,7,4,2,7,4,7,7,8,48,7,4,3,7,8,60,7,4,5,7,8,42,7,6,16,9,9,1152,7,4,6, +7,8,32,7,5,8,7,8,58,9,5,64,7,5,10,7,4,4,7,4,2,7,4,7,7,7,22,7,4,3,7,5,11,7,4,5, +7,7,26,7,5,9,9,8,640,7,4,6,7,8,38,9,5,128,7,7,25,7,6,15,9,8,384,7,4,4,7,4,2,7,4,7, +7,6,13,7,4,3,7,7,18,7,4,5,7,7,21,7,6,17,9,7,256,7,4,6,7,6,1,7,5,8,9,6,192,9,5,64, +7,5,10,7,4,4,7,4,2,7,4,7 +}; +const TIFFFaxTabEnt TIFFFaxBlackTable[8192] = { +12,11,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,18,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,17,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,11,1792,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,23,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,20,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,25,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,12,128,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,56,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,30,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,11,1856,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,57,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,21,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,54,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,52,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,48,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,12,2112,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,44,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,36,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,12,384,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,28,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,60,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,40,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,12,2368,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,16,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,10,64,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,18,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,17,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,12,1984,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,50,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,34,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,13,1664,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,26,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,13,1408,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,32,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,11,1920,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,61,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,42,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,13,1024,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,13,768,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,62,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,12,2240,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,46,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,38,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,13,512,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,19,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,24,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,22,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,12,2496,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,16,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,10,64,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,12,11,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,18,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,17,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,11,1792,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,23,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,20,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,25,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,12,192,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,13,1280,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,31,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,11,1856,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,58,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,21,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,13,896,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,13,640,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,49,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,12,2176,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,45,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,37,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,12,448,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,29,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,13,1536,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,41,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,12,2432,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,16,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,10,64,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,18,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,17,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,12,2048,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,51,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,35,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,12,320,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,27,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,59,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,33,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,11,1920,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,12,256,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,43,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,13,1152,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,55,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,63,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,12,2304,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,47,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,39,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,53,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,19,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,24,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,22,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,12,2560,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,16,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,10,64,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,12,11,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,18,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,17,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,11,1792,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,23,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,20,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,25,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,12,128,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,56,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,30,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,11,1856,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,57,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,21,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,54,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,52,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,48,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,12,2112,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,44,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,36,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,12,384,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,28,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,60,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,40,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,12,2368,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,16,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,10,64,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,18,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,17,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,12,1984,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,50,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,34,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,13,1728,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,26,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,13,1472,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,32,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,11,1920,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,61,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,42,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,13,1088,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,13,832,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,62,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,12,2240,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,46,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,38,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,13,576,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,19,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,24,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,22,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,12,2496,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,16,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,10,64,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +12,11,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,18,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,17,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,11,1792,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,23,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,20,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,25,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,12,192,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,13,1344,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,31,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,11,1856,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,58,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,11,21,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,13,960,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,13,704,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,49,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,12,2176,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,45,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,37,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,12,448,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,29,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,13,1600,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,41,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,12,2432,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,16,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,10,64,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,18,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,10,17,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,12,2048,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,51,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,35,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,12,320,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,27,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,59,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,33,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,11,11,1920,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +10,12,256,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,43,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,10,13,1216,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,13,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,9,15,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,55,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,63,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,11,12,2304,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,12,47,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,12,39,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,12,53,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,8,14,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,0,0,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,13,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,19,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,11,24,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,7,11,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,11,22,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +11,12,2560,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,9,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,10,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,10,16,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,10,0,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,10,10,64,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,6,9,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2,8,7,11,8,2,3,8,3,1,8,2,2, +8,4,6,8,2,3,8,3,4,8,2,2,8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2, +8,8,14,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2,8,6,8,8,2,3,8,3,1,8,2,2, +8,4,5,8,2,3,8,3,4,8,2,2,8,7,12,8,2,3,8,3,1,8,2,2,8,4,6,8,2,3,8,3,4,8,2,2, +8,5,7,8,2,3,8,3,1,8,2,2,8,4,5,8,2,3,8,3,4,8,2,2 +}; diff --git a/SlnkDWFImpl/CxImage/tiff/libtiff.def b/SlnkDWFImpl/CxImage/tiff/libtiff.def new file mode 100644 index 0000000..2be223a --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/libtiff.def @@ -0,0 +1,77 @@ +LIBRARY libtiff +EXPORTS TIFFOpen + TIFFGetVersion + TIFFClose + TIFFFlush + TIFFFlushData + TIFFGetField + TIFFVGetField + TIFFGetFieldDefaulted + TIFFVGetFieldDefaulted + TIFFReadDirectory + TIFFScanlineSize + TIFFStripSize + TIFFVStripSize + TIFFTileRowSize + TIFFTileSize + TIFFVTileSize + TIFFFileno + TIFFGetMode + TIFFIsTiled + TIFFIsByteSwapped + TIFFCurrentRow + TIFFCurrentDirectory + TIFFCurrentStrip + TIFFCurrentTile + TIFFReadBufferSetup + TIFFLastDirectory + TIFFSetDirectory + TIFFSetSubDirectory + TIFFUnlinkDirectory + TIFFSetField + TIFFVSetField + TIFFWriteDirectory + TIFFPrintDirectory + TIFFReadScanline + TIFFWriteScanline + TIFFReadRGBAImage + TIFFPrintDirectory + TIFFReadScanline + TIFFWriteScanline + TIFFReadRGBAImage + TIFFFdOpen + TIFFClientOpen + TIFFFileName + TIFFError + TIFFWarning + TIFFSetErrorHandler + TIFFSetWarningHandler + TIFFComputeTile + TIFFCheckTile + TIFFNumberOfTiles + TIFFReadTile + TIFFWriteTile + TIFFComputeStrip + TIFFNumberOfStrips + TIFFReadEncodedStrip + TIFFReadRawStrip + TIFFReadEncodedTile + TIFFReadRawTile + TIFFWriteEncodedStrip + TIFFWriteRawStrip + TIFFWriteEncodedTile + TIFFWriteRawTile + TIFFSetWriteOffset + TIFFSwabShort + TIFFSwabLong + TIFFSwabArrayOfShort + TIFFSwabArrayOfLong + TIFFReverseBits + TIFFGetBitRevTable + _TIFFmalloc + _TIFFrealloc + _TIFFfree + _TIFFmemset + _TIFFmemcpy + _TIFFmemcmp + diff --git a/SlnkDWFImpl/CxImage/tiff/t4.h b/SlnkDWFImpl/CxImage/tiff/t4.h new file mode 100644 index 0000000..308ad28 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/t4.h @@ -0,0 +1,285 @@ +/* $Id: t4.h,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _T4_ +#define _T4_ +/* + * CCITT T.4 1D Huffman runlength codes and + * related definitions. Given the small sizes + * of these tables it does not seem + * worthwhile to make code & length 8 bits. + */ +typedef struct tableentry { + unsigned short length; /* bit length of g3 code */ + unsigned short code; /* g3 code */ + short runlen; /* run length in bits */ +} tableentry; + +#define EOL 0x001 /* EOL code value - 0000 0000 0000 1 */ + +/* status values returned instead of a run length */ +#define G3CODE_EOL -1 /* NB: ACT_EOL - ACT_WRUNT */ +#define G3CODE_INVALID -2 /* NB: ACT_INVALID - ACT_WRUNT */ +#define G3CODE_EOF -3 /* end of input data */ +#define G3CODE_INCOMP -4 /* incomplete run code */ + +/* + * Note that these tables are ordered such that the + * index into the table is known to be either the + * run length, or (run length / 64) + a fixed offset. + * + * NB: The G3CODE_INVALID entries are only used + * during state generation (see mkg3states.c). + */ +#ifdef G3CODES +const tableentry TIFFFaxWhiteCodes[] = { + { 8, 0x35, 0 }, /* 0011 0101 */ + { 6, 0x7, 1 }, /* 0001 11 */ + { 4, 0x7, 2 }, /* 0111 */ + { 4, 0x8, 3 }, /* 1000 */ + { 4, 0xB, 4 }, /* 1011 */ + { 4, 0xC, 5 }, /* 1100 */ + { 4, 0xE, 6 }, /* 1110 */ + { 4, 0xF, 7 }, /* 1111 */ + { 5, 0x13, 8 }, /* 1001 1 */ + { 5, 0x14, 9 }, /* 1010 0 */ + { 5, 0x7, 10 }, /* 0011 1 */ + { 5, 0x8, 11 }, /* 0100 0 */ + { 6, 0x8, 12 }, /* 0010 00 */ + { 6, 0x3, 13 }, /* 0000 11 */ + { 6, 0x34, 14 }, /* 1101 00 */ + { 6, 0x35, 15 }, /* 1101 01 */ + { 6, 0x2A, 16 }, /* 1010 10 */ + { 6, 0x2B, 17 }, /* 1010 11 */ + { 7, 0x27, 18 }, /* 0100 111 */ + { 7, 0xC, 19 }, /* 0001 100 */ + { 7, 0x8, 20 }, /* 0001 000 */ + { 7, 0x17, 21 }, /* 0010 111 */ + { 7, 0x3, 22 }, /* 0000 011 */ + { 7, 0x4, 23 }, /* 0000 100 */ + { 7, 0x28, 24 }, /* 0101 000 */ + { 7, 0x2B, 25 }, /* 0101 011 */ + { 7, 0x13, 26 }, /* 0010 011 */ + { 7, 0x24, 27 }, /* 0100 100 */ + { 7, 0x18, 28 }, /* 0011 000 */ + { 8, 0x2, 29 }, /* 0000 0010 */ + { 8, 0x3, 30 }, /* 0000 0011 */ + { 8, 0x1A, 31 }, /* 0001 1010 */ + { 8, 0x1B, 32 }, /* 0001 1011 */ + { 8, 0x12, 33 }, /* 0001 0010 */ + { 8, 0x13, 34 }, /* 0001 0011 */ + { 8, 0x14, 35 }, /* 0001 0100 */ + { 8, 0x15, 36 }, /* 0001 0101 */ + { 8, 0x16, 37 }, /* 0001 0110 */ + { 8, 0x17, 38 }, /* 0001 0111 */ + { 8, 0x28, 39 }, /* 0010 1000 */ + { 8, 0x29, 40 }, /* 0010 1001 */ + { 8, 0x2A, 41 }, /* 0010 1010 */ + { 8, 0x2B, 42 }, /* 0010 1011 */ + { 8, 0x2C, 43 }, /* 0010 1100 */ + { 8, 0x2D, 44 }, /* 0010 1101 */ + { 8, 0x4, 45 }, /* 0000 0100 */ + { 8, 0x5, 46 }, /* 0000 0101 */ + { 8, 0xA, 47 }, /* 0000 1010 */ + { 8, 0xB, 48 }, /* 0000 1011 */ + { 8, 0x52, 49 }, /* 0101 0010 */ + { 8, 0x53, 50 }, /* 0101 0011 */ + { 8, 0x54, 51 }, /* 0101 0100 */ + { 8, 0x55, 52 }, /* 0101 0101 */ + { 8, 0x24, 53 }, /* 0010 0100 */ + { 8, 0x25, 54 }, /* 0010 0101 */ + { 8, 0x58, 55 }, /* 0101 1000 */ + { 8, 0x59, 56 }, /* 0101 1001 */ + { 8, 0x5A, 57 }, /* 0101 1010 */ + { 8, 0x5B, 58 }, /* 0101 1011 */ + { 8, 0x4A, 59 }, /* 0100 1010 */ + { 8, 0x4B, 60 }, /* 0100 1011 */ + { 8, 0x32, 61 }, /* 0011 0010 */ + { 8, 0x33, 62 }, /* 0011 0011 */ + { 8, 0x34, 63 }, /* 0011 0100 */ + { 5, 0x1B, 64 }, /* 1101 1 */ + { 5, 0x12, 128 }, /* 1001 0 */ + { 6, 0x17, 192 }, /* 0101 11 */ + { 7, 0x37, 256 }, /* 0110 111 */ + { 8, 0x36, 320 }, /* 0011 0110 */ + { 8, 0x37, 384 }, /* 0011 0111 */ + { 8, 0x64, 448 }, /* 0110 0100 */ + { 8, 0x65, 512 }, /* 0110 0101 */ + { 8, 0x68, 576 }, /* 0110 1000 */ + { 8, 0x67, 640 }, /* 0110 0111 */ + { 9, 0xCC, 704 }, /* 0110 0110 0 */ + { 9, 0xCD, 768 }, /* 0110 0110 1 */ + { 9, 0xD2, 832 }, /* 0110 1001 0 */ + { 9, 0xD3, 896 }, /* 0110 1001 1 */ + { 9, 0xD4, 960 }, /* 0110 1010 0 */ + { 9, 0xD5, 1024 }, /* 0110 1010 1 */ + { 9, 0xD6, 1088 }, /* 0110 1011 0 */ + { 9, 0xD7, 1152 }, /* 0110 1011 1 */ + { 9, 0xD8, 1216 }, /* 0110 1100 0 */ + { 9, 0xD9, 1280 }, /* 0110 1100 1 */ + { 9, 0xDA, 1344 }, /* 0110 1101 0 */ + { 9, 0xDB, 1408 }, /* 0110 1101 1 */ + { 9, 0x98, 1472 }, /* 0100 1100 0 */ + { 9, 0x99, 1536 }, /* 0100 1100 1 */ + { 9, 0x9A, 1600 }, /* 0100 1101 0 */ + { 6, 0x18, 1664 }, /* 0110 00 */ + { 9, 0x9B, 1728 }, /* 0100 1101 1 */ + { 11, 0x8, 1792 }, /* 0000 0001 000 */ + { 11, 0xC, 1856 }, /* 0000 0001 100 */ + { 11, 0xD, 1920 }, /* 0000 0001 101 */ + { 12, 0x12, 1984 }, /* 0000 0001 0010 */ + { 12, 0x13, 2048 }, /* 0000 0001 0011 */ + { 12, 0x14, 2112 }, /* 0000 0001 0100 */ + { 12, 0x15, 2176 }, /* 0000 0001 0101 */ + { 12, 0x16, 2240 }, /* 0000 0001 0110 */ + { 12, 0x17, 2304 }, /* 0000 0001 0111 */ + { 12, 0x1C, 2368 }, /* 0000 0001 1100 */ + { 12, 0x1D, 2432 }, /* 0000 0001 1101 */ + { 12, 0x1E, 2496 }, /* 0000 0001 1110 */ + { 12, 0x1F, 2560 }, /* 0000 0001 1111 */ + { 12, 0x1, G3CODE_EOL }, /* 0000 0000 0001 */ + { 9, 0x1, G3CODE_INVALID }, /* 0000 0000 1 */ + { 10, 0x1, G3CODE_INVALID }, /* 0000 0000 01 */ + { 11, 0x1, G3CODE_INVALID }, /* 0000 0000 001 */ + { 12, 0x0, G3CODE_INVALID }, /* 0000 0000 0000 */ +}; + +const tableentry TIFFFaxBlackCodes[] = { + { 10, 0x37, 0 }, /* 0000 1101 11 */ + { 3, 0x2, 1 }, /* 010 */ + { 2, 0x3, 2 }, /* 11 */ + { 2, 0x2, 3 }, /* 10 */ + { 3, 0x3, 4 }, /* 011 */ + { 4, 0x3, 5 }, /* 0011 */ + { 4, 0x2, 6 }, /* 0010 */ + { 5, 0x3, 7 }, /* 0001 1 */ + { 6, 0x5, 8 }, /* 0001 01 */ + { 6, 0x4, 9 }, /* 0001 00 */ + { 7, 0x4, 10 }, /* 0000 100 */ + { 7, 0x5, 11 }, /* 0000 101 */ + { 7, 0x7, 12 }, /* 0000 111 */ + { 8, 0x4, 13 }, /* 0000 0100 */ + { 8, 0x7, 14 }, /* 0000 0111 */ + { 9, 0x18, 15 }, /* 0000 1100 0 */ + { 10, 0x17, 16 }, /* 0000 0101 11 */ + { 10, 0x18, 17 }, /* 0000 0110 00 */ + { 10, 0x8, 18 }, /* 0000 0010 00 */ + { 11, 0x67, 19 }, /* 0000 1100 111 */ + { 11, 0x68, 20 }, /* 0000 1101 000 */ + { 11, 0x6C, 21 }, /* 0000 1101 100 */ + { 11, 0x37, 22 }, /* 0000 0110 111 */ + { 11, 0x28, 23 }, /* 0000 0101 000 */ + { 11, 0x17, 24 }, /* 0000 0010 111 */ + { 11, 0x18, 25 }, /* 0000 0011 000 */ + { 12, 0xCA, 26 }, /* 0000 1100 1010 */ + { 12, 0xCB, 27 }, /* 0000 1100 1011 */ + { 12, 0xCC, 28 }, /* 0000 1100 1100 */ + { 12, 0xCD, 29 }, /* 0000 1100 1101 */ + { 12, 0x68, 30 }, /* 0000 0110 1000 */ + { 12, 0x69, 31 }, /* 0000 0110 1001 */ + { 12, 0x6A, 32 }, /* 0000 0110 1010 */ + { 12, 0x6B, 33 }, /* 0000 0110 1011 */ + { 12, 0xD2, 34 }, /* 0000 1101 0010 */ + { 12, 0xD3, 35 }, /* 0000 1101 0011 */ + { 12, 0xD4, 36 }, /* 0000 1101 0100 */ + { 12, 0xD5, 37 }, /* 0000 1101 0101 */ + { 12, 0xD6, 38 }, /* 0000 1101 0110 */ + { 12, 0xD7, 39 }, /* 0000 1101 0111 */ + { 12, 0x6C, 40 }, /* 0000 0110 1100 */ + { 12, 0x6D, 41 }, /* 0000 0110 1101 */ + { 12, 0xDA, 42 }, /* 0000 1101 1010 */ + { 12, 0xDB, 43 }, /* 0000 1101 1011 */ + { 12, 0x54, 44 }, /* 0000 0101 0100 */ + { 12, 0x55, 45 }, /* 0000 0101 0101 */ + { 12, 0x56, 46 }, /* 0000 0101 0110 */ + { 12, 0x57, 47 }, /* 0000 0101 0111 */ + { 12, 0x64, 48 }, /* 0000 0110 0100 */ + { 12, 0x65, 49 }, /* 0000 0110 0101 */ + { 12, 0x52, 50 }, /* 0000 0101 0010 */ + { 12, 0x53, 51 }, /* 0000 0101 0011 */ + { 12, 0x24, 52 }, /* 0000 0010 0100 */ + { 12, 0x37, 53 }, /* 0000 0011 0111 */ + { 12, 0x38, 54 }, /* 0000 0011 1000 */ + { 12, 0x27, 55 }, /* 0000 0010 0111 */ + { 12, 0x28, 56 }, /* 0000 0010 1000 */ + { 12, 0x58, 57 }, /* 0000 0101 1000 */ + { 12, 0x59, 58 }, /* 0000 0101 1001 */ + { 12, 0x2B, 59 }, /* 0000 0010 1011 */ + { 12, 0x2C, 60 }, /* 0000 0010 1100 */ + { 12, 0x5A, 61 }, /* 0000 0101 1010 */ + { 12, 0x66, 62 }, /* 0000 0110 0110 */ + { 12, 0x67, 63 }, /* 0000 0110 0111 */ + { 10, 0xF, 64 }, /* 0000 0011 11 */ + { 12, 0xC8, 128 }, /* 0000 1100 1000 */ + { 12, 0xC9, 192 }, /* 0000 1100 1001 */ + { 12, 0x5B, 256 }, /* 0000 0101 1011 */ + { 12, 0x33, 320 }, /* 0000 0011 0011 */ + { 12, 0x34, 384 }, /* 0000 0011 0100 */ + { 12, 0x35, 448 }, /* 0000 0011 0101 */ + { 13, 0x6C, 512 }, /* 0000 0011 0110 0 */ + { 13, 0x6D, 576 }, /* 0000 0011 0110 1 */ + { 13, 0x4A, 640 }, /* 0000 0010 0101 0 */ + { 13, 0x4B, 704 }, /* 0000 0010 0101 1 */ + { 13, 0x4C, 768 }, /* 0000 0010 0110 0 */ + { 13, 0x4D, 832 }, /* 0000 0010 0110 1 */ + { 13, 0x72, 896 }, /* 0000 0011 1001 0 */ + { 13, 0x73, 960 }, /* 0000 0011 1001 1 */ + { 13, 0x74, 1024 }, /* 0000 0011 1010 0 */ + { 13, 0x75, 1088 }, /* 0000 0011 1010 1 */ + { 13, 0x76, 1152 }, /* 0000 0011 1011 0 */ + { 13, 0x77, 1216 }, /* 0000 0011 1011 1 */ + { 13, 0x52, 1280 }, /* 0000 0010 1001 0 */ + { 13, 0x53, 1344 }, /* 0000 0010 1001 1 */ + { 13, 0x54, 1408 }, /* 0000 0010 1010 0 */ + { 13, 0x55, 1472 }, /* 0000 0010 1010 1 */ + { 13, 0x5A, 1536 }, /* 0000 0010 1101 0 */ + { 13, 0x5B, 1600 }, /* 0000 0010 1101 1 */ + { 13, 0x64, 1664 }, /* 0000 0011 0010 0 */ + { 13, 0x65, 1728 }, /* 0000 0011 0010 1 */ + { 11, 0x8, 1792 }, /* 0000 0001 000 */ + { 11, 0xC, 1856 }, /* 0000 0001 100 */ + { 11, 0xD, 1920 }, /* 0000 0001 101 */ + { 12, 0x12, 1984 }, /* 0000 0001 0010 */ + { 12, 0x13, 2048 }, /* 0000 0001 0011 */ + { 12, 0x14, 2112 }, /* 0000 0001 0100 */ + { 12, 0x15, 2176 }, /* 0000 0001 0101 */ + { 12, 0x16, 2240 }, /* 0000 0001 0110 */ + { 12, 0x17, 2304 }, /* 0000 0001 0111 */ + { 12, 0x1C, 2368 }, /* 0000 0001 1100 */ + { 12, 0x1D, 2432 }, /* 0000 0001 1101 */ + { 12, 0x1E, 2496 }, /* 0000 0001 1110 */ + { 12, 0x1F, 2560 }, /* 0000 0001 1111 */ + { 12, 0x1, G3CODE_EOL }, /* 0000 0000 0001 */ + { 9, 0x1, G3CODE_INVALID }, /* 0000 0000 1 */ + { 10, 0x1, G3CODE_INVALID }, /* 0000 0000 01 */ + { 11, 0x1, G3CODE_INVALID }, /* 0000 0000 001 */ + { 12, 0x0, G3CODE_INVALID }, /* 0000 0000 0000 */ +}; +#else +extern const tableentry TIFFFaxWhiteCodes[]; +extern const tableentry TIFFFaxBlackCodes[]; +#endif +#endif /* _T4_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_aux.c b/SlnkDWFImpl/CxImage/tiff/tif_aux.c new file mode 100644 index 0000000..604fc35 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_aux.c @@ -0,0 +1,206 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_aux.c,v 1.3 2000/03/03 15:22:00 warmerda Exp $ */ + +/* + * Copyright (c) 1991-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Auxiliary Support Routines. + */ +#include "tiffiop.h" + +#ifdef COLORIMETRY_SUPPORT +#include + +static void +TIFFDefaultTransferFunction(TIFFDirectory* td) +{ + uint16 **tf = td->td_transferfunction; + long i, n = 1<td_bitspersample; + + tf[0] = (uint16 *)_TIFFmalloc(n * sizeof (uint16)); + tf[0][0] = 0; + for (i = 1; i < n; i++) { + double t = (double)i/((double) n-1.); + tf[0][i] = (uint16)floor(65535.*pow(t, 2.2) + .5); + } + if (td->td_samplesperpixel - td->td_extrasamples > 1) { + tf[1] = (uint16 *)_TIFFmalloc(n * sizeof (uint16)); + _TIFFmemcpy(tf[1], tf[0], n * sizeof (uint16)); + tf[2] = (uint16 *)_TIFFmalloc(n * sizeof (uint16)); + _TIFFmemcpy(tf[2], tf[0], n * sizeof (uint16)); + } +} + +static void +TIFFDefaultRefBlackWhite(TIFFDirectory* td) +{ + int i; + + td->td_refblackwhite = (float *)_TIFFmalloc(6*sizeof (float)); + for (i = 0; i < 3; i++) { + td->td_refblackwhite[2*i+0] = 0; + td->td_refblackwhite[2*i+1] = (float)((1L<td_bitspersample)-1L); + } +} +#endif + +/* + * Like TIFFGetField, but return any default + * value if the tag is not present in the directory. + * + * NB: We use the value in the directory, rather than + * explcit values so that defaults exist only one + * place in the library -- in TIFFDefaultDirectory. + */ +int +TIFFVGetFieldDefaulted(TIFF* tif, ttag_t tag, va_list ap) +{ + TIFFDirectory *td = &tif->tif_dir; + + if (TIFFVGetField(tif, tag, ap)) + return (1); + switch (tag) { + case TIFFTAG_SUBFILETYPE: + *va_arg(ap, uint32 *) = td->td_subfiletype; + return (1); + case TIFFTAG_BITSPERSAMPLE: + *va_arg(ap, uint16 *) = td->td_bitspersample; + return (1); + case TIFFTAG_THRESHHOLDING: + *va_arg(ap, uint16 *) = td->td_threshholding; + return (1); + case TIFFTAG_FILLORDER: + *va_arg(ap, uint16 *) = td->td_fillorder; + return (1); + case TIFFTAG_ORIENTATION: + *va_arg(ap, uint16 *) = td->td_orientation; + return (1); + case TIFFTAG_SAMPLESPERPIXEL: + *va_arg(ap, uint16 *) = td->td_samplesperpixel; + return (1); + case TIFFTAG_ROWSPERSTRIP: + *va_arg(ap, uint32 *) = td->td_rowsperstrip; + return (1); + case TIFFTAG_MINSAMPLEVALUE: + *va_arg(ap, uint16 *) = td->td_minsamplevalue; + return (1); + case TIFFTAG_MAXSAMPLEVALUE: + *va_arg(ap, uint16 *) = td->td_maxsamplevalue; + return (1); + case TIFFTAG_PLANARCONFIG: + *va_arg(ap, uint16 *) = td->td_planarconfig; + return (1); + case TIFFTAG_RESOLUTIONUNIT: + *va_arg(ap, uint16 *) = td->td_resolutionunit; + return (1); +#ifdef CMYK_SUPPORT + case TIFFTAG_DOTRANGE: + *va_arg(ap, uint16 *) = 0; + *va_arg(ap, uint16 *) = (1<td_bitspersample)-1; + return (1); + case TIFFTAG_INKSET: + *va_arg(ap, uint16 *) = td->td_inkset; + return (1); + case TIFFTAG_NUMBEROFINKS: + *va_arg(ap, uint16 *) = td->td_ninks; + return (1); +#endif + case TIFFTAG_EXTRASAMPLES: + *va_arg(ap, uint16 *) = td->td_extrasamples; + *va_arg(ap, uint16 **) = td->td_sampleinfo; + return (1); + case TIFFTAG_MATTEING: + *va_arg(ap, uint16 *) = + (td->td_extrasamples == 1 && + td->td_sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA); + return (1); + case TIFFTAG_TILEDEPTH: + *va_arg(ap, uint32 *) = td->td_tiledepth; + return (1); + case TIFFTAG_DATATYPE: + *va_arg(ap, uint16 *) = td->td_sampleformat-1; + return (1); + case TIFFTAG_SAMPLEFORMAT: + *va_arg(ap, uint16 *) = td->td_sampleformat; + return(1); + case TIFFTAG_IMAGEDEPTH: + *va_arg(ap, uint32 *) = td->td_imagedepth; + return (1); +#ifdef YCBCR_SUPPORT + case TIFFTAG_YCBCRCOEFFICIENTS: + if (!td->td_ycbcrcoeffs) { + td->td_ycbcrcoeffs = (float *) + _TIFFmalloc(3*sizeof (float)); + /* defaults are from CCIR Recommendation 601-1 */ + td->td_ycbcrcoeffs[0] = 0.299f; + td->td_ycbcrcoeffs[1] = 0.587f; + td->td_ycbcrcoeffs[2] = 0.114f; + } + *va_arg(ap, float **) = td->td_ycbcrcoeffs; + return (1); + case TIFFTAG_YCBCRSUBSAMPLING: + *va_arg(ap, uint16 *) = td->td_ycbcrsubsampling[0]; + *va_arg(ap, uint16 *) = td->td_ycbcrsubsampling[1]; + return (1); + case TIFFTAG_YCBCRPOSITIONING: + *va_arg(ap, uint16 *) = td->td_ycbcrpositioning; + return (1); +#endif +#ifdef COLORIMETRY_SUPPORT + case TIFFTAG_TRANSFERFUNCTION: + if (!td->td_transferfunction[0]) + TIFFDefaultTransferFunction(td); + *va_arg(ap, uint16 **) = td->td_transferfunction[0]; + if (td->td_samplesperpixel - td->td_extrasamples > 1) { + *va_arg(ap, uint16 **) = td->td_transferfunction[1]; + *va_arg(ap, uint16 **) = td->td_transferfunction[2]; + } + return (1); + case TIFFTAG_REFERENCEBLACKWHITE: + if (!td->td_refblackwhite) + TIFFDefaultRefBlackWhite(td); + *va_arg(ap, float **) = td->td_refblackwhite; + return (1); +#endif + } + return (0); +} + +/* + * Like TIFFGetField, but return any default + * value if the tag is not present in the directory. + */ +int +TIFFGetFieldDefaulted(TIFF* tif, ttag_t tag, ...) +{ + int ok; + va_list ap; + + va_start(ap, tag); + ok = TIFFVGetFieldDefaulted(tif, tag, ap); + va_end(ap); + return (ok); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_close.c b/SlnkDWFImpl/CxImage/tiff/tif_close.c new file mode 100644 index 0000000..bb18935 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_close.c @@ -0,0 +1,50 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_close.c,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + */ +#include "tiffiop.h" + +void +TIFFClose(TIFF* tif) +{ + if (tif->tif_mode != O_RDONLY) + /* + * Flush buffered data and directory (if dirty). + */ + TIFFFlush(tif); + (*tif->tif_cleanup)(tif); + TIFFFreeDirectory(tif); + if (tif->tif_rawdata && (tif->tif_flags&TIFF_MYBUFFER)) + _TIFFfree(tif->tif_rawdata); + if (isMapped(tif)) + TIFFUnmapFileContents(tif, tif->tif_base, tif->tif_size); + (void) TIFFCloseFile(tif); + if (tif->tif_fieldinfo) + _TIFFfree(tif->tif_fieldinfo); + _TIFFfree(tif); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_codec.c b/SlnkDWFImpl/CxImage/tiff/tif_codec.c new file mode 100644 index 0000000..6938945 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_codec.c @@ -0,0 +1,117 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_codec.c,v 1.2 1999/12/07 17:11:38 mwelles Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library + * + * Builtin Compression Scheme Configuration Support. + */ +#include "tiffiop.h" + +static int NotConfigured(TIFF*, int); + +#ifndef LZW_SUPPORT +#define TIFFInitLZW NotConfigured +#endif +#ifndef PACKBITS_SUPPORT +#define TIFFInitPackbits NotConfigured +#endif +#ifndef THUNDER_SUPPORT +#define TIFFInitThunderScan NotConfigured +#endif +#ifndef NEXT_SUPPORT +#define TIFFInitNeXT NotConfigured +#endif +#ifndef JPEG_SUPPORT +#define TIFFInitJPEG NotConfigured +#endif +#ifndef OJPEG_SUPPORT +#define TIFFInitOJPEG NotConfigured +#endif +#ifndef CCITT_SUPPORT +#define TIFFInitCCITTRLE NotConfigured +#define TIFFInitCCITTRLEW NotConfigured +#define TIFFInitCCITTFax3 NotConfigured +#define TIFFInitCCITTFax4 NotConfigured +#endif +#ifndef JBIG_SUPPORT +#define TIFFInitJBIG NotConfigured +#endif +#ifndef ZIP_SUPPORT +#define TIFFInitZIP NotConfigured +#endif +#ifndef PIXARLOG_SUPPORT +#define TIFFInitPixarLog NotConfigured +#endif +#ifndef LOGLUV_SUPPORT +#define TIFFInitSGILog NotConfigured +#endif + +/* + * Compression schemes statically built into the library. + */ +#ifdef VMS +const TIFFCodec _TIFFBuiltinCODECS[] = { +#else +TIFFCodec _TIFFBuiltinCODECS[] = { +#endif + { "None", COMPRESSION_NONE, TIFFInitDumpMode }, + { "LZW", COMPRESSION_LZW, TIFFInitLZW }, + { "PackBits", COMPRESSION_PACKBITS, TIFFInitPackBits }, + { "ThunderScan", COMPRESSION_THUNDERSCAN,TIFFInitThunderScan }, + { "NeXT", COMPRESSION_NEXT, TIFFInitNeXT }, + { "JPEG", COMPRESSION_JPEG, TIFFInitJPEG }, + { "Old-style JPEG", COMPRESSION_OJPEG, TIFFInitOJPEG }, + { "CCITT RLE", COMPRESSION_CCITTRLE, TIFFInitCCITTRLE }, + { "CCITT RLE/W", COMPRESSION_CCITTRLEW, TIFFInitCCITTRLEW }, + { "CCITT Group 3", COMPRESSION_CCITTFAX3, TIFFInitCCITTFax3 }, + { "CCITT Group 4", COMPRESSION_CCITTFAX4, TIFFInitCCITTFax4 }, + { "ISO JBIG", COMPRESSION_JBIG, TIFFInitJBIG }, + { "Deflate", COMPRESSION_DEFLATE, TIFFInitZIP }, + { "AdobeDeflate", COMPRESSION_ADOBE_DEFLATE , TIFFInitZIP }, + { "PixarLog", COMPRESSION_PIXARLOG, TIFFInitPixarLog }, + { "SGILog", COMPRESSION_SGILOG, TIFFInitSGILog }, + { "SGILog24", COMPRESSION_SGILOG24, TIFFInitSGILog }, + { NULL } +}; + +static int +_notConfigured(TIFF* tif) +{ + const TIFFCodec* c = TIFFFindCODEC(tif->tif_dir.td_compression); + + TIFFError(tif->tif_name, + "%s compression support is not configured", c->name); + return (0); +} + +static int +NotConfigured(TIFF* tif, int scheme) +{ + tif->tif_setupdecode = _notConfigured; + tif->tif_setupencode = _notConfigured; + return (1); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_compress.c b/SlnkDWFImpl/CxImage/tiff/tif_compress.c new file mode 100644 index 0000000..de90bf3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_compress.c @@ -0,0 +1,231 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_compress.c,v 1.4 1999/12/21 17:03:03 mwelles Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library + * + * Compression Scheme Configuration Support. + */ +#include "tiffiop.h" + +static int +TIFFNoEncode(TIFF* tif, char* method) +{ + const TIFFCodec* c = TIFFFindCODEC(tif->tif_dir.td_compression); + + if (c) { + if (! strncmp(c->name, "LZW", 3) ){ + TIFFError(tif->tif_name, + "%s %s encoding is no longer implemented due to Unisys patent enforcement", + c->name, method); + } else { + TIFFError(tif->tif_name, "%s %s encoding is not implemented", + c->name, method); + } + } + else { + TIFFError(tif->tif_name, + "Compression scheme %u %s encoding is not implemented", + tif->tif_dir.td_compression, method); + } + return (-1); +} + +int +_TIFFNoRowEncode(TIFF* tif, tidata_t pp, tsize_t cc, tsample_t s) +{ + (void) pp; (void) cc; (void) s; + return (TIFFNoEncode(tif, "scanline")); +} + +int +_TIFFNoStripEncode(TIFF* tif, tidata_t pp, tsize_t cc, tsample_t s) +{ + (void) pp; (void) cc; (void) s; + return (TIFFNoEncode(tif, "strip")); +} + +int +_TIFFNoTileEncode(TIFF* tif, tidata_t pp, tsize_t cc, tsample_t s) +{ + (void) pp; (void) cc; (void) s; + return (TIFFNoEncode(tif, "tile")); +} + +static int +TIFFNoDecode(TIFF* tif, char* method) +{ + const TIFFCodec* c = TIFFFindCODEC(tif->tif_dir.td_compression); + + if (c) + TIFFError(tif->tif_name, "%s %s decoding is not implemented", + c->name, method); + else + TIFFError(tif->tif_name, + "Compression scheme %u %s decoding is not implemented", + tif->tif_dir.td_compression, method); + return (-1); +} + +int +_TIFFNoRowDecode(TIFF* tif, tidata_t pp, tsize_t cc, tsample_t s) +{ + (void) pp; (void) cc; (void) s; + return (TIFFNoDecode(tif, "scanline")); +} + +int +_TIFFNoStripDecode(TIFF* tif, tidata_t pp, tsize_t cc, tsample_t s) +{ + (void) pp; (void) cc; (void) s; + return (TIFFNoDecode(tif, "strip")); +} + +int +_TIFFNoTileDecode(TIFF* tif, tidata_t pp, tsize_t cc, tsample_t s) +{ + (void) pp; (void) cc; (void) s; + return (TIFFNoDecode(tif, "tile")); +} + +int +_TIFFNoSeek(TIFF* tif, uint32 off) +{ + (void) off; + TIFFError(tif->tif_name, + "Compression algorithm does not support random access"); + return (0); +} + +int +_TIFFNoPreCode(TIFF* tif, tsample_t s) +{ + (void) tif; (void) s; + return (1); +} + +static int _TIFFtrue(TIFF* tif) { (void) tif; return (1); } +static void _TIFFvoid(TIFF* tif) { (void) tif; } + +void +_TIFFSetDefaultCompressionState(TIFF* tif) +{ + tif->tif_setupdecode = _TIFFtrue; + tif->tif_predecode = _TIFFNoPreCode; + tif->tif_decoderow = _TIFFNoRowDecode; + tif->tif_decodestrip = _TIFFNoStripDecode; + tif->tif_decodetile = _TIFFNoTileDecode; + tif->tif_setupencode = _TIFFtrue; + tif->tif_preencode = _TIFFNoPreCode; + tif->tif_postencode = _TIFFtrue; + tif->tif_encoderow = _TIFFNoRowEncode; + tif->tif_encodestrip = _TIFFNoStripEncode; + tif->tif_encodetile = _TIFFNoTileEncode; + tif->tif_close = _TIFFvoid; + tif->tif_seek = _TIFFNoSeek; + tif->tif_cleanup = _TIFFvoid; + tif->tif_defstripsize = _TIFFDefaultStripSize; + tif->tif_deftilesize = _TIFFDefaultTileSize; + tif->tif_flags &= ~TIFF_NOBITREV; +} + +int +TIFFSetCompressionScheme(TIFF* tif, int scheme) +{ + const TIFFCodec *c = TIFFFindCODEC((uint16) scheme); + + _TIFFSetDefaultCompressionState(tif); + /* + * Don't treat an unknown compression scheme as an error. + * This permits applications to open files with data that + * the library does not have builtin support for, but which + * may still be meaningful. + */ + return (c ? (*c->init)(tif, scheme) : 1); +} + +/* + * Other compression schemes may be registered. Registered + * schemes can also override the builtin versions provided + * by this library. + */ +typedef struct _codec { + struct _codec* next; + TIFFCodec* info; +} codec_t; +static codec_t* registeredCODECS = NULL; + +const TIFFCodec* +TIFFFindCODEC(uint16 scheme) +{ + const TIFFCodec* c; + codec_t* cd; + + for (cd = registeredCODECS; cd; cd = cd->next) + if (cd->info->scheme == scheme) + return ((const TIFFCodec*) cd->info); + for (c = _TIFFBuiltinCODECS; c->name; c++) + if (c->scheme == scheme) + return (c); + return ((const TIFFCodec*) 0); +} + +TIFFCodec* +TIFFRegisterCODEC(uint16 scheme, const char* name, TIFFInitMethod init) +{ + codec_t* cd = (codec_t*) + _TIFFmalloc(sizeof (codec_t) + sizeof (TIFFCodec) + strlen(name)+1); + + if (cd != NULL) { + cd->info = (TIFFCodec*) ((tidata_t) cd + sizeof (codec_t)); + cd->info->name = (char*) + ((tidata_t) cd->info + sizeof (TIFFCodec)); + strcpy(cd->info->name, name); + cd->info->scheme = scheme; + cd->info->init = init; + cd->next = registeredCODECS; + registeredCODECS = cd; + } else + TIFFError("TIFFRegisterCODEC", + "No space to register compression scheme %s", name); + return (cd->info); +} + +void +TIFFUnRegisterCODEC(TIFFCodec* c) +{ + codec_t* cd; + codec_t** pcd; + + for (pcd = ®isteredCODECS; (cd = *pcd); pcd = &cd->next) + if (cd->info == c) { + *pcd = cd->next; + _TIFFfree(cd); + return; + } + TIFFError("TIFFUnRegisterCODEC", + "Cannot remove compression scheme %s; not registered", c->name); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_dir.c b/SlnkDWFImpl/CxImage/tiff/tif_dir.c new file mode 100644 index 0000000..32b78b5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_dir.c @@ -0,0 +1,1304 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_dir.c,v 1.16 2001/09/25 01:33:54 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Directory Tag Get & Set Routines. + * (and also some miscellaneous stuff) + */ +#include "tiffiop.h" + +/* + * These are used in the backwards compatibility code... + */ +#define DATATYPE_VOID 0 /* !untyped data */ +#define DATATYPE_INT 1 /* !signed integer data */ +#define DATATYPE_UINT 2 /* !unsigned integer data */ +#define DATATYPE_IEEEFP 3 /* !IEEE floating point data */ + +void +_TIFFsetByteArray(void** vpp, void* vp, long n) +{ + if (*vpp) + _TIFFfree(*vpp), *vpp = 0; + if (vp && (*vpp = (void*) _TIFFmalloc(n))) + _TIFFmemcpy(*vpp, vp, n); +} +void _TIFFsetString(char** cpp, char* cp) + { _TIFFsetByteArray((void**) cpp, (void*) cp, (long) (strlen(cp)+1)); } +void _TIFFsetNString(char** cpp, char* cp, long n) + { _TIFFsetByteArray((void**) cpp, (void*) cp, n); } +void _TIFFsetShortArray(uint16** wpp, uint16* wp, long n) + { _TIFFsetByteArray((void**) wpp, (void*) wp, n*sizeof (uint16)); } +void _TIFFsetLongArray(uint32** lpp, uint32* lp, long n) + { _TIFFsetByteArray((void**) lpp, (void*) lp, n*sizeof (uint32)); } +void _TIFFsetFloatArray(float** fpp, float* fp, long n) + { _TIFFsetByteArray((void**) fpp, (void*) fp, n*sizeof (float)); } +void _TIFFsetDoubleArray(double** dpp, double* dp, long n) + { _TIFFsetByteArray((void**) dpp, (void*) dp, n*sizeof (double)); } + +/* + * Install extra samples information. + */ +static int +setExtraSamples(TIFFDirectory* td, va_list ap, int* v) +{ + uint16* va; + int i; + + *v = va_arg(ap, int); + if ((uint16) *v > td->td_samplesperpixel) + return (0); + va = va_arg(ap, uint16*); + if (*v > 0 && va == NULL) /* typically missing param */ + return (0); + for (i = 0; i < *v; i++) + if (va[i] > EXTRASAMPLE_UNASSALPHA) + return (0); + td->td_extrasamples = (uint16) *v; + _TIFFsetShortArray(&td->td_sampleinfo, va, td->td_extrasamples); + return (1); +} + +#ifdef CMYK_SUPPORT +static int +checkInkNamesString(TIFF* tif, int slen, const char* s) +{ + TIFFDirectory* td = &tif->tif_dir; + int i = td->td_samplesperpixel; + + if (slen > 0) { + const char* ep = s+slen; + const char* cp = s; + for (; i > 0; i--) { + for (; *cp != '\0'; cp++) + if (cp >= ep) + goto bad; + cp++; /* skip \0 */ + } + return (cp-s); + } +bad: + TIFFError("TIFFSetField", + "%s: Invalid InkNames value; expecting %d names, found %d", + tif->tif_name, + td->td_samplesperpixel, + td->td_samplesperpixel-i); + return (0); +} +#endif + +static int +_TIFFVSetField(TIFF* tif, ttag_t tag, va_list ap) +{ + TIFFDirectory* td = &tif->tif_dir; + int status = 1; + uint32 v32; + int i, v; + double d; + char* s; + + switch (tag) { + case TIFFTAG_SUBFILETYPE: + td->td_subfiletype = va_arg(ap, uint32); + break; + case TIFFTAG_IMAGEWIDTH: + td->td_imagewidth = va_arg(ap, uint32); + break; + case TIFFTAG_IMAGELENGTH: + td->td_imagelength = va_arg(ap, uint32); + break; + case TIFFTAG_BITSPERSAMPLE: + td->td_bitspersample = (uint16) va_arg(ap, int); + /* + * If the data require post-decoding processing + * to byte-swap samples, set it up here. Note + * that since tags are required to be ordered, + * compression code can override this behaviour + * in the setup method if it wants to roll the + * post decoding work in with its normal work. + */ + if (tif->tif_flags & TIFF_SWAB) { + if (td->td_bitspersample == 16) + tif->tif_postdecode = _TIFFSwab16BitData; + else if (td->td_bitspersample == 32) + tif->tif_postdecode = _TIFFSwab32BitData; + else if (td->td_bitspersample == 64) + tif->tif_postdecode = _TIFFSwab64BitData; + } + break; + case TIFFTAG_COMPRESSION: + v = va_arg(ap, int) & 0xffff; + /* + * If we're changing the compression scheme, + * the notify the previous module so that it + * can cleanup any state it's setup. + */ + if (TIFFFieldSet(tif, FIELD_COMPRESSION)) { + if (td->td_compression == v) + break; + (*tif->tif_cleanup)(tif); + tif->tif_flags &= ~TIFF_CODERSETUP; + } + /* + * Setup new compression routine state. + */ + if( (status = TIFFSetCompressionScheme(tif, v)) != 0 ) + td->td_compression = v; + else + status = 0; + break; + case TIFFTAG_PHOTOMETRIC: + td->td_photometric = (uint16) va_arg(ap, int); + break; + case TIFFTAG_THRESHHOLDING: + td->td_threshholding = (uint16) va_arg(ap, int); + break; + case TIFFTAG_FILLORDER: + v = va_arg(ap, int); + if (v != FILLORDER_LSB2MSB && v != FILLORDER_MSB2LSB) + goto badvalue; + td->td_fillorder = (uint16) v; + break; + case TIFFTAG_DOCUMENTNAME: + _TIFFsetString(&td->td_documentname, va_arg(ap, char*)); + break; + case TIFFTAG_ARTIST: + _TIFFsetString(&td->td_artist, va_arg(ap, char*)); + break; + case TIFFTAG_DATETIME: + _TIFFsetString(&td->td_datetime, va_arg(ap, char*)); + break; + case TIFFTAG_HOSTCOMPUTER: + _TIFFsetString(&td->td_hostcomputer, va_arg(ap, char*)); + break; + case TIFFTAG_IMAGEDESCRIPTION: + _TIFFsetString(&td->td_imagedescription, va_arg(ap, char*)); + break; + case TIFFTAG_MAKE: + _TIFFsetString(&td->td_make, va_arg(ap, char*)); + break; + case TIFFTAG_MODEL: + _TIFFsetString(&td->td_model, va_arg(ap, char*)); + break; + case TIFFTAG_SOFTWARE: + _TIFFsetString(&td->td_software, va_arg(ap, char*)); + break; + case TIFFTAG_COPYRIGHT: + _TIFFsetString(&td->td_copyright, va_arg(ap, char*)); + break; + case TIFFTAG_ORIENTATION: + v = va_arg(ap, int); + if (v < ORIENTATION_TOPLEFT || ORIENTATION_LEFTBOT < v) { + TIFFWarning(tif->tif_name, + "Bad value %ld for \"%s\" tag ignored", + v, _TIFFFieldWithTag(tif, tag)->field_name); + } else + td->td_orientation = (uint16) v; + break; + case TIFFTAG_SAMPLESPERPIXEL: + /* XXX should cross check -- e.g. if pallette, then 1 */ + v = va_arg(ap, int); + if (v == 0) + goto badvalue; + td->td_samplesperpixel = (uint16) v; + break; + case TIFFTAG_ROWSPERSTRIP: + v32 = va_arg(ap, uint32); + if (v32 == 0) + goto badvalue32; + td->td_rowsperstrip = v32; + if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { + td->td_tilelength = v32; + td->td_tilewidth = td->td_imagewidth; + } + break; + case TIFFTAG_MINSAMPLEVALUE: + td->td_minsamplevalue = (uint16) va_arg(ap, int); + break; + case TIFFTAG_MAXSAMPLEVALUE: + td->td_maxsamplevalue = (uint16) va_arg(ap, int); + break; + case TIFFTAG_SMINSAMPLEVALUE: + td->td_sminsamplevalue = (double) va_arg(ap, dblparam_t); + break; + case TIFFTAG_SMAXSAMPLEVALUE: + td->td_smaxsamplevalue = (double) va_arg(ap, dblparam_t); + break; + case TIFFTAG_XRESOLUTION: + td->td_xresolution = (float) va_arg(ap, dblparam_t); + break; + case TIFFTAG_YRESOLUTION: + td->td_yresolution = (float) va_arg(ap, dblparam_t); + break; + case TIFFTAG_PLANARCONFIG: + v = va_arg(ap, int); + if (v != PLANARCONFIG_CONTIG && v != PLANARCONFIG_SEPARATE) + goto badvalue; + td->td_planarconfig = (uint16) v; + break; + case TIFFTAG_PAGENAME: + _TIFFsetString(&td->td_pagename, va_arg(ap, char*)); + break; + case TIFFTAG_XPOSITION: + td->td_xposition = (float) va_arg(ap, dblparam_t); + break; + case TIFFTAG_YPOSITION: + td->td_yposition = (float) va_arg(ap, dblparam_t); + break; + case TIFFTAG_RESOLUTIONUNIT: + v = va_arg(ap, int); + if (v < RESUNIT_NONE || RESUNIT_CENTIMETER < v) + goto badvalue; + td->td_resolutionunit = (uint16) v; + break; + case TIFFTAG_PAGENUMBER: + td->td_pagenumber[0] = (uint16) va_arg(ap, int); + td->td_pagenumber[1] = (uint16) va_arg(ap, int); + break; + case TIFFTAG_HALFTONEHINTS: + td->td_halftonehints[0] = (uint16) va_arg(ap, int); + td->td_halftonehints[1] = (uint16) va_arg(ap, int); + break; + case TIFFTAG_COLORMAP: + v32 = (uint32)(1L<td_bitspersample); + _TIFFsetShortArray(&td->td_colormap[0], va_arg(ap, uint16*), v32); + _TIFFsetShortArray(&td->td_colormap[1], va_arg(ap, uint16*), v32); + _TIFFsetShortArray(&td->td_colormap[2], va_arg(ap, uint16*), v32); + break; + case TIFFTAG_EXTRASAMPLES: + if (!setExtraSamples(td, ap, &v)) + goto badvalue; + break; + case TIFFTAG_MATTEING: + td->td_extrasamples = (uint16) (va_arg(ap, int) != 0); + if (td->td_extrasamples) { + uint16 sv = EXTRASAMPLE_ASSOCALPHA; + _TIFFsetShortArray(&td->td_sampleinfo, &sv, 1); + } + break; + case TIFFTAG_TILEWIDTH: + v32 = va_arg(ap, uint32); + if (v32 % 16) { + if (tif->tif_mode != O_RDONLY) + goto badvalue32; + TIFFWarning(tif->tif_name, + "Nonstandard tile width %d, convert file", v32); + } + td->td_tilewidth = v32; + tif->tif_flags |= TIFF_ISTILED; + break; + case TIFFTAG_TILELENGTH: + v32 = va_arg(ap, uint32); + if (v32 % 16) { + if (tif->tif_mode != O_RDONLY) + goto badvalue32; + TIFFWarning(tif->tif_name, + "Nonstandard tile length %d, convert file", v32); + } + td->td_tilelength = v32; + tif->tif_flags |= TIFF_ISTILED; + break; + case TIFFTAG_TILEDEPTH: + v32 = va_arg(ap, uint32); + if (v32 == 0) + goto badvalue32; + td->td_tiledepth = v32; + break; + case TIFFTAG_DATATYPE: + v = va_arg(ap, int); + switch (v) { + case DATATYPE_VOID: v = SAMPLEFORMAT_VOID; break; + case DATATYPE_INT: v = SAMPLEFORMAT_INT; break; + case DATATYPE_UINT: v = SAMPLEFORMAT_UINT; break; + case DATATYPE_IEEEFP: v = SAMPLEFORMAT_IEEEFP;break; + default: goto badvalue; + } + td->td_sampleformat = (uint16) v; + break; + case TIFFTAG_SAMPLEFORMAT: + v = va_arg(ap, int); + if (v < SAMPLEFORMAT_UINT || SAMPLEFORMAT_COMPLEXIEEEFP < v) + goto badvalue; + td->td_sampleformat = (uint16) v; + break; + case TIFFTAG_IMAGEDEPTH: + td->td_imagedepth = va_arg(ap, uint32); + break; + case TIFFTAG_STONITS: + d = va_arg(ap, dblparam_t); + if (d <= 0.) + goto badvaluedbl; + td->td_stonits = d; + break; + + /* Begin Pixar Tags */ + case TIFFTAG_PIXAR_IMAGEFULLWIDTH: + td->td_imagefullwidth = va_arg(ap, uint32); + break; + case TIFFTAG_PIXAR_IMAGEFULLLENGTH: + td->td_imagefulllength = va_arg(ap, uint32); + break; + case TIFFTAG_PIXAR_TEXTUREFORMAT: + _TIFFsetString(&td->td_textureformat, va_arg(ap, char*)); + break; + case TIFFTAG_PIXAR_WRAPMODES: + _TIFFsetString(&td->td_wrapmodes, va_arg(ap, char*)); + break; + case TIFFTAG_PIXAR_FOVCOT: + td->td_fovcot = (float) va_arg(ap, dblparam_t); + break; + case TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN: + _TIFFsetFloatArray(&td->td_matrixWorldToScreen, + va_arg(ap, float*), 16); + break; + case TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA: + _TIFFsetFloatArray(&td->td_matrixWorldToCamera, + va_arg(ap, float*), 16); + break; + /* End Pixar Tags */ + +#if SUBIFD_SUPPORT + case TIFFTAG_SUBIFD: + if ((tif->tif_flags & TIFF_INSUBIFD) == 0) { + td->td_nsubifd = (uint16) va_arg(ap, int); + _TIFFsetLongArray(&td->td_subifd, va_arg(ap, uint32*), + (long) td->td_nsubifd); + } else { + TIFFError(tif->tif_name, "Sorry, cannot nest SubIFDs"); + status = 0; + } + break; +#endif +#ifdef YCBCR_SUPPORT + case TIFFTAG_YCBCRCOEFFICIENTS: + _TIFFsetFloatArray(&td->td_ycbcrcoeffs, va_arg(ap, float*), 3); + break; + case TIFFTAG_YCBCRPOSITIONING: + td->td_ycbcrpositioning = (uint16) va_arg(ap, int); + break; + case TIFFTAG_YCBCRSUBSAMPLING: + td->td_ycbcrsubsampling[0] = (uint16) va_arg(ap, int); + td->td_ycbcrsubsampling[1] = (uint16) va_arg(ap, int); + break; +#endif +#ifdef COLORIMETRY_SUPPORT + case TIFFTAG_WHITEPOINT: + _TIFFsetFloatArray(&td->td_whitepoint, va_arg(ap, float*), 2); + break; + case TIFFTAG_PRIMARYCHROMATICITIES: + _TIFFsetFloatArray(&td->td_primarychromas, va_arg(ap, float*), 6); + break; + case TIFFTAG_TRANSFERFUNCTION: + v = (td->td_samplesperpixel - td->td_extrasamples) > 1 ? 3 : 1; + for (i = 0; i < v; i++) + _TIFFsetShortArray(&td->td_transferfunction[i], + va_arg(ap, uint16*), 1L<td_bitspersample); + break; + case TIFFTAG_REFERENCEBLACKWHITE: + /* XXX should check for null range */ + _TIFFsetFloatArray(&td->td_refblackwhite, va_arg(ap, float*), 6); + break; +#endif +#ifdef CMYK_SUPPORT + case TIFFTAG_INKSET: + td->td_inkset = (uint16) va_arg(ap, int); + break; + case TIFFTAG_DOTRANGE: + /* XXX should check for null range */ + td->td_dotrange[0] = (uint16) va_arg(ap, int); + td->td_dotrange[1] = (uint16) va_arg(ap, int); + break; + case TIFFTAG_INKNAMES: + i = va_arg(ap, int); + s = va_arg(ap, char*); + i = checkInkNamesString(tif, i, s); + status = i > 0; + if( i > 0 ) { + _TIFFsetNString(&td->td_inknames, s, i); + td->td_inknameslen = i; + } + break; + case TIFFTAG_NUMBEROFINKS: + td->td_ninks = (uint16) va_arg(ap, int); + break; + case TIFFTAG_TARGETPRINTER: + _TIFFsetString(&td->td_targetprinter, va_arg(ap, char*)); + break; +#endif +#ifdef ICC_SUPPORT + case TIFFTAG_ICCPROFILE: + td->td_profileLength = (uint32) va_arg(ap, uint32); + _TIFFsetByteArray(&td->td_profileData, va_arg(ap, void*), + td->td_profileLength); + break; +#endif +#ifdef PHOTOSHOP_SUPPORT + case TIFFTAG_PHOTOSHOP: + td->td_photoshopLength = (uint32) va_arg(ap, uint32); + _TIFFsetByteArray (&td->td_photoshopData, va_arg(ap, void*), + td->td_photoshopLength); + break; +#endif +#ifdef IPTC_SUPPORT + case TIFFTAG_RICHTIFFIPTC: + td->td_richtiffiptcLength = (uint32) va_arg(ap, uint32); +#ifdef PHOTOSHOP_SUPPORT + _TIFFsetLongArray ((uint32**)&td->td_richtiffiptcData, va_arg(ap, uint32*), + td->td_richtiffiptcLength); +#else + _TIFFsetByteArray (&td->td_photoshopData, va_arg(ap, void*), + td->td_photoshopLength); +#endif + break; +#endif + default: + /* + * This can happen if multiple images are open with + * different codecs which have private tags. The + * global tag information table may then have tags + * that are valid for one file but not the other. + * If the client tries to set a tag that is not valid + * for the image's codec then we'll arrive here. This + * happens, for example, when tiffcp is used to convert + * between compression schemes and codec-specific tags + * are blindly copied. + */ + TIFFError("TIFFSetField", + "%s: Invalid %stag \"%s\" (not supported by codec)", + tif->tif_name, isPseudoTag(tag) ? "pseduo-" : "", + _TIFFFieldWithTag(tif, tag)->field_name); + status = 0; + break; + } + if (status) { + TIFFSetFieldBit(tif, _TIFFFieldWithTag(tif, tag)->field_bit); + tif->tif_flags |= TIFF_DIRTYDIRECT; + } + va_end(ap); + return (status); +badvalue: + TIFFError(tif->tif_name, "%d: Bad value for \"%s\"", v, + _TIFFFieldWithTag(tif, tag)->field_name); + va_end(ap); + return (0); +badvalue32: + TIFFError(tif->tif_name, "%ld: Bad value for \"%s\"", v32, + _TIFFFieldWithTag(tif, tag)->field_name); + va_end(ap); + return (0); +badvaluedbl: + TIFFError(tif->tif_name, "%f: Bad value for \"%s\"", d, + _TIFFFieldWithTag(tif, tag)->field_name); + va_end(ap); + return (0); +} + +/* + * Return 1/0 according to whether or not + * it is permissible to set the tag's value. + * Note that we allow ImageLength to be changed + * so that we can append and extend to images. + * Any other tag may not be altered once writing + * has commenced, unless its value has no effect + * on the format of the data that is written. + */ +static int +OkToChangeTag(TIFF* tif, ttag_t tag) +{ + const TIFFFieldInfo* fip = _TIFFFindFieldInfo(tif, tag, TIFF_ANY); + if (!fip) { /* unknown tag */ + TIFFError("TIFFSetField", "%s: Unknown %stag %u", + tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "", tag); + return (0); + } + if (tag != TIFFTAG_IMAGELENGTH && (tif->tif_flags & TIFF_BEENWRITING) && + !fip->field_oktochange) { + /* + * Consult info table to see if tag can be changed + * after we've started writing. We only allow changes + * to those tags that don't/shouldn't affect the + * compression and/or format of the data. + */ + TIFFError("TIFFSetField", + "%s: Cannot modify tag \"%s\" while writing", + tif->tif_name, fip->field_name); + return (0); + } + return (1); +} + +/* + * Record the value of a field in the + * internal directory structure. The + * field will be written to the file + * when/if the directory structure is + * updated. + */ +int +TIFFSetField(TIFF* tif, ttag_t tag, ...) +{ + va_list ap; + int status; + + va_start(ap, tag); + status = TIFFVSetField(tif, tag, ap); + va_end(ap); + return (status); +} + +/* + * Like TIFFSetField, but taking a varargs + * parameter list. This routine is useful + * for building higher-level interfaces on + * top of the library. + */ +int +TIFFVSetField(TIFF* tif, ttag_t tag, va_list ap) +{ + return OkToChangeTag(tif, tag) ? + (*tif->tif_vsetfield)(tif, tag, ap) : 0; +} + +static int +_TIFFVGetField(TIFF* tif, ttag_t tag, va_list ap) +{ + TIFFDirectory* td = &tif->tif_dir; + + switch (tag) { + case TIFFTAG_SUBFILETYPE: + *va_arg(ap, uint32*) = td->td_subfiletype; + break; + case TIFFTAG_IMAGEWIDTH: + *va_arg(ap, uint32*) = td->td_imagewidth; + break; + case TIFFTAG_IMAGELENGTH: + *va_arg(ap, uint32*) = td->td_imagelength; + break; + case TIFFTAG_BITSPERSAMPLE: + *va_arg(ap, uint16*) = td->td_bitspersample; + break; + case TIFFTAG_COMPRESSION: + *va_arg(ap, uint16*) = td->td_compression; + break; + case TIFFTAG_PHOTOMETRIC: + *va_arg(ap, uint16*) = td->td_photometric; + break; + case TIFFTAG_THRESHHOLDING: + *va_arg(ap, uint16*) = td->td_threshholding; + break; + case TIFFTAG_FILLORDER: + *va_arg(ap, uint16*) = td->td_fillorder; + break; + case TIFFTAG_DOCUMENTNAME: + *va_arg(ap, char**) = td->td_documentname; + break; + case TIFFTAG_ARTIST: + *va_arg(ap, char**) = td->td_artist; + break; + case TIFFTAG_DATETIME: + *va_arg(ap, char**) = td->td_datetime; + break; + case TIFFTAG_HOSTCOMPUTER: + *va_arg(ap, char**) = td->td_hostcomputer; + break; + case TIFFTAG_IMAGEDESCRIPTION: + *va_arg(ap, char**) = td->td_imagedescription; + break; + case TIFFTAG_MAKE: + *va_arg(ap, char**) = td->td_make; + break; + case TIFFTAG_MODEL: + *va_arg(ap, char**) = td->td_model; + break; + case TIFFTAG_SOFTWARE: + *va_arg(ap, char**) = td->td_software; + break; + case TIFFTAG_COPYRIGHT: + *va_arg(ap, char**) = td->td_copyright; + break; + case TIFFTAG_ORIENTATION: + *va_arg(ap, uint16*) = td->td_orientation; + break; + case TIFFTAG_SAMPLESPERPIXEL: + *va_arg(ap, uint16*) = td->td_samplesperpixel; + break; + case TIFFTAG_ROWSPERSTRIP: + *va_arg(ap, uint32*) = td->td_rowsperstrip; + break; + case TIFFTAG_MINSAMPLEVALUE: + *va_arg(ap, uint16*) = td->td_minsamplevalue; + break; + case TIFFTAG_MAXSAMPLEVALUE: + *va_arg(ap, uint16*) = td->td_maxsamplevalue; + break; + case TIFFTAG_SMINSAMPLEVALUE: + *va_arg(ap, double*) = td->td_sminsamplevalue; + break; + case TIFFTAG_SMAXSAMPLEVALUE: + *va_arg(ap, double*) = td->td_smaxsamplevalue; + break; + case TIFFTAG_XRESOLUTION: + *va_arg(ap, float*) = td->td_xresolution; + break; + case TIFFTAG_YRESOLUTION: + *va_arg(ap, float*) = td->td_yresolution; + break; + case TIFFTAG_PLANARCONFIG: + *va_arg(ap, uint16*) = td->td_planarconfig; + break; + case TIFFTAG_XPOSITION: + *va_arg(ap, float*) = td->td_xposition; + break; + case TIFFTAG_YPOSITION: + *va_arg(ap, float*) = td->td_yposition; + break; + case TIFFTAG_PAGENAME: + *va_arg(ap, char**) = td->td_pagename; + break; + case TIFFTAG_RESOLUTIONUNIT: + *va_arg(ap, uint16*) = td->td_resolutionunit; + break; + case TIFFTAG_PAGENUMBER: + *va_arg(ap, uint16*) = td->td_pagenumber[0]; + *va_arg(ap, uint16*) = td->td_pagenumber[1]; + break; + case TIFFTAG_HALFTONEHINTS: + *va_arg(ap, uint16*) = td->td_halftonehints[0]; + *va_arg(ap, uint16*) = td->td_halftonehints[1]; + break; + case TIFFTAG_COLORMAP: + *va_arg(ap, uint16**) = td->td_colormap[0]; + *va_arg(ap, uint16**) = td->td_colormap[1]; + *va_arg(ap, uint16**) = td->td_colormap[2]; + break; + case TIFFTAG_STRIPOFFSETS: + case TIFFTAG_TILEOFFSETS: + *va_arg(ap, uint32**) = td->td_stripoffset; + break; + case TIFFTAG_STRIPBYTECOUNTS: + case TIFFTAG_TILEBYTECOUNTS: + *va_arg(ap, uint32**) = td->td_stripbytecount; + break; + case TIFFTAG_MATTEING: + *va_arg(ap, uint16*) = + (td->td_extrasamples == 1 && + td->td_sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA); + break; + case TIFFTAG_EXTRASAMPLES: + *va_arg(ap, uint16*) = td->td_extrasamples; + *va_arg(ap, uint16**) = td->td_sampleinfo; + break; + case TIFFTAG_TILEWIDTH: + *va_arg(ap, uint32*) = td->td_tilewidth; + break; + case TIFFTAG_TILELENGTH: + *va_arg(ap, uint32*) = td->td_tilelength; + break; + case TIFFTAG_TILEDEPTH: + *va_arg(ap, uint32*) = td->td_tiledepth; + break; + case TIFFTAG_DATATYPE: + switch (td->td_sampleformat) { + case SAMPLEFORMAT_UINT: + *va_arg(ap, uint16*) = DATATYPE_UINT; + break; + case SAMPLEFORMAT_INT: + *va_arg(ap, uint16*) = DATATYPE_INT; + break; + case SAMPLEFORMAT_IEEEFP: + *va_arg(ap, uint16*) = DATATYPE_IEEEFP; + break; + case SAMPLEFORMAT_VOID: + *va_arg(ap, uint16*) = DATATYPE_VOID; + break; + } + break; + case TIFFTAG_SAMPLEFORMAT: + *va_arg(ap, uint16*) = td->td_sampleformat; + break; + case TIFFTAG_IMAGEDEPTH: + *va_arg(ap, uint32*) = td->td_imagedepth; + break; + case TIFFTAG_STONITS: + *va_arg(ap, double*) = td->td_stonits; + break; +#if SUBIFD_SUPPORT + case TIFFTAG_SUBIFD: + *va_arg(ap, uint16*) = td->td_nsubifd; + *va_arg(ap, uint32**) = td->td_subifd; + break; +#endif +#ifdef YCBCR_SUPPORT + case TIFFTAG_YCBCRCOEFFICIENTS: + *va_arg(ap, float**) = td->td_ycbcrcoeffs; + break; + case TIFFTAG_YCBCRPOSITIONING: + *va_arg(ap, uint16*) = td->td_ycbcrpositioning; + break; + case TIFFTAG_YCBCRSUBSAMPLING: + *va_arg(ap, uint16*) = td->td_ycbcrsubsampling[0]; + *va_arg(ap, uint16*) = td->td_ycbcrsubsampling[1]; + break; +#endif +#ifdef COLORIMETRY_SUPPORT + case TIFFTAG_WHITEPOINT: + *va_arg(ap, float**) = td->td_whitepoint; + break; + case TIFFTAG_PRIMARYCHROMATICITIES: + *va_arg(ap, float**) = td->td_primarychromas; + break; + case TIFFTAG_TRANSFERFUNCTION: + *va_arg(ap, uint16**) = td->td_transferfunction[0]; + if (td->td_samplesperpixel - td->td_extrasamples > 1) { + *va_arg(ap, uint16**) = td->td_transferfunction[1]; + *va_arg(ap, uint16**) = td->td_transferfunction[2]; + } + break; + case TIFFTAG_REFERENCEBLACKWHITE: + *va_arg(ap, float**) = td->td_refblackwhite; + break; +#endif +#ifdef CMYK_SUPPORT + case TIFFTAG_INKSET: + *va_arg(ap, uint16*) = td->td_inkset; + break; + case TIFFTAG_DOTRANGE: + *va_arg(ap, uint16*) = td->td_dotrange[0]; + *va_arg(ap, uint16*) = td->td_dotrange[1]; + break; + case TIFFTAG_INKNAMES: + *va_arg(ap, char**) = td->td_inknames; + break; + case TIFFTAG_NUMBEROFINKS: + *va_arg(ap, uint16*) = td->td_ninks; + break; + case TIFFTAG_TARGETPRINTER: + *va_arg(ap, char**) = td->td_targetprinter; + break; +#endif +#ifdef ICC_SUPPORT + case TIFFTAG_ICCPROFILE: + *va_arg(ap, uint32*) = td->td_profileLength; + *va_arg(ap, void**) = td->td_profileData; + break; +#endif +#ifdef PHOTOSHOP_SUPPORT + case TIFFTAG_PHOTOSHOP: + *va_arg(ap, uint32*) = td->td_photoshopLength; + *va_arg(ap, void**) = td->td_photoshopData; + break; +#endif +#ifdef IPTC_SUPPORT + case TIFFTAG_RICHTIFFIPTC: + *va_arg(ap, uint32*) = td->td_richtiffiptcLength; + *va_arg(ap, void**) = td->td_richtiffiptcData; + break; +#endif + /* Begin Pixar Tags */ + case TIFFTAG_PIXAR_IMAGEFULLWIDTH: + *va_arg(ap, uint32*) = td->td_imagefullwidth; + break; + case TIFFTAG_PIXAR_IMAGEFULLLENGTH: + *va_arg(ap, uint32*) = td->td_imagefulllength; + break; + case TIFFTAG_PIXAR_TEXTUREFORMAT: + *va_arg(ap, char**) = td->td_textureformat; + break; + case TIFFTAG_PIXAR_WRAPMODES: + *va_arg(ap, char**) = td->td_wrapmodes; + break; + case TIFFTAG_PIXAR_FOVCOT: + *va_arg(ap, float*) = td->td_fovcot; + break; + case TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN: + *va_arg(ap, float**) = td->td_matrixWorldToScreen; + break; + case TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA: + *va_arg(ap, float**) = td->td_matrixWorldToCamera; + break; + /* End Pixar Tags */ + + default: + /* + * This can happen if multiple images are open with + * different codecs which have private tags. The + * global tag information table may then have tags + * that are valid for one file but not the other. + * If the client tries to get a tag that is not valid + * for the image's codec then we'll arrive here. + */ + TIFFError("TIFFGetField", + "%s: Invalid %stag \"%s\" (not supported by codec)", + tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "", + _TIFFFieldWithTag(tif, tag)->field_name); + break; + } + return (1); +} + +/* + * Return the value of a field in the + * internal directory structure. + */ +int +TIFFGetField(TIFF* tif, ttag_t tag, ...) +{ + int status; + va_list ap; + + va_start(ap, tag); + status = TIFFVGetField(tif, tag, ap); + va_end(ap); + return (status); +} + +/* + * Like TIFFGetField, but taking a varargs + * parameter list. This routine is useful + * for building higher-level interfaces on + * top of the library. + */ +int +TIFFVGetField(TIFF* tif, ttag_t tag, va_list ap) +{ + const TIFFFieldInfo* fip = _TIFFFindFieldInfo(tif, tag, TIFF_ANY); + return (fip && (isPseudoTag(tag) || TIFFFieldSet(tif, fip->field_bit)) ? + (*tif->tif_vgetfield)(tif, tag, ap) : 0); +} + +#define CleanupField(member) { \ + if (td->member) { \ + _TIFFfree(td->member); \ + td->member = 0; \ + } \ +} + +/* + * Release storage associated with a directory. + */ +void +TIFFFreeDirectory(TIFF* tif) +{ + register TIFFDirectory *td = &tif->tif_dir; + + CleanupField(td_colormap[0]); + CleanupField(td_colormap[1]); + CleanupField(td_colormap[2]); + CleanupField(td_documentname); + CleanupField(td_artist); + CleanupField(td_datetime); + CleanupField(td_hostcomputer); + CleanupField(td_imagedescription); + CleanupField(td_make); + CleanupField(td_model); + CleanupField(td_software); + CleanupField(td_copyright); + CleanupField(td_pagename); + CleanupField(td_sampleinfo); +#if SUBIFD_SUPPORT + CleanupField(td_subifd); +#endif +#ifdef YCBCR_SUPPORT + CleanupField(td_ycbcrcoeffs); +#endif +#ifdef CMYK_SUPPORT + CleanupField(td_inknames); + CleanupField(td_targetprinter); +#endif +#ifdef COLORIMETRY_SUPPORT + CleanupField(td_whitepoint); + CleanupField(td_primarychromas); + CleanupField(td_refblackwhite); + CleanupField(td_transferfunction[0]); + CleanupField(td_transferfunction[1]); + CleanupField(td_transferfunction[2]); +#endif +#ifdef ICC_SUPPORT + CleanupField(td_profileData); +#endif +#ifdef PHOTOSHOP_SUPPORT + CleanupField(td_photoshopData); +#endif +#ifdef IPTC_SUPPORT + CleanupField(td_richtiffiptcData); +#endif + CleanupField(td_stripoffset); + CleanupField(td_stripbytecount); + /* Begin Pixar Tags */ + CleanupField(td_textureformat); + CleanupField(td_wrapmodes); + CleanupField(td_matrixWorldToScreen); + CleanupField(td_matrixWorldToCamera); + /* End Pixar Tags */ +} +#undef CleanupField + +/* + * Client Tag extension support (from Niles Ritter). + */ +static TIFFExtendProc _TIFFextender = (TIFFExtendProc) NULL; + +TIFFExtendProc +TIFFSetTagExtender(TIFFExtendProc extender) +{ + TIFFExtendProc prev = _TIFFextender; + _TIFFextender = extender; + return (prev); +} + +/* + * Setup for a new directory. Should we automatically call + * TIFFWriteDirectory() if the current one is dirty? + * + * The newly created directory will not exist on the file till + * TIFFWriteDirectory(), TIFFFlush() or TIFFClose() is called. + */ +int +TIFFCreateDirectory(TIFF* tif) +{ + TIFFDefaultDirectory(tif); + tif->tif_diroff = 0; + tif->tif_nextdiroff = 0; + tif->tif_curoff = 0; + tif->tif_row = (uint32) -1; + tif->tif_curstrip = (tstrip_t) -1; + + return 0; +} + +/* + * Setup a default directory structure. + */ +int +TIFFDefaultDirectory(TIFF* tif) +{ + register TIFFDirectory* td = &tif->tif_dir; + + _TIFFSetupFieldInfo(tif); + _TIFFmemset(td, 0, sizeof (*td)); + td->td_fillorder = FILLORDER_MSB2LSB; + td->td_bitspersample = 1; + td->td_threshholding = THRESHHOLD_BILEVEL; + td->td_orientation = ORIENTATION_TOPLEFT; + td->td_samplesperpixel = 1; + td->td_rowsperstrip = (uint32) -1; + td->td_tilewidth = (uint32) -1; + td->td_tilelength = (uint32) -1; + td->td_tiledepth = 1; + td->td_resolutionunit = RESUNIT_INCH; + td->td_sampleformat = SAMPLEFORMAT_UINT; + td->td_imagedepth = 1; +#ifdef YCBCR_SUPPORT + td->td_ycbcrsubsampling[0] = 2; + td->td_ycbcrsubsampling[1] = 2; + td->td_ycbcrpositioning = YCBCRPOSITION_CENTERED; +#endif +#ifdef CMYK_SUPPORT + td->td_inkset = INKSET_CMYK; + td->td_ninks = 4; +#endif + tif->tif_postdecode = _TIFFNoPostDecode; + tif->tif_vsetfield = _TIFFVSetField; + tif->tif_vgetfield = _TIFFVGetField; + tif->tif_printdir = NULL; + /* + * Give client code a chance to install their own + * tag extensions & methods, prior to compression overloads. + */ + if (_TIFFextender) + (*_TIFFextender)(tif); + (void) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE); + /* + * NB: The directory is marked dirty as a result of setting + * up the default compression scheme. However, this really + * isn't correct -- we want TIFF_DIRTYDIRECT to be set only + * if the user does something. We could just do the setup + * by hand, but it seems better to use the normal mechanism + * (i.e. TIFFSetField). + */ + tif->tif_flags &= ~TIFF_DIRTYDIRECT; + + /* + * As per http://bugzilla.remotesensing.org/show_bug.cgi?id=19 + * we clear the ISTILED flag when setting up a new directory. + * Should we also be clearing stuff like INSUBIFD? + */ + tif->tif_flags &= ~TIFF_ISTILED; + + return (1); +} + +static int +TIFFAdvanceDirectory(TIFF* tif, uint32* nextdir, toff_t* off) +{ + static const char module[] = "TIFFAdvanceDirectory"; + uint16 dircount; + if (isMapped(tif)) + { + toff_t poff=*nextdir; + if (poff+sizeof(uint16) > tif->tif_size) + { + TIFFError(module, "%s: Error fetching directory count", + tif->tif_name); + return (0); + } + _TIFFmemcpy(&dircount, tif->tif_base+poff, sizeof (uint16)); + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabShort(&dircount); + poff+=sizeof (uint16)+dircount*sizeof (TIFFDirEntry); + if (off != NULL) + *off = poff; + if (((toff_t) (poff+sizeof (uint32))) > tif->tif_size) + { + TIFFError(module, "%s: Error fetching directory link", + tif->tif_name); + return (0); + } + _TIFFmemcpy(nextdir, tif->tif_base+poff, sizeof (uint32)); + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabLong(nextdir); + return (1); + } + else + { + if (!SeekOK(tif, *nextdir) || + !ReadOK(tif, &dircount, sizeof (uint16))) { + TIFFError(module, "%s: Error fetching directory count", + tif->tif_name); + return (0); + } + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabShort(&dircount); + if (off != NULL) + *off = TIFFSeekFile(tif, + dircount*sizeof (TIFFDirEntry), SEEK_CUR); + else + (void) TIFFSeekFile(tif, + dircount*sizeof (TIFFDirEntry), SEEK_CUR); + if (!ReadOK(tif, nextdir, sizeof (uint32))) { + TIFFError(module, "%s: Error fetching directory link", + tif->tif_name); + return (0); + } + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabLong(nextdir); + return (1); + } +} + +/* + * Count the number of directories in a file. + */ +tdir_t +TIFFNumberOfDirectories(TIFF* tif) +{ + toff_t nextdir = tif->tif_header.tiff_diroff; + tdir_t n = 0; + + while (nextdir != 0 && TIFFAdvanceDirectory(tif, &nextdir, NULL)) + n++; + return (n); +} + +/* + * Set the n-th directory as the current directory. + * NB: Directories are numbered starting at 0. + */ +int +TIFFSetDirectory(TIFF* tif, tdir_t dirn) +{ + toff_t nextdir; + tdir_t n; + + nextdir = tif->tif_header.tiff_diroff; + for (n = dirn; n > 0 && nextdir != 0; n--) + if (!TIFFAdvanceDirectory(tif, &nextdir, NULL)) + return (0); + tif->tif_nextdiroff = nextdir; + /* + * Set curdir to the actual directory index. The + * -1 is because TIFFReadDirectory will increment + * tif_curdir after successfully reading the directory. + */ + tif->tif_curdir = (dirn - n) - 1; + return (TIFFReadDirectory(tif)); +} + +/* + * Set the current directory to be the directory + * located at the specified file offset. This interface + * is used mainly to access directories linked with + * the SubIFD tag (e.g. thumbnail images). + */ +int +TIFFSetSubDirectory(TIFF* tif, uint32 diroff) +{ + tif->tif_nextdiroff = diroff; + return (TIFFReadDirectory(tif)); +} + +/* + * Return file offset of the current directory. + */ +uint32 +TIFFCurrentDirOffset(TIFF* tif) +{ + return (tif->tif_diroff); +} + +/* + * Return an indication of whether or not we are + * at the last directory in the file. + */ +int +TIFFLastDirectory(TIFF* tif) +{ + return (tif->tif_nextdiroff == 0); +} + +/* + * Unlink the specified directory from the directory chain. + */ +int +TIFFUnlinkDirectory(TIFF* tif, tdir_t dirn) +{ + static const char module[] = "TIFFUnlinkDirectory"; + toff_t nextdir; + toff_t off; + tdir_t n; + + if (tif->tif_mode == O_RDONLY) { + TIFFError(module, "Can not unlink directory in read-only file"); + return (0); + } + /* + * Go to the directory before the one we want + * to unlink and nab the offset of the link + * field we'll need to patch. + */ + nextdir = tif->tif_header.tiff_diroff; + off = sizeof (uint16) + sizeof (uint16); + for (n = dirn-1; n > 0; n--) { + if (nextdir == 0) { + TIFFError(module, "Directory %d does not exist", dirn); + return (0); + } + if (!TIFFAdvanceDirectory(tif, &nextdir, &off)) + return (0); + } + /* + * Advance to the directory to be unlinked and fetch + * the offset of the directory that follows. + */ + if (!TIFFAdvanceDirectory(tif, &nextdir, NULL)) + return (0); + /* + * Go back and patch the link field of the preceding + * directory to point to the offset of the directory + * that follows. + */ + (void) TIFFSeekFile(tif, off, SEEK_SET); + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabLong(&nextdir); + if (!WriteOK(tif, &nextdir, sizeof (uint32))) { + TIFFError(module, "Error writing directory link"); + return (0); + } + /* + * Leave directory state setup safely. We don't have + * facilities for doing inserting and removing directories, + * so it's safest to just invalidate everything. This + * means that the caller can only append to the directory + * chain. + */ + (*tif->tif_cleanup)(tif); + if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { + _TIFFfree(tif->tif_rawdata); + tif->tif_rawdata = NULL; + tif->tif_rawcc = 0; + } + tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP|TIFF_POSTENCODE); + TIFFFreeDirectory(tif); + TIFFDefaultDirectory(tif); + tif->tif_diroff = 0; /* force link on next write */ + tif->tif_nextdiroff = 0; /* next write must be at end */ + tif->tif_curoff = 0; + tif->tif_row = (uint32) -1; + tif->tif_curstrip = (tstrip_t) -1; + return (1); +} + +/* [BFC] + * + * Author: Bruce Cameron + * + * Set a table of tags that are to be replaced during directory process by the + * 'IGNORE' state - or return TRUE/FALSE for the requested tag such that + * 'ReadDirectory' can use the stored information. + */ +int +TIFFReassignTagToIgnore (enum TIFFIgnoreSense task, int TIFFtagID) +{ + static int TIFFignoretags [FIELD_LAST]; + static int tagcount = 0 ; + int i; /* Loop index */ + int j; /* Loop index */ + + switch (task) + { + case TIS_STORE: + if ( tagcount < (FIELD_LAST - 1) ) + { + for ( j = 0 ; j < tagcount ; ++j ) + { /* Do not add duplicate tag */ + if ( TIFFignoretags [j] == TIFFtagID ) + return (TRUE) ; + } + TIFFignoretags [tagcount++] = TIFFtagID ; + return (TRUE) ; + } + break ; + + case TIS_EXTRACT: + for ( i = 0 ; i < tagcount ; ++i ) + { + if ( TIFFignoretags [i] == TIFFtagID ) + return (TRUE) ; + } + break; + + case TIS_EMPTY: + tagcount = 0 ; /* Clear the list */ + return (TRUE) ; + + default: + break; + } + + return (FALSE); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_dir.h b/SlnkDWFImpl/CxImage/tiff/tif_dir.h new file mode 100644 index 0000000..8a0d3b9 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_dir.h @@ -0,0 +1,270 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_dir.h,v 1.3 2001/03/02 04:59:52 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _TIFFDIR_ +#define _TIFFDIR_ +/* + * ``Library-private'' Directory-related Definitions. + */ + +/* + * Internal format of a TIFF directory entry. + */ +typedef struct { +#define FIELD_SETLONGS 3 + /* bit vector of fields that are set */ + u_long td_fieldsset[FIELD_SETLONGS]; + + uint32 td_imagewidth, td_imagelength, td_imagedepth; + uint32 td_tilewidth, td_tilelength, td_tiledepth; + uint32 td_subfiletype; + uint16 td_bitspersample; + uint16 td_sampleformat; + uint16 td_compression; + uint16 td_photometric; + uint16 td_threshholding; + uint16 td_fillorder; + uint16 td_orientation; + uint16 td_samplesperpixel; + uint32 td_rowsperstrip; + uint16 td_minsamplevalue, td_maxsamplevalue; + double td_sminsamplevalue, td_smaxsamplevalue; + float td_xresolution, td_yresolution; + uint16 td_resolutionunit; + uint16 td_planarconfig; + float td_xposition, td_yposition; + uint16 td_pagenumber[2]; + uint16* td_colormap[3]; + uint16 td_halftonehints[2]; + uint16 td_extrasamples; + uint16* td_sampleinfo; + double td_stonits; + char* td_documentname; + char* td_artist; + char* td_datetime; + char* td_hostcomputer; + char* td_imagedescription; + char* td_make; + char* td_model; + char* td_software; + char* td_copyright; + char* td_pagename; + tstrip_t td_stripsperimage; + tstrip_t td_nstrips; /* size of offset & bytecount arrays */ + uint32* td_stripoffset; + uint32* td_stripbytecount; +#if SUBIFD_SUPPORT + uint16 td_nsubifd; + uint32* td_subifd; +#endif +#ifdef YCBCR_SUPPORT + float* td_ycbcrcoeffs; + uint16 td_ycbcrsubsampling[2]; + uint16 td_ycbcrpositioning; +#endif +#ifdef COLORIMETRY_SUPPORT + float* td_whitepoint; + float* td_primarychromas; + float* td_refblackwhite; + uint16* td_transferfunction[3]; +#endif +#ifdef CMYK_SUPPORT + uint16 td_inkset; + uint16 td_ninks; + uint16 td_dotrange[2]; + int td_inknameslen; + char* td_inknames; + char* td_targetprinter; +#endif +#ifdef ICC_SUPPORT + uint32 td_profileLength; + void *td_profileData; +#endif +#ifdef PHOTOSHOP_SUPPORT + uint32 td_photoshopLength; + void *td_photoshopData; +#endif +#ifdef IPTC_SUPPORT + uint32 td_richtiffiptcLength; + void *td_richtiffiptcData; +#endif + /* Begin Pixar Tag values. */ + uint32 td_imagefullwidth, td_imagefulllength; + char* td_textureformat; + char* td_wrapmodes; + float td_fovcot; + float* td_matrixWorldToScreen; + float* td_matrixWorldToCamera; + /* End Pixar Tag Values. */ +} TIFFDirectory; + +/* + * Field flags used to indicate fields that have + * been set in a directory, and to reference fields + * when manipulating a directory. + */ + +/* + * FIELD_IGNORE is used to signify tags that are to + * be processed but otherwise ignored. This permits + * antiquated tags to be quietly read and discarded. + * Note that a bit *is* allocated for ignored tags; + * this is understood by the directory reading logic + * which uses this fact to avoid special-case handling + */ +#define FIELD_IGNORE 0 + +/* multi-item fields */ +#define FIELD_IMAGEDIMENSIONS 1 +#define FIELD_TILEDIMENSIONS 2 +#define FIELD_RESOLUTION 3 +#define FIELD_POSITION 4 + +/* single-item fields */ +#define FIELD_SUBFILETYPE 5 +#define FIELD_BITSPERSAMPLE 6 +#define FIELD_COMPRESSION 7 +#define FIELD_PHOTOMETRIC 8 +#define FIELD_THRESHHOLDING 9 +#define FIELD_FILLORDER 10 +#define FIELD_DOCUMENTNAME 11 +#define FIELD_IMAGEDESCRIPTION 12 +#define FIELD_MAKE 13 +#define FIELD_MODEL 14 +#define FIELD_ORIENTATION 15 +#define FIELD_SAMPLESPERPIXEL 16 +#define FIELD_ROWSPERSTRIP 17 +#define FIELD_MINSAMPLEVALUE 18 +#define FIELD_MAXSAMPLEVALUE 19 +#define FIELD_PLANARCONFIG 20 +#define FIELD_PAGENAME 21 +#define FIELD_RESOLUTIONUNIT 22 +#define FIELD_PAGENUMBER 23 +#define FIELD_STRIPBYTECOUNTS 24 +#define FIELD_STRIPOFFSETS 25 +#define FIELD_COLORMAP 26 +#define FIELD_ARTIST 27 +#define FIELD_DATETIME 28 +#define FIELD_HOSTCOMPUTER 29 +#define FIELD_SOFTWARE 30 +#define FIELD_EXTRASAMPLES 31 +#define FIELD_SAMPLEFORMAT 32 +#define FIELD_SMINSAMPLEVALUE 33 +#define FIELD_SMAXSAMPLEVALUE 34 +#define FIELD_IMAGEDEPTH 35 +#define FIELD_TILEDEPTH 36 +#define FIELD_HALFTONEHINTS 37 +#define FIELD_YCBCRCOEFFICIENTS 38 +#define FIELD_YCBCRSUBSAMPLING 39 +#define FIELD_YCBCRPOSITIONING 40 +#define FIELD_REFBLACKWHITE 41 +#define FIELD_WHITEPOINT 42 +#define FIELD_PRIMARYCHROMAS 43 +#define FIELD_TRANSFERFUNCTION 44 +#define FIELD_INKSET 45 +#define FIELD_INKNAMES 46 +#define FIELD_DOTRANGE 47 +#define FIELD_TARGETPRINTER 48 +#define FIELD_SUBIFD 49 +#define FIELD_NUMBEROFINKS 50 +#define FIELD_ICCPROFILE 51 +#define FIELD_PHOTOSHOP 52 +#define FIELD_RICHTIFFIPTC 53 +#define FIELD_STONITS 54 +/* Begin PIXAR */ +#define FIELD_IMAGEFULLWIDTH 55 +#define FIELD_IMAGEFULLLENGTH 56 +#define FIELD_TEXTUREFORMAT 57 +#define FIELD_WRAPMODES 58 +#define FIELD_FOVCOT 59 +#define FIELD_MATRIX_WORLDTOSCREEN 60 +#define FIELD_MATRIX_WORLDTOCAMERA 61 +#define FIELD_COPYRIGHT 62 +/* end of support for well-known tags; codec-private tags follow */ +#define FIELD_CODEC 63 /* base of codec-private tags */ +/* + * Pseudo-tags don't normally need field bits since they + * are not written to an output file (by definition). + * The library also has express logic to always query a + * codec for a pseudo-tag so allocating a field bit for + * one is a waste. If codec wants to promote the notion + * of a pseudo-tag being ``set'' or ``unset'' then it can + * do using internal state flags without polluting the + * field bit space defined for real tags. + */ +#define FIELD_PSEUDO 0 + +#define FIELD_LAST (32*FIELD_SETLONGS-1) + +#define TIFFExtractData(tif, type, v) \ + ((uint32) ((tif)->tif_header.tiff_magic == TIFF_BIGENDIAN ? \ + ((v) >> (tif)->tif_typeshift[type]) & (tif)->tif_typemask[type] : \ + (v) & (tif)->tif_typemask[type])) +#define TIFFInsertData(tif, type, v) \ + ((uint32) ((tif)->tif_header.tiff_magic == TIFF_BIGENDIAN ? \ + ((v) & (tif)->tif_typemask[type]) << (tif)->tif_typeshift[type] : \ + (v) & (tif)->tif_typemask[type])) + +typedef struct { + ttag_t field_tag; /* field's tag */ + short field_readcount; /* read count/TIFF_VARIABLE/TIFF_SPP */ + short field_writecount; /* write count/TIFF_VARIABLE */ + TIFFDataType field_type; /* type of associated data */ + u_short field_bit; /* bit in fieldsset bit vector */ + u_char field_oktochange; /* if true, can change while writing */ + u_char field_passcount; /* if true, pass dir count on set */ + char *field_name; /* ASCII name */ +} TIFFFieldInfo; + +#define TIFF_ANY TIFF_NOTYPE /* for field descriptor searching */ +#define TIFF_VARIABLE -1 /* marker for variable length tags */ +#define TIFF_SPP -2 /* marker for SamplesPerPixel tags */ +#define TIFF_VARIABLE2 -3 /* marker for uint32 var-length tags */ + +extern const int tiffDataWidth[]; /* table of tag datatype widths */ + +#define BITn(n) (((u_long)1L)<<((n)&0x1f)) +#define BITFIELDn(tif, n) ((tif)->tif_dir.td_fieldsset[(n)/32]) +#define TIFFFieldSet(tif, field) (BITFIELDn(tif, field) & BITn(field)) +#define TIFFSetFieldBit(tif, field) (BITFIELDn(tif, field) |= BITn(field)) +#define TIFFClrFieldBit(tif, field) (BITFIELDn(tif, field) &= ~BITn(field)) + +#define FieldSet(fields, f) (fields[(f)/32] & BITn(f)) +#define ResetFieldBit(fields, f) (fields[(f)/32] &= ~BITn(f)) + +#if defined(__cplusplus) +extern "C" { +#endif +extern void _TIFFSetupFieldInfo(TIFF*); +extern void _TIFFMergeFieldInfo(TIFF*, const TIFFFieldInfo[], int); +extern void _TIFFPrintFieldInfo(TIFF*, FILE*); +extern const TIFFFieldInfo* _TIFFFindFieldInfo(TIFF*, ttag_t, TIFFDataType); +extern const TIFFFieldInfo* _TIFFFieldWithTag(TIFF*, ttag_t); +extern TIFFDataType _TIFFSampleToTagType(TIFF*); +#if defined(__cplusplus) +} +#endif +#endif /* _TIFFDIR_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_dirinfo.c b/SlnkDWFImpl/CxImage/tiff/tif_dirinfo.c new file mode 100644 index 0000000..641580e --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_dirinfo.c @@ -0,0 +1,411 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_dirinfo.c,v 1.8 2001/05/09 01:33:16 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Core Directory Tag Support. + */ +#include "tiffiop.h" +#include + +/* + * NB: NB: THIS ARRAY IS ASSUMED TO BE SORTED BY TAG. + * If a tag can have both LONG and SHORT types + * then the LONG must be placed before the SHORT for + * writing to work properly. + * + * NOTE: The second field (field_readcount) and third field (field_writecount) + * sometimes use the values TIFF_VARIABLE (-1), TIFF_VARIABLE2 (-3) + * and TIFFTAG_SPP (-2). The macros should be used but would throw off + * the formatting of the code, so please interprete the -1, -2 and -3 + * values accordingly. + */ +#ifndef VMS +static +#endif +const TIFFFieldInfo tiffFieldInfo[] = { + { TIFFTAG_SUBFILETYPE, 1, 1, TIFF_LONG, FIELD_SUBFILETYPE, + TRUE, FALSE, "SubfileType" }, +/* XXX SHORT for compatibility w/ old versions of the library */ + { TIFFTAG_SUBFILETYPE, 1, 1, TIFF_SHORT, FIELD_SUBFILETYPE, + TRUE, FALSE, "SubfileType" }, + { TIFFTAG_OSUBFILETYPE, 1, 1, TIFF_SHORT, FIELD_SUBFILETYPE, + TRUE, FALSE, "OldSubfileType" }, + { TIFFTAG_IMAGEWIDTH, 1, 1, TIFF_LONG, FIELD_IMAGEDIMENSIONS, + FALSE, FALSE, "ImageWidth" }, + { TIFFTAG_IMAGEWIDTH, 1, 1, TIFF_SHORT, FIELD_IMAGEDIMENSIONS, + FALSE, FALSE, "ImageWidth" }, + { TIFFTAG_IMAGELENGTH, 1, 1, TIFF_LONG, FIELD_IMAGEDIMENSIONS, + TRUE, FALSE, "ImageLength" }, + { TIFFTAG_IMAGELENGTH, 1, 1, TIFF_SHORT, FIELD_IMAGEDIMENSIONS, + TRUE, FALSE, "ImageLength" }, + { TIFFTAG_BITSPERSAMPLE, -1,-1, TIFF_SHORT, FIELD_BITSPERSAMPLE, + FALSE, FALSE, "BitsPerSample" }, + { TIFFTAG_COMPRESSION, -1, 1, TIFF_SHORT, FIELD_COMPRESSION, + FALSE, FALSE, "Compression" }, + { TIFFTAG_PHOTOMETRIC, 1, 1, TIFF_SHORT, FIELD_PHOTOMETRIC, + FALSE, FALSE, "PhotometricInterpretation" }, + { TIFFTAG_THRESHHOLDING, 1, 1, TIFF_SHORT, FIELD_THRESHHOLDING, + TRUE, FALSE, "Threshholding" }, + { TIFFTAG_CELLWIDTH, 1, 1, TIFF_SHORT, FIELD_IGNORE, + TRUE, FALSE, "CellWidth" }, + { TIFFTAG_CELLLENGTH, 1, 1, TIFF_SHORT, FIELD_IGNORE, + TRUE, FALSE, "CellLength" }, + { TIFFTAG_FILLORDER, 1, 1, TIFF_SHORT, FIELD_FILLORDER, + FALSE, FALSE, "FillOrder" }, + { TIFFTAG_DOCUMENTNAME, -1,-1, TIFF_ASCII, FIELD_DOCUMENTNAME, + TRUE, FALSE, "DocumentName" }, + { TIFFTAG_IMAGEDESCRIPTION, -1,-1, TIFF_ASCII, FIELD_IMAGEDESCRIPTION, + TRUE, FALSE, "ImageDescription" }, + { TIFFTAG_MAKE, -1,-1, TIFF_ASCII, FIELD_MAKE, + TRUE, FALSE, "Make" }, + { TIFFTAG_MODEL, -1,-1, TIFF_ASCII, FIELD_MODEL, + TRUE, FALSE, "Model" }, + { TIFFTAG_STRIPOFFSETS, -1,-1, TIFF_LONG, FIELD_STRIPOFFSETS, + FALSE, FALSE, "StripOffsets" }, + { TIFFTAG_STRIPOFFSETS, -1,-1, TIFF_SHORT, FIELD_STRIPOFFSETS, + FALSE, FALSE, "StripOffsets" }, + { TIFFTAG_ORIENTATION, 1, 1, TIFF_SHORT, FIELD_ORIENTATION, + FALSE, FALSE, "Orientation" }, + { TIFFTAG_SAMPLESPERPIXEL, 1, 1, TIFF_SHORT, FIELD_SAMPLESPERPIXEL, + FALSE, FALSE, "SamplesPerPixel" }, + { TIFFTAG_ROWSPERSTRIP, 1, 1, TIFF_LONG, FIELD_ROWSPERSTRIP, + FALSE, FALSE, "RowsPerStrip" }, + { TIFFTAG_ROWSPERSTRIP, 1, 1, TIFF_SHORT, FIELD_ROWSPERSTRIP, + FALSE, FALSE, "RowsPerStrip" }, + { TIFFTAG_STRIPBYTECOUNTS, -1,-1, TIFF_LONG, FIELD_STRIPBYTECOUNTS, + FALSE, FALSE, "StripByteCounts" }, + { TIFFTAG_STRIPBYTECOUNTS, -1,-1, TIFF_SHORT, FIELD_STRIPBYTECOUNTS, + FALSE, FALSE, "StripByteCounts" }, + { TIFFTAG_MINSAMPLEVALUE, -2,-1, TIFF_SHORT, FIELD_MINSAMPLEVALUE, + TRUE, FALSE, "MinSampleValue" }, + { TIFFTAG_MAXSAMPLEVALUE, -2,-1, TIFF_SHORT, FIELD_MAXSAMPLEVALUE, + TRUE, FALSE, "MaxSampleValue" }, + { TIFFTAG_XRESOLUTION, 1, 1, TIFF_RATIONAL, FIELD_RESOLUTION, + FALSE, FALSE, "XResolution" }, + { TIFFTAG_YRESOLUTION, 1, 1, TIFF_RATIONAL, FIELD_RESOLUTION, + FALSE, FALSE, "YResolution" }, + { TIFFTAG_PLANARCONFIG, 1, 1, TIFF_SHORT, FIELD_PLANARCONFIG, + FALSE, FALSE, "PlanarConfiguration" }, + { TIFFTAG_PAGENAME, -1,-1, TIFF_ASCII, FIELD_PAGENAME, + TRUE, FALSE, "PageName" }, + { TIFFTAG_XPOSITION, 1, 1, TIFF_RATIONAL, FIELD_POSITION, + TRUE, FALSE, "XPosition" }, + { TIFFTAG_YPOSITION, 1, 1, TIFF_RATIONAL, FIELD_POSITION, + TRUE, FALSE, "YPosition" }, + { TIFFTAG_FREEOFFSETS, -1,-1, TIFF_LONG, FIELD_IGNORE, + FALSE, FALSE, "FreeOffsets" }, + { TIFFTAG_FREEBYTECOUNTS, -1,-1, TIFF_LONG, FIELD_IGNORE, + FALSE, FALSE, "FreeByteCounts" }, + { TIFFTAG_GRAYRESPONSEUNIT, 1, 1, TIFF_SHORT, FIELD_IGNORE, + TRUE, FALSE, "GrayResponseUnit" }, + { TIFFTAG_GRAYRESPONSECURVE,-1,-1, TIFF_SHORT, FIELD_IGNORE, + TRUE, FALSE, "GrayResponseCurve" }, + { TIFFTAG_RESOLUTIONUNIT, 1, 1, TIFF_SHORT, FIELD_RESOLUTIONUNIT, + FALSE, FALSE, "ResolutionUnit" }, + { TIFFTAG_PAGENUMBER, 2, 2, TIFF_SHORT, FIELD_PAGENUMBER, + TRUE, FALSE, "PageNumber" }, + { TIFFTAG_COLORRESPONSEUNIT, 1, 1, TIFF_SHORT, FIELD_IGNORE, + TRUE, FALSE, "ColorResponseUnit" }, +#ifdef COLORIMETRY_SUPPORT + { TIFFTAG_TRANSFERFUNCTION, -1,-1, TIFF_SHORT, FIELD_TRANSFERFUNCTION, + TRUE, FALSE, "TransferFunction" }, +#endif + { TIFFTAG_SOFTWARE, -1,-1, TIFF_ASCII, FIELD_SOFTWARE, + TRUE, FALSE, "Software" }, + { TIFFTAG_DATETIME, 20,20, TIFF_ASCII, FIELD_DATETIME, + TRUE, FALSE, "DateTime" }, + { TIFFTAG_ARTIST, -1,-1, TIFF_ASCII, FIELD_ARTIST, + TRUE, FALSE, "Artist" }, + { TIFFTAG_HOSTCOMPUTER, -1,-1, TIFF_ASCII, FIELD_HOSTCOMPUTER, + TRUE, FALSE, "HostComputer" }, +#ifdef COLORIMETRY_SUPPORT + { TIFFTAG_WHITEPOINT, 2, 2, TIFF_RATIONAL,FIELD_WHITEPOINT, + TRUE, FALSE, "WhitePoint" }, + { TIFFTAG_PRIMARYCHROMATICITIES,6,6,TIFF_RATIONAL,FIELD_PRIMARYCHROMAS, + TRUE, FALSE, "PrimaryChromaticities" }, +#endif + { TIFFTAG_COLORMAP, -1,-1, TIFF_SHORT, FIELD_COLORMAP, + TRUE, FALSE, "ColorMap" }, + { TIFFTAG_HALFTONEHINTS, 2, 2, TIFF_SHORT, FIELD_HALFTONEHINTS, + TRUE, FALSE, "HalftoneHints" }, + { TIFFTAG_TILEWIDTH, 1, 1, TIFF_LONG, FIELD_TILEDIMENSIONS, + FALSE, FALSE, "TileWidth" }, + { TIFFTAG_TILEWIDTH, 1, 1, TIFF_SHORT, FIELD_TILEDIMENSIONS, + FALSE, FALSE, "TileWidth" }, + { TIFFTAG_TILELENGTH, 1, 1, TIFF_LONG, FIELD_TILEDIMENSIONS, + FALSE, FALSE, "TileLength" }, + { TIFFTAG_TILELENGTH, 1, 1, TIFF_SHORT, FIELD_TILEDIMENSIONS, + FALSE, FALSE, "TileLength" }, + { TIFFTAG_TILEOFFSETS, -1, 1, TIFF_LONG, FIELD_STRIPOFFSETS, + FALSE, FALSE, "TileOffsets" }, + { TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_LONG, FIELD_STRIPBYTECOUNTS, + FALSE, FALSE, "TileByteCounts" }, + { TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_SHORT, FIELD_STRIPBYTECOUNTS, + FALSE, FALSE, "TileByteCounts" }, +#ifdef TIFFTAG_SUBIFD + { TIFFTAG_SUBIFD, -1,-1, TIFF_LONG, FIELD_SUBIFD, + TRUE, TRUE, "SubIFD" }, +#endif +#ifdef CMYK_SUPPORT /* 6.0 CMYK tags */ + { TIFFTAG_INKSET, 1, 1, TIFF_SHORT, FIELD_INKSET, + FALSE, FALSE, "InkSet" }, + { TIFFTAG_INKNAMES, -1,-1, TIFF_ASCII, FIELD_INKNAMES, + TRUE, TRUE, "InkNames" }, + { TIFFTAG_NUMBEROFINKS, 1, 1, TIFF_SHORT, FIELD_NUMBEROFINKS, + TRUE, FALSE, "NumberOfInks" }, + { TIFFTAG_DOTRANGE, 2, 2, TIFF_SHORT, FIELD_DOTRANGE, + FALSE, FALSE, "DotRange" }, + { TIFFTAG_DOTRANGE, 2, 2, TIFF_BYTE, FIELD_DOTRANGE, + FALSE, FALSE, "DotRange" }, + { TIFFTAG_TARGETPRINTER, -1,-1, TIFF_ASCII, FIELD_TARGETPRINTER, + TRUE, FALSE, "TargetPrinter" }, +#endif + { TIFFTAG_EXTRASAMPLES, -1,-1, TIFF_SHORT, FIELD_EXTRASAMPLES, + FALSE, FALSE, "ExtraSamples" }, +/* XXX for bogus Adobe Photoshop v2.5 files */ + { TIFFTAG_EXTRASAMPLES, -1,-1, TIFF_BYTE, FIELD_EXTRASAMPLES, + FALSE, FALSE, "ExtraSamples" }, + { TIFFTAG_SAMPLEFORMAT, -1,-1, TIFF_SHORT, FIELD_SAMPLEFORMAT, + FALSE, FALSE, "SampleFormat" }, + { TIFFTAG_SMINSAMPLEVALUE, -2,-1, TIFF_ANY, FIELD_SMINSAMPLEVALUE, + TRUE, FALSE, "SMinSampleValue" }, + { TIFFTAG_SMAXSAMPLEVALUE, -2,-1, TIFF_ANY, FIELD_SMAXSAMPLEVALUE, + TRUE, FALSE, "SMaxSampleValue" }, +#ifdef YCBCR_SUPPORT /* 6.0 YCbCr tags */ + { TIFFTAG_YCBCRCOEFFICIENTS, 3, 3, TIFF_RATIONAL, FIELD_YCBCRCOEFFICIENTS, + FALSE, FALSE, "YCbCrCoefficients" }, + { TIFFTAG_YCBCRSUBSAMPLING, 2, 2, TIFF_SHORT, FIELD_YCBCRSUBSAMPLING, + FALSE, FALSE, "YCbCrSubsampling" }, + { TIFFTAG_YCBCRPOSITIONING, 1, 1, TIFF_SHORT, FIELD_YCBCRPOSITIONING, + FALSE, FALSE, "YCbCrPositioning" }, +#endif +#ifdef COLORIMETRY_SUPPORT + { TIFFTAG_REFERENCEBLACKWHITE,6,6,TIFF_RATIONAL, FIELD_REFBLACKWHITE, + TRUE, FALSE, "ReferenceBlackWhite" }, +/* XXX temporarily accept LONG for backwards compatibility */ + { TIFFTAG_REFERENCEBLACKWHITE,6,6,TIFF_LONG, FIELD_REFBLACKWHITE, + TRUE, FALSE, "ReferenceBlackWhite" }, +#endif +/* begin SGI tags */ + { TIFFTAG_MATTEING, 1, 1, TIFF_SHORT, FIELD_EXTRASAMPLES, + FALSE, FALSE, "Matteing" }, + { TIFFTAG_DATATYPE, -2,-1, TIFF_SHORT, FIELD_SAMPLEFORMAT, + FALSE, FALSE, "DataType" }, + { TIFFTAG_IMAGEDEPTH, 1, 1, TIFF_LONG, FIELD_IMAGEDEPTH, + FALSE, FALSE, "ImageDepth" }, + { TIFFTAG_IMAGEDEPTH, 1, 1, TIFF_SHORT, FIELD_IMAGEDEPTH, + FALSE, FALSE, "ImageDepth" }, + { TIFFTAG_TILEDEPTH, 1, 1, TIFF_LONG, FIELD_TILEDEPTH, + FALSE, FALSE, "TileDepth" }, + { TIFFTAG_TILEDEPTH, 1, 1, TIFF_SHORT, FIELD_TILEDEPTH, + FALSE, FALSE, "TileDepth" }, +/* end SGI tags */ +/* begin Pixar tags */ + { TIFFTAG_PIXAR_IMAGEFULLWIDTH, 1, 1, TIFF_LONG, FIELD_IMAGEFULLWIDTH, + TRUE, FALSE, "ImageFullWidth" }, + { TIFFTAG_PIXAR_IMAGEFULLLENGTH, 1, 1, TIFF_LONG, FIELD_IMAGEFULLLENGTH, + TRUE, FALSE, "ImageFullLength" }, + { TIFFTAG_PIXAR_TEXTUREFORMAT, -1,-1, TIFF_ASCII, FIELD_TEXTUREFORMAT, + TRUE, FALSE, "TextureFormat" }, + { TIFFTAG_PIXAR_WRAPMODES, -1,-1, TIFF_ASCII, FIELD_WRAPMODES, + TRUE, FALSE, "TextureWrapModes" }, + { TIFFTAG_PIXAR_FOVCOT, 1, 1, TIFF_FLOAT, FIELD_FOVCOT, + TRUE, FALSE, "FieldOfViewCotan" }, + { TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN, 16,16, TIFF_FLOAT, + FIELD_MATRIX_WORLDTOSCREEN, TRUE, FALSE, "MatrixWorldToScreen" }, + { TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA, 16,16, TIFF_FLOAT, + FIELD_MATRIX_WORLDTOCAMERA, TRUE, FALSE, "MatrixWorldToCamera" }, + { TIFFTAG_COPYRIGHT, -1,-1, TIFF_ASCII, FIELD_COPYRIGHT, + TRUE, FALSE, "Copyright" }, +/* end Pixar tags */ +#ifdef IPTC_SUPPORT +#ifdef PHOTOSHOP_SUPPORT + { TIFFTAG_RICHTIFFIPTC, -1,-1, TIFF_LONG, FIELD_RICHTIFFIPTC, + FALSE, TRUE, "RichTIFFIPTC" }, +#else + { TIFFTAG_RICHTIFFIPTC, -1,-3, TIFF_UNDEFINED, FIELD_RICHTIFFIPTC, + FALSE, TRUE, "RichTIFFIPTC" }, +#endif +#endif +#ifdef PHOTOSHOP_SUPPORT + { TIFFTAG_PHOTOSHOP, -1,-3, TIFF_BYTE, FIELD_PHOTOSHOP, + FALSE, TRUE, "Photoshop" }, +#endif +#ifdef ICC_SUPPORT + { TIFFTAG_ICCPROFILE, -1,-3, TIFF_UNDEFINED, FIELD_ICCPROFILE, + FALSE, TRUE, "ICC Profile" }, +#endif + { TIFFTAG_STONITS, 1, 1, TIFF_DOUBLE, FIELD_STONITS, + FALSE, FALSE, "StoNits" }, +}; +#define N(a) (sizeof (a) / sizeof (a[0])) + +void +_TIFFSetupFieldInfo(TIFF* tif) +{ + if (tif->tif_fieldinfo) { + _TIFFfree(tif->tif_fieldinfo); + tif->tif_nfields = 0; + } + _TIFFMergeFieldInfo(tif, tiffFieldInfo, N(tiffFieldInfo)); +} + +static int +tagCompare(const void* a, const void* b) +{ + const TIFFFieldInfo* ta = *(const TIFFFieldInfo**) a; + const TIFFFieldInfo* tb = *(const TIFFFieldInfo**) b; + /* NB: be careful of return values for 16-bit platforms */ + if (ta->field_tag != tb->field_tag) + return (ta->field_tag < tb->field_tag ? -1 : 1); + else + return (tb->field_type < ta->field_type ? -1 : 1); +} + +void +_TIFFMergeFieldInfo(TIFF* tif, const TIFFFieldInfo info[], int n) +{ + TIFFFieldInfo** tp; + int i; + + if (tif->tif_nfields > 0) { + tif->tif_fieldinfo = (TIFFFieldInfo**) + _TIFFrealloc(tif->tif_fieldinfo, + (tif->tif_nfields+n) * sizeof (TIFFFieldInfo*)); + } else { + tif->tif_fieldinfo = (TIFFFieldInfo**) + _TIFFmalloc(n * sizeof (TIFFFieldInfo*)); + } + tp = &tif->tif_fieldinfo[tif->tif_nfields]; + for (i = 0; i < n; i++) + tp[i] = (TIFFFieldInfo*) &info[i]; /* XXX */ + /* + * NB: the core tags are presumed sorted correctly. + */ + if (tif->tif_nfields > 0) + qsort(tif->tif_fieldinfo, (size_t) (tif->tif_nfields += n), + sizeof (TIFFFieldInfo*), tagCompare); + else + tif->tif_nfields += n; +} + +void +_TIFFPrintFieldInfo(TIFF* tif, FILE* fd) +{ + int i; + + fprintf(fd, "%s: \n", tif->tif_name); + for (i = 0; i < tif->tif_nfields; i++) { + const TIFFFieldInfo* fip = tif->tif_fieldinfo[i]; + fprintf(fd, "field[%2d] %5lu, %2d, %2d, %d, %2d, %5s, %5s, %s\n" + , i + , (unsigned long) fip->field_tag + , fip->field_readcount, fip->field_writecount + , fip->field_type + , fip->field_bit + , fip->field_oktochange ? "TRUE" : "FALSE" + , fip->field_passcount ? "TRUE" : "FALSE" + , fip->field_name + ); + } +} + +const int tiffDataWidth[] = { + 1, /* nothing */ + 1, /* TIFF_BYTE */ + 1, /* TIFF_ASCII */ + 2, /* TIFF_SHORT */ + 4, /* TIFF_LONG */ + 8, /* TIFF_RATIONAL */ + 1, /* TIFF_SBYTE */ + 1, /* TIFF_UNDEFINED */ + 2, /* TIFF_SSHORT */ + 4, /* TIFF_SLONG */ + 8, /* TIFF_SRATIONAL */ + 4, /* TIFF_FLOAT */ + 8, /* TIFF_DOUBLE */ +}; + +/* + * Return nearest TIFFDataType to the sample type of an image. + */ +TIFFDataType +_TIFFSampleToTagType(TIFF* tif) +{ + int bps = (int) TIFFhowmany(tif->tif_dir.td_bitspersample, 8); + + switch (tif->tif_dir.td_sampleformat) { + case SAMPLEFORMAT_IEEEFP: + return (bps == 4 ? TIFF_FLOAT : TIFF_DOUBLE); + case SAMPLEFORMAT_INT: + return (bps <= 1 ? TIFF_SBYTE : + bps <= 2 ? TIFF_SSHORT : TIFF_SLONG); + case SAMPLEFORMAT_UINT: + return (bps <= 1 ? TIFF_BYTE : + bps <= 2 ? TIFF_SHORT : TIFF_LONG); + case SAMPLEFORMAT_VOID: + return (TIFF_UNDEFINED); + } + /*NOTREACHED*/ + return (TIFF_UNDEFINED); +} + +const TIFFFieldInfo* +_TIFFFindFieldInfo(TIFF* tif, ttag_t tag, TIFFDataType dt) +{ + static const TIFFFieldInfo *last = NULL; + int i, n; + + if (last && last->field_tag == tag && + (dt == TIFF_ANY || dt == last->field_type)) + return (last); + /* NB: if table gets big, use sorted search (e.g. binary search) */ + for (i = 0, n = tif->tif_nfields; i < n; i++) { + const TIFFFieldInfo* fip = tif->tif_fieldinfo[i]; + if (fip->field_tag == tag && + (dt == TIFF_ANY || fip->field_type == dt)) + return (last = fip); + } + return ((const TIFFFieldInfo *)0); +} + +#include +#include + +const TIFFFieldInfo* +_TIFFFieldWithTag(TIFF* tif, ttag_t tag) +{ + const TIFFFieldInfo* fip = _TIFFFindFieldInfo(tif, tag, TIFF_ANY); + if (!fip) { + TIFFError("TIFFFieldWithTag", + "Internal error, unknown tag 0x%x", (u_int) tag); + assert(fip != NULL); + /*NOTREACHED*/ + } + return (fip); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_dirread.c b/SlnkDWFImpl/CxImage/tiff/tif_dirread.c new file mode 100644 index 0000000..f5716b3 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_dirread.c @@ -0,0 +1,1375 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_dirread.c,v 1.6 2000/04/21 21:45:33 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Directory Read Support Routines. + */ +#include "tiffiop.h" + +#define IGNORE 0 /* tag placeholder used below */ + +#if HAVE_IEEEFP +#define TIFFCvtIEEEFloatToNative(tif, n, fp) +#define TIFFCvtIEEEDoubleToNative(tif, n, dp) +#else +extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*); +extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*); +#endif + +static void EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16); +static void MissingRequired(TIFF*, const char*); +static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32); +static tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*); +static tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*); +static float TIFFFetchRational(TIFF*, TIFFDirEntry*); +static int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*); +static int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, int*); +static int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*); +static int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*); +static int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**); +static int TIFFFetchExtraSamples(TIFF*, TIFFDirEntry*); +static int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*); +static float TIFFFetchFloat(TIFF*, TIFFDirEntry*); +static int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*); +static int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*); +static int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*); +static int TIFFFetchShortPair(TIFF*, TIFFDirEntry*); +static void ChopUpSingleUncompressedStrip(TIFF*); + +static char * +CheckMalloc(TIFF* tif, tsize_t n, const char* what) +{ + char *cp = (char*)_TIFFmalloc(n); + if (cp == NULL) + TIFFError(tif->tif_name, "No space %s", what); + return (cp); +} + +/* + * Read the next TIFF directory from a file + * and convert it to the internal format. + * We read directories sequentially. + */ +int +TIFFReadDirectory(TIFF* tif) +{ + register TIFFDirEntry* dp; + register int n; + register TIFFDirectory* td; + TIFFDirEntry* dir; + int iv; + long v; + double dv; + const TIFFFieldInfo* fip; + int fix; + uint16 dircount; + toff_t nextdiroff; + char* cp; + int diroutoforderwarning = 0; + + tif->tif_diroff = tif->tif_nextdiroff; + if (tif->tif_diroff == 0) /* no more directories */ + return (0); + /* + * Cleanup any previous compression state. + */ + (*tif->tif_cleanup)(tif); + tif->tif_curdir++; + nextdiroff = 0; + if (!isMapped(tif)) { + if (!SeekOK(tif, tif->tif_diroff)) { + TIFFError(tif->tif_name, + "Seek error accessing TIFF directory"); + return (0); + } + if (!ReadOK(tif, &dircount, sizeof (uint16))) { + TIFFError(tif->tif_name, + "Can not read TIFF directory count"); + return (0); + } + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabShort(&dircount); + dir = (TIFFDirEntry *)CheckMalloc(tif, + dircount * sizeof (TIFFDirEntry), "to read TIFF directory"); + if (dir == NULL) + return (0); + if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) { + TIFFError(tif->tif_name, "Can not read TIFF directory"); + goto bad; + } + /* + * Read offset to next directory for sequential scans. + */ + (void) ReadOK(tif, &nextdiroff, sizeof (uint32)); + } else { + toff_t off = tif->tif_diroff; + + if (off + sizeof (uint16) > tif->tif_size) { + TIFFError(tif->tif_name, + "Can not read TIFF directory count"); + return (0); + } else + _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); + off += sizeof (uint16); + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabShort(&dircount); + dir = (TIFFDirEntry *)CheckMalloc(tif, + dircount * sizeof (TIFFDirEntry), "to read TIFF directory"); + if (dir == NULL) + return (0); + if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) { + TIFFError(tif->tif_name, "Can not read TIFF directory"); + goto bad; + } else + _TIFFmemcpy(dir, tif->tif_base + off, + dircount*sizeof (TIFFDirEntry)); + off += dircount* sizeof (TIFFDirEntry); + if (off + sizeof (uint32) <= tif->tif_size) + _TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32)); + } + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabLong(&nextdiroff); + tif->tif_nextdiroff = nextdiroff; + + tif->tif_flags &= ~TIFF_BEENWRITING; /* reset before new dir */ + /* + * Setup default value and then make a pass over + * the fields to check type and tag information, + * and to extract info required to size data + * structures. A second pass is made afterwards + * to read in everthing not taken in the first pass. + */ + td = &tif->tif_dir; + /* free any old stuff and reinit */ + TIFFFreeDirectory(tif); + TIFFDefaultDirectory(tif); + /* + * Electronic Arts writes gray-scale TIFF files + * without a PlanarConfiguration directory entry. + * Thus we setup a default value here, even though + * the TIFF spec says there is no default value. + */ + TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); + + /* + * Sigh, we must make a separate pass through the + * directory for the following reason: + * + * We must process the Compression tag in the first pass + * in order to merge in codec-private tag definitions (otherwise + * we may get complaints about unknown tags). However, the + * Compression tag may be dependent on the SamplesPerPixel + * tag value because older TIFF specs permited Compression + * to be written as a SamplesPerPixel-count tag entry. + * Thus if we don't first figure out the correct SamplesPerPixel + * tag value then we may end up ignoring the Compression tag + * value because it has an incorrect count value (if the + * true value of SamplesPerPixel is not 1). + * + * It sure would have been nice if Aldus had really thought + * this stuff through carefully. + */ + for (dp = dir, n = dircount; n > 0; n--, dp++) { + if (tif->tif_flags & TIFF_SWAB) { + TIFFSwabArrayOfShort(&dp->tdir_tag, 2); + TIFFSwabArrayOfLong(&dp->tdir_count, 2); + } + if (dp->tdir_tag == TIFFTAG_SAMPLESPERPIXEL) { + if (!TIFFFetchNormalTag(tif, dp)) + goto bad; + dp->tdir_tag = IGNORE; + } + } + /* + * First real pass over the directory. + */ + fix = 0; + for (dp = dir, n = dircount; n > 0; n--, dp++) { + + /* + * Find the field information entry for this tag. + * Added check for tags to ignore ... [BFC] + */ + if( TIFFReassignTagToIgnore(TIS_EXTRACT, dp->tdir_tag) ) + dp->tdir_tag = IGNORE; + + if (dp->tdir_tag == IGNORE) + continue; + + /* + * Silicon Beach (at least) writes unordered + * directory tags (violating the spec). Handle + * it here, but be obnoxious (maybe they'll fix it?). + */ + if (dp->tdir_tag < tif->tif_fieldinfo[fix]->field_tag) { + if (!diroutoforderwarning) { + TIFFWarning(tif->tif_name, + "invalid TIFF directory; tags are not sorted in ascending order"); + diroutoforderwarning = 1; + } + fix = 0; /* O(n^2) */ + } + while (fix < tif->tif_nfields && + tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) + fix++; + if (fix == tif->tif_nfields || + tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { + TIFFWarning(tif->tif_name, + "unknown field with tag %d (0x%x) ignored", + dp->tdir_tag, dp->tdir_tag); + dp->tdir_tag = IGNORE; + fix = 0; /* restart search */ + continue; + } + /* + * Null out old tags that we ignore. + */ + if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { + ignore: + dp->tdir_tag = IGNORE; + continue; + } + /* + * Check data type. + */ + fip = tif->tif_fieldinfo[fix]; + while (dp->tdir_type != (u_short) fip->field_type) { + if (fip->field_type == TIFF_ANY) /* wildcard */ + break; + fip++, fix++; + if (fix == tif->tif_nfields || + fip->field_tag != dp->tdir_tag) { + TIFFWarning(tif->tif_name, + "wrong data type %d for \"%s\"; tag ignored", + dp->tdir_type, fip[-1].field_name); + goto ignore; + } + } + /* + * Check count if known in advance. + */ + if (fip->field_readcount != TIFF_VARIABLE) { + uint32 expected = (fip->field_readcount == TIFF_SPP) ? + (uint32) td->td_samplesperpixel : + (uint32) fip->field_readcount; + if (!CheckDirCount(tif, dp, expected)) + goto ignore; + } + + switch (dp->tdir_tag) { + case TIFFTAG_COMPRESSION: + /* + * The 5.0 spec says the Compression tag has + * one value, while earlier specs say it has + * one value per sample. Because of this, we + * accept the tag if one value is supplied. + */ + if (dp->tdir_count == 1) { + v = TIFFExtractData(tif, + dp->tdir_type, dp->tdir_offset); + if (!TIFFSetField(tif, dp->tdir_tag, (int)v)) + goto bad; + break; + } + if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || + !TIFFSetField(tif, dp->tdir_tag, iv)) + goto bad; + dp->tdir_tag = IGNORE; + break; + case TIFFTAG_STRIPOFFSETS: + case TIFFTAG_STRIPBYTECOUNTS: + case TIFFTAG_TILEOFFSETS: + case TIFFTAG_TILEBYTECOUNTS: + TIFFSetFieldBit(tif, fip->field_bit); + break; + case TIFFTAG_IMAGEWIDTH: + case TIFFTAG_IMAGELENGTH: + case TIFFTAG_IMAGEDEPTH: + case TIFFTAG_TILELENGTH: + case TIFFTAG_TILEWIDTH: + case TIFFTAG_TILEDEPTH: + case TIFFTAG_PLANARCONFIG: + case TIFFTAG_ROWSPERSTRIP: + if (!TIFFFetchNormalTag(tif, dp)) + goto bad; + dp->tdir_tag = IGNORE; + break; + case TIFFTAG_EXTRASAMPLES: + (void) TIFFFetchExtraSamples(tif, dp); + dp->tdir_tag = IGNORE; + break; + } + } + + /* + * Allocate directory structure and setup defaults. + */ + if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { + MissingRequired(tif, "ImageLength"); + goto bad; + } + if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { + MissingRequired(tif, "PlanarConfiguration"); + goto bad; + } + /* + * Setup appropriate structures (by strip or by tile) + */ + if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { + td->td_nstrips = TIFFNumberOfStrips(tif); + td->td_tilewidth = td->td_imagewidth; + td->td_tilelength = td->td_rowsperstrip; + td->td_tiledepth = td->td_imagedepth; + tif->tif_flags &= ~TIFF_ISTILED; + } else { + td->td_nstrips = TIFFNumberOfTiles(tif); + tif->tif_flags |= TIFF_ISTILED; + } + td->td_stripsperimage = td->td_nstrips; + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) + td->td_stripsperimage /= td->td_samplesperpixel; + if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) { + MissingRequired(tif, + isTiled(tif) ? "TileOffsets" : "StripOffsets"); + goto bad; + } + + /* + * Second pass: extract other information. + */ + for (dp = dir, n = dircount; n > 0; n--, dp++) { + if (dp->tdir_tag == IGNORE) + continue; + switch (dp->tdir_tag) { + case TIFFTAG_MINSAMPLEVALUE: + case TIFFTAG_MAXSAMPLEVALUE: + case TIFFTAG_BITSPERSAMPLE: + /* + * The 5.0 spec says the Compression tag has + * one value, while earlier specs say it has + * one value per sample. Because of this, we + * accept the tag if one value is supplied. + * + * The MinSampleValue, MaxSampleValue and + * BitsPerSample tags are supposed to be written + * as one value/sample, but some vendors incorrectly + * write one value only -- so we accept that + * as well (yech). + */ + if (dp->tdir_count == 1) { + v = TIFFExtractData(tif, + dp->tdir_type, dp->tdir_offset); + if (!TIFFSetField(tif, dp->tdir_tag, (int)v)) + goto bad; + break; + } + /* fall thru... */ + case TIFFTAG_DATATYPE: + case TIFFTAG_SAMPLEFORMAT: + if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || + !TIFFSetField(tif, dp->tdir_tag, iv)) + goto bad; + break; + case TIFFTAG_SMINSAMPLEVALUE: + case TIFFTAG_SMAXSAMPLEVALUE: + if (!TIFFFetchPerSampleAnys(tif, dp, &dv) || + !TIFFSetField(tif, dp->tdir_tag, dv)) + goto bad; + break; + case TIFFTAG_STRIPOFFSETS: + case TIFFTAG_TILEOFFSETS: + if (!TIFFFetchStripThing(tif, dp, + td->td_nstrips, &td->td_stripoffset)) + goto bad; + break; + case TIFFTAG_STRIPBYTECOUNTS: + case TIFFTAG_TILEBYTECOUNTS: + if (!TIFFFetchStripThing(tif, dp, + td->td_nstrips, &td->td_stripbytecount)) + goto bad; + break; + case TIFFTAG_COLORMAP: + case TIFFTAG_TRANSFERFUNCTION: + /* + * TransferFunction can have either 1x or 3x data + * values; Colormap can have only 3x items. + */ + v = 1L<td_bitspersample; + if (dp->tdir_tag == TIFFTAG_COLORMAP || + dp->tdir_count != (uint32) v) { + if (!CheckDirCount(tif, dp, (uint32)(3*v))) + break; + } + v *= sizeof (uint16); + cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint16), + "to read \"TransferFunction\" tag"); + if (cp != NULL) { + if (TIFFFetchData(tif, dp, cp)) { + /* + * This deals with there being only + * one array to apply to all samples. + */ + uint32 c = + (uint32)1 << td->td_bitspersample; + if (dp->tdir_count == c) + v = 0; + TIFFSetField(tif, dp->tdir_tag, + cp, cp+v, cp+2*v); + } + _TIFFfree(cp); + } + break; + case TIFFTAG_PAGENUMBER: + case TIFFTAG_HALFTONEHINTS: + case TIFFTAG_YCBCRSUBSAMPLING: + case TIFFTAG_DOTRANGE: + (void) TIFFFetchShortPair(tif, dp); + break; +#ifdef COLORIMETRY_SUPPORT + case TIFFTAG_REFERENCEBLACKWHITE: + (void) TIFFFetchRefBlackWhite(tif, dp); + break; +#endif +/* BEGIN REV 4.0 COMPATIBILITY */ + case TIFFTAG_OSUBFILETYPE: + v = 0; + switch (TIFFExtractData(tif, dp->tdir_type, + dp->tdir_offset)) { + case OFILETYPE_REDUCEDIMAGE: + v = FILETYPE_REDUCEDIMAGE; + break; + case OFILETYPE_PAGE: + v = FILETYPE_PAGE; + break; + } + if (v) + (void) TIFFSetField(tif, + TIFFTAG_SUBFILETYPE, (int)v); + break; +/* END REV 4.0 COMPATIBILITY */ + default: + (void) TIFFFetchNormalTag(tif, dp); + break; + } + } + /* + * Verify Palette image has a Colormap. + */ + if (td->td_photometric == PHOTOMETRIC_PALETTE && + !TIFFFieldSet(tif, FIELD_COLORMAP)) { + MissingRequired(tif, "Colormap"); + goto bad; + } + /* + * Attempt to deal with a missing StripByteCounts tag. + */ + if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) { + /* + * Some manufacturers violate the spec by not giving + * the size of the strips. In this case, assume there + * is one uncompressed strip of data. + */ + if ((td->td_planarconfig == PLANARCONFIG_CONTIG && + td->td_nstrips > 1) || + (td->td_planarconfig == PLANARCONFIG_SEPARATE && + td->td_nstrips != td->td_samplesperpixel)) { + MissingRequired(tif, "StripByteCounts"); + goto bad; + } + TIFFWarning(tif->tif_name, + "TIFF directory is missing required \"%s\" field, calculating from imagelength", + _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); + EstimateStripByteCounts(tif, dir, dircount); +#define BYTECOUNTLOOKSBAD \ + ((td->td_stripbytecount[0] == 0 && td->td_stripoffset[0] != 0) || \ + (td->td_compression == COMPRESSION_NONE && \ + td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0])) + } else if (td->td_nstrips == 1 && BYTECOUNTLOOKSBAD) { + /* + * Plexus (and others) sometimes give a value + * of zero for a tag when they don't know what + * the correct value is! Try and handle the + * simple case of estimating the size of a one + * strip image. + */ + TIFFWarning(tif->tif_name, + "Bogus \"%s\" field, ignoring and calculating from imagelength", + _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); + EstimateStripByteCounts(tif, dir, dircount); + } + if (dir) + _TIFFfree((char *)dir); + if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE)) + td->td_maxsamplevalue = (uint16)((1L<td_bitspersample)-1); + /* + * Setup default compression scheme. + */ + if (!TIFFFieldSet(tif, FIELD_COMPRESSION)) + TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE); + /* + * Some manufacturers make life difficult by writing + * large amounts of uncompressed data as a single strip. + * This is contrary to the recommendations of the spec. + * The following makes an attempt at breaking such images + * into strips closer to the recommended 8k bytes. A + * side effect, however, is that the RowsPerStrip tag + * value may be changed. + */ + if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE && + (tif->tif_flags & (TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP) + ChopUpSingleUncompressedStrip(tif); + /* + * Reinitialize i/o since we are starting on a new directory. + */ + tif->tif_row = (uint32) -1; + tif->tif_curstrip = (tstrip_t) -1; + tif->tif_col = (uint32) -1; + tif->tif_curtile = (ttile_t) -1; + tif->tif_tilesize = TIFFTileSize(tif); + tif->tif_scanlinesize = TIFFScanlineSize(tif); + return (1); +bad: + if (dir) + _TIFFfree(dir); + return (0); +} + +static void +EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) +{ + register TIFFDirEntry *dp; + register TIFFDirectory *td = &tif->tif_dir; + uint16 i; + + if (td->td_stripbytecount) + _TIFFfree(td->td_stripbytecount); + td->td_stripbytecount = (uint32*) + CheckMalloc(tif, td->td_nstrips * sizeof (uint32), + "for \"StripByteCounts\" array"); + if (td->td_compression != COMPRESSION_NONE) { + uint32 space = (uint32)(sizeof (TIFFHeader) + + sizeof (uint16) + + (dircount * sizeof (TIFFDirEntry)) + + sizeof (uint32)); + toff_t filesize = TIFFGetFileSize(tif); + uint16 n; + + /* calculate amount of space used by indirect values */ + for (dp = dir, n = dircount; n > 0; n--, dp++) { + uint32 cc = dp->tdir_count*tiffDataWidth[dp->tdir_type]; + if (cc > sizeof (uint32)) + space += cc; + } + space = filesize - space; + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) + space /= td->td_samplesperpixel; + for (i = 0; i < td->td_nstrips; i++) + td->td_stripbytecount[i] = space; + /* + * This gross hack handles the case were the offset to + * the last strip is past the place where we think the strip + * should begin. Since a strip of data must be contiguous, + * it's safe to assume that we've overestimated the amount + * of data in the strip and trim this number back accordingly. + */ + i--; + if (((toff_t)(td->td_stripoffset[i]+td->td_stripbytecount[i])) + > filesize) + td->td_stripbytecount[i] = + filesize - td->td_stripoffset[i]; + } else { + uint32 rowbytes = TIFFScanlineSize(tif); + uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage; + for (i = 0; i < td->td_nstrips; i++) + td->td_stripbytecount[i] = rowbytes*rowsperstrip; + } + TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); + if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP)) + td->td_rowsperstrip = td->td_imagelength; +} + +static void +MissingRequired(TIFF* tif, const char* tagname) +{ + TIFFError(tif->tif_name, + "TIFF directory is missing required \"%s\" field", tagname); +} + +/* + * Check the count field of a directory + * entry against a known value. The caller + * is expected to skip/ignore the tag if + * there is a mismatch. + */ +static int +CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count) +{ + if (count != dir->tdir_count) { + TIFFWarning(tif->tif_name, + "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored", + _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, + dir->tdir_count, count); + return (0); + } + return (1); +} + +/* + * Fetch a contiguous directory item. + */ +static tsize_t +TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp) +{ + int w = tiffDataWidth[dir->tdir_type]; + tsize_t cc = dir->tdir_count * w; + + if (!isMapped(tif)) { + if (!SeekOK(tif, dir->tdir_offset)) + goto bad; + if (!ReadOK(tif, cp, cc)) + goto bad; + } else { + if (dir->tdir_offset + cc > tif->tif_size) + goto bad; + _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc); + } + if (tif->tif_flags & TIFF_SWAB) { + switch (dir->tdir_type) { + case TIFF_SHORT: + case TIFF_SSHORT: + TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); + break; + case TIFF_LONG: + case TIFF_SLONG: + case TIFF_FLOAT: + TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); + break; + case TIFF_RATIONAL: + case TIFF_SRATIONAL: + TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); + break; + case TIFF_DOUBLE: + TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); + break; + } + } + return (cc); +bad: + TIFFError(tif->tif_name, "Error fetching data for field \"%s\"", + _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); + return ((tsize_t) 0); +} + +/* + * Fetch an ASCII item from the file. + */ +static tsize_t +TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp) +{ + if (dir->tdir_count <= 4) { + uint32 l = dir->tdir_offset; + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabLong(&l); + _TIFFmemcpy(cp, &l, dir->tdir_count); + return (1); + } + return (TIFFFetchData(tif, dir, cp)); +} + +/* + * Convert numerator+denominator to float. + */ +static int +cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv) +{ + if (denom == 0) { + TIFFError(tif->tif_name, + "%s: Rational with zero denominator (num = %lu)", + _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num); + return (0); + } else { + if (dir->tdir_type == TIFF_RATIONAL) + *rv = ((float)num / (float)denom); + else + *rv = ((float)(int32)num / (float)(int32)denom); + return (1); + } +} + +/* + * Fetch a rational item from the file + * at offset off and return the value + * as a floating point number. + */ +static float +TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir) +{ + uint32 l[2]; + float v; + + return (!TIFFFetchData(tif, dir, (char *)l) || + !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v); +} + +/* + * Fetch a single floating point value + * from the offset field and return it + * as a native float. + */ +static float +TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir) +{ + long l = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); + float v = *(float*) &l; + TIFFCvtIEEEFloatToNative(tif, 1, &v); + return (v); +} + +/* + * Fetch an array of BYTE or SBYTE values. + */ +static int +TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) +{ + if (dir->tdir_count <= 4) { + /* + * Extract data from offset field. + */ + if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { + switch (dir->tdir_count) { + case 4: v[3] = (uint16)(dir->tdir_offset & 0xff); + case 3: v[2] = (uint16)((dir->tdir_offset >> 8) & 0xff); + case 2: v[1] = (uint16)((dir->tdir_offset >> 16) & 0xff); + case 1: v[0] = (uint16)(dir->tdir_offset >> 24); + } + } else { + switch (dir->tdir_count) { + case 4: v[3] = (uint16)(dir->tdir_offset >> 24); + case 3: v[2] = (uint16)((dir->tdir_offset >> 16) & 0xff); + case 2: v[1] = (uint16)((dir->tdir_offset >> 8) & 0xff); + case 1: v[0] = (uint16)(dir->tdir_offset & 0xff); + } + } + return (1); + } else + return (TIFFFetchData(tif, dir, (char*) v) != 0); /* XXX */ +} + +/* + * Fetch an array of SHORT or SSHORT values. + */ +static int +TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) +{ + if (dir->tdir_count <= 2) { + if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { + switch (dir->tdir_count) { + case 2: v[1] = (uint16) (dir->tdir_offset & 0xffff); + case 1: v[0] = (uint16) (dir->tdir_offset >> 16); + } + } else { + switch (dir->tdir_count) { + case 2: v[1] = (uint16) (dir->tdir_offset >> 16); + case 1: v[0] = (uint16) (dir->tdir_offset & 0xffff); + } + } + return (1); + } else + return (TIFFFetchData(tif, dir, (char *)v) != 0); +} + +/* + * Fetch a pair of SHORT or BYTE values. + */ +static int +TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir) +{ + uint16 v[2]; + int ok = 0; + + switch (dir->tdir_type) { + case TIFF_SHORT: + case TIFF_SSHORT: + ok = TIFFFetchShortArray(tif, dir, v); + break; + case TIFF_BYTE: + case TIFF_SBYTE: + ok = TIFFFetchByteArray(tif, dir, v); + break; + } + if (ok) + TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); + return (ok); +} + +/* + * Fetch an array of LONG or SLONG values. + */ +static int +TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) +{ + if (dir->tdir_count == 1) { + v[0] = dir->tdir_offset; + return (1); + } else + return (TIFFFetchData(tif, dir, (char*) v) != 0); +} + +/* + * Fetch an array of RATIONAL or SRATIONAL values. + */ +static int +TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) +{ + int ok = 0; + uint32* l; + + l = (uint32*)CheckMalloc(tif, + dir->tdir_count*tiffDataWidth[dir->tdir_type], + "to fetch array of rationals"); + if (l) { + if (TIFFFetchData(tif, dir, (char *)l)) { + uint32 i; + for (i = 0; i < dir->tdir_count; i++) { + ok = cvtRational(tif, dir, + l[2*i+0], l[2*i+1], &v[i]); + if (!ok) + break; + } + } + _TIFFfree((char *)l); + } + return (ok); +} + +/* + * Fetch an array of FLOAT values. + */ +static int +TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) +{ + + if (dir->tdir_count == 1) { + v[0] = *(float*) &dir->tdir_offset; + TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); + return (1); + } else if (TIFFFetchData(tif, dir, (char*) v)) { + TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); + return (1); + } else + return (0); +} + +/* + * Fetch an array of DOUBLE values. + */ +static int +TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) +{ + if (TIFFFetchData(tif, dir, (char*) v)) { + TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v); + return (1); + } else + return (0); +} + +/* + * Fetch an array of ANY values. The actual values are + * returned as doubles which should be able hold all the + * types. Yes, there really should be an tany_t to avoid + * this potential non-portability ... Note in particular + * that we assume that the double return value vector is + * large enough to read in any fundamental type. We use + * that vector as a buffer to read in the base type vector + * and then convert it in place to double (from end + * to front of course). + */ +static int +TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v) +{ + int i; + + switch (dir->tdir_type) { + case TIFF_BYTE: + case TIFF_SBYTE: + if (!TIFFFetchByteArray(tif, dir, (uint16*) v)) + return (0); + if (dir->tdir_type == TIFF_BYTE) { + uint16* vp = (uint16*) v; + for (i = dir->tdir_count-1; i >= 0; i--) + v[i] = vp[i]; + } else { + int16* vp = (int16*) v; + for (i = dir->tdir_count-1; i >= 0; i--) + v[i] = vp[i]; + } + break; + case TIFF_SHORT: + case TIFF_SSHORT: + if (!TIFFFetchShortArray(tif, dir, (uint16*) v)) + return (0); + if (dir->tdir_type == TIFF_SHORT) { + uint16* vp = (uint16*) v; + for (i = dir->tdir_count-1; i >= 0; i--) + v[i] = vp[i]; + } else { + int16* vp = (int16*) v; + for (i = dir->tdir_count-1; i >= 0; i--) + v[i] = vp[i]; + } + break; + case TIFF_LONG: + case TIFF_SLONG: + if (!TIFFFetchLongArray(tif, dir, (uint32*) v)) + return (0); + if (dir->tdir_type == TIFF_LONG) { + uint32* vp = (uint32*) v; + for (i = dir->tdir_count-1; i >= 0; i--) + v[i] = vp[i]; + } else { + int32* vp = (int32*) v; + for (i = dir->tdir_count-1; i >= 0; i--) + v[i] = vp[i]; + } + break; + case TIFF_RATIONAL: + case TIFF_SRATIONAL: + if (!TIFFFetchRationalArray(tif, dir, (float*) v)) + return (0); + { float* vp = (float*) v; + for (i = dir->tdir_count-1; i >= 0; i--) + v[i] = vp[i]; + } + break; + case TIFF_FLOAT: + if (!TIFFFetchFloatArray(tif, dir, (float*) v)) + return (0); + { float* vp = (float*) v; + for (i = dir->tdir_count-1; i >= 0; i--) + v[i] = vp[i]; + } + break; + case TIFF_DOUBLE: + return (TIFFFetchDoubleArray(tif, dir, (double*) v)); + default: + /* TIFF_NOTYPE */ + /* TIFF_ASCII */ + /* TIFF_UNDEFINED */ + TIFFError(tif->tif_name, + "Cannot read TIFF_ANY type %d for field \"%s\"", + _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); + return (0); + } + return (1); +} + +/* + * Fetch a tag that is not handled by special case code. + */ +static int +TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp) +{ + static const char mesg[] = "to fetch tag value"; + int ok = 0; + const TIFFFieldInfo* fip = _TIFFFieldWithTag(tif, dp->tdir_tag); + + if (dp->tdir_count > 1) { /* array of values */ + char* cp = NULL; + + switch (dp->tdir_type) { + case TIFF_BYTE: + case TIFF_SBYTE: + /* NB: always expand BYTE values to shorts */ + cp = CheckMalloc(tif, + dp->tdir_count * sizeof (uint16), mesg); + ok = cp && TIFFFetchByteArray(tif, dp, (uint16*) cp); + break; + case TIFF_SHORT: + case TIFF_SSHORT: + cp = CheckMalloc(tif, + dp->tdir_count * sizeof (uint16), mesg); + ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp); + break; + case TIFF_LONG: + case TIFF_SLONG: + cp = CheckMalloc(tif, + dp->tdir_count * sizeof (uint32), mesg); + ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp); + break; + case TIFF_RATIONAL: + case TIFF_SRATIONAL: + cp = CheckMalloc(tif, + dp->tdir_count * sizeof (float), mesg); + ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp); + break; + case TIFF_FLOAT: + cp = CheckMalloc(tif, + dp->tdir_count * sizeof (float), mesg); + ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp); + break; + case TIFF_DOUBLE: + cp = CheckMalloc(tif, + dp->tdir_count * sizeof (double), mesg); + ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp); + break; + case TIFF_ASCII: + case TIFF_UNDEFINED: /* bit of a cheat... */ + /* + * Some vendors write strings w/o the trailing + * NULL byte, so always append one just in case. + */ + cp = CheckMalloc(tif, dp->tdir_count+1, mesg); + if( (ok = (cp && TIFFFetchString(tif, dp, cp))) != 0 ) + cp[dp->tdir_count] = '\0'; /* XXX */ + break; + } + if (ok) { + ok = (fip->field_passcount ? + TIFFSetField(tif, dp->tdir_tag, dp->tdir_count, cp) + : TIFFSetField(tif, dp->tdir_tag, cp)); + } + if (cp != NULL) + _TIFFfree(cp); + } else if (CheckDirCount(tif, dp, 1)) { /* singleton value */ + switch (dp->tdir_type) { + case TIFF_BYTE: + case TIFF_SBYTE: + case TIFF_SHORT: + case TIFF_SSHORT: + /* + * If the tag is also acceptable as a LONG or SLONG + * then TIFFSetField will expect an uint32 parameter + * passed to it (through varargs). Thus, for machines + * where sizeof (int) != sizeof (uint32) we must do + * a careful check here. It's hard to say if this + * is worth optimizing. + * + * NB: We use TIFFFieldWithTag here knowing that + * it returns us the first entry in the table + * for the tag and that that entry is for the + * widest potential data type the tag may have. + */ + { TIFFDataType type = fip->field_type; + if (type != TIFF_LONG && type != TIFF_SLONG) { + uint16 v = (uint16) + TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); + ok = (fip->field_passcount ? + TIFFSetField(tif, dp->tdir_tag, 1, &v) + : TIFFSetField(tif, dp->tdir_tag, v)); + break; + } + } + /* fall thru... */ + case TIFF_LONG: + case TIFF_SLONG: + { uint32 v32 = + TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); + ok = (fip->field_passcount ? + TIFFSetField(tif, dp->tdir_tag, 1, &v32) + : TIFFSetField(tif, dp->tdir_tag, v32)); + } + break; + case TIFF_RATIONAL: + case TIFF_SRATIONAL: + case TIFF_FLOAT: + { float v = (dp->tdir_type == TIFF_FLOAT ? + TIFFFetchFloat(tif, dp) + : TIFFFetchRational(tif, dp)); + ok = (fip->field_passcount ? + TIFFSetField(tif, dp->tdir_tag, 1, &v) + : TIFFSetField(tif, dp->tdir_tag, v)); + } + break; + case TIFF_DOUBLE: + { double v; + ok = (TIFFFetchDoubleArray(tif, dp, &v) && + (fip->field_passcount ? + TIFFSetField(tif, dp->tdir_tag, 1, &v) + : TIFFSetField(tif, dp->tdir_tag, v)) + ); + } + break; + case TIFF_ASCII: + case TIFF_UNDEFINED: /* bit of a cheat... */ + { char c[2]; + if( (ok = (TIFFFetchString(tif, dp, c) != 0)) != 0 ){ + c[1] = '\0'; /* XXX paranoid */ + ok = TIFFSetField(tif, dp->tdir_tag, c); + } + } + break; + } + } + return (ok); +} + +#define NITEMS(x) (sizeof (x) / sizeof (x[0])) +/* + * Fetch samples/pixel short values for + * the specified tag and verify that + * all values are the same. + */ +static int +TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, int* pl) +{ + int samples = tif->tif_dir.td_samplesperpixel; + int status = 0; + + if (CheckDirCount(tif, dir, (uint32) samples)) { + uint16 buf[10]; + uint16* v = buf; + + if (samples > NITEMS(buf)) + v = (uint16*) _TIFFmalloc(samples * sizeof (uint16)); + if (TIFFFetchShortArray(tif, dir, v)) { + int i; + for (i = 1; i < samples; i++) + if (v[i] != v[0]) { + TIFFError(tif->tif_name, + "Cannot handle different per-sample values for field \"%s\"", + _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); + goto bad; + } + *pl = v[0]; + status = 1; + } + bad: + if (v != buf) + _TIFFfree((char*) v); + } + return (status); +} + +/* + * Fetch samples/pixel ANY values for + * the specified tag and verify that + * all values are the same. + */ +static int +TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl) +{ + int samples = (int) tif->tif_dir.td_samplesperpixel; + int status = 0; + + if (CheckDirCount(tif, dir, (uint32) samples)) { + double buf[10]; + double* v = buf; + + if (samples > NITEMS(buf)) + v = (double*) _TIFFmalloc(samples * sizeof (double)); + if (TIFFFetchAnyArray(tif, dir, v)) { + int i; + for (i = 1; i < samples; i++) + if (v[i] != v[0]) { + TIFFError(tif->tif_name, + "Cannot handle different per-sample values for field \"%s\"", + _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); + goto bad; + } + *pl = v[0]; + status = 1; + } + bad: + if (v != buf) + _TIFFfree(v); + } + return (status); +} +#undef NITEMS + +/* + * Fetch a set of offsets or lengths. + * While this routine says "strips", + * in fact it's also used for tiles. + */ +static int +TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp) +{ + register uint32* lp; + int status; + + if (!CheckDirCount(tif, dir, (uint32) nstrips)) + return (0); + /* + * Allocate space for strip information. + */ + if (*lpp == NULL && + (*lpp = (uint32 *)CheckMalloc(tif, + nstrips * sizeof (uint32), "for strip array")) == NULL) + return (0); + lp = *lpp; + if (dir->tdir_type == (int)TIFF_SHORT) { + /* + * Handle uint16->uint32 expansion. + */ + uint16* dp = (uint16*) CheckMalloc(tif, + dir->tdir_count* sizeof (uint16), "to fetch strip tag"); + if (dp == NULL) + return (0); + if( (status = TIFFFetchShortArray(tif, dir, dp)) != 0 ) { + register uint16* wp = dp; + while (nstrips-- > 0) + *lp++ = *wp++; + } + _TIFFfree((char*) dp); + } else + status = TIFFFetchLongArray(tif, dir, lp); + return (status); +} + +#define NITEMS(x) (sizeof (x) / sizeof (x[0])) +/* + * Fetch and set the ExtraSamples tag. + */ +static int +TIFFFetchExtraSamples(TIFF* tif, TIFFDirEntry* dir) +{ + uint16 buf[10]; + uint16* v = buf; + int status; + + if (dir->tdir_count > NITEMS(buf)) + v = (uint16*) _TIFFmalloc(dir->tdir_count * sizeof (uint16)); + if (dir->tdir_type == TIFF_BYTE) + status = TIFFFetchByteArray(tif, dir, v); + else + status = TIFFFetchShortArray(tif, dir, v); + if (status) + status = TIFFSetField(tif, dir->tdir_tag, dir->tdir_count, v); + if (v != buf) + _TIFFfree((char*) v); + return (status); +} +#undef NITEMS + +#ifdef COLORIMETRY_SUPPORT +/* + * Fetch and set the RefBlackWhite tag. + */ +static int +TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir) +{ + static const char mesg[] = "for \"ReferenceBlackWhite\" array"; + char* cp; + int ok; + + if (dir->tdir_type == TIFF_RATIONAL) + return (TIFFFetchNormalTag(tif, dir)); + /* + * Handle LONG's for backward compatibility. + */ + cp = CheckMalloc(tif, dir->tdir_count * sizeof (uint32), mesg); + if( (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) != 0) { + float* fp = (float*) + CheckMalloc(tif, dir->tdir_count * sizeof (float), mesg); + if( (ok = (fp != NULL)) != 0 ) { + uint32 i; + for (i = 0; i < dir->tdir_count; i++) + fp[i] = (float)((uint32*) cp)[i]; + ok = TIFFSetField(tif, dir->tdir_tag, fp); + _TIFFfree((char*) fp); + } + } + if (cp) + _TIFFfree(cp); + return (ok); +} +#endif + +/* + * Replace a single strip (tile) of uncompressed data by + * multiple strips (tiles), each approximately 8Kbytes. + * This is useful for dealing with large images or + * for dealing with machines with a limited amount + * memory. + */ +static void +ChopUpSingleUncompressedStrip(TIFF* tif) +{ + register TIFFDirectory *td = &tif->tif_dir; + uint32 bytecount = td->td_stripbytecount[0]; + uint32 offset = td->td_stripoffset[0]; + tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes; + tstrip_t strip, nstrips, rowsperstrip; + uint32* newcounts; + uint32* newoffsets; + + /* + * Make the rows hold at least one + * scanline, but fill 8k if possible. + */ + if (rowbytes > 8192) { + stripbytes = rowbytes; + rowsperstrip = 1; + } else { + rowsperstrip = 8192 / rowbytes; + stripbytes = rowbytes * rowsperstrip; + } + /* never increase the number of strips in an image */ + if (rowsperstrip >= td->td_rowsperstrip) + return; + nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes); + newcounts = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32), + "for chopped \"StripByteCounts\" array"); + newoffsets = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32), + "for chopped \"StripOffsets\" array"); + if (newcounts == NULL || newoffsets == NULL) { + /* + * Unable to allocate new strip information, give + * up and use the original one strip information. + */ + if (newcounts != NULL) + _TIFFfree(newcounts); + if (newoffsets != NULL) + _TIFFfree(newoffsets); + return; + } + /* + * Fill the strip information arrays with + * new bytecounts and offsets that reflect + * the broken-up format. + */ + for (strip = 0; strip < nstrips; strip++) { + if (stripbytes > (tsize_t) bytecount) + stripbytes = bytecount; + newcounts[strip] = stripbytes; + newoffsets[strip] = offset; + offset += stripbytes; + bytecount -= stripbytes; + } + /* + * Replace old single strip info with multi-strip info. + */ + td->td_stripsperimage = td->td_nstrips = nstrips; + TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); + + _TIFFfree(td->td_stripbytecount); + _TIFFfree(td->td_stripoffset); + td->td_stripbytecount = newcounts; + td->td_stripoffset = newoffsets; +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_dirwrite.c b/SlnkDWFImpl/CxImage/tiff/tif_dirwrite.c new file mode 100644 index 0000000..db2eb44 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_dirwrite.c @@ -0,0 +1,1101 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_dirwrite.c,v 1.9 2001/09/26 17:42:18 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Directory Write Support Routines. + */ +#include "tiffiop.h" + +#if HAVE_IEEEFP +#define TIFFCvtNativeToIEEEFloat(tif, n, fp) +#define TIFFCvtNativeToIEEEDouble(tif, n, dp) +#else +extern void TIFFCvtNativeToIEEEFloat(TIFF*, uint32, float*); +extern void TIFFCvtNativeToIEEEDouble(TIFF*, uint32, double*); +#endif + +static int TIFFWriteNormalTag(TIFF*, TIFFDirEntry*, const TIFFFieldInfo*); +static void TIFFSetupShortLong(TIFF*, ttag_t, TIFFDirEntry*, uint32); +static int TIFFSetupShortPair(TIFF*, ttag_t, TIFFDirEntry*); +static int TIFFWritePerSampleShorts(TIFF*, ttag_t, TIFFDirEntry*); +static int TIFFWritePerSampleAnys(TIFF*, TIFFDataType, ttag_t, TIFFDirEntry*); +static int TIFFWriteShortTable(TIFF*, ttag_t, TIFFDirEntry*, uint32, uint16**); +static int TIFFWriteShortArray(TIFF*, + TIFFDataType, ttag_t, TIFFDirEntry*, uint32, uint16*); +static int TIFFWriteLongArray(TIFF *, + TIFFDataType, ttag_t, TIFFDirEntry*, uint32, uint32*); +static int TIFFWriteRationalArray(TIFF *, + TIFFDataType, ttag_t, TIFFDirEntry*, uint32, float*); +static int TIFFWriteFloatArray(TIFF *, + TIFFDataType, ttag_t, TIFFDirEntry*, uint32, float*); +static int TIFFWriteDoubleArray(TIFF *, + TIFFDataType, ttag_t, TIFFDirEntry*, uint32, double*); +static int TIFFWriteByteArray(TIFF*, TIFFDirEntry*, char*); +static int TIFFWriteAnyArray(TIFF*, + TIFFDataType, ttag_t, TIFFDirEntry*, uint32, double*); +#ifdef COLORIMETRY_SUPPORT +static int TIFFWriteTransferFunction(TIFF*, TIFFDirEntry*); +#endif +#ifdef CMYK_SUPPORT +static int TIFFWriteInkNames(TIFF*, TIFFDirEntry*); +#endif +static int TIFFWriteData(TIFF*, TIFFDirEntry*, char*); +static int TIFFLinkDirectory(TIFF*); + +#define WriteRationalPair(type, tag1, v1, tag2, v2) { \ + if (!TIFFWriteRational(tif, type, tag1, dir, v1)) \ + goto bad; \ + if (!TIFFWriteRational(tif, type, tag2, dir+1, v2)) \ + goto bad; \ + dir++; \ +} +#define TIFFWriteRational(tif, type, tag, dir, v) \ + TIFFWriteRationalArray((tif), (type), (tag), (dir), 1, &(v)) +#ifndef TIFFWriteRational +static int TIFFWriteRational(TIFF*, + TIFFDataType, ttag_t, TIFFDirEntry*, float); +#endif + +/* + * Write the contents of the current directory + * to the specified file. This routine doesn't + * handle overwriting a directory with auxiliary + * storage that's been changed. + */ +int +TIFFWriteDirectory(TIFF* tif) +{ + uint16 dircount; + toff_t diroff; + ttag_t tag; + uint32 nfields; + tsize_t dirsize; + char* data; + TIFFDirEntry* dir; + TIFFDirectory* td; + u_long b, fields[FIELD_SETLONGS]; + int fi, nfi; + + if (tif->tif_mode == O_RDONLY) + return (1); + /* + * Clear write state so that subsequent images with + * different characteristics get the right buffers + * setup for them. + */ + if (tif->tif_flags & TIFF_POSTENCODE) { + tif->tif_flags &= ~TIFF_POSTENCODE; + if (!(*tif->tif_postencode)(tif)) { + TIFFError(tif->tif_name, + "Error post-encoding before directory write"); + return (0); + } + } + (*tif->tif_close)(tif); /* shutdown encoder */ + /* + * Flush any data that might have been written + * by the compression close+cleanup routines. + */ + if (tif->tif_rawcc > 0 && !TIFFFlushData1(tif)) { + TIFFError(tif->tif_name, + "Error flushing data before directory write"); + return (0); + } + if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { + _TIFFfree(tif->tif_rawdata); + tif->tif_rawdata = NULL; + tif->tif_rawcc = 0; + tif->tif_rawdatasize = 0; + } + tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP); + + td = &tif->tif_dir; + /* + * Size the directory so that we can calculate + * offsets for the data items that aren't kept + * in-place in each field. + */ + nfields = 0; + for (b = 0; b <= FIELD_LAST; b++) + if (TIFFFieldSet(tif, b)) + nfields += (b < FIELD_SUBFILETYPE ? 2 : 1); + dirsize = nfields * sizeof (TIFFDirEntry); + data = (char*) _TIFFmalloc(dirsize); + if (data == NULL) { + TIFFError(tif->tif_name, + "Cannot write directory, out of space"); + return (0); + } + /* + * Directory hasn't been placed yet, put + * it at the end of the file and link it + * into the existing directory structure. + */ + if (tif->tif_diroff == 0 && !TIFFLinkDirectory(tif)) + goto bad; + tif->tif_dataoff = (toff_t)( + tif->tif_diroff + sizeof (uint16) + dirsize + sizeof (toff_t)); + if (tif->tif_dataoff & 1) + tif->tif_dataoff++; + (void) TIFFSeekFile(tif, tif->tif_dataoff, SEEK_SET); + tif->tif_curdir++; + dir = (TIFFDirEntry*) data; + /* + * Setup external form of directory + * entries and write data items. + */ + _TIFFmemcpy(fields, td->td_fieldsset, sizeof (fields)); + /* + * Write out ExtraSamples tag only if + * extra samples are present in the data. + */ + if (FieldSet(fields, FIELD_EXTRASAMPLES) && !td->td_extrasamples) { + ResetFieldBit(fields, FIELD_EXTRASAMPLES); + nfields--; + dirsize -= sizeof (TIFFDirEntry); + } /*XXX*/ + for (fi = 0, nfi = tif->tif_nfields; nfi > 0; nfi--, fi++) { + const TIFFFieldInfo* fip = tif->tif_fieldinfo[fi]; + if (!FieldSet(fields, fip->field_bit)) + continue; + switch (fip->field_bit) { + case FIELD_STRIPOFFSETS: + /* + * We use one field bit for both strip and tile + * offsets, and so must be careful in selecting + * the appropriate field descriptor (so that tags + * are written in sorted order). + */ + tag = isTiled(tif) ? + TIFFTAG_TILEOFFSETS : TIFFTAG_STRIPOFFSETS; + if (tag != fip->field_tag) + continue; + if (!TIFFWriteLongArray(tif, TIFF_LONG, tag, dir, + (uint32) td->td_nstrips, td->td_stripoffset)) + goto bad; + break; + case FIELD_STRIPBYTECOUNTS: + /* + * We use one field bit for both strip and tile + * byte counts, and so must be careful in selecting + * the appropriate field descriptor (so that tags + * are written in sorted order). + */ + tag = isTiled(tif) ? + TIFFTAG_TILEBYTECOUNTS : TIFFTAG_STRIPBYTECOUNTS; + if (tag != fip->field_tag) + continue; + if (!TIFFWriteLongArray(tif, TIFF_LONG, tag, dir, + (uint32) td->td_nstrips, td->td_stripbytecount)) + goto bad; + break; + case FIELD_ROWSPERSTRIP: + TIFFSetupShortLong(tif, TIFFTAG_ROWSPERSTRIP, + dir, td->td_rowsperstrip); + break; + case FIELD_COLORMAP: + if (!TIFFWriteShortTable(tif, TIFFTAG_COLORMAP, dir, + 3, td->td_colormap)) + goto bad; + break; + case FIELD_IMAGEDIMENSIONS: + TIFFSetupShortLong(tif, TIFFTAG_IMAGEWIDTH, + dir++, td->td_imagewidth); + TIFFSetupShortLong(tif, TIFFTAG_IMAGELENGTH, + dir, td->td_imagelength); + break; + case FIELD_TILEDIMENSIONS: + TIFFSetupShortLong(tif, TIFFTAG_TILEWIDTH, + dir++, td->td_tilewidth); + TIFFSetupShortLong(tif, TIFFTAG_TILELENGTH, + dir, td->td_tilelength); + break; + case FIELD_POSITION: + WriteRationalPair(TIFF_RATIONAL, + TIFFTAG_XPOSITION, td->td_xposition, + TIFFTAG_YPOSITION, td->td_yposition); + break; + case FIELD_RESOLUTION: + WriteRationalPair(TIFF_RATIONAL, + TIFFTAG_XRESOLUTION, td->td_xresolution, + TIFFTAG_YRESOLUTION, td->td_yresolution); + break; + case FIELD_BITSPERSAMPLE: + case FIELD_MINSAMPLEVALUE: + case FIELD_MAXSAMPLEVALUE: + case FIELD_SAMPLEFORMAT: + if (!TIFFWritePerSampleShorts(tif, fip->field_tag, dir)) + goto bad; + break; + case FIELD_SMINSAMPLEVALUE: + case FIELD_SMAXSAMPLEVALUE: + if (!TIFFWritePerSampleAnys(tif, + _TIFFSampleToTagType(tif), fip->field_tag, dir)) + goto bad; + break; + case FIELD_PAGENUMBER: + case FIELD_HALFTONEHINTS: +#ifdef YCBCR_SUPPORT + case FIELD_YCBCRSUBSAMPLING: +#endif +#ifdef CMYK_SUPPORT + case FIELD_DOTRANGE: +#endif + if (!TIFFSetupShortPair(tif, fip->field_tag, dir)) + goto bad; + break; +#ifdef CMYK_SUPPORT + case FIELD_INKNAMES: + if (!TIFFWriteInkNames(tif, dir)) + goto bad; + break; +#endif +#ifdef COLORIMETRY_SUPPORT + case FIELD_TRANSFERFUNCTION: + if (!TIFFWriteTransferFunction(tif, dir)) + goto bad; + break; +#endif +#if SUBIFD_SUPPORT + case FIELD_SUBIFD: + if (!TIFFWriteNormalTag(tif, dir, fip)) + goto bad; + /* + * Total hack: if this directory includes a SubIFD + * tag then force the next directories to be + * written as ``sub directories'' of this one. This + * is used to write things like thumbnails and + * image masks that one wants to keep out of the + * normal directory linkage access mechanism. + */ + if (dir->tdir_count > 0) { + tif->tif_flags |= TIFF_INSUBIFD; + tif->tif_nsubifd = (uint16) dir->tdir_count; + if (dir->tdir_count > 1) + tif->tif_subifdoff = dir->tdir_offset; + else + tif->tif_subifdoff = (uint32)( + tif->tif_diroff + + sizeof (uint16) + + ((char*)&dir->tdir_offset-data)); + } + break; +#endif + default: + if (!TIFFWriteNormalTag(tif, dir, fip)) + goto bad; + break; + } + dir++; + ResetFieldBit(fields, fip->field_bit); + } + /* + * Write directory. + */ + dircount = (uint16) nfields; + diroff = (uint32) tif->tif_nextdiroff; + if (tif->tif_flags & TIFF_SWAB) { + /* + * The file's byte order is opposite to the + * native machine architecture. We overwrite + * the directory information with impunity + * because it'll be released below after we + * write it to the file. Note that all the + * other tag construction routines assume that + * we do this byte-swapping; i.e. they only + * byte-swap indirect data. + */ + for (dir = (TIFFDirEntry*) data; dircount; dir++, dircount--) { + TIFFSwabArrayOfShort(&dir->tdir_tag, 2); + TIFFSwabArrayOfLong(&dir->tdir_count, 2); + } + dircount = (uint16) nfields; + TIFFSwabShort(&dircount); + TIFFSwabLong(&diroff); + } + (void) TIFFSeekFile(tif, tif->tif_diroff, SEEK_SET); + if (!WriteOK(tif, &dircount, sizeof (dircount))) { + TIFFError(tif->tif_name, "Error writing directory count"); + goto bad; + } + if (!WriteOK(tif, data, dirsize)) { + TIFFError(tif->tif_name, "Error writing directory contents"); + goto bad; + } + if (!WriteOK(tif, &diroff, sizeof (diroff))) { + TIFFError(tif->tif_name, "Error writing directory link"); + goto bad; + } + TIFFFreeDirectory(tif); + _TIFFfree(data); + tif->tif_flags &= ~TIFF_DIRTYDIRECT; + (*tif->tif_cleanup)(tif); + + /* + * Reset directory-related state for subsequent + * directories. + */ + TIFFCreateDirectory(tif); + return (1); +bad: + _TIFFfree(data); + return (0); +} +#undef WriteRationalPair + +/* + * Process tags that are not special cased. + */ +static int +TIFFWriteNormalTag(TIFF* tif, TIFFDirEntry* dir, const TIFFFieldInfo* fip) +{ + u_short wc = (u_short) fip->field_writecount; + uint32 wc2; + + dir->tdir_tag = (uint16) fip->field_tag; + dir->tdir_type = (u_short) fip->field_type; + dir->tdir_count = wc; +#define WRITEF(x,y) x(tif, fip->field_type, fip->field_tag, dir, wc, y) + switch (fip->field_type) { + case TIFF_SHORT: + case TIFF_SSHORT: + if (wc > 1) { + uint16* wp; + if (wc == (u_short) TIFF_VARIABLE) + TIFFGetField(tif, fip->field_tag, &wc, &wp); + else + TIFFGetField(tif, fip->field_tag, &wp); + if (!WRITEF(TIFFWriteShortArray, wp)) + return (0); + } else { + uint16 sv; + TIFFGetField(tif, fip->field_tag, &sv); + dir->tdir_offset = + TIFFInsertData(tif, dir->tdir_type, sv); + } + break; + case TIFF_LONG: + case TIFF_SLONG: + if (wc > 1) { + uint32* lp; + if (wc == (u_short) TIFF_VARIABLE) + TIFFGetField(tif, fip->field_tag, &wc, &lp); + else + TIFFGetField(tif, fip->field_tag, &lp); + if (!WRITEF(TIFFWriteLongArray, lp)) + return (0); + } else { + /* XXX handle LONG->SHORT conversion */ + TIFFGetField(tif, fip->field_tag, &dir->tdir_offset); + } + break; + case TIFF_RATIONAL: + case TIFF_SRATIONAL: + if (wc > 1) { + float* fp; + if (wc == (u_short) TIFF_VARIABLE) + TIFFGetField(tif, fip->field_tag, &wc, &fp); + else + TIFFGetField(tif, fip->field_tag, &fp); + if (!WRITEF(TIFFWriteRationalArray, fp)) + return (0); + } else { + float fv; + TIFFGetField(tif, fip->field_tag, &fv); + if (!WRITEF(TIFFWriteRationalArray, &fv)) + return (0); + } + break; + case TIFF_FLOAT: + if (wc > 1) { + float* fp; + if (wc == (u_short) TIFF_VARIABLE) + TIFFGetField(tif, fip->field_tag, &wc, &fp); + else + TIFFGetField(tif, fip->field_tag, &fp); + if (!WRITEF(TIFFWriteFloatArray, fp)) + return (0); + } else { + float fv; + TIFFGetField(tif, fip->field_tag, &fv); + if (!WRITEF(TIFFWriteFloatArray, &fv)) + return (0); + } + break; + case TIFF_DOUBLE: + if (wc > 1) { + double* dp; + if (wc == (u_short) TIFF_VARIABLE) + TIFFGetField(tif, fip->field_tag, &wc, &dp); + else + TIFFGetField(tif, fip->field_tag, &dp); + if (!WRITEF(TIFFWriteDoubleArray, dp)) + return (0); + } else { + double dv; + TIFFGetField(tif, fip->field_tag, &dv); + if (!WRITEF(TIFFWriteDoubleArray, &dv)) + return (0); + } + break; + case TIFF_ASCII: + { char* cp; + TIFFGetField(tif, fip->field_tag, &cp); + dir->tdir_count = (uint32) (strlen(cp) + 1); + if (!TIFFWriteByteArray(tif, dir, cp)) + return (0); + } + break; + + /* added based on patch request from MARTIN.MCBRIDE.MM@agfa.co.uk, + correctness not verified (FW, 99/08) */ + case TIFF_BYTE: + case TIFF_SBYTE: + if (wc > 1) { + char* cp; + if (wc == (u_short) TIFF_VARIABLE) { + TIFFGetField(tif, fip->field_tag, &wc, &cp); + dir->tdir_count = wc; + } else if (wc == (u_short) TIFF_VARIABLE2) { + TIFFGetField(tif, fip->field_tag, &wc2, &cp); + dir->tdir_count = wc2; + } else + TIFFGetField(tif, fip->field_tag, &cp); + if (!TIFFWriteByteArray(tif, dir, cp)) + return (0); + } else { + char cv; + TIFFGetField(tif, fip->field_tag, &cv); + if (!TIFFWriteByteArray(tif, dir, &cv)) + return (0); + } + break; + + case TIFF_UNDEFINED: + { char* cp; + if (wc == (u_short) TIFF_VARIABLE) { + TIFFGetField(tif, fip->field_tag, &wc, &cp); + dir->tdir_count = wc; + } else if (wc == (u_short) TIFF_VARIABLE2) { + TIFFGetField(tif, fip->field_tag, &wc2, &cp); + dir->tdir_count = wc2; + } else + TIFFGetField(tif, fip->field_tag, &cp); + if (!TIFFWriteByteArray(tif, dir, cp)) + return (0); + } + break; + + case TIFF_NOTYPE: + break; + } + return (1); +} +#undef WRITEF + +/* + * Setup a directory entry with either a SHORT + * or LONG type according to the value. + */ +static void +TIFFSetupShortLong(TIFF* tif, ttag_t tag, TIFFDirEntry* dir, uint32 v) +{ + dir->tdir_tag = (uint16) tag; + dir->tdir_count = 1; + if (v > 0xffffL) { + dir->tdir_type = (short) TIFF_LONG; + dir->tdir_offset = v; + } else { + dir->tdir_type = (short) TIFF_SHORT; + dir->tdir_offset = TIFFInsertData(tif, (int) TIFF_SHORT, v); + } +} +#undef MakeShortDirent + +#ifndef TIFFWriteRational +/* + * Setup a RATIONAL directory entry and + * write the associated indirect value. + */ +static int +TIFFWriteRational(TIFF* tif, + TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, float v) +{ + return (TIFFWriteRationalArray(tif, type, tag, dir, 1, &v)); +} +#endif + +#define NITEMS(x) (sizeof (x) / sizeof (x[0])) +/* + * Setup a directory entry that references a + * samples/pixel array of SHORT values and + * (potentially) write the associated indirect + * values. + */ +static int +TIFFWritePerSampleShorts(TIFF* tif, ttag_t tag, TIFFDirEntry* dir) +{ + uint16 buf[10], v; + uint16* w = buf; + int i, status, samples = tif->tif_dir.td_samplesperpixel; + + if (samples > NITEMS(buf)) + w = (uint16*) _TIFFmalloc(samples * sizeof (uint16)); + TIFFGetField(tif, tag, &v); + for (i = 0; i < samples; i++) + w[i] = v; + status = TIFFWriteShortArray(tif, TIFF_SHORT, tag, dir, samples, w); + if (w != buf) + _TIFFfree((char*) w); + return (status); +} + +/* + * Setup a directory entry that references a samples/pixel array of ``type'' + * values and (potentially) write the associated indirect values. The source + * data from TIFFGetField() for the specified tag must be returned as double. + */ +static int +TIFFWritePerSampleAnys(TIFF* tif, + TIFFDataType type, ttag_t tag, TIFFDirEntry* dir) +{ + double buf[10], v; + double* w = buf; + int i, status; + int samples = (int) tif->tif_dir.td_samplesperpixel; + + if (samples > NITEMS(buf)) + w = (double*) _TIFFmalloc(samples * sizeof (double)); + TIFFGetField(tif, tag, &v); + for (i = 0; i < samples; i++) + w[i] = v; + status = TIFFWriteAnyArray(tif, type, tag, dir, samples, w); + if (w != buf) + _TIFFfree(w); + return (status); +} +#undef NITEMS + +/* + * Setup a pair of shorts that are returned by + * value, rather than as a reference to an array. + */ +static int +TIFFSetupShortPair(TIFF* tif, ttag_t tag, TIFFDirEntry* dir) +{ + uint16 v[2]; + + TIFFGetField(tif, tag, &v[0], &v[1]); + return (TIFFWriteShortArray(tif, TIFF_SHORT, tag, dir, 2, v)); +} + +/* + * Setup a directory entry for an NxM table of shorts, + * where M is known to be 2**bitspersample, and write + * the associated indirect data. + */ +static int +TIFFWriteShortTable(TIFF* tif, + ttag_t tag, TIFFDirEntry* dir, uint32 n, uint16** table) +{ + uint32 i, off; + + dir->tdir_tag = (uint16) tag; + dir->tdir_type = (short) TIFF_SHORT; + /* XXX -- yech, fool TIFFWriteData */ + dir->tdir_count = (uint32) (1L<tif_dir.td_bitspersample); + off = tif->tif_dataoff; + for (i = 0; i < n; i++) + if (!TIFFWriteData(tif, dir, (char *)table[i])) + return (0); + dir->tdir_count *= n; + dir->tdir_offset = off; + return (1); +} + +/* + * Write/copy data associated with an ASCII or opaque tag value. + */ +static int +TIFFWriteByteArray(TIFF* tif, TIFFDirEntry* dir, char* cp) +{ + if (dir->tdir_count > 4) { + if (!TIFFWriteData(tif, dir, cp)) + return (0); + } else + _TIFFmemcpy(&dir->tdir_offset, cp, dir->tdir_count); + return (1); +} + +/* + * Setup a directory entry of an array of SHORT + * or SSHORT and write the associated indirect values. + */ +static int +TIFFWriteShortArray(TIFF* tif, + TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, uint32 n, uint16* v) +{ + dir->tdir_tag = (uint16) tag; + dir->tdir_type = (short) type; + dir->tdir_count = n; + if (n <= 2) { + if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { + dir->tdir_offset = (uint32) ((long) v[0] << 16); + if (n == 2) + dir->tdir_offset |= v[1] & 0xffff; + } else { + dir->tdir_offset = v[0] & 0xffff; + if (n == 2) + dir->tdir_offset |= (long) v[1] << 16; + } + return (1); + } else + return (TIFFWriteData(tif, dir, (char*) v)); +} + +/* + * Setup a directory entry of an array of LONG + * or SLONG and write the associated indirect values. + */ +static int +TIFFWriteLongArray(TIFF* tif, + TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, uint32 n, uint32* v) +{ + dir->tdir_tag = (uint16) tag; + dir->tdir_type = (short) type; + dir->tdir_count = n; + if (n == 1) { + dir->tdir_offset = v[0]; + return (1); + } else + return (TIFFWriteData(tif, dir, (char*) v)); +} + +/* + * Setup a directory entry of an array of RATIONAL + * or SRATIONAL and write the associated indirect values. + */ +static int +TIFFWriteRationalArray(TIFF* tif, + TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, uint32 n, float* v) +{ + uint32 i; + uint32* t; + int status; + + dir->tdir_tag = (uint16) tag; + dir->tdir_type = (short) type; + dir->tdir_count = n; + t = (uint32*) _TIFFmalloc(2*n * sizeof (uint32)); + for (i = 0; i < n; i++) { + float fv = v[i]; + int sign = 1; + uint32 den; + + if (fv < 0) { + if (type == TIFF_RATIONAL) { + TIFFWarning(tif->tif_name, + "\"%s\": Information lost writing value (%g) as (unsigned) RATIONAL", + _TIFFFieldWithTag(tif,tag)->field_name, fv); + fv = 0; + } else + fv = -fv, sign = -1; + } + den = 1L; + if (fv > 0) { + while (fv < 1L<<(31-3) && den < 1L<<(31-3)) + fv *= 1<<3, den *= 1L<<3; + } + t[2*i+0] = (uint32) (sign * (fv + 0.5)); + t[2*i+1] = den; + } + status = TIFFWriteData(tif, dir, (char *)t); + _TIFFfree((char*) t); + return (status); +} + +static int +TIFFWriteFloatArray(TIFF* tif, + TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, uint32 n, float* v) +{ + dir->tdir_tag = (uint16) tag; + dir->tdir_type = (short) type; + dir->tdir_count = n; + TIFFCvtNativeToIEEEFloat(tif, n, v); + if (n == 1) { + dir->tdir_offset = *(uint32*) &v[0]; + return (1); + } else + return (TIFFWriteData(tif, dir, (char*) v)); +} + +static int +TIFFWriteDoubleArray(TIFF* tif, + TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, uint32 n, double* v) +{ + dir->tdir_tag = (uint16) tag; + dir->tdir_type = (short) type; + dir->tdir_count = n; + TIFFCvtNativeToIEEEDouble(tif, n, v); + return (TIFFWriteData(tif, dir, (char*) v)); +} + +/* + * Write an array of ``type'' values for a specified tag (i.e. this is a tag + * which is allowed to have different types, e.g. SMaxSampleType). + * Internally the data values are represented as double since a double can + * hold any of the TIFF tag types (yes, this should really be an abstract + * type tany_t for portability). The data is converted into the specified + * type in a temporary buffer and then handed off to the appropriate array + * writer. + */ +static int +TIFFWriteAnyArray(TIFF* tif, + TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, uint32 n, double* v) +{ + char buf[10 * sizeof(double)]; + char* w = buf; + int i, status = 0; + + if (n * tiffDataWidth[type] > sizeof buf) + w = (char*) _TIFFmalloc(n * tiffDataWidth[type]); + switch (type) { + case TIFF_BYTE: + { uint8* bp = (uint8*) w; + for (i = 0; i < (int) n; i++) + bp[i] = (uint8) v[i]; + dir->tdir_tag = (uint16) tag; + dir->tdir_type = (short) type; + dir->tdir_count = n; + if (!TIFFWriteByteArray(tif, dir, (char*) bp)) + goto out; + } + break; + case TIFF_SBYTE: + { int8* bp = (int8*) w; + for (i = 0; i < (int) n; i++) + bp[i] = (int8) v[i]; + dir->tdir_tag = (uint16) tag; + dir->tdir_type = (short) type; + dir->tdir_count = n; + if (!TIFFWriteByteArray(tif, dir, (char*) bp)) + goto out; + } + break; + case TIFF_SHORT: + { uint16* bp = (uint16*) w; + for (i = 0; i < (int) n; i++) + bp[i] = (uint16) v[i]; + if (!TIFFWriteShortArray(tif, type, tag, dir, n, (uint16*)bp)) + goto out; + } + break; + case TIFF_SSHORT: + { int16* bp = (int16*) w; + for (i = 0; i < (int) n; i++) + bp[i] = (int16) v[i]; + if (!TIFFWriteShortArray(tif, type, tag, dir, n, (uint16*)bp)) + goto out; + } + break; + case TIFF_LONG: + { uint32* bp = (uint32*) w; + for (i = 0; i < (int) n; i++) + bp[i] = (uint32) v[i]; + if (!TIFFWriteLongArray(tif, type, tag, dir, n, bp)) + goto out; + } + break; + case TIFF_SLONG: + { int32* bp = (int32*) w; + for (i = 0; i < (int) n; i++) + bp[i] = (int32) v[i]; + if (!TIFFWriteLongArray(tif, type, tag, dir, n, (uint32*) bp)) + goto out; + } + break; + case TIFF_FLOAT: + { float* bp = (float*) w; + for (i = 0; i < (int) n; i++) + bp[i] = (float) v[i]; + if (!TIFFWriteFloatArray(tif, type, tag, dir, n, bp)) + goto out; + } + break; + case TIFF_DOUBLE: + return (TIFFWriteDoubleArray(tif, type, tag, dir, n, v)); + default: + /* TIFF_NOTYPE */ + /* TIFF_ASCII */ + /* TIFF_UNDEFINED */ + /* TIFF_RATIONAL */ + /* TIFF_SRATIONAL */ + goto out; + } + status = 1; + out: + if (w != buf) + _TIFFfree(w); + return (status); +} + +#ifdef COLORIMETRY_SUPPORT +static int +TIFFWriteTransferFunction(TIFF* tif, TIFFDirEntry* dir) +{ + TIFFDirectory* td = &tif->tif_dir; + tsize_t n = (1L<td_bitspersample) * sizeof (uint16); + uint16** tf = td->td_transferfunction; + int ncols; + + /* + * Check if the table can be written as a single column, + * or if it must be written as 3 columns. Note that we + * write a 3-column tag if there are 2 samples/pixel and + * a single column of data won't suffice--hmm. + */ + switch (td->td_samplesperpixel - td->td_extrasamples) { + default: if (_TIFFmemcmp(tf[0], tf[2], n)) { ncols = 3; break; } + case 2: if (_TIFFmemcmp(tf[0], tf[1], n)) { ncols = 3; break; } + case 1: case 0: ncols = 1; + } + return (TIFFWriteShortTable(tif, + TIFFTAG_TRANSFERFUNCTION, dir, ncols, tf)); +} +#endif + +#ifdef CMYK_SUPPORT +static int +TIFFWriteInkNames(TIFF* tif, TIFFDirEntry* dir) +{ + TIFFDirectory* td = &tif->tif_dir; + + dir->tdir_tag = TIFFTAG_INKNAMES; + dir->tdir_type = (short) TIFF_ASCII; + dir->tdir_count = td->td_inknameslen; + return (TIFFWriteByteArray(tif, dir, td->td_inknames)); +} +#endif + +/* + * Write a contiguous directory item. + */ +static int +TIFFWriteData(TIFF* tif, TIFFDirEntry* dir, char* cp) +{ + tsize_t cc; + + if (tif->tif_flags & TIFF_SWAB) { + switch (dir->tdir_type) { + case TIFF_SHORT: + case TIFF_SSHORT: + TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); + break; + case TIFF_LONG: + case TIFF_SLONG: + case TIFF_FLOAT: + TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); + break; + case TIFF_RATIONAL: + case TIFF_SRATIONAL: + TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); + break; + case TIFF_DOUBLE: + TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); + break; + } + } + dir->tdir_offset = tif->tif_dataoff; + cc = dir->tdir_count * tiffDataWidth[dir->tdir_type]; + if (SeekOK(tif, dir->tdir_offset) && + WriteOK(tif, cp, cc)) { + tif->tif_dataoff += (cc + 1) & ~1; + return (1); + } + TIFFError(tif->tif_name, "Error writing data for field \"%s\"", + _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); + return (0); +} + +/* + * Similar to TIFFWriteDirectory(), but if the directory has already + * been written once, it is relocated to the end of the file, in case it + * has changed in size. Note that this will result in the loss of the + * previously used directory space. + */ + +int +TIFFRewriteDirectory( TIFF *tif ) +{ + static const char module[] = "TIFFRewriteDirectory"; + + /* We don't need to do anything special if it hasn't been written. */ + if( tif->tif_diroff == 0 ) + return TIFFWriteDirectory( tif ); + + /* + ** Find and zero the pointer to this directory, so that TIFFLinkDirectory + ** will cause it to be added after this directories current pre-link. + */ + + /* Is it the first directory in the file? */ + if (tif->tif_header.tiff_diroff == tif->tif_diroff) + { + tif->tif_header.tiff_diroff = 0; + tif->tif_diroff = 0; + +#define HDROFF(f) ((toff_t) &(((TIFFHeader*) 0)->f)) + TIFFSeekFile(tif, HDROFF(tiff_diroff), SEEK_SET); + if (!WriteOK(tif, &(tif->tif_header.tiff_diroff), + sizeof (tif->tif_diroff))) + { + TIFFError(tif->tif_name, "Error updating TIFF header"); + return (0); + } + } + else + { + toff_t nextdir, off; + + nextdir = tif->tif_header.tiff_diroff; + do { + uint16 dircount; + + if (!SeekOK(tif, nextdir) || + !ReadOK(tif, &dircount, sizeof (dircount))) { + TIFFError(module, "Error fetching directory count"); + return (0); + } + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabShort(&dircount); + (void) TIFFSeekFile(tif, + dircount * sizeof (TIFFDirEntry), SEEK_CUR); + if (!ReadOK(tif, &nextdir, sizeof (nextdir))) { + TIFFError(module, "Error fetching directory link"); + return (0); + } + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabLong(&nextdir); + } while (nextdir != tif->tif_diroff && nextdir != 0); + off = TIFFSeekFile(tif, 0, SEEK_CUR); /* get current offset */ + (void) TIFFSeekFile(tif, off - (toff_t)sizeof(nextdir), SEEK_SET); + tif->tif_diroff = 0; + if (!WriteOK(tif, &(tif->tif_diroff), sizeof (nextdir))) { + TIFFError(module, "Error writing directory link"); + return (0); + } + } + + /* + ** Now use TIFFWriteDirectory() normally. + */ + + return TIFFWriteDirectory( tif ); +} + + +/* + * Link the current directory into the + * directory chain for the file. + */ +static int +TIFFLinkDirectory(TIFF* tif) +{ + static const char module[] = "TIFFLinkDirectory"; + toff_t nextdir; + toff_t diroff, off; + + tif->tif_diroff = (TIFFSeekFile(tif, (toff_t) 0, SEEK_END)+1) &~ 1; + diroff = tif->tif_diroff; + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabLong(&diroff); +#if SUBIFD_SUPPORT + if (tif->tif_flags & TIFF_INSUBIFD) { + (void) TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET); + if (!WriteOK(tif, &diroff, sizeof (diroff))) { + TIFFError(module, + "%s: Error writing SubIFD directory link", + tif->tif_name); + return (0); + } + /* + * Advance to the next SubIFD or, if this is + * the last one configured, revert back to the + * normal directory linkage. + */ + if (--tif->tif_nsubifd) + tif->tif_subifdoff += sizeof (diroff); + else + tif->tif_flags &= ~TIFF_INSUBIFD; + return (1); + } +#endif + if (tif->tif_header.tiff_diroff == 0) { + /* + * First directory, overwrite offset in header. + */ + tif->tif_header.tiff_diroff = tif->tif_diroff; +#define HDROFF(f) ((toff_t) &(((TIFFHeader*) 0)->f)) + (void) TIFFSeekFile(tif, HDROFF(tiff_diroff), SEEK_SET); + if (!WriteOK(tif, &diroff, sizeof (diroff))) { + TIFFError(tif->tif_name, "Error writing TIFF header"); + return (0); + } + return (1); + } + /* + * Not the first directory, search to the last and append. + */ + nextdir = tif->tif_header.tiff_diroff; + do { + uint16 dircount; + + if (!SeekOK(tif, nextdir) || + !ReadOK(tif, &dircount, sizeof (dircount))) { + TIFFError(module, "Error fetching directory count"); + return (0); + } + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabShort(&dircount); + (void) TIFFSeekFile(tif, + dircount * sizeof (TIFFDirEntry), SEEK_CUR); + if (!ReadOK(tif, &nextdir, sizeof (nextdir))) { + TIFFError(module, "Error fetching directory link"); + return (0); + } + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabLong(&nextdir); + } while (nextdir != 0); + off = TIFFSeekFile(tif, 0, SEEK_CUR); /* get current offset */ + (void) TIFFSeekFile(tif, off - (toff_t)sizeof(nextdir), SEEK_SET); + if (!WriteOK(tif, &diroff, sizeof (diroff))) { + TIFFError(module, "Error writing directory link"); + return (0); + } + return (1); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_dumpmode.c b/SlnkDWFImpl/CxImage/tiff/tif_dumpmode.c new file mode 100644 index 0000000..0b2f0db --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_dumpmode.c @@ -0,0 +1,118 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_dumpmode.c,v 1.2 2000/01/28 15:08:10 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * "Null" Compression Algorithm Support. + */ +#include "tiffiop.h" +#include + +/* + * Encode a hunk of pixels. + */ +static int +DumpModeEncode(TIFF* tif, tidata_t pp, tsize_t cc, tsample_t s) +{ + (void) s; + while (cc > 0) { + tsize_t n; + + n = cc; + if (tif->tif_rawcc + n > tif->tif_rawdatasize) + n = tif->tif_rawdatasize - tif->tif_rawcc; + + assert( n > 0 ); + + /* + * Avoid copy if client has setup raw + * data buffer to avoid extra copy. + */ + if (tif->tif_rawcp != pp) + _TIFFmemcpy(tif->tif_rawcp, pp, n); + tif->tif_rawcp += n; + tif->tif_rawcc += n; + pp += n; + cc -= n; + if (tif->tif_rawcc >= tif->tif_rawdatasize && + !TIFFFlushData1(tif)) + return (-1); + } + return (1); +} + +/* + * Decode a hunk of pixels. + */ +static int +DumpModeDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s) +{ + (void) s; + if (tif->tif_rawcc < cc) { + TIFFError(tif->tif_name, + "DumpModeDecode: Not enough data for scanline %d", + tif->tif_row); + return (0); + } + /* + * Avoid copy if client has setup raw + * data buffer to avoid extra copy. + */ + if (tif->tif_rawcp != buf) + _TIFFmemcpy(buf, tif->tif_rawcp, cc); + tif->tif_rawcp += cc; + tif->tif_rawcc -= cc; + return (1); +} + +/* + * Seek forwards nrows in the current strip. + */ +static int +DumpModeSeek(TIFF* tif, uint32 nrows) +{ + tif->tif_rawcp += nrows * tif->tif_scanlinesize; + tif->tif_rawcc -= nrows * tif->tif_scanlinesize; + return (1); +} + +/* + * Initialize dump mode. + */ +int +TIFFInitDumpMode(TIFF* tif, int scheme) +{ + (void) scheme; + tif->tif_decoderow = DumpModeDecode; + tif->tif_decodestrip = DumpModeDecode; + tif->tif_decodetile = DumpModeDecode; + tif->tif_encoderow = DumpModeEncode; + tif->tif_encodestrip = DumpModeEncode; + tif->tif_encodetile = DumpModeEncode; + tif->tif_seek = DumpModeSeek; + return (1); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_error.c b/SlnkDWFImpl/CxImage/tiff/tif_error.c new file mode 100644 index 0000000..4f407a2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_error.c @@ -0,0 +1,49 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_error.c,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + */ +#include "tiffiop.h" + +TIFFErrorHandler +TIFFSetErrorHandler(TIFFErrorHandler handler) +{ + TIFFErrorHandler prev = _TIFFerrorHandler; + _TIFFerrorHandler = handler; + return (prev); +} + +void +TIFFError(const char* module, const char* fmt, ...) +{ + if (_TIFFerrorHandler) { + va_list ap; + va_start(ap, fmt); + (*_TIFFerrorHandler)(module, fmt, ap); + va_end(ap); + } +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_fax3.c b/SlnkDWFImpl/CxImage/tiff/tif_fax3.c new file mode 100644 index 0000000..18055f0 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_fax3.c @@ -0,0 +1,1538 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_fax3.c,v 1.15 2001/09/09 16:10:37 warmerda Exp $ */ + +/* + * Copyright (c) 1990-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef CCITT_SUPPORT +/* + * TIFF Library. + * + * CCITT Group 3 (T.4) and Group 4 (T.6) Compression Support. + * + * This file contains support for decoding and encoding TIFF + * compression algorithms 2, 3, 4, and 32771. + * + * Decoder support is derived, with permission, from the code + * in Frank Cringle's viewfax program; + * Copyright (C) 1990, 1995 Frank D. Cringle. + */ +#include "tif_fax3.h" +#define G3CODES +#include "t4.h" +#include +#include + +/* + * Compression+decompression state blocks are + * derived from this ``base state'' block. + */ +typedef struct { + int rw_mode; /* O_RDONLY for decode, else encode */ + int mode; /* operating mode */ + uint32 rowbytes; /* bytes in a decoded scanline */ + uint32 rowpixels; /* pixels in a scanline */ + + uint16 cleanfaxdata; /* CleanFaxData tag */ + uint32 badfaxrun; /* BadFaxRun tag */ + uint32 badfaxlines; /* BadFaxLines tag */ + uint32 groupoptions; /* Group 3/4 options tag */ + uint32 recvparams; /* encoded Class 2 session params */ + char* subaddress; /* subaddress string */ + uint32 recvtime; /* time spent receiving (secs) */ + TIFFVGetMethod vgetparent; /* super-class method */ + TIFFVSetMethod vsetparent; /* super-class method */ +} Fax3BaseState; +#define Fax3State(tif) ((Fax3BaseState*) (tif)->tif_data) + +typedef struct { + Fax3BaseState b; + const u_char* bitmap; /* bit reversal table */ + uint32 data; /* current i/o byte/word */ + int bit; /* current i/o bit in byte */ + int EOLcnt; /* count of EOL codes recognized */ + TIFFFaxFillFunc fill; /* fill routine */ + uint32* runs; /* b&w runs for current/previous row */ + uint32* refruns; /* runs for reference line */ + uint32* curruns; /* runs for current line */ +} Fax3DecodeState; +#define DecoderState(tif) ((Fax3DecodeState*) Fax3State(tif)) + +typedef enum { G3_1D, G3_2D } Ttag; +typedef struct { + Fax3BaseState b; + int data; /* current i/o byte */ + int bit; /* current i/o bit in byte */ + Ttag tag; /* encoding state */ + u_char* refline; /* reference line for 2d decoding */ + int k; /* #rows left that can be 2d encoded */ + int maxk; /* max #rows that can be 2d encoded */ +} Fax3EncodeState; +#define EncoderState(tif) ((Fax3EncodeState*) Fax3State(tif)) + +#define is2DEncoding(sp) \ + (sp->b.groupoptions & GROUP3OPT_2DENCODING) +#define isAligned(p,t) ((((u_long)(p)) & (sizeof (t)-1)) == 0) + +/* + * Group 3 and Group 4 Decoding. + */ + +/* + * These macros glue the TIFF library state to + * the state expected by Frank's decoder. + */ +#define DECLARE_STATE(tif, sp, mod) \ + static const char module[] = mod; \ + Fax3DecodeState* sp = DecoderState(tif); \ + int a0; /* reference element */ \ + int lastx = sp->b.rowpixels; /* last element in row */ \ + uint32 BitAcc; /* bit accumulator */ \ + int BitsAvail; /* # valid bits in BitAcc */ \ + int RunLength; /* length of current run */ \ + u_char* cp; /* next byte of input data */ \ + u_char* ep; /* end of input data */ \ + uint32* pa; /* place to stuff next run */ \ + uint32* thisrun; /* current row's run array */ \ + int EOLcnt; /* # EOL codes recognized */ \ + const u_char* bitmap = sp->bitmap; /* input data bit reverser */ \ + const TIFFFaxTabEnt* TabEnt +#define DECLARE_STATE_2D(tif, sp, mod) \ + DECLARE_STATE(tif, sp, mod); \ + int b1; /* next change on prev line */ \ + uint32* pb /* next run in reference line */\ +/* + * Load any state that may be changed during decoding. + */ +#define CACHE_STATE(tif, sp) do { \ + BitAcc = sp->data; \ + BitsAvail = sp->bit; \ + EOLcnt = sp->EOLcnt; \ + cp = (unsigned char*) tif->tif_rawcp; \ + ep = cp + tif->tif_rawcc; \ +} while (0) +/* + * Save state possibly changed during decoding. + */ +#define UNCACHE_STATE(tif, sp) do { \ + sp->bit = BitsAvail; \ + sp->data = BitAcc; \ + sp->EOLcnt = EOLcnt; \ + tif->tif_rawcc -= (tidata_t) cp - tif->tif_rawcp; \ + tif->tif_rawcp = (tidata_t) cp; \ +} while (0) + +/* + * Setup state for decoding a strip. + */ +static int +Fax3PreDecode(TIFF* tif, tsample_t s) +{ + Fax3DecodeState* sp = DecoderState(tif); + + (void) s; + assert(sp != NULL); + sp->bit = 0; /* force initial read */ + sp->data = 0; + sp->EOLcnt = 0; /* force initial scan for EOL */ + /* + * Decoder assumes lsb-to-msb bit order. Note that we select + * this here rather than in Fax3SetupState so that viewers can + * hold the image open, fiddle with the FillOrder tag value, + * and then re-decode the image. Otherwise they'd need to close + * and open the image to get the state reset. + */ + sp->bitmap = + TIFFGetBitRevTable(tif->tif_dir.td_fillorder != FILLORDER_LSB2MSB); + if (sp->refruns) { /* init reference line to white */ + sp->refruns[0] = (uint32) sp->b.rowpixels; + sp->refruns[1] = 0; + } + return (1); +} + +/* + * Routine for handling various errors/conditions. + * Note how they are "glued into the decoder" by + * overriding the definitions used by the decoder. + */ + +static void +Fax3Unexpected(const char* module, TIFF* tif, uint32 a0) +{ + TIFFError(module, "%s: Bad code word at scanline %d (x %lu)", + tif->tif_name, tif->tif_row, (u_long) a0); +} +#define unexpected(table, a0) Fax3Unexpected(module, tif, a0) + +static void +Fax3Extension(const char* module, TIFF* tif, uint32 a0) +{ + TIFFError(module, + "%s: Uncompressed data (not supported) at scanline %d (x %lu)", + tif->tif_name, tif->tif_row, (u_long) a0); +} +#define extension(a0) Fax3Extension(module, tif, a0) + +static void +Fax3BadLength(const char* module, TIFF* tif, uint32 a0, uint32 lastx) +{ + TIFFWarning(module, "%s: %s at scanline %d (got %lu, expected %lu)", + tif->tif_name, + a0 < lastx ? "Premature EOL" : "Line length mismatch", + tif->tif_row, (u_long) a0, (u_long) lastx); +} +#define badlength(a0,lastx) Fax3BadLength(module, tif, a0, lastx) + +static void +Fax3PrematureEOF(const char* module, TIFF* tif, uint32 a0) +{ + TIFFWarning(module, "%s: Premature EOF at scanline %d (x %lu)", + tif->tif_name, tif->tif_row, (u_long) a0); +} +#define prematureEOF(a0) Fax3PrematureEOF(module, tif, a0) + +#define Nop + +/* + * Decode the requested amount of G3 1D-encoded data. + */ +static int +Fax3Decode1D(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s) +{ + DECLARE_STATE(tif, sp, "Fax3Decode1D"); + + (void) s; + CACHE_STATE(tif, sp); + thisrun = sp->curruns; + while ((long)occ > 0) { + a0 = 0; + RunLength = 0; + pa = thisrun; +#ifdef FAX3_DEBUG + printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail); + printf("-------------------- %d\n", tif->tif_row); + fflush(stdout); +#endif + SYNC_EOL(EOF1D); + EXPAND1D(EOF1Da); + (*sp->fill)(buf, thisrun, pa, lastx); + buf += sp->b.rowbytes; + occ -= sp->b.rowbytes; + if (occ != 0) + tif->tif_row++; + continue; + EOF1D: /* premature EOF */ + CLEANUP_RUNS(); + EOF1Da: /* premature EOF */ + (*sp->fill)(buf, thisrun, pa, lastx); + UNCACHE_STATE(tif, sp); + return (-1); + } + UNCACHE_STATE(tif, sp); + return (1); +} + +#define SWAP(t,a,b) { t x; x = (a); (a) = (b); (b) = x; } +/* + * Decode the requested amount of G3 2D-encoded data. + */ +static int +Fax3Decode2D(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s) +{ + DECLARE_STATE_2D(tif, sp, "Fax3Decode2D"); + int is1D; /* current line is 1d/2d-encoded */ + + (void) s; + CACHE_STATE(tif, sp); + while ((long)occ > 0) { + a0 = 0; + RunLength = 0; + pa = thisrun = sp->curruns; +#ifdef FAX3_DEBUG + printf("\nBitAcc=%08X, BitsAvail = %d EOLcnt = %d", + BitAcc, BitsAvail, EOLcnt); +#endif + SYNC_EOL(EOF2D); + NeedBits8(1, EOF2D); + is1D = GetBits(1); /* 1D/2D-encoding tag bit */ + ClrBits(1); +#ifdef FAX3_DEBUG + printf(" %s\n-------------------- %d\n", + is1D ? "1D" : "2D", tif->tif_row); + fflush(stdout); +#endif + pb = sp->refruns; + b1 = *pb++; + if (is1D) + EXPAND1D(EOF2Da); + else + EXPAND2D(EOF2Da); + (*sp->fill)(buf, thisrun, pa, lastx); + SETVAL(0); /* imaginary change for reference */ + SWAP(uint32*, sp->curruns, sp->refruns); + buf += sp->b.rowbytes; + occ -= sp->b.rowbytes; + if (occ != 0) + tif->tif_row++; + continue; + EOF2D: /* premature EOF */ + CLEANUP_RUNS(); + EOF2Da: /* premature EOF */ + (*sp->fill)(buf, thisrun, pa, lastx); + UNCACHE_STATE(tif, sp); + return (-1); + } + UNCACHE_STATE(tif, sp); + return (1); +} +#undef SWAP + +/* + * The ZERO & FILL macros must handle spans < 2*sizeof(long) bytes. + * For machines with 64-bit longs this is <16 bytes; otherwise + * this is <8 bytes. We optimize the code here to reflect the + * machine characteristics. + */ +#if defined(__alpha) || _MIPS_SZLONG == 64 || defined(__LP64__) +#define FILL(n, cp) \ + switch (n) { \ + case 15:(cp)[14] = 0xff; case 14:(cp)[13] = 0xff; case 13: (cp)[12] = 0xff;\ + case 12:(cp)[11] = 0xff; case 11:(cp)[10] = 0xff; case 10: (cp)[9] = 0xff;\ + case 9: (cp)[8] = 0xff; case 8: (cp)[7] = 0xff; case 7: (cp)[6] = 0xff;\ + case 6: (cp)[5] = 0xff; case 5: (cp)[4] = 0xff; case 4: (cp)[3] = 0xff;\ + case 3: (cp)[2] = 0xff; case 2: (cp)[1] = 0xff; \ + case 1: (cp)[0] = 0xff; (cp) += (n); case 0: ; \ + } +#define ZERO(n, cp) \ + switch (n) { \ + case 15:(cp)[14] = 0; case 14:(cp)[13] = 0; case 13: (cp)[12] = 0; \ + case 12:(cp)[11] = 0; case 11:(cp)[10] = 0; case 10: (cp)[9] = 0; \ + case 9: (cp)[8] = 0; case 8: (cp)[7] = 0; case 7: (cp)[6] = 0; \ + case 6: (cp)[5] = 0; case 5: (cp)[4] = 0; case 4: (cp)[3] = 0; \ + case 3: (cp)[2] = 0; case 2: (cp)[1] = 0; \ + case 1: (cp)[0] = 0; (cp) += (n); case 0: ; \ + } +#else +#define FILL(n, cp) \ + switch (n) { \ + case 7: (cp)[6] = 0xff; case 6: (cp)[5] = 0xff; case 5: (cp)[4] = 0xff; \ + case 4: (cp)[3] = 0xff; case 3: (cp)[2] = 0xff; case 2: (cp)[1] = 0xff; \ + case 1: (cp)[0] = 0xff; (cp) += (n); case 0: ; \ + } +#define ZERO(n, cp) \ + switch (n) { \ + case 7: (cp)[6] = 0; case 6: (cp)[5] = 0; case 5: (cp)[4] = 0; \ + case 4: (cp)[3] = 0; case 3: (cp)[2] = 0; case 2: (cp)[1] = 0; \ + case 1: (cp)[0] = 0; (cp) += (n); case 0: ; \ + } +#endif + +/* + * Bit-fill a row according to the white/black + * runs generated during G3/G4 decoding. + */ +void +_TIFFFax3fillruns(u_char* buf, uint32* runs, uint32* erun, uint32 lastx) +{ + static const unsigned char _fillmasks[] = + { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff }; + u_char* cp; + uint32 x, bx, run; + int32 n, nw; + long* lp; + + if ((erun-runs)&1) + *erun++ = 0; + x = 0; + for (; runs < erun; runs += 2) { + run = runs[0]; + if (x+run > lastx || run > lastx ) + run = runs[0] = (uint32) (lastx - x); + if (run) { + cp = buf + (x>>3); + bx = x&7; + if (run > 8-bx) { + if (bx) { /* align to byte boundary */ + *cp++ &= 0xff << (8-bx); + run -= 8-bx; + } + if( (n = run >> 3) != 0 ) { /* multiple bytes to fill */ + if ((n/sizeof (long)) > 1) { + /* + * Align to longword boundary and fill. + */ + for (; n && !isAligned(cp, long); n--) + *cp++ = 0x00; + lp = (long*) cp; + nw = (int32)(n / sizeof (long)); + n -= nw * sizeof (long); + do { + *lp++ = 0L; + } while (--nw); + cp = (u_char*) lp; + } + ZERO(n, cp); + run &= 7; + } + if (run) + cp[0] &= 0xff >> run; + } else + cp[0] &= ~(_fillmasks[run]>>bx); + x += runs[0]; + } + run = runs[1]; + if (x+run > lastx || run > lastx ) + run = runs[1] = lastx - x; + if (run) { + cp = buf + (x>>3); + bx = x&7; + if (run > 8-bx) { + if (bx) { /* align to byte boundary */ + *cp++ |= 0xff >> bx; + run -= 8-bx; + } + if( (n = run>>3) != 0 ) { /* multiple bytes to fill */ + if ((n/sizeof (long)) > 1) { + /* + * Align to longword boundary and fill. + */ + for (; n && !isAligned(cp, long); n--) + *cp++ = 0xff; + lp = (long*) cp; + nw = (int32)(n / sizeof (long)); + n -= nw * sizeof (long); + do { + *lp++ = -1L; + } while (--nw); + cp = (u_char*) lp; + } + FILL(n, cp); + run &= 7; + } + if (run) + cp[0] |= 0xff00 >> run; + } else + cp[0] |= _fillmasks[run]>>bx; + x += runs[1]; + } + } + assert(x == lastx); +} +#undef ZERO +#undef FILL + +/* + * Setup G3/G4-related compression/decompression state + * before data is processed. This routine is called once + * per image -- it sets up different state based on whether + * or not decoding or encoding is being done and whether + * 1D- or 2D-encoded data is involved. + */ +static int +Fax3SetupState(TIFF* tif) +{ + TIFFDirectory* td = &tif->tif_dir; + Fax3BaseState* sp = Fax3State(tif); + long rowbytes, rowpixels; + int needsRefLine; + + if (td->td_bitspersample != 1) { + TIFFError(tif->tif_name, + "Bits/sample must be 1 for Group 3/4 encoding/decoding"); + return (0); + } + /* + * Calculate the scanline/tile widths. + */ + if (isTiled(tif)) { + rowbytes = TIFFTileRowSize(tif); + rowpixels = td->td_tilewidth; + } else { + rowbytes = TIFFScanlineSize(tif); + rowpixels = td->td_imagewidth; + } + sp->rowbytes = (uint32) rowbytes; + sp->rowpixels = (uint32) rowpixels; + /* + * Allocate any additional space required for decoding/encoding. + */ + needsRefLine = ( + (sp->groupoptions & GROUP3OPT_2DENCODING) || + td->td_compression == COMPRESSION_CCITTFAX4 + ); + if (sp->rw_mode == O_RDONLY) { /* 1d/2d decoding */ + Fax3DecodeState* dsp = DecoderState(tif); + uint32 nruns = needsRefLine ? + 2*TIFFroundup(rowpixels,32) : rowpixels; + + dsp->runs = (uint32*) _TIFFmalloc((2*nruns+3)*sizeof (uint32)); + if (dsp->runs == NULL) { + TIFFError("Fax3SetupState", + "%s: No space for Group 3/4 run arrays", + tif->tif_name); + return (0); + } + dsp->curruns = dsp->runs; + if (needsRefLine) + dsp->refruns = dsp->runs + (nruns>>1); + else + dsp->refruns = NULL; + if (is2DEncoding(dsp)) { /* NB: default is 1D routine */ + tif->tif_decoderow = Fax3Decode2D; + tif->tif_decodestrip = Fax3Decode2D; + tif->tif_decodetile = Fax3Decode2D; + } + } else if (needsRefLine) { /* 2d encoding */ + Fax3EncodeState* esp = EncoderState(tif); + /* + * 2d encoding requires a scanline + * buffer for the ``reference line''; the + * scanline against which delta encoding + * is referenced. The reference line must + * be initialized to be ``white'' (done elsewhere). + */ + esp->refline = (u_char*) _TIFFmalloc(rowbytes); + if (esp->refline == NULL) { + TIFFError("Fax3SetupState", + "%s: No space for Group 3/4 reference line", + tif->tif_name); + return (0); + } + } else /* 1d encoding */ + EncoderState(tif)->refline = NULL; + return (1); +} + +/* + * CCITT Group 3 FAX Encoding. + */ + +#define Fax3FlushBits(tif, sp) { \ + if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \ + (void) TIFFFlushData1(tif); \ + *(tif)->tif_rawcp++ = (sp)->data; \ + (tif)->tif_rawcc++; \ + (sp)->data = 0, (sp)->bit = 8; \ +} +#define _FlushBits(tif) { \ + if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \ + (void) TIFFFlushData1(tif); \ + *(tif)->tif_rawcp++ = data; \ + (tif)->tif_rawcc++; \ + data = 0, bit = 8; \ +} +static const int _msbmask[9] = + { 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff }; +#define _PutBits(tif, bits, length) { \ + while (length > bit) { \ + data |= bits >> (length - bit); \ + length -= bit; \ + _FlushBits(tif); \ + } \ + data |= (bits & _msbmask[length]) << (bit - length); \ + bit -= length; \ + if (bit == 0) \ + _FlushBits(tif); \ +} + +/* + * Write a variable-length bit-value to + * the output stream. Values are + * assumed to be at most 16 bits. + */ +static void +Fax3PutBits(TIFF* tif, u_int bits, u_int length) +{ + Fax3EncodeState* sp = EncoderState(tif); + u_int bit = sp->bit; + int data = sp->data; + + _PutBits(tif, bits, length); + + sp->data = data; + sp->bit = bit; +} + +/* + * Write a code to the output stream. + */ +#define putcode(tif, te) Fax3PutBits(tif, (te)->code, (te)->length) + +#ifdef FAX3_DEBUG +#define DEBUG_COLOR(w) (tab == TIFFFaxWhiteCodes ? w "W" : w "B") +#define DEBUG_PRINT(what,len) { \ + int t; \ + printf("%08X/%-2d: %s%5d\t", data, bit, DEBUG_COLOR(what), len); \ + for (t = length-1; t >= 0; t--) \ + putchar(code & (1<bit; + int data = sp->data; + u_int code, length; + + while (span >= 2624) { + const tableentry* te = &tab[63 + (2560>>6)]; + code = te->code, length = te->length; +#ifdef FAX3_DEBUG + DEBUG_PRINT("MakeUp", te->runlen); +#endif + _PutBits(tif, code, length); + span -= te->runlen; + } + if (span >= 64) { + const tableentry* te = &tab[63 + (span>>6)]; + assert(te->runlen == 64*(span>>6)); + code = te->code, length = te->length; +#ifdef FAX3_DEBUG + DEBUG_PRINT("MakeUp", te->runlen); +#endif + _PutBits(tif, code, length); + span -= te->runlen; + } + code = tab[span].code, length = tab[span].length; +#ifdef FAX3_DEBUG + DEBUG_PRINT(" Term", tab[span].runlen); +#endif + _PutBits(tif, code, length); + + sp->data = data; + sp->bit = bit; +} + +/* + * Write an EOL code to the output stream. The zero-fill + * logic for byte-aligning encoded scanlines is handled + * here. We also handle writing the tag bit for the next + * scanline when doing 2d encoding. + */ +static void +Fax3PutEOL(TIFF* tif) +{ + Fax3EncodeState* sp = EncoderState(tif); + u_int bit = sp->bit; + int data = sp->data; + u_int code, length, tparm; + + if (sp->b.groupoptions & GROUP3OPT_FILLBITS) { + /* + * Force bit alignment so EOL will terminate on + * a byte boundary. That is, force the bit alignment + * to 16-12 = 4 before putting out the EOL code. + */ + int align = 8 - 4; + if (align != sp->bit) { + if (align > sp->bit) + align = sp->bit + (8 - align); + else + align = sp->bit - align; + code = 0; + tparm=align; + _PutBits(tif, 0, tparm); + } + } + code = EOL, length = 12; + if (is2DEncoding(sp)) + code = (code<<1) | (sp->tag == G3_1D), length++; + _PutBits(tif, code, length); + + sp->data = data; + sp->bit = bit; +} + +/* + * Reset encoding state at the start of a strip. + */ +static int +Fax3PreEncode(TIFF* tif, tsample_t s) +{ + Fax3EncodeState* sp = EncoderState(tif); + + (void) s; + assert(sp != NULL); + sp->bit = 8; + sp->data = 0; + sp->tag = G3_1D; + /* + * This is necessary for Group 4; otherwise it isn't + * needed because the first scanline of each strip ends + * up being copied into the refline. + */ + if (sp->refline) + _TIFFmemset(sp->refline, 0x00, sp->b.rowbytes); + if (is2DEncoding(sp)) { + float res = tif->tif_dir.td_yresolution; + /* + * The CCITT spec says that when doing 2d encoding, you + * should only do it on K consecutive scanlines, where K + * depends on the resolution of the image being encoded + * (2 for <= 200 lpi, 4 for > 200 lpi). Since the directory + * code initializes td_yresolution to 0, this code will + * select a K of 2 unless the YResolution tag is set + * appropriately. (Note also that we fudge a little here + * and use 150 lpi to avoid problems with units conversion.) + */ + if (tif->tif_dir.td_resolutionunit == RESUNIT_CENTIMETER) + res *= 2.54f; /* convert to inches */ + sp->maxk = (res > 150 ? 4 : 2); + sp->k = sp->maxk-1; + } else + sp->k = sp->maxk = 0; + return (1); +} + +static const u_char zeroruns[256] = { + 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, /* 0x00 - 0x0f */ + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x10 - 0x1f */ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x20 - 0x2f */ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x30 - 0x3f */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 - 0x4f */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x50 - 0x5f */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 - 0x6f */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x70 - 0x7f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xa0 - 0xaf */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xb0 - 0xbf */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xc0 - 0xcf */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xd0 - 0xdf */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xe0 - 0xef */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xf0 - 0xff */ +}; +static const u_char oneruns[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 - 0x0f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 - 0x1f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 - 0x2f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x6f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7f */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x80 - 0x8f */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x90 - 0x9f */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xa0 - 0xaf */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xb0 - 0xbf */ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xc0 - 0xcf */ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xd0 - 0xdf */ + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xe0 - 0xef */ + 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, /* 0xf0 - 0xff */ +}; + +/* + * On certain systems it pays to inline + * the routines that find pixel spans. + */ +#ifdef VAXC +static int32 find0span(u_char*, int32, int32); +static int32 find1span(u_char*, int32, int32); +#pragma inline(find0span,find1span) +#endif + +/* + * Find a span of ones or zeros using the supplied + * table. The ``base'' of the bit string is supplied + * along with the start+end bit indices. + */ +INLINE static int32 +find0span(u_char* bp, int32 bs, int32 be) +{ + int32 bits = be - bs; + int32 n, span; + + bp += bs>>3; + /* + * Check partial byte on lhs. + */ + if (bits > 0 && (n = (bs & 7))) { + span = zeroruns[(*bp << n) & 0xff]; + if (span > 8-n) /* table value too generous */ + span = 8-n; + if (span > bits) /* constrain span to bit range */ + span = bits; + if (n+span < 8) /* doesn't extend to edge of byte */ + return (span); + bits -= span; + bp++; + } else + span = 0; + if (bits >= 2*8*sizeof (long)) { + long* lp; + /* + * Align to longword boundary and check longwords. + */ + while (!isAligned(bp, long)) { + if (*bp != 0x00) + return (span + zeroruns[*bp]); + span += 8, bits -= 8; + bp++; + } + lp = (long*) bp; + while (bits >= 8*sizeof (long) && *lp == 0) { + span += 8*sizeof (long), bits -= 8*sizeof (long); + lp++; + } + bp = (u_char*) lp; + } + /* + * Scan full bytes for all 0's. + */ + while (bits >= 8) { + if (*bp != 0x00) /* end of run */ + return (span + zeroruns[*bp]); + span += 8, bits -= 8; + bp++; + } + /* + * Check partial byte on rhs. + */ + if (bits > 0) { + n = zeroruns[*bp]; + span += (n > bits ? bits : n); + } + return (span); +} + +INLINE static int32 +find1span(u_char* bp, int32 bs, int32 be) +{ + int32 bits = be - bs; + int32 n, span; + + bp += bs>>3; + /* + * Check partial byte on lhs. + */ + if (bits > 0 && (n = (bs & 7))) { + span = oneruns[(*bp << n) & 0xff]; + if (span > 8-n) /* table value too generous */ + span = 8-n; + if (span > bits) /* constrain span to bit range */ + span = bits; + if (n+span < 8) /* doesn't extend to edge of byte */ + return (span); + bits -= span; + bp++; + } else + span = 0; + if (bits >= 2*8*sizeof (long)) { + long* lp; + /* + * Align to longword boundary and check longwords. + */ + while (!isAligned(bp, long)) { + if (*bp != 0xff) + return (span + oneruns[*bp]); + span += 8, bits -= 8; + bp++; + } + lp = (long*) bp; + while (bits >= 8*sizeof (long) && *lp == ~0) { + span += 8*sizeof (long), bits -= 8*sizeof (long); + lp++; + } + bp = (u_char*) lp; + } + /* + * Scan full bytes for all 1's. + */ + while (bits >= 8) { + if (*bp != 0xff) /* end of run */ + return (span + oneruns[*bp]); + span += 8, bits -= 8; + bp++; + } + /* + * Check partial byte on rhs. + */ + if (bits > 0) { + n = oneruns[*bp]; + span += (n > bits ? bits : n); + } + return (span); +} + +/* + * Return the offset of the next bit in the range + * [bs..be] that is different from the specified + * color. The end, be, is returned if no such bit + * exists. + */ +#define finddiff(_cp, _bs, _be, _color) \ + (_bs + (_color ? find1span(_cp,_bs,_be) : find0span(_cp,_bs,_be))) +/* + * Like finddiff, but also check the starting bit + * against the end in case start > end. + */ +#define finddiff2(_cp, _bs, _be, _color) \ + (_bs < _be ? finddiff(_cp,_bs,_be,_color) : _be) + +/* + * 1d-encode a row of pixels. The encoding is + * a sequence of all-white or all-black spans + * of pixels encoded with Huffman codes. + */ +static int +Fax3Encode1DRow(TIFF* tif, u_char* bp, uint32 bits) +{ + Fax3EncodeState* sp = EncoderState(tif); + int32 span; + uint32 bs = 0; + + for (;;) { + span = find0span(bp, bs, bits); /* white span */ + putspan(tif, span, TIFFFaxWhiteCodes); + bs += span; + if (bs >= bits) + break; + span = find1span(bp, bs, bits); /* black span */ + putspan(tif, span, TIFFFaxBlackCodes); + bs += span; + if (bs >= bits) + break; + } + if (sp->b.mode & (FAXMODE_BYTEALIGN|FAXMODE_WORDALIGN)) { + if (sp->bit != 8) /* byte-align */ + Fax3FlushBits(tif, sp); + if ((sp->b.mode&FAXMODE_WORDALIGN) && + !isAligned(tif->tif_rawcp, uint16)) + Fax3FlushBits(tif, sp); + } + return (1); +} + +static const tableentry horizcode = + { 3, 0x1 }; /* 001 */ +static const tableentry passcode = + { 4, 0x1 }; /* 0001 */ +static const tableentry vcodes[7] = { + { 7, 0x03 }, /* 0000 011 */ + { 6, 0x03 }, /* 0000 11 */ + { 3, 0x03 }, /* 011 */ + { 1, 0x1 }, /* 1 */ + { 3, 0x2 }, /* 010 */ + { 6, 0x02 }, /* 0000 10 */ + { 7, 0x02 } /* 0000 010 */ +}; + +/* + * 2d-encode a row of pixels. Consult the CCITT + * documentation for the algorithm. + */ +static int +Fax3Encode2DRow(TIFF* tif, u_char* bp, u_char* rp, uint32 bits) +{ +#define PIXEL(buf,ix) ((((buf)[(ix)>>3]) >> (7-((ix)&7))) & 1) + uint32 a0 = 0; + uint32 a1 = (PIXEL(bp, 0) != 0 ? 0 : finddiff(bp, 0, bits, 0)); + uint32 b1 = (PIXEL(rp, 0) != 0 ? 0 : finddiff(rp, 0, bits, 0)); + uint32 a2, b2; + + for (;;) { + b2 = finddiff2(rp, b1, bits, PIXEL(rp,b1)); + if (b2 >= a1) { + int32 d = b1 - a1; + if (!(-3 <= d && d <= 3)) { /* horizontal mode */ + a2 = finddiff2(bp, a1, bits, PIXEL(bp,a1)); + putcode(tif, &horizcode); + if (a0+a1 == 0 || PIXEL(bp, a0) == 0) { + putspan(tif, a1-a0, TIFFFaxWhiteCodes); + putspan(tif, a2-a1, TIFFFaxBlackCodes); + } else { + putspan(tif, a1-a0, TIFFFaxBlackCodes); + putspan(tif, a2-a1, TIFFFaxWhiteCodes); + } + a0 = a2; + } else { /* vertical mode */ + putcode(tif, &vcodes[d+3]); + a0 = a1; + } + } else { /* pass mode */ + putcode(tif, &passcode); + a0 = b2; + } + if (a0 >= bits) + break; + a1 = finddiff(bp, a0, bits, PIXEL(bp,a0)); + b1 = finddiff(rp, a0, bits, !PIXEL(bp,a0)); + b1 = finddiff(rp, b1, bits, PIXEL(bp,a0)); + } + return (1); +#undef PIXEL +} + +/* + * Encode a buffer of pixels. + */ +static int +Fax3Encode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + Fax3EncodeState* sp = EncoderState(tif); + + (void) s; + while ((long)cc > 0) { + if ((sp->b.mode & FAXMODE_NOEOL) == 0) + Fax3PutEOL(tif); + if (is2DEncoding(sp)) { + if (sp->tag == G3_1D) { + if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels)) + return (0); + sp->tag = G3_2D; + } else { + if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels)) + return (0); + sp->k--; + } + if (sp->k == 0) { + sp->tag = G3_1D; + sp->k = sp->maxk-1; + } else + _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes); + } else { + if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels)) + return (0); + } + bp += sp->b.rowbytes; + cc -= sp->b.rowbytes; + if (cc != 0) + tif->tif_row++; + } + return (1); +} + +static int +Fax3PostEncode(TIFF* tif) +{ + Fax3EncodeState* sp = EncoderState(tif); + + if (sp->bit != 8) + Fax3FlushBits(tif, sp); + return (1); +} + +static void +Fax3Close(TIFF* tif) +{ + if ((Fax3State(tif)->mode & FAXMODE_NORTC) == 0) { + Fax3EncodeState* sp = EncoderState(tif); + u_int code = EOL; + u_int length = 12; + int i; + + if (is2DEncoding(sp)) + code = (code<<1) | (sp->tag == G3_1D), length++; + for (i = 0; i < 6; i++) + Fax3PutBits(tif, code, length); + Fax3FlushBits(tif, sp); + } +} + +static void +Fax3Cleanup(TIFF* tif) +{ + if (tif->tif_data) { + if (Fax3State(tif)->rw_mode == O_RDONLY) { + Fax3DecodeState* sp = DecoderState(tif); + if (sp->runs) + _TIFFfree(sp->runs); + } else { + Fax3EncodeState* sp = EncoderState(tif); + if (sp->refline) + _TIFFfree(sp->refline); + } + if (Fax3State(tif)->subaddress) + _TIFFfree(Fax3State(tif)->subaddress); + _TIFFfree(tif->tif_data); + tif->tif_data = NULL; + } +} + +#define FIELD_BADFAXLINES (FIELD_CODEC+0) +#define FIELD_CLEANFAXDATA (FIELD_CODEC+1) +#define FIELD_BADFAXRUN (FIELD_CODEC+2) +#define FIELD_RECVPARAMS (FIELD_CODEC+3) +#define FIELD_SUBADDRESS (FIELD_CODEC+4) +#define FIELD_RECVTIME (FIELD_CODEC+5) + +#define FIELD_OPTIONS (FIELD_CODEC+6) + +static const TIFFFieldInfo faxFieldInfo[] = { + { TIFFTAG_FAXMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO, + FALSE, FALSE, "FaxMode" }, + { TIFFTAG_FAXFILLFUNC, 0, 0, TIFF_ANY, FIELD_PSEUDO, + FALSE, FALSE, "FaxFillFunc" }, + { TIFFTAG_BADFAXLINES, 1, 1, TIFF_LONG, FIELD_BADFAXLINES, + TRUE, FALSE, "BadFaxLines" }, + { TIFFTAG_BADFAXLINES, 1, 1, TIFF_SHORT, FIELD_BADFAXLINES, + TRUE, FALSE, "BadFaxLines" }, + { TIFFTAG_CLEANFAXDATA, 1, 1, TIFF_SHORT, FIELD_CLEANFAXDATA, + TRUE, FALSE, "CleanFaxData" }, + { TIFFTAG_CONSECUTIVEBADFAXLINES,1,1, TIFF_LONG, FIELD_BADFAXRUN, + TRUE, FALSE, "ConsecutiveBadFaxLines" }, + { TIFFTAG_CONSECUTIVEBADFAXLINES,1,1, TIFF_SHORT, FIELD_BADFAXRUN, + TRUE, FALSE, "ConsecutiveBadFaxLines" }, + { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, FIELD_RECVPARAMS, + TRUE, FALSE, "FaxRecvParams" }, + { TIFFTAG_FAXSUBADDRESS, -1,-1, TIFF_ASCII, FIELD_SUBADDRESS, + TRUE, FALSE, "FaxSubAddress" }, + { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, FIELD_RECVTIME, + TRUE, FALSE, "FaxRecvTime" }, +}; +static const TIFFFieldInfo fax3FieldInfo[] = { + { TIFFTAG_GROUP3OPTIONS, 1, 1, TIFF_LONG, FIELD_OPTIONS, + FALSE, FALSE, "Group3Options" }, +}; +static const TIFFFieldInfo fax4FieldInfo[] = { + { TIFFTAG_GROUP4OPTIONS, 1, 1, TIFF_LONG, FIELD_OPTIONS, + FALSE, FALSE, "Group4Options" }, +}; +#define N(a) (sizeof (a) / sizeof (a[0])) + +static int +Fax3VSetField(TIFF* tif, ttag_t tag, va_list ap) +{ + Fax3BaseState* sp = Fax3State(tif); + + switch (tag) { + case TIFFTAG_FAXMODE: + sp->mode = va_arg(ap, int); + return (1); /* NB: pseudo tag */ + case TIFFTAG_FAXFILLFUNC: + if (sp->rw_mode == O_RDONLY) + DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc); + return (1); /* NB: pseudo tag */ + case TIFFTAG_GROUP3OPTIONS: + case TIFFTAG_GROUP4OPTIONS: + sp->groupoptions = va_arg(ap, uint32); + break; + case TIFFTAG_BADFAXLINES: + sp->badfaxlines = va_arg(ap, uint32); + break; + case TIFFTAG_CLEANFAXDATA: + sp->cleanfaxdata = (uint16) va_arg(ap, int); + break; + case TIFFTAG_CONSECUTIVEBADFAXLINES: + sp->badfaxrun = va_arg(ap, uint32); + break; + case TIFFTAG_FAXRECVPARAMS: + sp->recvparams = va_arg(ap, uint32); + break; + case TIFFTAG_FAXSUBADDRESS: + _TIFFsetString(&sp->subaddress, va_arg(ap, char*)); + break; + case TIFFTAG_FAXRECVTIME: + sp->recvtime = va_arg(ap, uint32); + break; + default: + return (*sp->vsetparent)(tif, tag, ap); + } + TIFFSetFieldBit(tif, _TIFFFieldWithTag(tif, tag)->field_bit); + tif->tif_flags |= TIFF_DIRTYDIRECT; + return (1); +} + +static int +Fax3VGetField(TIFF* tif, ttag_t tag, va_list ap) +{ + Fax3BaseState* sp = Fax3State(tif); + + switch (tag) { + case TIFFTAG_FAXMODE: + *va_arg(ap, int*) = sp->mode; + break; + case TIFFTAG_FAXFILLFUNC: + if (sp->rw_mode == O_RDONLY) + *va_arg(ap, TIFFFaxFillFunc*) = DecoderState(tif)->fill; + break; + case TIFFTAG_GROUP3OPTIONS: + case TIFFTAG_GROUP4OPTIONS: + *va_arg(ap, uint32*) = sp->groupoptions; + break; + case TIFFTAG_BADFAXLINES: + *va_arg(ap, uint32*) = sp->badfaxlines; + break; + case TIFFTAG_CLEANFAXDATA: + *va_arg(ap, uint16*) = sp->cleanfaxdata; + break; + case TIFFTAG_CONSECUTIVEBADFAXLINES: + *va_arg(ap, uint32*) = sp->badfaxrun; + break; + case TIFFTAG_FAXRECVPARAMS: + *va_arg(ap, uint32*) = sp->recvparams; + break; + case TIFFTAG_FAXSUBADDRESS: + *va_arg(ap, char**) = sp->subaddress; + break; + case TIFFTAG_FAXRECVTIME: + *va_arg(ap, uint32*) = sp->recvtime; + break; + default: + return (*sp->vgetparent)(tif, tag, ap); + } + return (1); +} + +static void +Fax3PrintDir(TIFF* tif, FILE* fd, long flags) +{ + Fax3BaseState* sp = Fax3State(tif); + + (void) flags; + if (TIFFFieldSet(tif,FIELD_OPTIONS)) { + const char* sep = " "; + if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4) { + fprintf(fd, " Group 4 Options:"); + if (sp->groupoptions & GROUP4OPT_UNCOMPRESSED) + fprintf(fd, "%suncompressed data", sep); + } else { + + fprintf(fd, " Group 3 Options:"); + if (sp->groupoptions & GROUP3OPT_2DENCODING) + fprintf(fd, "%s2-d encoding", sep), sep = "+"; + if (sp->groupoptions & GROUP3OPT_FILLBITS) + fprintf(fd, "%sEOL padding", sep), sep = "+"; + if (sp->groupoptions & GROUP3OPT_UNCOMPRESSED) + fprintf(fd, "%suncompressed data", sep); + } + fprintf(fd, " (%lu = 0x%lx)\n", + (u_long) sp->groupoptions, (u_long) sp->groupoptions); + } + if (TIFFFieldSet(tif,FIELD_CLEANFAXDATA)) { + fprintf(fd, " Fax Data:"); + switch (sp->cleanfaxdata) { + case CLEANFAXDATA_CLEAN: + fprintf(fd, " clean"); + break; + case CLEANFAXDATA_REGENERATED: + fprintf(fd, " receiver regenerated"); + break; + case CLEANFAXDATA_UNCLEAN: + fprintf(fd, " uncorrected errors"); + break; + } + fprintf(fd, " (%u = 0x%x)\n", + sp->cleanfaxdata, sp->cleanfaxdata); + } + if (TIFFFieldSet(tif,FIELD_BADFAXLINES)) + fprintf(fd, " Bad Fax Lines: %lu\n", (u_long) sp->badfaxlines); + if (TIFFFieldSet(tif,FIELD_BADFAXRUN)) + fprintf(fd, " Consecutive Bad Fax Lines: %lu\n", + (u_long) sp->badfaxrun); + if (TIFFFieldSet(tif,FIELD_RECVPARAMS)) + fprintf(fd, " Fax Receive Parameters: %08lx\n", + (u_long) sp->recvparams); + if (TIFFFieldSet(tif,FIELD_SUBADDRESS)) + fprintf(fd, " Fax SubAddress: %s\n", sp->subaddress); + if (TIFFFieldSet(tif,FIELD_RECVTIME)) + fprintf(fd, " Fax Receive Time: %lu secs\n", + (u_long) sp->recvtime); +} + +static int +InitCCITTFax3(TIFF* tif) +{ + Fax3BaseState* sp; + + /* + * Allocate state block so tag methods have storage to record values. + */ + if (tif->tif_mode == O_RDONLY) + tif->tif_data = (tidata_t) + _TIFFmalloc(sizeof (Fax3DecodeState)); + else + tif->tif_data = (tidata_t) + _TIFFmalloc(sizeof (Fax3EncodeState)); + + if (tif->tif_data == NULL) { + TIFFError("TIFFInitCCITTFax3", + "%s: No space for state block", tif->tif_name); + return (0); + } + + sp = Fax3State(tif); + sp->rw_mode = tif->tif_mode; + + /* + * Merge codec-specific tag information and + * override parent get/set field methods. + */ + _TIFFMergeFieldInfo(tif, faxFieldInfo, N(faxFieldInfo)); + sp->vgetparent = tif->tif_vgetfield; + tif->tif_vgetfield = Fax3VGetField; /* hook for codec tags */ + sp->vsetparent = tif->tif_vsetfield; + tif->tif_vsetfield = Fax3VSetField; /* hook for codec tags */ + tif->tif_printdir = Fax3PrintDir; /* hook for codec tags */ + sp->groupoptions = 0; + sp->recvparams = 0; + sp->subaddress = NULL; + + if (sp->rw_mode == O_RDONLY) { + tif->tif_flags |= TIFF_NOBITREV;/* decoder does bit reversal */ + DecoderState(tif)->runs = NULL; + TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, _TIFFFax3fillruns); + } else + EncoderState(tif)->refline = NULL; + + /* + * Install codec methods. + */ + tif->tif_setupdecode = Fax3SetupState; + tif->tif_predecode = Fax3PreDecode; + tif->tif_decoderow = Fax3Decode1D; + tif->tif_decodestrip = Fax3Decode1D; + tif->tif_decodetile = Fax3Decode1D; + tif->tif_setupencode = Fax3SetupState; + tif->tif_preencode = Fax3PreEncode; + tif->tif_postencode = Fax3PostEncode; + tif->tif_encoderow = Fax3Encode; + tif->tif_encodestrip = Fax3Encode; + tif->tif_encodetile = Fax3Encode; + tif->tif_close = Fax3Close; + tif->tif_cleanup = Fax3Cleanup; + + return (1); +} + +int +TIFFInitCCITTFax3(TIFF* tif, int scheme) +{ + if (InitCCITTFax3(tif)) { + _TIFFMergeFieldInfo(tif, fax3FieldInfo, N(fax3FieldInfo)); + + /* + * The default format is Class/F-style w/o RTC. + */ + return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_CLASSF); + } else + return (0); +} + +/* + * CCITT Group 4 (T.6) Facsimile-compatible + * Compression Scheme Support. + */ + +#define SWAP(t,a,b) { t x; x = (a); (a) = (b); (b) = x; } +/* + * Decode the requested amount of G4-encoded data. + */ +static int +Fax4Decode(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s) +{ + DECLARE_STATE_2D(tif, sp, "Fax4Decode"); + + (void) s; + CACHE_STATE(tif, sp); + while ((long)occ > 0) { + a0 = 0; + RunLength = 0; + pa = thisrun = sp->curruns; + pb = sp->refruns; + b1 = *pb++; +#ifdef FAX3_DEBUG + printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail); + printf("-------------------- %d\n", tif->tif_row); + fflush(stdout); +#endif + EXPAND2D(EOFG4); + if (EOLcnt) + goto EOFG4; + (*sp->fill)(buf, thisrun, pa, lastx); + SETVAL(0); /* imaginary change for reference */ + SWAP(uint32*, sp->curruns, sp->refruns); + buf += sp->b.rowbytes; + occ -= sp->b.rowbytes; + if (occ != 0) + tif->tif_row++; + continue; + EOFG4: + NeedBits16( 13, BADG4 ); + BADG4: +#ifdef FAX3_DEBUG + if( GetBits(13) != 0x1001 ) + fputs( "Bad RTC\n", stderr ); +#endif + ClrBits( 13 ); + (*sp->fill)(buf, thisrun, pa, lastx); + UNCACHE_STATE(tif, sp); + return (-1); + } + UNCACHE_STATE(tif, sp); + return (1); +} +#undef SWAP + +/* + * Encode the requested amount of data. + */ +static int +Fax4Encode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + Fax3EncodeState *sp = EncoderState(tif); + + (void) s; + while ((long)cc > 0) { + if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels)) + return (0); + _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes); + bp += sp->b.rowbytes; + cc -= sp->b.rowbytes; + if (cc != 0) + tif->tif_row++; + } + return (1); +} + +static int +Fax4PostEncode(TIFF* tif) +{ + Fax3EncodeState *sp = EncoderState(tif); + + /* terminate strip w/ EOFB */ + Fax3PutBits(tif, EOL, 12); + Fax3PutBits(tif, EOL, 12); + if (sp->bit != 8) + Fax3FlushBits(tif, sp); + return (1); +} + +int +TIFFInitCCITTFax4(TIFF* tif, int scheme) +{ + if (InitCCITTFax3(tif)) { /* reuse G3 support */ + _TIFFMergeFieldInfo(tif, fax4FieldInfo, N(fax4FieldInfo)); + + tif->tif_decoderow = Fax4Decode; + tif->tif_decodestrip = Fax4Decode; + tif->tif_decodetile = Fax4Decode; + tif->tif_encoderow = Fax4Encode; + tif->tif_encodestrip = Fax4Encode; + tif->tif_encodetile = Fax4Encode; + tif->tif_postencode = Fax4PostEncode; + /* + * Suppress RTC at the end of each strip. + */ + return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_NORTC); + } else + return (0); +} + +/* + * CCITT Group 3 1-D Modified Huffman RLE Compression Support. + * (Compression algorithms 2 and 32771) + */ + +/* + * Decode the requested amount of RLE-encoded data. + */ +static int +Fax3DecodeRLE(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s) +{ + DECLARE_STATE(tif, sp, "Fax3DecodeRLE"); + int mode = sp->b.mode; + + (void) s; + CACHE_STATE(tif, sp); + thisrun = sp->curruns; + while ((long)occ > 0) { + a0 = 0; + RunLength = 0; + pa = thisrun; +#ifdef FAX3_DEBUG + printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail); + printf("-------------------- %d\n", tif->tif_row); + fflush(stdout); +#endif + EXPAND1D(EOFRLE); + (*sp->fill)(buf, thisrun, pa, lastx); + /* + * Cleanup at the end of the row. + */ + if (mode & FAXMODE_BYTEALIGN) { + int n = BitsAvail - (BitsAvail &~ 7); + ClrBits(n); + } else if (mode & FAXMODE_WORDALIGN) { + int n = BitsAvail - (BitsAvail &~ 15); + ClrBits(n); + if (BitsAvail == 0 && !isAligned(cp, uint16)) + cp++; + } + buf += sp->b.rowbytes; + occ -= sp->b.rowbytes; + if (occ != 0) + tif->tif_row++; + continue; + EOFRLE: /* premature EOF */ + (*sp->fill)(buf, thisrun, pa, lastx); + UNCACHE_STATE(tif, sp); + return (-1); + } + UNCACHE_STATE(tif, sp); + return (1); +} + +int +TIFFInitCCITTRLE(TIFF* tif, int scheme) +{ + if (InitCCITTFax3(tif)) { /* reuse G3 support */ + tif->tif_decoderow = Fax3DecodeRLE; + tif->tif_decodestrip = Fax3DecodeRLE; + tif->tif_decodetile = Fax3DecodeRLE; + /* + * Suppress RTC+EOLs when encoding and byte-align data. + */ + return TIFFSetField(tif, TIFFTAG_FAXMODE, + FAXMODE_NORTC|FAXMODE_NOEOL|FAXMODE_BYTEALIGN); + } else + return (0); +} + +int +TIFFInitCCITTRLEW(TIFF* tif, int scheme) +{ + if (InitCCITTFax3(tif)) { /* reuse G3 support */ + tif->tif_decoderow = Fax3DecodeRLE; + tif->tif_decodestrip = Fax3DecodeRLE; + tif->tif_decodetile = Fax3DecodeRLE; + /* + * Suppress RTC+EOLs when encoding and word-align data. + */ + return TIFFSetField(tif, TIFFTAG_FAXMODE, + FAXMODE_NORTC|FAXMODE_NOEOL|FAXMODE_WORDALIGN); + } else + return (0); +} +#endif /* CCITT_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_fax3.h b/SlnkDWFImpl/CxImage/tiff/tif_fax3.h new file mode 100644 index 0000000..fbd5d6c --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_fax3.h @@ -0,0 +1,525 @@ +/* $Id: tif_fax3.h,v 1.4 2000/12/01 15:46:46 warmerda Exp $ */ + +/* + * Copyright (c) 1990-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _FAX3_ +#define _FAX3_ +/* + * TIFF Library. + * + * CCITT Group 3 (T.4) and Group 4 (T.6) Decompression Support. + * + * Decoder support is derived, with permission, from the code + * in Frank Cringle's viewfax program; + * Copyright (C) 1990, 1995 Frank D. Cringle. + */ +#include "tiff.h" + +/* + * To override the default routine used to image decoded + * spans one can use the pseduo tag TIFFTAG_FAXFILLFUNC. + * The routine must have the type signature given below; + * for example: + * + * fillruns(unsigned char* buf, uint32* runs, uint32* erun, uint32 lastx) + * + * where buf is place to set the bits, runs is the array of b&w run + * lengths (white then black), erun is the last run in the array, and + * lastx is the width of the row in pixels. Fill routines can assume + * the run array has room for at least lastx runs and can overwrite + * data in the run array as needed (e.g. to append zero runs to bring + * the count up to a nice multiple). + */ +typedef void (*TIFFFaxFillFunc)(unsigned char*, uint32*, uint32*, uint32); + +/* + * The default run filler; made external for other decoders. + */ +#if defined(__cplusplus) +extern "C" { +#endif +extern void _TIFFFax3fillruns(unsigned char*, uint32*, uint32*, uint32); +#if defined(__cplusplus) +} +#endif + + +/* finite state machine codes */ +#define S_Null 0 +#define S_Pass 1 +#define S_Horiz 2 +#define S_V0 3 +#define S_VR 4 +#define S_VL 5 +#define S_Ext 6 +#define S_TermW 7 +#define S_TermB 8 +#define S_MakeUpW 9 +#define S_MakeUpB 10 +#define S_MakeUp 11 +#define S_EOL 12 + +typedef struct { /* state table entry */ + unsigned char State; /* see above */ + unsigned char Width; /* width of code in bits */ + uint32 Param; /* unsigned 32-bit run length in bits */ +} TIFFFaxTabEnt; + +extern const TIFFFaxTabEnt TIFFFaxMainTable[]; +extern const TIFFFaxTabEnt TIFFFaxWhiteTable[]; +extern const TIFFFaxTabEnt TIFFFaxBlackTable[]; + +/* + * The following macros define the majority of the G3/G4 decoder + * algorithm using the state tables defined elsewhere. To build + * a decoder you need some setup code and some glue code. Note + * that you may also need/want to change the way the NeedBits* + * macros get input data if, for example, you know the data to be + * decoded is properly aligned and oriented (doing so before running + * the decoder can be a big performance win). + * + * Consult the decoder in the TIFF library for an idea of what you + * need to define and setup to make use of these definitions. + * + * NB: to enable a debugging version of these macros define FAX3_DEBUG + * before including this file. Trace output goes to stdout. + */ + +#ifndef EndOfData +#define EndOfData() (cp >= ep) +#endif +/* + * Need <=8 or <=16 bits of input data. Unlike viewfax we + * cannot use/assume a word-aligned, properly bit swizzled + * input data set because data may come from an arbitrarily + * aligned, read-only source such as a memory-mapped file. + * Note also that the viewfax decoder does not check for + * running off the end of the input data buffer. This is + * possible for G3-encoded data because it prescans the input + * data to count EOL markers, but can cause problems for G4 + * data. In any event, we don't prescan and must watch for + * running out of data since we can't permit the library to + * scan past the end of the input data buffer. + * + * Finally, note that we must handle remaindered data at the end + * of a strip specially. The coder asks for a fixed number of + * bits when scanning for the next code. This may be more bits + * than are actually present in the data stream. If we appear + * to run out of data but still have some number of valid bits + * remaining then we makeup the requested amount with zeros and + * return successfully. If the returned data is incorrect then + * we should be called again and get a premature EOF error; + * otherwise we should get the right answer. + */ +#ifndef NeedBits8 +#define NeedBits8(n,eoflab) do { \ + if (BitsAvail < (n)) { \ + if (EndOfData()) { \ + if (BitsAvail == 0) /* no valid bits */ \ + goto eoflab; \ + BitsAvail = (n); /* pad with zeros */ \ + } else { \ + BitAcc |= ((uint32) bitmap[*cp++])<>= (n); \ +} while (0) + +#ifdef FAX3_DEBUG +static const char* StateNames[] = { + "Null ", + "Pass ", + "Horiz ", + "V0 ", + "VR ", + "VL ", + "Ext ", + "TermW ", + "TermB ", + "MakeUpW", + "MakeUpB", + "MakeUp ", + "EOL ", +}; +#define DEBUG_SHOW putchar(BitAcc & (1 << t) ? '1' : '0') +#define LOOKUP8(wid,tab,eoflab) do { \ + int t; \ + NeedBits8(wid,eoflab); \ + TabEnt = tab + GetBits(wid); \ + printf("%08lX/%d: %s%5d\t", (long) BitAcc, BitsAvail, \ + StateNames[TabEnt->State], TabEnt->Param); \ + for (t = 0; t < TabEnt->Width; t++) \ + DEBUG_SHOW; \ + putchar('\n'); \ + fflush(stdout); \ + ClrBits(TabEnt->Width); \ +} while (0) +#define LOOKUP16(wid,tab,eoflab) do { \ + int t; \ + NeedBits16(wid,eoflab); \ + TabEnt = tab + GetBits(wid); \ + printf("%08lX/%d: %s%5d\t", (long) BitAcc, BitsAvail, \ + StateNames[TabEnt->State], TabEnt->Param); \ + for (t = 0; t < TabEnt->Width; t++) \ + DEBUG_SHOW; \ + putchar('\n'); \ + fflush(stdout); \ + ClrBits(TabEnt->Width); \ +} while (0) + +#define SETVAL(x) do { \ + *pa++ = RunLength + (x); \ + printf("SETVAL: %d\t%d\n", RunLength + (x), a0); \ + a0 += x; \ + RunLength = 0; \ +} while (0) +#else +#define LOOKUP8(wid,tab,eoflab) do { \ + NeedBits8(wid,eoflab); \ + TabEnt = tab + GetBits(wid); \ + ClrBits(TabEnt->Width); \ +} while (0) +#define LOOKUP16(wid,tab,eoflab) do { \ + NeedBits16(wid,eoflab); \ + TabEnt = tab + GetBits(wid); \ + ClrBits(TabEnt->Width); \ +} while (0) + +/* + * Append a run to the run length array for the + * current row and reset decoding state. + */ +#define SETVAL(x) do { \ + *pa++ = RunLength + (x); \ + a0 += (x); \ + RunLength = 0; \ +} while (0) +#endif + +/* + * Synchronize input decoding at the start of each + * row by scanning for an EOL (if appropriate) and + * skipping any trash data that might be present + * after a decoding error. Note that the decoding + * done elsewhere that recognizes an EOL only consumes + * 11 consecutive zero bits. This means that if EOLcnt + * is non-zero then we still need to scan for the final flag + * bit that is part of the EOL code. + */ +#define SYNC_EOL(eoflab) do { \ + if (EOLcnt == 0) { \ + for (;;) { \ + NeedBits16(11,eoflab); \ + if (GetBits(11) == 0) \ + break; \ + ClrBits(1); \ + } \ + } \ + for (;;) { \ + NeedBits8(8,eoflab); \ + if (GetBits(8)) \ + break; \ + ClrBits(8); \ + } \ + while (GetBits(1) == 0) \ + ClrBits(1); \ + ClrBits(1); /* EOL bit */ \ + EOLcnt = 0; /* reset EOL counter/flag */ \ +} while (0) + +/* + * Cleanup the array of runs after decoding a row. + * We adjust final runs to insure the user buffer is not + * overwritten and/or undecoded area is white filled. + */ +#define CLEANUP_RUNS() do { \ + if (RunLength) \ + SETVAL(0); \ + if (a0 != lastx) { \ + badlength(a0, lastx); \ + while (a0 > lastx && pa > thisrun) \ + a0 -= *--pa; \ + if (a0 < lastx) { \ + if (a0 < 0) \ + a0 = 0; \ + if ((pa-thisrun)&1) \ + SETVAL(0); \ + SETVAL(lastx - a0); \ + } else if (a0 > lastx) { \ + SETVAL(lastx); \ + SETVAL(0); \ + } \ + } \ +} while (0) + +/* + * Decode a line of 1D-encoded data. + * + * The line expanders are written as macros so that they can be reused + * but still have direct access to the local variables of the "calling" + * function. + * + * Note that unlike the original version we have to explicitly test for + * a0 >= lastx after each black/white run is decoded. This is because + * the original code depended on the input data being zero-padded to + * insure the decoder recognized an EOL before running out of data. + */ +#define EXPAND1D(eoflab) do { \ + for (;;) { \ + for (;;) { \ + LOOKUP16(12, TIFFFaxWhiteTable, eof1d); \ + switch (TabEnt->State) { \ + case S_EOL: \ + EOLcnt = 1; \ + goto done1d; \ + case S_TermW: \ + SETVAL(TabEnt->Param); \ + goto doneWhite1d; \ + case S_MakeUpW: \ + case S_MakeUp: \ + a0 += TabEnt->Param; \ + RunLength += TabEnt->Param; \ + break; \ + default: \ + unexpected("WhiteTable", a0); \ + goto done1d; \ + } \ + } \ + doneWhite1d: \ + if (a0 >= lastx) \ + goto done1d; \ + for (;;) { \ + LOOKUP16(13, TIFFFaxBlackTable, eof1d); \ + switch (TabEnt->State) { \ + case S_EOL: \ + EOLcnt = 1; \ + goto done1d; \ + case S_TermB: \ + SETVAL(TabEnt->Param); \ + goto doneBlack1d; \ + case S_MakeUpB: \ + case S_MakeUp: \ + a0 += TabEnt->Param; \ + RunLength += TabEnt->Param; \ + break; \ + default: \ + unexpected("BlackTable", a0); \ + goto done1d; \ + } \ + } \ + doneBlack1d: \ + if (a0 >= lastx) \ + goto done1d; \ + if( *(pa-1) == 0 && *(pa-2) == 0 ) \ + pa -= 2; \ + } \ +eof1d: \ + prematureEOF(a0); \ + CLEANUP_RUNS(); \ + goto eoflab; \ +done1d: \ + CLEANUP_RUNS(); \ +} while (0) + +/* + * Update the value of b1 using the array + * of runs for the reference line. + */ +#define CHECK_b1 do { \ + if (pa != thisrun) while (b1 <= a0 && b1 < lastx) { \ + b1 += pb[0] + pb[1]; \ + pb += 2; \ + } \ +} while (0) + +/* + * Expand a row of 2D-encoded data. + */ +#define EXPAND2D(eoflab) do { \ + while (a0 < lastx) { \ + LOOKUP8(7, TIFFFaxMainTable, eof2d); \ + switch (TabEnt->State) { \ + case S_Pass: \ + CHECK_b1; \ + b1 += *pb++; \ + RunLength += b1 - a0; \ + a0 = b1; \ + b1 += *pb++; \ + break; \ + case S_Horiz: \ + if ((pa-thisrun)&1) { \ + for (;;) { /* black first */ \ + LOOKUP16(13, TIFFFaxBlackTable, eof2d); \ + switch (TabEnt->State) { \ + case S_TermB: \ + SETVAL(TabEnt->Param); \ + goto doneWhite2da; \ + case S_MakeUpB: \ + case S_MakeUp: \ + a0 += TabEnt->Param; \ + RunLength += TabEnt->Param; \ + break; \ + default: \ + goto badBlack2d; \ + } \ + } \ + doneWhite2da:; \ + for (;;) { /* then white */ \ + LOOKUP16(12, TIFFFaxWhiteTable, eof2d); \ + switch (TabEnt->State) { \ + case S_TermW: \ + SETVAL(TabEnt->Param); \ + goto doneBlack2da; \ + case S_MakeUpW: \ + case S_MakeUp: \ + a0 += TabEnt->Param; \ + RunLength += TabEnt->Param; \ + break; \ + default: \ + goto badWhite2d; \ + } \ + } \ + doneBlack2da:; \ + } else { \ + for (;;) { /* white first */ \ + LOOKUP16(12, TIFFFaxWhiteTable, eof2d); \ + switch (TabEnt->State) { \ + case S_TermW: \ + SETVAL(TabEnt->Param); \ + goto doneWhite2db; \ + case S_MakeUpW: \ + case S_MakeUp: \ + a0 += TabEnt->Param; \ + RunLength += TabEnt->Param; \ + break; \ + default: \ + goto badWhite2d; \ + } \ + } \ + doneWhite2db:; \ + for (;;) { /* then black */ \ + LOOKUP16(13, TIFFFaxBlackTable, eof2d); \ + switch (TabEnt->State) { \ + case S_TermB: \ + SETVAL(TabEnt->Param); \ + goto doneBlack2db; \ + case S_MakeUpB: \ + case S_MakeUp: \ + a0 += TabEnt->Param; \ + RunLength += TabEnt->Param; \ + break; \ + default: \ + goto badBlack2d; \ + } \ + } \ + doneBlack2db:; \ + } \ + CHECK_b1; \ + break; \ + case S_V0: \ + CHECK_b1; \ + SETVAL(b1 - a0); \ + b1 += *pb++; \ + break; \ + case S_VR: \ + CHECK_b1; \ + SETVAL(b1 - a0 + TabEnt->Param); \ + b1 += *pb++; \ + break; \ + case S_VL: \ + CHECK_b1; \ + SETVAL(b1 - a0 - TabEnt->Param); \ + b1 -= *--pb; \ + break; \ + case S_Ext: \ + *pa++ = lastx - a0; \ + extension(a0); \ + goto eol2d; \ + case S_EOL: \ + *pa++ = lastx - a0; \ + NeedBits8(4,eof2d); \ + if (GetBits(4)) \ + unexpected("EOL", a0); \ + ClrBits(4); \ + EOLcnt = 1; \ + goto eol2d; \ + default: \ + badMain2d: \ + unexpected("MainTable", a0); \ + goto eol2d; \ + badBlack2d: \ + unexpected("BlackTable", a0); \ + goto eol2d; \ + badWhite2d: \ + unexpected("WhiteTable", a0); \ + goto eol2d; \ + eof2d: \ + prematureEOF(a0); \ + CLEANUP_RUNS(); \ + goto eoflab; \ + } \ + } \ + if (RunLength) { \ + if (RunLength + a0 < lastx) { \ + /* expect a final V0 */ \ + NeedBits8(1,eof2d); \ + if (!GetBits(1)) \ + goto badMain2d; \ + ClrBits(1); \ + } \ + SETVAL(0); \ + } \ +eol2d: \ + CLEANUP_RUNS(); \ +} while (0) +#endif /* _FAX3_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_flush.c b/SlnkDWFImpl/CxImage/tiff/tif_flush.c new file mode 100644 index 0000000..66f9295 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_flush.c @@ -0,0 +1,67 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_flush.c,v 1.3 2000/09/15 20:52:42 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + */ +#include "tiffiop.h" + +int +TIFFFlush(TIFF* tif) +{ + + if (tif->tif_mode != O_RDONLY) { + if (!TIFFFlushData(tif)) + return (0); + if ((tif->tif_flags & TIFF_DIRTYDIRECT) && + !TIFFWriteDirectory(tif)) + return (0); + } + return (1); +} + +/* + * Flush buffered data to the file. + * + * Frank Warmerdam'2000: I modified this to return 1 if TIFF_BEENWRITING + * is not set, so that TIFFFlush() will proceed to write out the directory. + * The documentation says returning 1 is an error indicator, but not having + * been writing isn't exactly a an error. Hopefully this doesn't cause + * problems for other people. + */ +int +TIFFFlushData(TIFF* tif) +{ + if ((tif->tif_flags & TIFF_BEENWRITING) == 0) + return (0); + if (tif->tif_flags & TIFF_POSTENCODE) { + tif->tif_flags &= ~TIFF_POSTENCODE; + if (!(*tif->tif_postencode)(tif)) + return (0); + } + return (TIFFFlushData1(tif)); +} + diff --git a/SlnkDWFImpl/CxImage/tiff/tif_getimage.c b/SlnkDWFImpl/CxImage/tiff/tif_getimage.c new file mode 100644 index 0000000..299c8fc --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_getimage.c @@ -0,0 +1,2424 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_getimage.c,v 1.15 2001/09/24 19:40:37 warmerda Exp $ */ + +/* + * Copyright (c) 1991-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library + * + * Read and return a packed RGBA image. + */ + +#pragma warning (disable : 4550) + +#include "tiffiop.h" +#include +#include + +static int gtTileContig(TIFFRGBAImage*, uint32*, uint32, uint32); +static int gtTileSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); +static int gtStripContig(TIFFRGBAImage*, uint32*, uint32, uint32); +static int gtStripSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); +static int pickTileContigCase(TIFFRGBAImage*); +static int pickTileSeparateCase(TIFFRGBAImage*); + +static const char photoTag[] = "PhotometricInterpretation"; + +/* + * Check the image to see if TIFFReadRGBAImage can deal with it. + * 1/0 is returned according to whether or not the image can + * be handled. If 0 is returned, emsg contains the reason + * why it is being rejected. + */ +int +TIFFRGBAImageOK(TIFF* tif, char emsg[1024]) +{ + TIFFDirectory* td = &tif->tif_dir; + uint16 photometric; + int colorchannels; + + switch (td->td_bitspersample) { + case 1: case 2: case 4: + case 8: case 16: + break; + default: + sprintf(emsg, "Sorry, can not handle images with %d-bit samples", + td->td_bitspersample); + return (0); + } + colorchannels = td->td_samplesperpixel - td->td_extrasamples; + if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) { + switch (colorchannels) { + case 1: + photometric = PHOTOMETRIC_MINISBLACK; + break; + case 3: + photometric = PHOTOMETRIC_RGB; + break; + default: + sprintf(emsg, "Missing needed %s tag", photoTag); + return (0); + } + } + switch (photometric) { + case PHOTOMETRIC_MINISWHITE: + case PHOTOMETRIC_MINISBLACK: + case PHOTOMETRIC_PALETTE: + if (td->td_planarconfig == PLANARCONFIG_CONTIG + && td->td_samplesperpixel != 1 + && td->td_bitspersample < 8 ) { + sprintf(emsg, + "Sorry, can not handle contiguous data with %s=%d, " + "and %s=%d and Bits/Sample=%d", + photoTag, photometric, + "Samples/pixel", td->td_samplesperpixel, + td->td_bitspersample); + return (0); + } + /* + ** We should likely validate that any extra samples are either + ** to be ignored, or are alpha, and if alpha we should try to use + ** them. But for now we won't bother with this. + */ + break; + case PHOTOMETRIC_YCBCR: + if (td->td_planarconfig != PLANARCONFIG_CONTIG) { + sprintf(emsg, "Sorry, can not handle YCbCr images with %s=%d", + "Planarconfiguration", td->td_planarconfig); + return (0); + } + break; + case PHOTOMETRIC_RGB: + if (colorchannels < 3) { + sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", + "Color channels", colorchannels); + return (0); + } + break; +#ifdef CMYK_SUPPORT + case PHOTOMETRIC_SEPARATED: + if (td->td_inkset != INKSET_CMYK) { + sprintf(emsg, "Sorry, can not handle separated image with %s=%d", + "InkSet", td->td_inkset); + return (0); + } + if (td->td_samplesperpixel < 4) { + sprintf(emsg, "Sorry, can not handle separated image with %s=%d", + "Samples/pixel", td->td_samplesperpixel); + return (0); + } + break; +#endif + case PHOTOMETRIC_LOGL: + if (td->td_compression != COMPRESSION_SGILOG) { + sprintf(emsg, "Sorry, LogL data must have %s=%d", + "Compression", COMPRESSION_SGILOG); + return (0); + } + break; + case PHOTOMETRIC_LOGLUV: + if (td->td_compression != COMPRESSION_SGILOG && + td->td_compression != COMPRESSION_SGILOG24) { + sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", + "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); + return (0); + } + if (td->td_planarconfig != PLANARCONFIG_CONTIG) { + sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", + "Planarconfiguration", td->td_planarconfig); + return (0); + } + break; + default: + sprintf(emsg, "Sorry, can not handle image with %s=%d", + photoTag, photometric); + return (0); + } + return (1); +} + +void +TIFFRGBAImageEnd(TIFFRGBAImage* img) +{ + if (img->Map) + _TIFFfree(img->Map), img->Map = NULL; + if (img->BWmap) + _TIFFfree(img->BWmap), img->BWmap = NULL; + if (img->PALmap) + _TIFFfree(img->PALmap), img->PALmap = NULL; + if (img->ycbcr) + _TIFFfree(img->ycbcr), img->ycbcr = NULL; + + if( img->redcmap ) { + _TIFFfree( img->redcmap ); + _TIFFfree( img->greencmap ); + _TIFFfree( img->bluecmap ); + } +} + +static int +isCCITTCompression(TIFF* tif) +{ + uint16 compress; + TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress); + return (compress == COMPRESSION_CCITTFAX3 || + compress == COMPRESSION_CCITTFAX4 || + compress == COMPRESSION_CCITTRLE || + compress == COMPRESSION_CCITTRLEW); +} + +int +TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024]) +{ + uint16* sampleinfo; + uint16 extrasamples; + uint16 planarconfig; + uint16 compress; + int colorchannels; + uint16 *red_orig, *green_orig, *blue_orig; + int n_color; + + /* Initialize to normal values */ + img->row_offset = 0; + img->col_offset = 0; + img->redcmap = NULL; + img->greencmap = NULL; + img->bluecmap = NULL; + + img->tif = tif; + img->stoponerr = stop; + TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &img->bitspersample); + switch (img->bitspersample) { + case 1: case 2: case 4: + case 8: case 16: + break; + default: + sprintf(emsg, "Sorry, can not image with %d-bit samples", + img->bitspersample); + return (0); + } + img->alpha = 1; + TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &img->samplesperpixel); + TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, + &extrasamples, &sampleinfo); + if (extrasamples == 1) + switch (sampleinfo[0]) { + case EXTRASAMPLE_ASSOCALPHA: /* data is pre-multiplied */ + case EXTRASAMPLE_UNASSALPHA: /* data is not pre-multiplied */ + img->alpha = sampleinfo[0]; + break; + } + colorchannels = img->samplesperpixel - extrasamples; + TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compress); + TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfig); + if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) { + switch (colorchannels) { + case 1: + if (isCCITTCompression(tif)) + img->photometric = PHOTOMETRIC_MINISWHITE; + else + img->photometric = PHOTOMETRIC_MINISBLACK; + break; + case 3: + img->photometric = PHOTOMETRIC_RGB; + break; + default: + sprintf(emsg, "Missing needed %s tag", photoTag); + return (0); + } + } + switch (img->photometric) { + case PHOTOMETRIC_PALETTE: + if (!TIFFGetField(tif, TIFFTAG_COLORMAP, + &red_orig, &green_orig, &blue_orig)) { + TIFFError(TIFFFileName(tif), "Missing required \"Colormap\" tag"); + return (0); + } + + /* copy the colormaps so we can modify them */ + n_color = (1L << img->bitspersample); + img->redcmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); + img->greencmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); + img->bluecmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); + if( !img->redcmap || !img->greencmap || !img->bluecmap ) { + TIFFError(TIFFFileName(tif), "Out of memory for colormap copy"); + return (0); + } + + memcpy( img->redcmap, red_orig, n_color * 2 ); + memcpy( img->greencmap, green_orig, n_color * 2 ); + memcpy( img->bluecmap, blue_orig, n_color * 2 ); + + /* fall thru... */ + case PHOTOMETRIC_MINISWHITE: + case PHOTOMETRIC_MINISBLACK: + if (planarconfig == PLANARCONFIG_CONTIG + && img->samplesperpixel != 1 + && img->bitspersample < 8 ) { + sprintf(emsg, + "Sorry, can not handle contiguous data with %s=%d, " + "and %s=%d and Bits/Sample=%d", + photoTag, img->photometric, + "Samples/pixel", img->samplesperpixel, + img->bitspersample); + return (0); + } + break; + case PHOTOMETRIC_YCBCR: + if (planarconfig != PLANARCONFIG_CONTIG) { + sprintf(emsg, "Sorry, can not handle YCbCr images with %s=%d", + "Planarconfiguration", planarconfig); + return (0); + } + /* It would probably be nice to have a reality check here. */ + if (planarconfig == PLANARCONFIG_CONTIG) + /* can rely on libjpeg to convert to RGB */ + /* XXX should restore current state on exit */ + switch (compress) { + case COMPRESSION_OJPEG: + case COMPRESSION_JPEG: + TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); + img->photometric = PHOTOMETRIC_RGB; + break; + + default: + /* do nothing */; + break; + } + break; + case PHOTOMETRIC_RGB: + if (colorchannels < 3) { + sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", + "Color channels", colorchannels); + return (0); + } + break; + case PHOTOMETRIC_SEPARATED: { + uint16 inkset; + TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); + if (inkset != INKSET_CMYK) { + sprintf(emsg, "Sorry, can not handle separated image with %s=%d", + "InkSet", inkset); + return (0); + } + if (img->samplesperpixel < 4) { + sprintf(emsg, "Sorry, can not handle separated image with %s=%d", + "Samples/pixel", img->samplesperpixel); + return (0); + } + break; + } + case PHOTOMETRIC_LOGL: + if (compress != COMPRESSION_SGILOG) { + sprintf(emsg, "Sorry, LogL data must have %s=%d", + "Compression", COMPRESSION_SGILOG); + return (0); + } + TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); + img->photometric = PHOTOMETRIC_MINISBLACK; /* little white lie */ + img->bitspersample = 8; + break; + case PHOTOMETRIC_LOGLUV: + if (compress != COMPRESSION_SGILOG && compress != COMPRESSION_SGILOG24) { + sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", + "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); + return (0); + } + if (planarconfig != PLANARCONFIG_CONTIG) { + sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", + "Planarconfiguration", planarconfig); + return (0); + } + TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); + img->photometric = PHOTOMETRIC_RGB; /* little white lie */ + img->bitspersample = 8; + break; + default: + sprintf(emsg, "Sorry, can not handle image with %s=%d", + photoTag, img->photometric); + return (0); + } + img->Map = NULL; + img->BWmap = NULL; + img->PALmap = NULL; + img->ycbcr = NULL; + TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &img->width); + TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &img->height); + TIFFGetFieldDefaulted(tif, TIFFTAG_ORIENTATION, &img->orientation); + img->isContig = + !(planarconfig == PLANARCONFIG_SEPARATE && colorchannels > 1); + if (img->isContig) { + img->get = TIFFIsTiled(tif) ? gtTileContig : gtStripContig; + (void) pickTileContigCase(img); + } else { + img->get = TIFFIsTiled(tif) ? gtTileSeparate : gtStripSeparate; + (void) pickTileSeparateCase(img); + } + return (1); +} + +int +TIFFRGBAImageGet(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) +{ + if (img->get == NULL) { + TIFFError(TIFFFileName(img->tif), "No \"get\" routine setup"); + return (0); + } + if (img->put.any == NULL) { + TIFFError(TIFFFileName(img->tif), + "No \"put\" routine setupl; probably can not handle image format"); + return (0); + } + return (*img->get)(img, raster, w, h); +} + +/* + * Read the specified image into an ABGR-format raster. + */ +int +TIFFReadRGBAImage(TIFF* tif, + uint32 rwidth, uint32 rheight, uint32* raster, int stop) +{ + char emsg[1024]; + TIFFRGBAImage img; + int ok; + + if (TIFFRGBAImageBegin(&img, tif, stop, emsg)) { + /* XXX verify rwidth and rheight against width and height */ + ok = TIFFRGBAImageGet(&img, raster+(rheight-img.height)*rwidth, + rwidth, img.height); + TIFFRGBAImageEnd(&img); + } else { + TIFFError(TIFFFileName(tif), emsg); + ok = 0; + } + return (ok); +} + +static uint32 +setorientation(TIFFRGBAImage* img, uint32 h) +{ + TIFF* tif = img->tif; + uint32 y; + + switch (img->orientation) { + case ORIENTATION_BOTRIGHT: + case ORIENTATION_RIGHTBOT: /* XXX */ + case ORIENTATION_LEFTBOT: /* XXX */ + TIFFWarning(TIFFFileName(tif), "using bottom-left orientation"); + img->orientation = ORIENTATION_BOTLEFT; + /* fall thru... */ + case ORIENTATION_BOTLEFT: + y = 0; + break; + case ORIENTATION_TOPRIGHT: + case ORIENTATION_RIGHTTOP: /* XXX */ + case ORIENTATION_LEFTTOP: /* XXX */ + default: + TIFFWarning(TIFFFileName(tif), "using top-left orientation"); + img->orientation = ORIENTATION_TOPLEFT; + /* fall thru... */ + case ORIENTATION_TOPLEFT: + y = h-1; + break; + } + return (y); +} + +/* + * Get an tile-organized image that has + * PlanarConfiguration contiguous if SamplesPerPixel > 1 + * or + * SamplesPerPixel == 1 + */ +static int +gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) +{ + TIFF* tif = img->tif; + tileContigRoutine put = img->put.contig; + uint16 orientation; + uint32 col, row, y, rowstoread, ret = 1; + uint32 pos; + uint32 tw, th; + u_char* buf; + int32 fromskew, toskew; + uint32 nrow; + + buf = (u_char*) _TIFFmalloc(TIFFTileSize(tif)); + if (buf == 0) { + TIFFError(TIFFFileName(tif), "No space for tile buffer"); + return (0); + } + TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); + TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); + y = setorientation(img, h); + orientation = img->orientation; + toskew = -(int32) (orientation == ORIENTATION_TOPLEFT ? tw+w : tw-w); + for (row = 0; row < h; row += nrow) + { + rowstoread = th - (row + img->row_offset) % th; + nrow = (row + rowstoread > h ? h - row : rowstoread); + for (col = 0; col < w; col += tw) + { + if (TIFFReadTile(tif, buf, col+img->col_offset, + row+img->row_offset, 0, 0) < 0 && img->stoponerr) + { + ret = 0; + break; + } + + pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif); + + if (col + tw > w) + { + /* + * Tile is clipped horizontally. Calculate + * visible portion and skewing factors. + */ + uint32 npix = w - col; + fromskew = tw - npix; + (*put)(img, raster+y*w+col, col, y, + npix, nrow, fromskew, toskew + fromskew, buf + pos); + } + else + { + (*put)(img, raster+y*w+col, col, y, tw, nrow, 0, toskew, buf + pos); + } + } + + y += (orientation == ORIENTATION_TOPLEFT ? -(int32) nrow : (int32) nrow); + } + _TIFFfree(buf); + return (ret); +} + +/* + * Get an tile-organized image that has + * SamplesPerPixel > 1 + * PlanarConfiguration separated + * We assume that all such images are RGB. + */ +static int +gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) +{ + TIFF* tif = img->tif; + tileSeparateRoutine put = img->put.separate; + uint16 orientation; + uint32 col, row, y, rowstoread; + uint32 pos; + uint32 tw, th; + u_char* buf; + u_char* r; + u_char* g; + u_char* b; + u_char* a; + tsize_t tilesize; + int32 fromskew, toskew; + int alpha = img->alpha; + uint32 nrow; + int ret = 1; + + tilesize = TIFFTileSize(tif); + buf = (u_char*) _TIFFmalloc(4*tilesize); + if (buf == 0) { + TIFFError(TIFFFileName(tif), "No space for tile buffer"); + return (0); + } + r = buf; + g = r + tilesize; + b = g + tilesize; + a = b + tilesize; + if (!alpha) + memset(a, 0xff, tilesize); + TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); + TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); + y = setorientation(img, h); + orientation = img->orientation; + toskew = -(int32) (orientation == ORIENTATION_TOPLEFT ? tw+w : tw-w); + for (row = 0; row < h; row += nrow) + { + rowstoread = th - (row + img->row_offset) % th; + nrow = (row + rowstoread > h ? h - row : rowstoread); + for (col = 0; col < w; col += tw) + { + if (TIFFReadTile(tif, r, col+img->col_offset, + row+img->row_offset,0,0) < 0 && img->stoponerr) + { + ret = 0; + break; + } + if (TIFFReadTile(tif, g, col+img->col_offset, + row+img->row_offset,0,1) < 0 && img->stoponerr) + { + ret = 0; + break; + } + if (TIFFReadTile(tif, b, col+img->col_offset, + row+img->row_offset,0,2) < 0 && img->stoponerr) + { + ret = 0; + break; + } + if (alpha && TIFFReadTile(tif,a,col+img->col_offset, + row+img->row_offset,0,3) < 0 && img->stoponerr) + { + ret = 0; + break; + } + + pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif); + + if (col + tw > w) + { + /* + * Tile is clipped horizontally. Calculate + * visible portion and skewing factors. + */ + uint32 npix = w - col; + fromskew = tw - npix; + (*put)(img, raster+y*w+col, col, y, + npix, nrow, fromskew, toskew + fromskew, + r + pos, g + pos, b + pos, a + pos); + } + else + { + (*put)(img, raster+y*w+col, col, y, + tw, nrow, 0, toskew, r + pos, g + pos, b + pos, a + pos); + } + } + + y += (orientation == ORIENTATION_TOPLEFT ?-(int32) nrow : (int32) nrow); + } + _TIFFfree(buf); + return (ret); +} + +/* + * Get a strip-organized image that has + * PlanarConfiguration contiguous if SamplesPerPixel > 1 + * or + * SamplesPerPixel == 1 + */ +static int +gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) +{ + TIFF* tif = img->tif; + tileContigRoutine put = img->put.contig; + uint16 orientation; + uint32 row, y, nrow, rowstoread; + uint32 pos; + u_char* buf; + uint32 rowsperstrip; + uint32 imagewidth = img->width; + tsize_t scanline; + int32 fromskew, toskew; + int ret = 1; + + buf = (u_char*) _TIFFmalloc(TIFFStripSize(tif)); + if (buf == 0) { + TIFFError(TIFFFileName(tif), "No space for strip buffer"); + return (0); + } + y = setorientation(img, h); + orientation = img->orientation; + toskew = -(int32) (orientation == ORIENTATION_TOPLEFT ? w+w : w-w); + TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); + scanline = TIFFScanlineSize(tif); + fromskew = (w < imagewidth ? imagewidth - w : 0); + for (row = 0; row < h; row += nrow) + { + rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; + nrow = (row + rowstoread > h ? h - row : rowstoread); + if (TIFFReadEncodedStrip(tif, + TIFFComputeStrip(tif,row+img->row_offset, 0), + buf, + ((row + img->row_offset)%rowsperstrip + nrow) * scanline) < 0 + && img->stoponerr) + { + ret = 0; + break; + } + + pos = ((row + img->row_offset) % rowsperstrip) * scanline; + (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, buf + pos); + y += (orientation == ORIENTATION_TOPLEFT ?-(int32) nrow : (int32) nrow); + } + _TIFFfree(buf); + return (ret); +} + +/* + * Get a strip-organized image with + * SamplesPerPixel > 1 + * PlanarConfiguration separated + * We assume that all such images are RGB. + */ +static int +gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) +{ + TIFF* tif = img->tif; + tileSeparateRoutine put = img->put.separate; + uint16 orientation; + u_char *buf; + u_char *r, *g, *b, *a; + uint32 row, y, nrow, rowstoread; + uint32 pos; + tsize_t scanline; + uint32 rowsperstrip, offset_row; + uint32 imagewidth = img->width; + tsize_t stripsize; + int32 fromskew, toskew; + int alpha = img->alpha; + int ret = 1; + + stripsize = TIFFStripSize(tif); + r = buf = (u_char *)_TIFFmalloc(4*stripsize); + if (buf == 0) { + TIFFError(TIFFFileName(tif), "No space for tile buffer"); + return (0); + } + g = r + stripsize; + b = g + stripsize; + a = b + stripsize; + if (!alpha) + memset(a, 0xff, stripsize); + y = setorientation(img, h); + orientation = img->orientation; + toskew = -(int32) (orientation == ORIENTATION_TOPLEFT ? w+w : w-w); + TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); + scanline = TIFFScanlineSize(tif); + fromskew = (w < imagewidth ? imagewidth - w : 0); + for (row = 0; row < h; row += nrow) + { + rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; + nrow = (row + rowstoread > h ? h - row : rowstoread); + offset_row = row + img->row_offset; + if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 0), + r, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) < 0 + && img->stoponerr) + { + ret = 0; + break; + } + if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 1), + g, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) < 0 + && img->stoponerr) + { + ret = 0; + break; + } + if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 2), + b, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) < 0 + && img->stoponerr) + { + ret = 0; + break; + } + if (alpha && + (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 3), + a, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) < 0 + && img->stoponerr)) + { + ret = 0; + break; + } + + pos = ((row + img->row_offset) % rowsperstrip) * scanline; + (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, r + pos, g + pos, + b + pos, a + pos); + y += (orientation == ORIENTATION_TOPLEFT ? -(int32) nrow : (int32) nrow); + } + _TIFFfree(buf); + return (ret); +} + +/* + * The following routines move decoded data returned + * from the TIFF library into rasters filled with packed + * ABGR pixels (i.e. suitable for passing to lrecwrite.) + * + * The routines have been created according to the most + * important cases and optimized. pickTileContigCase and + * pickTileSeparateCase analyze the parameters and select + * the appropriate "put" routine to use. + */ +#define REPEAT8(op) REPEAT4(op); REPEAT4(op) +#define REPEAT4(op) REPEAT2(op); REPEAT2(op) +#define REPEAT2(op) op; op +#define CASE8(x,op) \ + switch (x) { \ + case 7: op; case 6: op; case 5: op; \ + case 4: op; case 3: op; case 2: op; \ + case 1: op; \ + } +#define CASE4(x,op) switch (x) { case 3: op; case 2: op; case 1: op; } +#define NOP + +#define UNROLL8(w, op1, op2) { \ + uint32 _x; \ + for (_x = w; _x >= 8; _x -= 8) { \ + op1; \ + REPEAT8(op2); \ + } \ + if (_x > 0) { \ + op1; \ + CASE8(_x,op2); \ + } \ +} +#define UNROLL4(w, op1, op2) { \ + uint32 _x; \ + for (_x = w; _x >= 4; _x -= 4) { \ + op1; \ + REPEAT4(op2); \ + } \ + if (_x > 0) { \ + op1; \ + CASE4(_x,op2); \ + } \ +} +#define UNROLL2(w, op1, op2) { \ + uint32 _x; \ + for (_x = w; _x >= 2; _x -= 2) { \ + op1; \ + REPEAT2(op2); \ + } \ + if (_x) { \ + op1; \ + op2; \ + } \ +} + +#define SKEW(r,g,b,skew) { r += skew; g += skew; b += skew; } +#define SKEW4(r,g,b,a,skew) { r += skew; g += skew; b += skew; a+= skew; } + +#define A1 ((uint32)(0xffL<<24)) +#define PACK(r,g,b) \ + ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|A1) +#define PACK4(r,g,b,a) \ + ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|((uint32)(a)<<24)) +#define W2B(v) (((v)>>8)&0xff) +#define PACKW(r,g,b) \ + ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|A1) +#define PACKW4(r,g,b,a) \ + ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|((uint32)W2B(a)<<24)) + +#define DECLAREContigPutFunc(name) \ +static void name(\ + TIFFRGBAImage* img, \ + uint32* cp, \ + uint32 x, uint32 y, \ + uint32 w, uint32 h, \ + int32 fromskew, int32 toskew, \ + u_char* pp \ +) + +/* + * 8-bit palette => colormap/RGB + */ +DECLAREContigPutFunc(put8bitcmaptile) +{ + uint32** PALmap = img->PALmap; + int samplesperpixel = img->samplesperpixel; + + (void) y; + while (h-- > 0) { + for (x = w; x-- > 0;) + { + *cp++ = PALmap[*pp][0]; + pp += samplesperpixel; + } + cp += toskew; + pp += fromskew; + } +} + +/* + * 4-bit palette => colormap/RGB + */ +DECLAREContigPutFunc(put4bitcmaptile) +{ + uint32** PALmap = img->PALmap; + + (void) x; (void) y; + fromskew /= 2; + while (h-- > 0) { + uint32* bw; + UNROLL2(w, bw = PALmap[*pp++], *cp++ = *bw++); + cp += toskew; + pp += fromskew; + } +} + +/* + * 2-bit palette => colormap/RGB + */ +DECLAREContigPutFunc(put2bitcmaptile) +{ + uint32** PALmap = img->PALmap; + + (void) x; (void) y; + fromskew /= 4; + while (h-- > 0) { + uint32* bw; + UNROLL4(w, bw = PALmap[*pp++], *cp++ = *bw++); + cp += toskew; + pp += fromskew; + } +} + +/* + * 1-bit palette => colormap/RGB + */ +DECLAREContigPutFunc(put1bitcmaptile) +{ + uint32** PALmap = img->PALmap; + + (void) x; (void) y; + fromskew /= 8; + while (h-- > 0) { + uint32* bw; + UNROLL8(w, bw = PALmap[*pp++], *cp++ = *bw++); + cp += toskew; + pp += fromskew; + } +} + +/* + * 8-bit greyscale => colormap/RGB + */ +DECLAREContigPutFunc(putgreytile) +{ + int samplesperpixel = img->samplesperpixel; + uint32** BWmap = img->BWmap; + + (void) y; + while (h-- > 0) { + for (x = w; x-- > 0;) + { + *cp++ = BWmap[*pp][0]; + pp += samplesperpixel; + } + cp += toskew; + pp += fromskew; + } +} + +/* + * 16-bit greyscale => colormap/RGB + */ +DECLAREContigPutFunc(put16bitbwtile) +{ + int samplesperpixel = img->samplesperpixel; + uint32** BWmap = img->BWmap; + + (void) y; + while (h-- > 0) { + uint16 *wp = (uint16 *) pp; + + for (x = w; x-- > 0;) + { + /* use high order byte of 16bit value */ + + *cp++ = BWmap[*wp >> 8][0]; + pp += 2 * samplesperpixel; + wp += samplesperpixel; + } + cp += toskew; + pp += fromskew; + } +} + +/* + * 1-bit bilevel => colormap/RGB + */ +DECLAREContigPutFunc(put1bitbwtile) +{ + uint32** BWmap = img->BWmap; + + (void) x; (void) y; + fromskew /= 8; + while (h-- > 0) { + uint32* bw; + UNROLL8(w, bw = BWmap[*pp++], *cp++ = *bw++); + cp += toskew; + pp += fromskew; + } +} + +/* + * 2-bit greyscale => colormap/RGB + */ +DECLAREContigPutFunc(put2bitbwtile) +{ + uint32** BWmap = img->BWmap; + + (void) x; (void) y; + fromskew /= 4; + while (h-- > 0) { + uint32* bw; + UNROLL4(w, bw = BWmap[*pp++], *cp++ = *bw++); + cp += toskew; + pp += fromskew; + } +} + +/* + * 4-bit greyscale => colormap/RGB + */ +DECLAREContigPutFunc(put4bitbwtile) +{ + uint32** BWmap = img->BWmap; + + (void) x; (void) y; + fromskew /= 2; + while (h-- > 0) { + uint32* bw; + UNROLL2(w, bw = BWmap[*pp++], *cp++ = *bw++); + cp += toskew; + pp += fromskew; + } +} + +/* + * 8-bit packed samples, no Map => RGB + */ +DECLAREContigPutFunc(putRGBcontig8bittile) +{ + int samplesperpixel = img->samplesperpixel; + + (void) x; (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + UNROLL8(w, NOP, + *cp++ = PACK(pp[0], pp[1], pp[2]); + pp += samplesperpixel); + cp += toskew; + pp += fromskew; + } +} + +/* + * 8-bit packed samples, w/ Map => RGB + */ +DECLAREContigPutFunc(putRGBcontig8bitMaptile) +{ + TIFFRGBValue* Map = img->Map; + int samplesperpixel = img->samplesperpixel; + + (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + for (x = w; x-- > 0;) { + *cp++ = PACK(Map[pp[0]], Map[pp[1]], Map[pp[2]]); + pp += samplesperpixel; + } + pp += fromskew; + cp += toskew; + } +} + +/* + * 8-bit packed samples => RGBA w/ associated alpha + * (known to have Map == NULL) + */ +DECLAREContigPutFunc(putRGBAAcontig8bittile) +{ + int samplesperpixel = img->samplesperpixel; + + (void) x; (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + UNROLL8(w, NOP, + *cp++ = PACK4(pp[0], pp[1], pp[2], pp[3]); + pp += samplesperpixel); + cp += toskew; + pp += fromskew; + } +} + +/* + * 8-bit packed samples => RGBA w/ unassociated alpha + * (known to have Map == NULL) + */ +DECLAREContigPutFunc(putRGBUAcontig8bittile) +{ + int samplesperpixel = img->samplesperpixel; + + (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + uint32 r, g, b, a; + for (x = w; x-- > 0;) { + a = pp[3]; + r = (pp[0] * a) / 255; + g = (pp[1] * a) / 255; + b = (pp[2] * a) / 255; + *cp++ = PACK4(r,g,b,a); + pp += samplesperpixel; + } + cp += toskew; + pp += fromskew; + } +} + +/* + * 16-bit packed samples => RGB + */ +DECLAREContigPutFunc(putRGBcontig16bittile) +{ + int samplesperpixel = img->samplesperpixel; + uint16 *wp = (uint16 *)pp; + + (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + for (x = w; x-- > 0;) { + *cp++ = PACKW(wp[0], wp[1], wp[2]); + wp += samplesperpixel; + } + cp += toskew; + wp += fromskew; + } +} + +/* + * 16-bit packed samples => RGBA w/ associated alpha + * (known to have Map == NULL) + */ +DECLAREContigPutFunc(putRGBAAcontig16bittile) +{ + int samplesperpixel = img->samplesperpixel; + uint16 *wp = (uint16 *)pp; + + (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + for (x = w; x-- > 0;) { + *cp++ = PACKW4(wp[0], wp[1], wp[2], wp[3]); + wp += samplesperpixel; + } + cp += toskew; + wp += fromskew; + } +} + +/* + * 16-bit packed samples => RGBA w/ unassociated alpha + * (known to have Map == NULL) + */ +DECLAREContigPutFunc(putRGBUAcontig16bittile) +{ + int samplesperpixel = img->samplesperpixel; + uint16 *wp = (uint16 *)pp; + + (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + uint32 r,g,b,a; + /* + * We shift alpha down four bits just in case unsigned + * arithmetic doesn't handle the full range. + * We still have plenty of accuracy, since the output is 8 bits. + * So we have (r * 0xffff) * (a * 0xfff)) = r*a * (0xffff*0xfff) + * Since we want r*a * 0xff for eight bit output, + * we divide by (0xffff * 0xfff) / 0xff == 0x10eff. + */ + for (x = w; x-- > 0;) { + a = wp[3] >> 4; + r = (wp[0] * a) / 0x10eff; + g = (wp[1] * a) / 0x10eff; + b = (wp[2] * a) / 0x10eff; + *cp++ = PACK4(r,g,b,a); + wp += samplesperpixel; + } + cp += toskew; + wp += fromskew; + } +} + +/* + * 8-bit packed CMYK samples w/o Map => RGB + * + * NB: The conversion of CMYK->RGB is *very* crude. + */ +DECLAREContigPutFunc(putRGBcontig8bitCMYKtile) +{ + int samplesperpixel = img->samplesperpixel; + uint16 r, g, b, k; + + (void) x; (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + UNROLL8(w, NOP, + k = 255 - pp[3]; + r = (k*(255-pp[0]))/255; + g = (k*(255-pp[1]))/255; + b = (k*(255-pp[2]))/255; + *cp++ = PACK(r, g, b); + pp += samplesperpixel); + cp += toskew; + pp += fromskew; + } +} + +/* + * 8-bit packed CMYK samples w/Map => RGB + * + * NB: The conversion of CMYK->RGB is *very* crude. + */ +DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile) +{ + int samplesperpixel = img->samplesperpixel; + TIFFRGBValue* Map = img->Map; + uint16 r, g, b, k; + + (void) y; + fromskew *= samplesperpixel; + while (h-- > 0) { + for (x = w; x-- > 0;) { + k = 255 - pp[3]; + r = (k*(255-pp[0]))/255; + g = (k*(255-pp[1]))/255; + b = (k*(255-pp[2]))/255; + *cp++ = PACK(Map[r], Map[g], Map[b]); + pp += samplesperpixel; + } + pp += fromskew; + cp += toskew; + } +} + +#define DECLARESepPutFunc(name) \ +static void name(\ + TIFFRGBAImage* img,\ + uint32* cp,\ + uint32 x, uint32 y, \ + uint32 w, uint32 h,\ + int32 fromskew, int32 toskew,\ + u_char* r, u_char* g, u_char* b, u_char* a\ +) + +/* + * 8-bit unpacked samples => RGB + */ +DECLARESepPutFunc(putRGBseparate8bittile) +{ + (void) img; (void) x; (void) y; (void) a; + while (h-- > 0) { + UNROLL8(w, NOP, *cp++ = PACK(*r++, *g++, *b++)); + SKEW(r, g, b, fromskew); + cp += toskew; + } +} + +/* + * 8-bit unpacked samples => RGB + */ +DECLARESepPutFunc(putRGBseparate8bitMaptile) +{ + TIFFRGBValue* Map = img->Map; + + (void) y; (void) a; + while (h-- > 0) { + for (x = w; x > 0; x--) + *cp++ = PACK(Map[*r++], Map[*g++], Map[*b++]); + SKEW(r, g, b, fromskew); + cp += toskew; + } +} + +/* + * 8-bit unpacked samples => RGBA w/ associated alpha + */ +DECLARESepPutFunc(putRGBAAseparate8bittile) +{ + (void) img; (void) x; (void) y; + while (h-- > 0) { + UNROLL8(w, NOP, *cp++ = PACK4(*r++, *g++, *b++, *a++)); + SKEW4(r, g, b, a, fromskew); + cp += toskew; + } +} + +/* + * 8-bit unpacked samples => RGBA w/ unassociated alpha + */ +DECLARESepPutFunc(putRGBUAseparate8bittile) +{ + (void) img; (void) y; + while (h-- > 0) { + uint32 rv, gv, bv, av; + for (x = w; x-- > 0;) { + av = *a++; + rv = (*r++ * av) / 255; + gv = (*g++ * av) / 255; + bv = (*b++ * av) / 255; + *cp++ = PACK4(rv,gv,bv,av); + } + SKEW4(r, g, b, a, fromskew); + cp += toskew; + } +} + +/* + * 16-bit unpacked samples => RGB + */ +DECLARESepPutFunc(putRGBseparate16bittile) +{ + uint16 *wr = (uint16*) r; + uint16 *wg = (uint16*) g; + uint16 *wb = (uint16*) b; + + (void) img; (void) y; (void) a; + while (h-- > 0) { + for (x = 0; x < w; x++) + *cp++ = PACKW(*wr++, *wg++, *wb++); + SKEW(wr, wg, wb, fromskew); + cp += toskew; + } +} + +/* + * 16-bit unpacked samples => RGBA w/ associated alpha + */ +DECLARESepPutFunc(putRGBAAseparate16bittile) +{ + uint16 *wr = (uint16*) r; + uint16 *wg = (uint16*) g; + uint16 *wb = (uint16*) b; + uint16 *wa = (uint16*) a; + + (void) img; (void) y; + while (h-- > 0) { + for (x = 0; x < w; x++) + *cp++ = PACKW4(*wr++, *wg++, *wb++, *wa++); + SKEW4(wr, wg, wb, wa, fromskew); + cp += toskew; + } +} + +/* + * 16-bit unpacked samples => RGBA w/ unassociated alpha + */ +DECLARESepPutFunc(putRGBUAseparate16bittile) +{ + uint16 *wr = (uint16*) r; + uint16 *wg = (uint16*) g; + uint16 *wb = (uint16*) b; + uint16 *wa = (uint16*) a; + + (void) img; (void) y; + while (h-- > 0) { + uint32 r,g,b,a; + /* + * We shift alpha down four bits just in case unsigned + * arithmetic doesn't handle the full range. + * We still have plenty of accuracy, since the output is 8 bits. + * So we have (r * 0xffff) * (a * 0xfff)) = r*a * (0xffff*0xfff) + * Since we want r*a * 0xff for eight bit output, + * we divide by (0xffff * 0xfff) / 0xff == 0x10eff. + */ + for (x = w; x-- > 0;) { + a = *wa++ >> 4; + r = (*wr++ * a) / 0x10eff; + g = (*wg++ * a) / 0x10eff; + b = (*wb++ * a) / 0x10eff; + *cp++ = PACK4(r,g,b,a); + } + SKEW4(wr, wg, wb, wa, fromskew); + cp += toskew; + } +} + +/* + * YCbCr -> RGB conversion and packing routines. The colorspace + * conversion algorithm comes from the IJG v5a code; see below + * for more information on how it works. + */ + +#define YCbCrtoRGB(dst, yc) { \ + int Y = (yc); \ + dst = PACK( \ + clamptab[Y+Crrtab[Cr]], \ + clamptab[Y + (int)((Cbgtab[Cb]+Crgtab[Cr])>>16)], \ + clamptab[Y+Cbbtab[Cb]]); \ +} +#define YCbCrSetup \ + TIFFYCbCrToRGB* ycbcr = img->ycbcr; \ + int* Crrtab = ycbcr->Cr_r_tab; \ + int* Cbbtab = ycbcr->Cb_b_tab; \ + int32* Crgtab = ycbcr->Cr_g_tab; \ + int32* Cbgtab = ycbcr->Cb_g_tab; \ + TIFFRGBValue* clamptab = ycbcr->clamptab + +/* + * 8-bit packed YCbCr samples => RGB + * This function is generic for different sampling sizes, + * and can handle blocks sizes that aren't multiples of the + * sampling size. However, it is substantially less optimized + * than the specific sampling cases. It is used as a fallback + * for difficult blocks. + */ +#ifdef notdef +static void putcontig8bitYCbCrGenericTile( + TIFFRGBAImage* img, + uint32* cp, + uint32 x, uint32 y, + uint32 w, uint32 h, + int32 fromskew, int32 toskew, + u_char* pp, + int h_group, + int v_group ) + +{ + YCbCrSetup; + + uint32* cp1 = cp+w+toskew; + uint32* cp2 = cp1+w+toskew; + uint32* cp3 = cp2+w+toskew; + int32 incr = 3*w+4*toskew; + int Cb, Cr; + int group_size = v_group * h_group + 2; + + (void) y; + fromskew = (fromskew * group_size) / h_group; + + for( yy = 0; yy < h; yy++ ) + { + u_char *pp_line; + int y_line_group = yy / v_group; + int y_remainder = yy - y_line_group * v_group; + + pp_line = pp + v_line_group * + + + for( xx = 0; xx < w; xx++ ) + { + Cb = pp + } + } + for (; h >= 4; h -= 4) { + x = w>>2; + do { + Cb = pp[16]; + Cr = pp[17]; + + YCbCrtoRGB(cp [0], pp[ 0]); + YCbCrtoRGB(cp [1], pp[ 1]); + YCbCrtoRGB(cp [2], pp[ 2]); + YCbCrtoRGB(cp [3], pp[ 3]); + YCbCrtoRGB(cp1[0], pp[ 4]); + YCbCrtoRGB(cp1[1], pp[ 5]); + YCbCrtoRGB(cp1[2], pp[ 6]); + YCbCrtoRGB(cp1[3], pp[ 7]); + YCbCrtoRGB(cp2[0], pp[ 8]); + YCbCrtoRGB(cp2[1], pp[ 9]); + YCbCrtoRGB(cp2[2], pp[10]); + YCbCrtoRGB(cp2[3], pp[11]); + YCbCrtoRGB(cp3[0], pp[12]); + YCbCrtoRGB(cp3[1], pp[13]); + YCbCrtoRGB(cp3[2], pp[14]); + YCbCrtoRGB(cp3[3], pp[15]); + + cp += 4, cp1 += 4, cp2 += 4, cp3 += 4; + pp += 18; + } while (--x); + cp += incr, cp1 += incr, cp2 += incr, cp3 += incr; + pp += fromskew; + } +} +#endif + +/* + * 8-bit packed YCbCr samples w/ 4,4 subsampling => RGB + */ +DECLAREContigPutFunc(putcontig8bitYCbCr44tile) +{ + YCbCrSetup; + uint32* cp1 = cp+w+toskew; + uint32* cp2 = cp1+w+toskew; + uint32* cp3 = cp2+w+toskew; + int32 incr = 3*w+4*toskew; + + (void) y; + /* adjust fromskew */ + fromskew = (fromskew * 18) / 4; + if ((h & 3) == 0 && (w & 3) == 0) { + for (; h >= 4; h -= 4) { + x = w>>2; + do { + int Cb = pp[16]; + int Cr = pp[17]; + + YCbCrtoRGB(cp [0], pp[ 0]); + YCbCrtoRGB(cp [1], pp[ 1]); + YCbCrtoRGB(cp [2], pp[ 2]); + YCbCrtoRGB(cp [3], pp[ 3]); + YCbCrtoRGB(cp1[0], pp[ 4]); + YCbCrtoRGB(cp1[1], pp[ 5]); + YCbCrtoRGB(cp1[2], pp[ 6]); + YCbCrtoRGB(cp1[3], pp[ 7]); + YCbCrtoRGB(cp2[0], pp[ 8]); + YCbCrtoRGB(cp2[1], pp[ 9]); + YCbCrtoRGB(cp2[2], pp[10]); + YCbCrtoRGB(cp2[3], pp[11]); + YCbCrtoRGB(cp3[0], pp[12]); + YCbCrtoRGB(cp3[1], pp[13]); + YCbCrtoRGB(cp3[2], pp[14]); + YCbCrtoRGB(cp3[3], pp[15]); + + cp += 4, cp1 += 4, cp2 += 4, cp3 += 4; + pp += 18; + } while (--x); + cp += incr, cp1 += incr, cp2 += incr, cp3 += incr; + pp += fromskew; + } + } else { + while (h > 0) { + for (x = w; x > 0;) { + int Cb = pp[16]; + int Cr = pp[17]; + switch (x) { + default: + switch (h) { + default: YCbCrtoRGB(cp3[3], pp[15]); /* FALLTHROUGH */ + case 3: YCbCrtoRGB(cp2[3], pp[11]); /* FALLTHROUGH */ + case 2: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + case 3: + switch (h) { + default: YCbCrtoRGB(cp3[2], pp[14]); /* FALLTHROUGH */ + case 3: YCbCrtoRGB(cp2[2], pp[10]); /* FALLTHROUGH */ + case 2: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + case 2: + switch (h) { + default: YCbCrtoRGB(cp3[1], pp[13]); /* FALLTHROUGH */ + case 3: YCbCrtoRGB(cp2[1], pp[ 9]); /* FALLTHROUGH */ + case 2: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + case 1: + switch (h) { + default: YCbCrtoRGB(cp3[0], pp[12]); /* FALLTHROUGH */ + case 3: YCbCrtoRGB(cp2[0], pp[ 8]); /* FALLTHROUGH */ + case 2: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + } + if (x < 4) { + cp += x; cp1 += x; cp2 += x; cp3 += x; + x = 0; + } + else { + cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; + x -= 4; + } + pp += 18; + } + if (h <= 4) + break; + h -= 4; + cp += incr, cp1 += incr, cp2 += incr, cp3 += incr; + pp += fromskew; + } + } +} + +/* + * 8-bit packed YCbCr samples w/ 4,2 subsampling => RGB + */ +DECLAREContigPutFunc(putcontig8bitYCbCr42tile) +{ + YCbCrSetup; + uint32* cp1 = cp+w+toskew; + int32 incr = 2*toskew+w; + + (void) y; + fromskew = (fromskew * 10) / 4; + if ((h & 3) == 0 && (w & 1) == 0) { + for (; h >= 2; h -= 2) { + x = w>>2; + do { + int Cb = pp[8]; + int Cr = pp[9]; + + YCbCrtoRGB(cp [0], pp[0]); + YCbCrtoRGB(cp [1], pp[1]); + YCbCrtoRGB(cp [2], pp[2]); + YCbCrtoRGB(cp [3], pp[3]); + YCbCrtoRGB(cp1[0], pp[4]); + YCbCrtoRGB(cp1[1], pp[5]); + YCbCrtoRGB(cp1[2], pp[6]); + YCbCrtoRGB(cp1[3], pp[7]); + + cp += 4, cp1 += 4; + pp += 10; + } while (--x); + cp += incr, cp1 += incr; + pp += fromskew; + } + } else { + while (h > 0) { + for (x = w; x > 0;) { + int Cb = pp[8]; + int Cr = pp[9]; + switch (x) { + default: + switch (h) { + default: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + case 3: + switch (h) { + default: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + case 2: + switch (h) { + default: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + case 1: + switch (h) { + default: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + } + if (x < 4) { + cp += x; cp1 += x; + x = 0; + } + else { + cp += 4; cp1 += 4; + x -= 4; + } + pp += 10; + } + if (h <= 2) + break; + h -= 2; + cp += incr, cp1 += incr; + pp += fromskew; + } + } +} + +/* + * 8-bit packed YCbCr samples w/ 4,1 subsampling => RGB + */ +DECLAREContigPutFunc(putcontig8bitYCbCr41tile) +{ + YCbCrSetup; + + (void) y; + /* XXX adjust fromskew */ + do { + x = w>>2; + do { + int Cb = pp[4]; + int Cr = pp[5]; + + YCbCrtoRGB(cp [0], pp[0]); + YCbCrtoRGB(cp [1], pp[1]); + YCbCrtoRGB(cp [2], pp[2]); + YCbCrtoRGB(cp [3], pp[3]); + + cp += 4; + pp += 6; + } while (--x); + + if( (w&3) != 0 ) + { + int Cb = pp[4]; + int Cr = pp[5]; + + switch( (w&3) ) { + case 3: YCbCrtoRGB(cp [2], pp[2]); + case 2: YCbCrtoRGB(cp [1], pp[1]); + case 1: YCbCrtoRGB(cp [0], pp[0]); + case 0: break; + } + + cp += (w&3); + pp += 6; + } + + cp += toskew; + pp += fromskew; + } while (--h); + +} + +/* + * 8-bit packed YCbCr samples w/ 2,2 subsampling => RGB + */ +DECLAREContigPutFunc(putcontig8bitYCbCr22tile) +{ + YCbCrSetup; + uint32* cp1 = cp+w+toskew; + int32 incr = 2*toskew+w; + + (void) y; + fromskew = (fromskew * 6) / 2; + if ((h & 1) == 0 && (w & 1) == 0) { + for (; h >= 2; h -= 2) { + x = w>>1; + do { + int Cb = pp[4]; + int Cr = pp[5]; + + YCbCrtoRGB(cp [0], pp[0]); + YCbCrtoRGB(cp [1], pp[1]); + YCbCrtoRGB(cp1[0], pp[2]); + YCbCrtoRGB(cp1[1], pp[3]); + + cp += 2, cp1 += 2; + pp += 6; + } while (--x); + cp += incr, cp1 += incr; + pp += fromskew; + } + } else { + while (h > 0) { + for (x = w; x > 0;) { + int Cb = pp[4]; + int Cr = pp[5]; + switch (x) { + default: + switch (h) { + default: YCbCrtoRGB(cp1[1], pp[ 3]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + case 1: + switch (h) { + default: YCbCrtoRGB(cp1[0], pp[ 2]); /* FALLTHROUGH */ + case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ + } /* FALLTHROUGH */ + } + if (x < 2) { + cp += x; cp1 += x; + x = 0; + } + else { + cp += 2; cp1 += 2; + x -= 2; + } + pp += 6; + } + if (h <= 2) + break; + h -= 2; + cp += incr, cp1 += incr; + pp += fromskew; + } + } +} + +/* + * 8-bit packed YCbCr samples w/ 2,1 subsampling => RGB + */ +DECLAREContigPutFunc(putcontig8bitYCbCr21tile) +{ + YCbCrSetup; + + (void) y; + fromskew = (fromskew * 4) / 2; + do { + x = w>>1; + do { + int Cb = pp[2]; + int Cr = pp[3]; + + YCbCrtoRGB(cp[0], pp[0]); + YCbCrtoRGB(cp[1], pp[1]); + + cp += 2; + pp += 4; + } while (--x); + + if( (w&1) != 0 ) + { + int Cb = pp[2]; + int Cr = pp[3]; + + YCbCrtoRGB(cp [0], pp[0]); + + cp += 1; + pp += 4; + } + + cp += toskew; + pp += fromskew; + } while (--h); +} + +/* + * 8-bit packed YCbCr samples w/ no subsampling => RGB + */ +DECLAREContigPutFunc(putcontig8bitYCbCr11tile) +{ + YCbCrSetup; + + (void) y; + fromskew *= 3; + do { + x = w; /* was x = w>>1; patched 2000/09/25 warmerda@home.com */ + do { + int Cb = pp[1]; + int Cr = pp[2]; + + YCbCrtoRGB(*cp++, pp[0]); + + pp += 3; + } while (--x); + cp += toskew; + pp += fromskew; + } while (--h); +} +#undef YCbCrSetup +#undef YCbCrtoRGB + +#define LumaRed coeffs[0] +#define LumaGreen coeffs[1] +#define LumaBlue coeffs[2] +#define SHIFT 16 +#define FIX(x) ((int32)((x) * (1L<RGB conversion tables. The conversion + * is done according to the 6.0 spec: + * + * R = Y + Cr*(2 - 2*LumaRed) + * B = Y + Cb*(2 - 2*LumaBlue) + * G = Y + * - LumaBlue*Cb*(2-2*LumaBlue)/LumaGreen + * - LumaRed*Cr*(2-2*LumaRed)/LumaGreen + * + * To avoid floating point arithmetic the fractional constants that + * come out of the equations are represented as fixed point values + * in the range 0...2^16. We also eliminate multiplications by + * pre-calculating possible values indexed by Cb and Cr (this code + * assumes conversion is being done for 8-bit samples). + */ +static void +TIFFYCbCrToRGBInit(TIFFYCbCrToRGB* ycbcr, TIFF* tif) +{ + TIFFRGBValue* clamptab; + float* coeffs; + int i; + + clamptab = (TIFFRGBValue*)( + (tidata_t) ycbcr+TIFFroundup(sizeof (TIFFYCbCrToRGB), sizeof (long))); + _TIFFmemset(clamptab, 0, 256); /* v < 0 => 0 */ + ycbcr->clamptab = (clamptab += 256); + for (i = 0; i < 256; i++) + clamptab[i] = i; + _TIFFmemset(clamptab+256, 255, 2*256); /* v > 255 => 255 */ + TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRCOEFFICIENTS, &coeffs); + _TIFFmemcpy(ycbcr->coeffs, coeffs, 3*sizeof (float)); + { float f1 = 2-2*LumaRed; int32 D1 = FIX(f1); + float f2 = LumaRed*f1/LumaGreen; int32 D2 = -FIX(f2); + float f3 = 2-2*LumaBlue; int32 D3 = FIX(f3); + float f4 = LumaBlue*f3/LumaGreen; int32 D4 = -FIX(f4); + int x; + + ycbcr->Cr_r_tab = (int*) (clamptab + 3*256); + ycbcr->Cb_b_tab = ycbcr->Cr_r_tab + 256; + ycbcr->Cr_g_tab = (int32*) (ycbcr->Cb_b_tab + 256); + ycbcr->Cb_g_tab = ycbcr->Cr_g_tab + 256; + /* + * i is the actual input pixel value in the range 0..255 + * Cb and Cr values are in the range -128..127 (actually + * they are in a range defined by the ReferenceBlackWhite + * tag) so there is some range shifting to do here when + * constructing tables indexed by the raw pixel data. + * + * XXX handle ReferenceBlackWhite correctly to calculate + * Cb/Cr values to use in constructing the tables. + */ + for (i = 0, x = -128; i < 256; i++, x++) { + ycbcr->Cr_r_tab[i] = (int)((D1*x + ONE_HALF)>>SHIFT); + ycbcr->Cb_b_tab[i] = (int)((D3*x + ONE_HALF)>>SHIFT); + ycbcr->Cr_g_tab[i] = D2*x; + ycbcr->Cb_g_tab[i] = D4*x + ONE_HALF; + } + } +} +#undef SHIFT +#undef ONE_HALF +#undef FIX +#undef LumaBlue +#undef LumaGreen +#undef LumaRed + +static tileContigRoutine +initYCbCrConversion(TIFFRGBAImage* img) +{ + uint16 hs, vs; + + if (img->ycbcr == NULL) { + img->ycbcr = (TIFFYCbCrToRGB*) _TIFFmalloc( + TIFFroundup(sizeof (TIFFYCbCrToRGB), sizeof (long)) + + 4*256*sizeof (TIFFRGBValue) + + 2*256*sizeof (int) + + 2*256*sizeof (int32) + ); + if (img->ycbcr == NULL) { + TIFFError(TIFFFileName(img->tif), + "No space for YCbCr->RGB conversion state"); + return (NULL); + } + TIFFYCbCrToRGBInit(img->ycbcr, img->tif); + } else { + float* coeffs; + + TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRCOEFFICIENTS, &coeffs); + if (_TIFFmemcmp(coeffs, img->ycbcr->coeffs, 3*sizeof (float)) != 0) + TIFFYCbCrToRGBInit(img->ycbcr, img->tif); + } + /* + * The 6.0 spec says that subsampling must be + * one of 1, 2, or 4, and that vertical subsampling + * must always be <= horizontal subsampling; so + * there are only a few possibilities and we just + * enumerate the cases. + */ + TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &hs, &vs); + switch ((hs<<4)|vs) { + case 0x44: return (putcontig8bitYCbCr44tile); + case 0x42: return (putcontig8bitYCbCr42tile); + case 0x41: return (putcontig8bitYCbCr41tile); + case 0x22: return (putcontig8bitYCbCr22tile); + case 0x21: return (putcontig8bitYCbCr21tile); + case 0x11: return (putcontig8bitYCbCr11tile); + } + return (NULL); +} + +/* + * Greyscale images with less than 8 bits/sample are handled + * with a table to avoid lots of shifts and masks. The table + * is setup so that put*bwtile (below) can retrieve 8/bitspersample + * pixel values simply by indexing into the table with one + * number. + */ +static int +makebwmap(TIFFRGBAImage* img) +{ + TIFFRGBValue* Map = img->Map; + int bitspersample = img->bitspersample; + int nsamples = 8 / bitspersample; + int i; + uint32* p; + + if( nsamples == 0 ) + nsamples = 1; + + img->BWmap = (uint32**) _TIFFmalloc( + 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); + if (img->BWmap == NULL) { + TIFFError(TIFFFileName(img->tif), "No space for B&W mapping table"); + return (0); + } + p = (uint32*)(img->BWmap + 256); + for (i = 0; i < 256; i++) { + TIFFRGBValue c; + img->BWmap[i] = p; + switch (bitspersample) { +#define GREY(x) c = Map[x]; *p++ = PACK(c,c,c); + case 1: + GREY(i>>7); + GREY((i>>6)&1); + GREY((i>>5)&1); + GREY((i>>4)&1); + GREY((i>>3)&1); + GREY((i>>2)&1); + GREY((i>>1)&1); + GREY(i&1); + break; + case 2: + GREY(i>>6); + GREY((i>>4)&3); + GREY((i>>2)&3); + GREY(i&3); + break; + case 4: + GREY(i>>4); + GREY(i&0xf); + break; + case 8: + case 16: + GREY(i); + break; + } +#undef GREY + } + return (1); +} + +/* + * Construct a mapping table to convert from the range + * of the data samples to [0,255] --for display. This + * process also handles inverting B&W images when needed. + */ +static int +setupMap(TIFFRGBAImage* img) +{ + int32 x, range; + + range = (int32)((1L<bitspersample)-1); + + /* treat 16 bit the same as eight bit */ + if( img->bitspersample == 16 ) + range = (int32) 255; + + img->Map = (TIFFRGBValue*) _TIFFmalloc((range+1) * sizeof (TIFFRGBValue)); + if (img->Map == NULL) { + TIFFError(TIFFFileName(img->tif), + "No space for photometric conversion table"); + return (0); + } + if (img->photometric == PHOTOMETRIC_MINISWHITE) { + for (x = 0; x <= range; x++) + img->Map[x] = (TIFFRGBValue) (((range - x) * 255) / range); + } else { + for (x = 0; x <= range; x++) + img->Map[x] = (TIFFRGBValue) ((x * 255) / range); + } + if (img->bitspersample <= 16 && + (img->photometric == PHOTOMETRIC_MINISBLACK || + img->photometric == PHOTOMETRIC_MINISWHITE)) { + /* + * Use photometric mapping table to construct + * unpacking tables for samples <= 8 bits. + */ + if (!makebwmap(img)) + return (0); + /* no longer need Map, free it */ + _TIFFfree(img->Map), img->Map = NULL; + } + return (1); +} + +static int +checkcmap(TIFFRGBAImage* img) +{ + uint16* r = img->redcmap; + uint16* g = img->greencmap; + uint16* b = img->bluecmap; + long n = 1L<bitspersample; + + while (n-- > 0) + if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) + return (16); + return (8); +} + +static void +cvtcmap(TIFFRGBAImage* img) +{ + uint16* r = img->redcmap; + uint16* g = img->greencmap; + uint16* b = img->bluecmap; + long i; + + for (i = (1L<bitspersample)-1; i >= 0; i--) { +#define CVT(x) ((uint16)((x)>>8)) + r[i] = CVT(r[i]); + g[i] = CVT(g[i]); + b[i] = CVT(b[i]); +#undef CVT + } +} + +/* + * Palette images with <= 8 bits/sample are handled + * with a table to avoid lots of shifts and masks. The table + * is setup so that put*cmaptile (below) can retrieve 8/bitspersample + * pixel values simply by indexing into the table with one + * number. + */ +static int +makecmap(TIFFRGBAImage* img) +{ + int bitspersample = img->bitspersample; + int nsamples = 8 / bitspersample; + uint16* r = img->redcmap; + uint16* g = img->greencmap; + uint16* b = img->bluecmap; + uint32 *p; + int i; + + img->PALmap = (uint32**) _TIFFmalloc( + 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); + if (img->PALmap == NULL) { + TIFFError(TIFFFileName(img->tif), "No space for Palette mapping table"); + return (0); + } + p = (uint32*)(img->PALmap + 256); + for (i = 0; i < 256; i++) { + TIFFRGBValue c; + img->PALmap[i] = p; +#define CMAP(x) c = x; *p++ = PACK(r[c]&0xff, g[c]&0xff, b[c]&0xff); + switch (bitspersample) { + case 1: + CMAP(i>>7); + CMAP((i>>6)&1); + CMAP((i>>5)&1); + CMAP((i>>4)&1); + CMAP((i>>3)&1); + CMAP((i>>2)&1); + CMAP((i>>1)&1); + CMAP(i&1); + break; + case 2: + CMAP(i>>6); + CMAP((i>>4)&3); + CMAP((i>>2)&3); + CMAP(i&3); + break; + case 4: + CMAP(i>>4); + CMAP(i&0xf); + break; + case 8: + CMAP(i); + break; + } +#undef CMAP + } + return (1); +} + +/* + * Construct any mapping table used + * by the associated put routine. + */ +static int +buildMap(TIFFRGBAImage* img) +{ + switch (img->photometric) { + case PHOTOMETRIC_RGB: + case PHOTOMETRIC_YCBCR: + case PHOTOMETRIC_SEPARATED: + if (img->bitspersample == 8) + break; + /* fall thru... */ + case PHOTOMETRIC_MINISBLACK: + case PHOTOMETRIC_MINISWHITE: + if (!setupMap(img)) + return (0); + break; + case PHOTOMETRIC_PALETTE: + /* + * Convert 16-bit colormap to 8-bit (unless it looks + * like an old-style 8-bit colormap). + */ + if (checkcmap(img) == 16) + cvtcmap(img); + else + TIFFWarning(TIFFFileName(img->tif), "Assuming 8-bit colormap"); + /* + * Use mapping table and colormap to construct + * unpacking tables for samples < 8 bits. + */ + if (img->bitspersample <= 8 && !makecmap(img)) + return (0); + break; + } + return (1); +} + +/* + * Select the appropriate conversion routine for packed data. + */ +static int +pickTileContigCase(TIFFRGBAImage* img) +{ + tileContigRoutine put = 0; + + if (buildMap(img)) { + switch (img->photometric) { + case PHOTOMETRIC_RGB: + switch (img->bitspersample) { + case 8: + if (!img->Map) { + if (img->alpha == EXTRASAMPLE_ASSOCALPHA) + put = putRGBAAcontig8bittile; + else if (img->alpha == EXTRASAMPLE_UNASSALPHA) + put = putRGBUAcontig8bittile; + else + put = putRGBcontig8bittile; + } else + put = putRGBcontig8bitMaptile; + break; + case 16: + put = putRGBcontig16bittile; + if (!img->Map) { + if (img->alpha == EXTRASAMPLE_ASSOCALPHA) + put = putRGBAAcontig16bittile; + else if (img->alpha == EXTRASAMPLE_UNASSALPHA) + put = putRGBUAcontig16bittile; + } + break; + } + break; + case PHOTOMETRIC_SEPARATED: + if (img->bitspersample == 8) { + if (!img->Map) + put = putRGBcontig8bitCMYKtile; + else + put = putRGBcontig8bitCMYKMaptile; + } + break; + case PHOTOMETRIC_PALETTE: + switch (img->bitspersample) { + case 8: put = put8bitcmaptile; break; + case 4: put = put4bitcmaptile; break; + case 2: put = put2bitcmaptile; break; + case 1: put = put1bitcmaptile; break; + } + break; + case PHOTOMETRIC_MINISWHITE: + case PHOTOMETRIC_MINISBLACK: + switch (img->bitspersample) { + case 16: put = put16bitbwtile; break; + case 8: put = putgreytile; break; + case 4: put = put4bitbwtile; break; + case 2: put = put2bitbwtile; break; + case 1: put = put1bitbwtile; break; + } + break; + case PHOTOMETRIC_YCBCR: + if (img->bitspersample == 8) + put = initYCbCrConversion(img); + break; + } + } + return ((img->put.contig = put) != 0); +} + +/* + * Select the appropriate conversion routine for unpacked data. + * + * NB: we assume that unpacked single channel data is directed + * to the "packed routines. + */ +static int +pickTileSeparateCase(TIFFRGBAImage* img) +{ + tileSeparateRoutine put = 0; + + if (buildMap(img)) { + switch (img->photometric) { + case PHOTOMETRIC_RGB: + switch (img->bitspersample) { + case 8: + if (!img->Map) { + if (img->alpha == EXTRASAMPLE_ASSOCALPHA) + put = putRGBAAseparate8bittile; + else if (img->alpha == EXTRASAMPLE_UNASSALPHA) + put = putRGBUAseparate8bittile; + else + put = putRGBseparate8bittile; + } else + put = putRGBseparate8bitMaptile; + break; + case 16: + put = putRGBseparate16bittile; + if (!img->Map) { + if (img->alpha == EXTRASAMPLE_ASSOCALPHA) + put = putRGBAAseparate16bittile; + else if (img->alpha == EXTRASAMPLE_UNASSALPHA) + put = putRGBUAseparate16bittile; + } + break; + } + break; + } + } + return ((img->put.separate = put) != 0); +} + +/* + * Read a whole strip off data from the file, and convert to RGBA form. + * If this is the last strip, then it will only contain the portion of + * the strip that is actually within the image space. The result is + * organized in bottom to top form. + */ + + +int +TIFFReadRGBAStrip(TIFF* tif, uint32 row, uint32 * raster ) + +{ + char emsg[1024]; + TIFFRGBAImage img; + int ok; + uint32 rowsperstrip, rows_to_read; + + if( TIFFIsTiled( tif ) ) + { + TIFFError(TIFFFileName(tif), + "Can't use TIFFReadRGBAStrip() with tiled file."); + return (0); + } + + TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); + if( (row % rowsperstrip) != 0 ) + { + TIFFError(TIFFFileName(tif), + "Row passed to TIFFReadRGBAStrip() must be first in a strip."); + return (0); + } + + if (TIFFRGBAImageBegin(&img, tif, 0, emsg)) { + + img.row_offset = row; + img.col_offset = 0; + + if( row + rowsperstrip > img.height ) + rows_to_read = img.height - row; + else + rows_to_read = rowsperstrip; + + ok = TIFFRGBAImageGet(&img, raster, img.width, rows_to_read ); + + TIFFRGBAImageEnd(&img); + } else { + TIFFError(TIFFFileName(tif), emsg); + ok = 0; + } + + return (ok); +} + +/* + * Read a whole tile off data from the file, and convert to RGBA form. + * The returned RGBA data is organized from bottom to top of tile, + * and may include zeroed areas if the tile extends off the image. + */ + +int +TIFFReadRGBATile(TIFF* tif, uint32 col, uint32 row, uint32 * raster) + +{ + char emsg[1024]; + TIFFRGBAImage img; + int ok; + uint32 tile_xsize, tile_ysize; + uint32 read_xsize, read_ysize; + uint32 i_row; + + /* + * Verify that our request is legal - on a tile file, and on a + * tile boundary. + */ + + if( !TIFFIsTiled( tif ) ) + { + TIFFError(TIFFFileName(tif), + "Can't use TIFFReadRGBATile() with stripped file."); + return (0); + } + + TIFFGetFieldDefaulted(tif, TIFFTAG_TILEWIDTH, &tile_xsize); + TIFFGetFieldDefaulted(tif, TIFFTAG_TILELENGTH, &tile_ysize); + if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 ) + { + TIFFError(TIFFFileName(tif), + "Row/col passed to TIFFReadRGBATile() must be top" + "left corner of a tile."); + return (0); + } + + /* + * Setup the RGBA reader. + */ + + if ( !TIFFRGBAImageBegin(&img, tif, 0, emsg)) { + TIFFError(TIFFFileName(tif), emsg); + return( 0 ); + } + + /* + * The TIFFRGBAImageGet() function doesn't allow us to get off the + * edge of the image, even to fill an otherwise valid tile. So we + * figure out how much we can read, and fix up the tile buffer to + * a full tile configuration afterwards. + */ + + if( row + tile_ysize > img.height ) + read_ysize = img.height - row; + else + read_ysize = tile_ysize; + + if( col + tile_xsize > img.width ) + read_xsize = img.width - col; + else + read_xsize = tile_xsize; + + /* + * Read the chunk of imagery. + */ + + img.row_offset = row; + img.col_offset = col; + + ok = TIFFRGBAImageGet(&img, raster, read_xsize, read_ysize ); + + TIFFRGBAImageEnd(&img); + + /* + * If our read was incomplete we will need to fix up the tile by + * shifting the data around as if a full tile of data is being returned. + * + * This is all the more complicated because the image is organized in + * bottom to top format. + */ + + if( read_xsize == tile_xsize && read_ysize == tile_ysize ) + return( ok ); + + for( i_row = 0; i_row < read_ysize; i_row++ ) + { + memmove( raster + (tile_ysize - i_row - 1) * tile_xsize, + raster + (read_ysize - i_row - 1) * read_xsize, + read_xsize * sizeof(uint32) ); + _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize, + 0, sizeof(uint32) * (tile_xsize - read_xsize) ); + } + + for( i_row = read_ysize; i_row < tile_ysize; i_row++ ) + { + _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize, + 0, sizeof(uint32) * tile_xsize ); + } + + return (ok); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_jpeg.c b/SlnkDWFImpl/CxImage/tiff/tif_jpeg.c new file mode 100644 index 0000000..db34d7e --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_jpeg.c @@ -0,0 +1,1478 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_jpeg.c,v 1.5 2001/07/20 15:00:35 warmerda Exp $ */ + +/* + * Copyright (c) 1994-1997 Sam Leffler + * Copyright (c) 1994-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef JPEG_SUPPORT +/* + * TIFF Library + * + * JPEG Compression support per TIFF Technical Note #2 + * (*not* per the original TIFF 6.0 spec). + * + * This file is simply an interface to the libjpeg library written by + * the Independent JPEG Group. You need release 5 or later of the IJG + * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/. + * + * Contributed by Tom Lane . + */ +#include +#include +#include + +/* We undefine FAR to avoid conflict with JPEG definition */ + +#ifdef FAR +#undef FAR +#endif + +/* The windows RPCNDR.H file defines boolean. */ +#ifdef __RPCNDR_H__ +#define HAVE_BOOLEAN +#endif + +#include "../jpeg/jpeglib.h" +#include "../jpeg/jerror.h" + +/* + * On some machines it may be worthwhile to use _setjmp or sigsetjmp + * in place of plain setjmp. These macros will make it easier. + */ +#define SETJMP(jbuf) setjmp(jbuf) +#define LONGJMP(jbuf,code) longjmp(jbuf,code) +#define JMP_BUF jmp_buf + +typedef struct jpeg_destination_mgr jpeg_destination_mgr; +typedef struct jpeg_source_mgr jpeg_source_mgr; +typedef struct jpeg_error_mgr jpeg_error_mgr; + +/* + * State block for each open TIFF file using + * libjpeg to do JPEG compression/decompression. + * + * libjpeg's visible state is either a jpeg_compress_struct + * or jpeg_decompress_struct depending on which way we + * are going. comm can be used to refer to the fields + * which are common to both. + * + * NB: cinfo is required to be the first member of JPEGState, + * so we can safely cast JPEGState* -> jpeg_xxx_struct* + * and vice versa! + */ +typedef struct { + union { + struct jpeg_compress_struct c; + struct jpeg_decompress_struct d; + struct jpeg_common_struct comm; + } cinfo; /* NB: must be first */ + jpeg_error_mgr err; /* libjpeg error manager */ + JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */ + /* + * The following two members could be a union, but + * they're small enough that it's not worth the effort. + */ + jpeg_destination_mgr dest; /* data dest for compression */ + jpeg_source_mgr src; /* data source for decompression */ + /* private state */ + TIFF* tif; /* back link needed by some code */ + uint16 photometric; /* copy of PhotometricInterpretation */ + uint16 h_sampling; /* luminance sampling factors */ + uint16 v_sampling; + tsize_t bytesperline; /* decompressed bytes per scanline */ + /* pointers to intermediate buffers when processing downsampled data */ + JSAMPARRAY ds_buffer[MAX_COMPONENTS]; + int scancount; /* number of "scanlines" accumulated */ + int samplesperclump; + + TIFFVGetMethod vgetparent; /* super-class method */ + TIFFVSetMethod vsetparent; /* super-class method */ + TIFFStripMethod defsparent; /* super-class method */ + TIFFTileMethod deftparent; /* super-class method */ + /* pseudo-tag fields */ + void* jpegtables; /* JPEGTables tag value, or NULL */ + uint32 jpegtables_length; /* number of bytes in same */ + int jpegquality; /* Compression quality level */ + int jpegcolormode; /* Auto RGB<=>YCbCr convert? */ + int jpegtablesmode; /* What to put in JPEGTables */ +} JPEGState; + +#define JState(tif) ((JPEGState*)(tif)->tif_data) + +static int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t); +static int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t); +static int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t); +static int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t); + +#define FIELD_JPEGTABLES (FIELD_CODEC+0) + +static const TIFFFieldInfo jpegFieldInfo[] = { + { TIFFTAG_JPEGTABLES, -1,-1, TIFF_UNDEFINED, FIELD_JPEGTABLES, + FALSE, TRUE, "JPEGTables" }, + { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, FIELD_PSEUDO, + TRUE, FALSE, "" }, + { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO, + FALSE, FALSE, "" }, + { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO, + FALSE, FALSE, "" }, +}; +#define N(a) (sizeof (a) / sizeof (a[0])) + +/* + * libjpeg interface layer. + * + * We use setjmp/longjmp to return control to libtiff + * when a fatal error is encountered within the JPEG + * library. We also direct libjpeg error and warning + * messages through the appropriate libtiff handlers. + */ + +/* + * Error handling routines (these replace corresponding + * IJG routines from jerror.c). These are used for both + * compression and decompression. + */ +static void +TIFFjpeg_error_exit(j_common_ptr cinfo) +{ + JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */ + char buffer[JMSG_LENGTH_MAX]; + + (*cinfo->err->format_message) (cinfo, buffer); + TIFFError("JPEGLib", buffer); /* display the error message */ + jpeg_abort(cinfo); /* clean up libjpeg state */ + LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */ +} + +/* + * This routine is invoked only for warning messages, + * since error_exit does its own thing and trace_level + * is never set > 0. + */ +static void +TIFFjpeg_output_message(j_common_ptr cinfo) +{ + char buffer[JMSG_LENGTH_MAX]; + + (*cinfo->err->format_message) (cinfo, buffer); + TIFFWarning("JPEGLib", buffer); +} + +/* + * Interface routines. This layer of routines exists + * primarily to limit side-effects from using setjmp. + * Also, normal/error returns are converted into return + * values per libtiff practice. + */ +#define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op)) +#define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1)) + +static int +TIFFjpeg_create_compress(JPEGState* sp) +{ + /* initialize JPEG error handling */ + sp->cinfo.c.err = jpeg_std_error(&sp->err); + sp->err.error_exit = TIFFjpeg_error_exit; + sp->err.output_message = TIFFjpeg_output_message; + + return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c)); +} + +static int +TIFFjpeg_create_decompress(JPEGState* sp) +{ + /* initialize JPEG error handling */ + sp->cinfo.d.err = jpeg_std_error(&sp->err); + sp->err.error_exit = TIFFjpeg_error_exit; + sp->err.output_message = TIFFjpeg_output_message; + + return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d)); +} + +static int +TIFFjpeg_set_defaults(JPEGState* sp) +{ + return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c)); +} + +static int +TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace) +{ + return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace)); +} + +static int +TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline) +{ + return CALLVJPEG(sp, + jpeg_set_quality(&sp->cinfo.c, quality, force_baseline)); +} + +static int +TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress) +{ + return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress)); +} + +static int +TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables) +{ + return CALLVJPEG(sp, + jpeg_start_compress(&sp->cinfo.c, write_all_tables)); +} + +static int +TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines) +{ + return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c, + scanlines, (JDIMENSION) num_lines)); +} + +static int +TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines) +{ + return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c, + data, (JDIMENSION) num_lines)); +} + +static int +TIFFjpeg_finish_compress(JPEGState* sp) +{ + return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c)); +} + +static int +TIFFjpeg_write_tables(JPEGState* sp) +{ + return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c)); +} + +static int +TIFFjpeg_read_header(JPEGState* sp, boolean require_image) +{ + return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image)); +} + +static int +TIFFjpeg_start_decompress(JPEGState* sp) +{ + return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d)); +} + +static int +TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines) +{ + return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d, + scanlines, (JDIMENSION) max_lines)); +} + +static int +TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines) +{ + return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d, + data, (JDIMENSION) max_lines)); +} + +static int +TIFFjpeg_finish_decompress(JPEGState* sp) +{ + return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d)); +} + +static int +TIFFjpeg_abort(JPEGState* sp) +{ + return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm)); +} + +static int +TIFFjpeg_destroy(JPEGState* sp) +{ + return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm)); +} + +static JSAMPARRAY +TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id, + JDIMENSION samplesperrow, JDIMENSION numrows) +{ + return CALLJPEG(sp, (JSAMPARRAY) NULL, + (*sp->cinfo.comm.mem->alloc_sarray) + (&sp->cinfo.comm, pool_id, samplesperrow, numrows)); +} + +/* + * JPEG library destination data manager. + * These routines direct compressed data from libjpeg into the + * libtiff output buffer. + */ + +static void +std_init_destination(j_compress_ptr cinfo) +{ + JPEGState* sp = (JPEGState*) cinfo; + TIFF* tif = sp->tif; + + sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata; + sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize; +} + +static boolean +std_empty_output_buffer(j_compress_ptr cinfo) +{ + JPEGState* sp = (JPEGState*) cinfo; + TIFF* tif = sp->tif; + + /* the entire buffer has been filled */ + tif->tif_rawcc = tif->tif_rawdatasize; + TIFFFlushData1(tif); + sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata; + sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize; + + return (TRUE); +} + +static void +std_term_destination(j_compress_ptr cinfo) +{ + JPEGState* sp = (JPEGState*) cinfo; + TIFF* tif = sp->tif; + + tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte; + tif->tif_rawcc = + tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer; + /* NB: libtiff does the final buffer flush */ +} + +static void +TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif) +{ + (void) tif; + sp->cinfo.c.dest = &sp->dest; + sp->dest.init_destination = std_init_destination; + sp->dest.empty_output_buffer = std_empty_output_buffer; + sp->dest.term_destination = std_term_destination; +} + +/* + * Alternate destination manager for outputting to JPEGTables field. + */ + +static void +tables_init_destination(j_compress_ptr cinfo) +{ + JPEGState* sp = (JPEGState*) cinfo; + + /* while building, jpegtables_length is allocated buffer size */ + sp->dest.next_output_byte = (JOCTET*) sp->jpegtables; + sp->dest.free_in_buffer = (size_t) sp->jpegtables_length; +} + +static boolean +tables_empty_output_buffer(j_compress_ptr cinfo) +{ + JPEGState* sp = (JPEGState*) cinfo; + void* newbuf; + + /* the entire buffer has been filled; enlarge it by 1000 bytes */ + newbuf = _TIFFrealloc((tdata_t) sp->jpegtables, + (tsize_t) (sp->jpegtables_length + 1000)); + if (newbuf == NULL) + ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100); + sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length; + sp->dest.free_in_buffer = (size_t) 1000; + sp->jpegtables = newbuf; + sp->jpegtables_length += 1000; + return (TRUE); +} + +static void +tables_term_destination(j_compress_ptr cinfo) +{ + JPEGState* sp = (JPEGState*) cinfo; + + /* set tables length to number of bytes actually emitted */ + sp->jpegtables_length -= sp->dest.free_in_buffer; +} + +static int +TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif) +{ + (void) tif; + /* + * Allocate a working buffer for building tables. + * Initial size is 1000 bytes, which is usually adequate. + */ + if (sp->jpegtables) + _TIFFfree(sp->jpegtables); + sp->jpegtables_length = 1000; + sp->jpegtables = (void*) _TIFFmalloc((tsize_t) sp->jpegtables_length); + if (sp->jpegtables == NULL) { + sp->jpegtables_length = 0; + TIFFError("TIFFjpeg_tables_dest", "No space for JPEGTables"); + return (0); + } + sp->cinfo.c.dest = &sp->dest; + sp->dest.init_destination = tables_init_destination; + sp->dest.empty_output_buffer = tables_empty_output_buffer; + sp->dest.term_destination = tables_term_destination; + return (1); +} + +/* + * JPEG library source data manager. + * These routines supply compressed data to libjpeg. + */ + +static void +std_init_source(j_decompress_ptr cinfo) +{ + JPEGState* sp = (JPEGState*) cinfo; + TIFF* tif = sp->tif; + + sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata; + sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc; +} + +static boolean +std_fill_input_buffer(j_decompress_ptr cinfo) +{ + JPEGState* sp = (JPEGState* ) cinfo; + static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI }; + + /* + * Should never get here since entire strip/tile is + * read into memory before the decompressor is called, + * and thus was supplied by init_source. + */ + WARNMS(cinfo, JWRN_JPEG_EOF); + /* insert a fake EOI marker */ + sp->src.next_input_byte = dummy_EOI; + sp->src.bytes_in_buffer = 2; + return (TRUE); +} + +static void +std_skip_input_data(j_decompress_ptr cinfo, long num_bytes) +{ + JPEGState* sp = (JPEGState*) cinfo; + + if (num_bytes > 0) { + if (num_bytes > (long) sp->src.bytes_in_buffer) { + /* oops, buffer overrun */ + (void) std_fill_input_buffer(cinfo); + } else { + sp->src.next_input_byte += (size_t) num_bytes; + sp->src.bytes_in_buffer -= (size_t) num_bytes; + } + } +} + +static void +std_term_source(j_decompress_ptr cinfo) +{ + /* No work necessary here */ + /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */ + /* (if so, need empty tables_term_source!) */ + (void) cinfo; +} + +static void +TIFFjpeg_data_src(JPEGState* sp, TIFF* tif) +{ + (void) tif; + sp->cinfo.d.src = &sp->src; + sp->src.init_source = std_init_source; + sp->src.fill_input_buffer = std_fill_input_buffer; + sp->src.skip_input_data = std_skip_input_data; + sp->src.resync_to_restart = jpeg_resync_to_restart; + sp->src.term_source = std_term_source; + sp->src.bytes_in_buffer = 0; /* for safety */ + sp->src.next_input_byte = NULL; +} + +/* + * Alternate source manager for reading from JPEGTables. + * We can share all the code except for the init routine. + */ + +static void +tables_init_source(j_decompress_ptr cinfo) +{ + JPEGState* sp = (JPEGState*) cinfo; + + sp->src.next_input_byte = (const JOCTET*) sp->jpegtables; + sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length; +} + +static void +TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif) +{ + TIFFjpeg_data_src(sp, tif); + sp->src.init_source = tables_init_source; +} + +/* + * Allocate downsampled-data buffers needed for downsampled I/O. + * We use values computed in jpeg_start_compress or jpeg_start_decompress. + * We use libjpeg's allocator so that buffers will be released automatically + * when done with strip/tile. + * This is also a handy place to compute samplesperclump, bytesperline. + */ +static int +alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info, + int num_components) +{ + JPEGState* sp = JState(tif); + int ci; + jpeg_component_info* compptr; + JSAMPARRAY buf; + int samples_per_clump = 0; + + for (ci = 0, compptr = comp_info; ci < num_components; + ci++, compptr++) { + samples_per_clump += compptr->h_samp_factor * + compptr->v_samp_factor; + buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE, + compptr->width_in_blocks * DCTSIZE, + (JDIMENSION) (compptr->v_samp_factor*DCTSIZE)); + if (buf == NULL) + return (0); + sp->ds_buffer[ci] = buf; + } + sp->samplesperclump = samples_per_clump; + return (1); +} + + +/* + * JPEG Decoding. + */ + +static int +JPEGSetupDecode(TIFF* tif) +{ + JPEGState* sp = JState(tif); + TIFFDirectory *td = &tif->tif_dir; + + assert(sp != NULL); + assert(sp->cinfo.comm.is_decompressor); + + /* Read JPEGTables if it is present */ + if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) { + TIFFjpeg_tables_src(sp, tif); + if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) { + TIFFError("JPEGSetupDecode", "Bogus JPEGTables field"); + return (0); + } + } + + /* Grab parameters that are same for all strips/tiles */ + sp->photometric = td->td_photometric; + switch (sp->photometric) { + case PHOTOMETRIC_YCBCR: + sp->h_sampling = td->td_ycbcrsubsampling[0]; + sp->v_sampling = td->td_ycbcrsubsampling[1]; + break; + default: + /* TIFF 6.0 forbids subsampling of all other color spaces */ + sp->h_sampling = 1; + sp->v_sampling = 1; + break; + } + + /* Set up for reading normal data */ + TIFFjpeg_data_src(sp, tif); + tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */ + return (1); +} + +/* + * Set up for decoding a strip or tile. + */ +static int +JPEGPreDecode(TIFF* tif, tsample_t s) +{ + JPEGState *sp = JState(tif); + TIFFDirectory *td = &tif->tif_dir; + static const char module[] = "JPEGPreDecode"; + uint32 segment_width, segment_height; + int downsampled_output; + //int ci; + + assert(sp != NULL); + assert(sp->cinfo.comm.is_decompressor); + /* + * Reset decoder state from any previous strip/tile, + * in case application didn't read the whole strip. + */ + if (!TIFFjpeg_abort(sp)) + return (0); + /* + * Read the header for this strip/tile. + */ + if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK) + return (0); + /* + * Check image parameters and set decompression parameters. + */ + segment_width = td->td_imagewidth; + segment_height = td->td_imagelength - tif->tif_row; + if (isTiled(tif)) { + if (segment_height > td->td_tilelength) + segment_height = td->td_tilelength; + sp->bytesperline = TIFFTileRowSize(tif); + } else { + if (segment_height > td->td_rowsperstrip) + segment_height = td->td_rowsperstrip; + sp->bytesperline = TIFFScanlineSize(tif); + } + if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) { + /* + * For PC 2, scale down the expected strip/tile size + * to match a downsampled component + */ + segment_width = TIFFhowmany(segment_width, sp->h_sampling); + segment_height = TIFFhowmany(segment_height, sp->v_sampling); + } + if (sp->cinfo.d.image_width != segment_width || + sp->cinfo.d.image_height != segment_height) { + TIFFError(module, "Improper JPEG strip/tile size"); + return (0); + } + if (sp->cinfo.d.num_components != + (td->td_planarconfig == PLANARCONFIG_CONTIG ? + td->td_samplesperpixel : 1)) { + TIFFError(module, "Improper JPEG component count"); + return (0); + } + if (sp->cinfo.d.data_precision != td->td_bitspersample) { + TIFFError(module, "Improper JPEG data precision"); + return (0); + } + /* avoid sampling factors check + if (td->td_planarconfig == PLANARCONFIG_CONTIG) { + // Component 0 should have expected sampling factors + if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling || + sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) { + TIFFError(module, "Improper JPEG sampling factors"); + return (0); + } + // Rest should have sampling factors 1,1 + for (ci = 1; ci < sp->cinfo.d.num_components; ci++) { + if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 || + sp->cinfo.d.comp_info[ci].v_samp_factor != 1) { + TIFFError(module, "Improper JPEG sampling factors"); + return (0); + } + } + } else { + // PC 2's single component should have sampling factors 1,1 + if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 || + sp->cinfo.d.comp_info[0].v_samp_factor != 1) { + TIFFError(module, "Improper JPEG sampling factors"); + return (0); + } + } + */ + downsampled_output = FALSE; + if (td->td_planarconfig == PLANARCONFIG_CONTIG && + sp->photometric == PHOTOMETRIC_YCBCR && + sp->jpegcolormode == JPEGCOLORMODE_RGB) { + /* Convert YCbCr to RGB */ + sp->cinfo.d.jpeg_color_space = JCS_YCbCr; + sp->cinfo.d.out_color_space = JCS_RGB; + } else { + /* Suppress colorspace handling */ + sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN; + sp->cinfo.d.out_color_space = JCS_UNKNOWN; + if (td->td_planarconfig == PLANARCONFIG_CONTIG && + (sp->h_sampling != 1 || sp->v_sampling != 1)) + downsampled_output = TRUE; + /* XXX what about up-sampling? */ + } + if (downsampled_output) { + /* Need to use raw-data interface to libjpeg */ + sp->cinfo.d.raw_data_out = TRUE; + tif->tif_decoderow = JPEGDecodeRaw; + tif->tif_decodestrip = JPEGDecodeRaw; + tif->tif_decodetile = JPEGDecodeRaw; + } else { + /* Use normal interface to libjpeg */ + sp->cinfo.d.raw_data_out = FALSE; + tif->tif_decoderow = JPEGDecode; + tif->tif_decodestrip = JPEGDecode; + tif->tif_decodetile = JPEGDecode; + } + /* Start JPEG decompressor */ + if (!TIFFjpeg_start_decompress(sp)) + return (0); + /* Allocate downsampled-data buffers if needed */ + if (downsampled_output) { + if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info, + sp->cinfo.d.num_components)) + return (0); + sp->scancount = DCTSIZE; /* mark buffer empty */ + } + return (1); +} + +/* + * Decode a chunk of pixels. + * "Standard" case: returned data is not downsampled. + */ +/*ARGSUSED*/ static int +JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s) +{ + JPEGState *sp = JState(tif); + tsize_t nrows; + + /* data is expected to be read in multiples of a scanline */ + if (nrows = sp->cinfo.d.image_height) + do { + JSAMPROW bufptr = (JSAMPROW)buf; + + if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1) + return (0); + ++tif->tif_row; + buf += sp->bytesperline; + cc -= sp->bytesperline; + } while (--nrows > 0); + /* Close down the decompressor if we've finished the strip or tile. */ + return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height + || TIFFjpeg_finish_decompress(sp); +} + +/* + * Decode a chunk of pixels. + * Returned data is downsampled per sampling factors. + */ +/*ARGSUSED*/ static int +JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s) +{ + JPEGState *sp = JState(tif); + tsize_t nrows; + + /* data is expected to be read in multiples of a scanline */ + if (nrows = sp->cinfo.d.image_height) { + /* Cb,Cr both have sampling factors 1, so this is correct */ + JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width; + int samples_per_clump = sp->samplesperclump; + + do { + jpeg_component_info *compptr; + int ci, clumpoffset; + + /* Reload downsampled-data buffer if needed */ + if (sp->scancount >= DCTSIZE) { + int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE; + + if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) + != n) + return (0); + sp->scancount = 0; + } + /* + * Fastest way to unseparate data is to make one pass + * over the scanline for each row of each component. + */ + clumpoffset = 0; /* first sample in clump */ + for (ci = 0, compptr = sp->cinfo.d.comp_info; + ci < sp->cinfo.d.num_components; + ci++, compptr++) { + int hsamp = compptr->h_samp_factor; + int vsamp = compptr->v_samp_factor; + int ypos; + + for (ypos = 0; ypos < vsamp; ypos++) { + JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos]; + JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset; + JDIMENSION nclump; + + if (hsamp == 1) { + /* fast path for at least Cb and Cr */ + for (nclump = clumps_per_line; nclump-- > 0; ) { + outptr[0] = *inptr++; + outptr += samples_per_clump; + } + } else { + int xpos; + + /* general case */ + for (nclump = clumps_per_line; nclump-- > 0; ) { + for (xpos = 0; xpos < hsamp; xpos++) + outptr[xpos] = *inptr++; + outptr += samples_per_clump; + } + } + clumpoffset += hsamp; + } + } + ++sp->scancount; + ++tif->tif_row; + buf += sp->bytesperline; + cc -= sp->bytesperline; + } while (--nrows > 0); + } + + /* Close down the decompressor if done. */ + return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height + || TIFFjpeg_finish_decompress(sp); +} + + +/* + * JPEG Encoding. + */ + +static void +unsuppress_quant_table (JPEGState* sp, int tblno) +{ + JQUANT_TBL* qtbl; + + if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL) + qtbl->sent_table = FALSE; +} + +static void +unsuppress_huff_table (JPEGState* sp, int tblno) +{ + JHUFF_TBL* htbl; + + if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL) + htbl->sent_table = FALSE; + if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL) + htbl->sent_table = FALSE; +} + +static int +prepare_JPEGTables(TIFF* tif) +{ + JPEGState* sp = JState(tif); + + /* Initialize quant tables for current quality setting */ + if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE)) + return (0); + /* Mark only the tables we want for output */ + /* NB: chrominance tables are currently used only with YCbCr */ + if (!TIFFjpeg_suppress_tables(sp, TRUE)) + return (0); + if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) { + unsuppress_quant_table(sp, 0); + if (sp->photometric == PHOTOMETRIC_YCBCR) + unsuppress_quant_table(sp, 1); + } + if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) { + unsuppress_huff_table(sp, 0); + if (sp->photometric == PHOTOMETRIC_YCBCR) + unsuppress_huff_table(sp, 1); + } + /* Direct libjpeg output into jpegtables */ + if (!TIFFjpeg_tables_dest(sp, tif)) + return (0); + /* Emit tables-only datastream */ + if (!TIFFjpeg_write_tables(sp)) + return (0); + + return (1); +} + +static int +JPEGSetupEncode(TIFF* tif) +{ + JPEGState* sp = JState(tif); + TIFFDirectory *td = &tif->tif_dir; + static const char module[] = "JPEGSetupEncode"; + + assert(sp != NULL); + assert(!sp->cinfo.comm.is_decompressor); + + /* + * Initialize all JPEG parameters to default values. + * Note that jpeg_set_defaults needs legal values for + * in_color_space and input_components. + */ + sp->cinfo.c.in_color_space = JCS_UNKNOWN; + sp->cinfo.c.input_components = 1; + if (!TIFFjpeg_set_defaults(sp)) + return (0); + /* Set per-file parameters */ + sp->photometric = td->td_photometric; + switch (sp->photometric) { + case PHOTOMETRIC_YCBCR: + sp->h_sampling = td->td_ycbcrsubsampling[0]; + sp->v_sampling = td->td_ycbcrsubsampling[1]; + /* + * A ReferenceBlackWhite field *must* be present since the + * default value is inappropriate for YCbCr. Fill in the + * proper value if application didn't set it. + */ +#ifdef COLORIMETRY_SUPPORT + if (!TIFFFieldSet(tif, FIELD_REFBLACKWHITE)) { + float refbw[6]; + long top = 1L << td->td_bitspersample; + refbw[0] = 0; + refbw[1] = (float)(top-1L); + refbw[2] = (float)(top>>1); + refbw[3] = refbw[1]; + refbw[4] = refbw[2]; + refbw[5] = refbw[1]; + TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE, refbw); + } +#endif + break; + case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */ + case PHOTOMETRIC_MASK: + TIFFError(module, + "PhotometricInterpretation %d not allowed for JPEG", + (int) sp->photometric); + return (0); + default: + /* TIFF 6.0 forbids subsampling of all other color spaces */ + sp->h_sampling = 1; + sp->v_sampling = 1; + break; + } + + /* Verify miscellaneous parameters */ + + /* + * This would need work if libtiff ever supports different + * depths for different components, or if libjpeg ever supports + * run-time selection of depth. Neither is imminent. + */ + if (td->td_bitspersample != BITS_IN_JSAMPLE) { + TIFFError(module, "BitsPerSample %d not allowed for JPEG", + (int) td->td_bitspersample); + return (0); + } + sp->cinfo.c.data_precision = td->td_bitspersample; + if (isTiled(tif)) { + if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) { + TIFFError(module, + "JPEG tile height must be multiple of %d", + sp->v_sampling * DCTSIZE); + return (0); + } + if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) { + TIFFError(module, + "JPEG tile width must be multiple of %d", + sp->h_sampling * DCTSIZE); + return (0); + } + } else { + if (td->td_rowsperstrip < td->td_imagelength && + (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) { + TIFFError(module, + "RowsPerStrip must be multiple of %d for JPEG", + sp->v_sampling * DCTSIZE); + return (0); + } + } + + /* Create a JPEGTables field if appropriate */ + if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) { + if (!prepare_JPEGTables(tif)) + return (0); + /* Mark the field present */ + /* Can't use TIFFSetField since BEENWRITING is already set! */ + TIFFSetFieldBit(tif, FIELD_JPEGTABLES); + tif->tif_flags |= TIFF_DIRTYDIRECT; + } else { + /* We do not support application-supplied JPEGTables, */ + /* so mark the field not present */ + TIFFClrFieldBit(tif, FIELD_JPEGTABLES); + } + + /* Direct libjpeg output to libtiff's output buffer */ + TIFFjpeg_data_dest(sp, tif); + + return (1); +} + +/* + * Set encoding state at the start of a strip or tile. + */ +static int +JPEGPreEncode(TIFF* tif, tsample_t s) +{ + JPEGState *sp = JState(tif); + TIFFDirectory *td = &tif->tif_dir; + static const char module[] = "JPEGPreEncode"; + uint32 segment_width, segment_height; + int downsampled_input; + + assert(sp != NULL); + assert(!sp->cinfo.comm.is_decompressor); + /* + * Set encoding parameters for this strip/tile. + */ + if (isTiled(tif)) { + segment_width = td->td_tilewidth; + segment_height = td->td_tilelength; + sp->bytesperline = TIFFTileRowSize(tif); + } else { + segment_width = td->td_imagewidth; + segment_height = td->td_imagelength - tif->tif_row; + if (segment_height > td->td_rowsperstrip) + segment_height = td->td_rowsperstrip; + sp->bytesperline = TIFFScanlineSize(tif); + } + if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) { + /* for PC 2, scale down the strip/tile size + * to match a downsampled component + */ + segment_width = TIFFhowmany(segment_width, sp->h_sampling); + segment_height = TIFFhowmany(segment_height, sp->v_sampling); + } + if (segment_width > 65535 || segment_height > 65535) { + TIFFError(module, "Strip/tile too large for JPEG"); + return (0); + } + sp->cinfo.c.image_width = segment_width; + sp->cinfo.c.image_height = segment_height; + downsampled_input = FALSE; + if (td->td_planarconfig == PLANARCONFIG_CONTIG) { + sp->cinfo.c.input_components = td->td_samplesperpixel; + if (sp->photometric == PHOTOMETRIC_YCBCR) { + if (sp->jpegcolormode == JPEGCOLORMODE_RGB) { + sp->cinfo.c.in_color_space = JCS_RGB; + } else { + sp->cinfo.c.in_color_space = JCS_YCbCr; + if (sp->h_sampling != 1 || sp->v_sampling != 1) + downsampled_input = TRUE; + } + if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr)) + return (0); + /* + * Set Y sampling factors; + * we assume jpeg_set_colorspace() set the rest to 1 + */ + sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling; + sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling; + } else { + sp->cinfo.c.in_color_space = JCS_UNKNOWN; + if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN)) + return (0); + /* jpeg_set_colorspace set all sampling factors to 1 */ + } + } else { + sp->cinfo.c.input_components = 1; + sp->cinfo.c.in_color_space = JCS_UNKNOWN; + if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN)) + return (0); + sp->cinfo.c.comp_info[0].component_id = s; + /* jpeg_set_colorspace() set sampling factors to 1 */ + if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) { + sp->cinfo.c.comp_info[0].quant_tbl_no = 1; + sp->cinfo.c.comp_info[0].dc_tbl_no = 1; + sp->cinfo.c.comp_info[0].ac_tbl_no = 1; + } + } + /* ensure libjpeg won't write any extraneous markers */ + sp->cinfo.c.write_JFIF_header = FALSE; + sp->cinfo.c.write_Adobe_marker = FALSE; + /* set up table handling correctly */ + if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) { + if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE)) + return (0); + unsuppress_quant_table(sp, 0); + unsuppress_quant_table(sp, 1); + } + if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) + sp->cinfo.c.optimize_coding = FALSE; + else + sp->cinfo.c.optimize_coding = TRUE; + if (downsampled_input) { + /* Need to use raw-data interface to libjpeg */ + sp->cinfo.c.raw_data_in = TRUE; + tif->tif_encoderow = JPEGEncodeRaw; + tif->tif_encodestrip = JPEGEncodeRaw; + tif->tif_encodetile = JPEGEncodeRaw; + } else { + /* Use normal interface to libjpeg */ + sp->cinfo.c.raw_data_in = FALSE; + tif->tif_encoderow = JPEGEncode; + tif->tif_encodestrip = JPEGEncode; + tif->tif_encodetile = JPEGEncode; + } + /* Start JPEG compressor */ + if (!TIFFjpeg_start_compress(sp, FALSE)) + return (0); + /* Allocate downsampled-data buffers if needed */ + if (downsampled_input) { + if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info, + sp->cinfo.c.num_components)) + return (0); + } + sp->scancount = 0; + + return (1); +} + +/* + * Encode a chunk of pixels. + * "Standard" case: incoming data is not downsampled. + */ +static int +JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s) +{ + JPEGState *sp = JState(tif); + tsize_t nrows; + JSAMPROW bufptr[1]; + + (void) s; + assert(sp != NULL); + /* data is expected to be supplied in multiples of a scanline */ + nrows = cc / sp->bytesperline; + if (cc % sp->bytesperline) + TIFFWarning(tif->tif_name, "fractional scanline discarded"); + + while (nrows-- > 0) { + bufptr[0] = (JSAMPROW) buf; + if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1) + return (0); + if (nrows > 0) + tif->tif_row++; + buf += sp->bytesperline; + } + return (1); +} + +/* + * Encode a chunk of pixels. + * Incoming data is expected to be downsampled per sampling factors. + */ +static int +JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s) +{ + JPEGState *sp = JState(tif); + JSAMPLE* inptr; + JSAMPLE* outptr; + tsize_t nrows; + JDIMENSION clumps_per_line, nclump; + int clumpoffset, ci, xpos, ypos; + jpeg_component_info* compptr; + int samples_per_clump = sp->samplesperclump; + + (void) s; + assert(sp != NULL); + /* data is expected to be supplied in multiples of a scanline */ + nrows = cc / sp->bytesperline; + if (cc % sp->bytesperline) + TIFFWarning(tif->tif_name, "fractional scanline discarded"); + + /* Cb,Cr both have sampling factors 1, so this is correct */ + clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width; + + while (nrows-- > 0) { + /* + * Fastest way to separate the data is to make one pass + * over the scanline for each row of each component. + */ + clumpoffset = 0; /* first sample in clump */ + for (ci = 0, compptr = sp->cinfo.c.comp_info; + ci < sp->cinfo.c.num_components; + ci++, compptr++) { + int hsamp = compptr->h_samp_factor; + int vsamp = compptr->v_samp_factor; + int padding = (int) (compptr->width_in_blocks * DCTSIZE - + clumps_per_line * hsamp); + for (ypos = 0; ypos < vsamp; ypos++) { + inptr = ((JSAMPLE*) buf) + clumpoffset; + outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos]; + if (hsamp == 1) { + /* fast path for at least Cb and Cr */ + for (nclump = clumps_per_line; nclump-- > 0; ) { + *outptr++ = inptr[0]; + inptr += samples_per_clump; + } + } else { + /* general case */ + for (nclump = clumps_per_line; nclump-- > 0; ) { + for (xpos = 0; xpos < hsamp; xpos++) + *outptr++ = inptr[xpos]; + inptr += samples_per_clump; + } + } + /* pad each scanline as needed */ + for (xpos = 0; xpos < padding; xpos++) { + *outptr = outptr[-1]; + outptr++; + } + clumpoffset += hsamp; + } + } + sp->scancount++; + if (sp->scancount >= DCTSIZE) { + int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE; + if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n) + return (0); + sp->scancount = 0; + } + if (nrows > 0) + tif->tif_row++; + buf += sp->bytesperline; + } + return (1); +} + +/* + * Finish up at the end of a strip or tile. + */ +static int +JPEGPostEncode(TIFF* tif) +{ + JPEGState *sp = JState(tif); + + if (sp->scancount > 0) { + /* + * Need to emit a partial bufferload of downsampled data. + * Pad the data vertically. + */ + int ci, ypos, n; + jpeg_component_info* compptr; + + for (ci = 0, compptr = sp->cinfo.c.comp_info; + ci < sp->cinfo.c.num_components; + ci++, compptr++) { + int vsamp = compptr->v_samp_factor; + tsize_t row_width = compptr->width_in_blocks * DCTSIZE + * sizeof(JSAMPLE); + for (ypos = sp->scancount * vsamp; + ypos < DCTSIZE * vsamp; ypos++) { + _TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos], + (tdata_t)sp->ds_buffer[ci][ypos-1], + row_width); + + } + } + n = sp->cinfo.c.max_v_samp_factor * DCTSIZE; + if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n) + return (0); + } + + return (TIFFjpeg_finish_compress(JState(tif))); +} + +static void +JPEGCleanup(TIFF* tif) +{ + if (tif->tif_data) { + JPEGState *sp = JState(tif); + TIFFjpeg_destroy(sp); /* release libjpeg resources */ + if (sp->jpegtables) /* tag value */ + _TIFFfree(sp->jpegtables); + _TIFFfree(tif->tif_data); /* release local state */ + tif->tif_data = NULL; + } +} + +static int +JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap) +{ + JPEGState* sp = JState(tif); + TIFFDirectory* td = &tif->tif_dir; + uint32 v32; + + switch (tag) { + case TIFFTAG_JPEGTABLES: + v32 = va_arg(ap, uint32); + if (v32 == 0) { + /* XXX */ + return (0); + } + _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*), + (long) v32); + sp->jpegtables_length = v32; + TIFFSetFieldBit(tif, FIELD_JPEGTABLES); + break; + case TIFFTAG_JPEGQUALITY: + sp->jpegquality = va_arg(ap, int); + return (1); /* pseudo tag */ + case TIFFTAG_JPEGCOLORMODE: + sp->jpegcolormode = va_arg(ap, int); + /* + * Mark whether returned data is up-sampled or not + * so TIFFStripSize and TIFFTileSize return values + * that reflect the true amount of data. + */ + tif->tif_flags &= ~TIFF_UPSAMPLED; + if (td->td_planarconfig == PLANARCONFIG_CONTIG) { + if (td->td_photometric == PHOTOMETRIC_YCBCR && + sp->jpegcolormode == JPEGCOLORMODE_RGB) { + tif->tif_flags |= TIFF_UPSAMPLED; + } else { + if (td->td_ycbcrsubsampling[0] != 1 || + td->td_ycbcrsubsampling[1] != 1) + ; /* XXX what about up-sampling? */ + } + } + /* + * Must recalculate cached tile size + * in case sampling state changed. + */ + tif->tif_tilesize = TIFFTileSize(tif); + return (1); /* pseudo tag */ + case TIFFTAG_JPEGTABLESMODE: + sp->jpegtablesmode = va_arg(ap, int); + return (1); /* pseudo tag */ + default: + return (*sp->vsetparent)(tif, tag, ap); + } + tif->tif_flags |= TIFF_DIRTYDIRECT; + return (1); +} + +static int +JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap) +{ + JPEGState* sp = JState(tif); + + switch (tag) { + case TIFFTAG_JPEGTABLES: + /* u_short is bogus --- should be uint32 ??? */ + /* TIFFWriteNormalTag needs fixed XXX */ + *va_arg(ap, u_short*) = (u_short) sp->jpegtables_length; + *va_arg(ap, void**) = sp->jpegtables; + break; + case TIFFTAG_JPEGQUALITY: + *va_arg(ap, int*) = sp->jpegquality; + break; + case TIFFTAG_JPEGCOLORMODE: + *va_arg(ap, int*) = sp->jpegcolormode; + break; + case TIFFTAG_JPEGTABLESMODE: + *va_arg(ap, int*) = sp->jpegtablesmode; + break; + default: + return (*sp->vgetparent)(tif, tag, ap); + } + return (1); +} + +static void +JPEGPrintDir(TIFF* tif, FILE* fd, long flags) +{ + JPEGState* sp = JState(tif); + + (void) flags; + if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) + fprintf(fd, " JPEG Tables: (%lu bytes)\n", + (u_long) sp->jpegtables_length); +} + +static uint32 +JPEGDefaultStripSize(TIFF* tif, uint32 s) +{ + JPEGState* sp = JState(tif); + TIFFDirectory *td = &tif->tif_dir; + + s = (*sp->defsparent)(tif, s); + if (s < td->td_imagelength) + s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE); + return (s); +} + +static void +JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th) +{ + JPEGState* sp = JState(tif); + TIFFDirectory *td = &tif->tif_dir; + + (*sp->deftparent)(tif, tw, th); + *tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE); + *th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE); +} + +int +TIFFInitJPEG(TIFF* tif, int scheme) +{ + JPEGState* sp; + + assert(scheme == COMPRESSION_JPEG); + + /* + * Allocate state block so tag methods have storage to record values. + */ + tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (JPEGState)); + if (tif->tif_data == NULL) { + TIFFError("TIFFInitJPEG", "No space for JPEG state block"); + return (0); + } + sp = JState(tif); + sp->tif = tif; /* back link */ + + /* + * Merge codec-specific tag information and + * override parent get/set field methods. + */ + _TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo)); + sp->vgetparent = tif->tif_vgetfield; + tif->tif_vgetfield = JPEGVGetField; /* hook for codec tags */ + sp->vsetparent = tif->tif_vsetfield; + tif->tif_vsetfield = JPEGVSetField; /* hook for codec tags */ + tif->tif_printdir = JPEGPrintDir; /* hook for codec tags */ + + /* Default values for codec-specific fields */ + sp->jpegtables = NULL; + sp->jpegtables_length = 0; + sp->jpegquality = 75; /* Default IJG quality */ + sp->jpegcolormode = JPEGCOLORMODE_RAW; + sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF; + + /* + * Install codec methods. + */ + tif->tif_setupdecode = JPEGSetupDecode; + tif->tif_predecode = JPEGPreDecode; + tif->tif_decoderow = JPEGDecode; + tif->tif_decodestrip = JPEGDecode; + tif->tif_decodetile = JPEGDecode; + tif->tif_setupencode = JPEGSetupEncode; + tif->tif_preencode = JPEGPreEncode; + tif->tif_postencode = JPEGPostEncode; + tif->tif_encoderow = JPEGEncode; + tif->tif_encodestrip = JPEGEncode; + tif->tif_encodetile = JPEGEncode; + tif->tif_cleanup = JPEGCleanup; + sp->defsparent = tif->tif_defstripsize; + tif->tif_defstripsize = JPEGDefaultStripSize; + sp->deftparent = tif->tif_deftilesize; + tif->tif_deftilesize = JPEGDefaultTileSize; + tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */ + + /* + * Initialize libjpeg. + */ + if (tif->tif_mode == O_RDONLY) { + if (!TIFFjpeg_create_decompress(sp)) + return (0); + } else { + if (!TIFFjpeg_create_compress(sp)) + return (0); + } + + return (1); +} +#endif /* JPEG_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_luv.c b/SlnkDWFImpl/CxImage/tiff/tif_luv.c new file mode 100644 index 0000000..7bf6f9f --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_luv.c @@ -0,0 +1,1586 @@ +/* + * Copyright (c) 1997 Greg Ward Larson + * Copyright (c) 1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler, Greg Larson and Silicon Graphics may not be used in any + * advertising or publicity relating to the software without the specific, + * prior written permission of Sam Leffler, Greg Larson and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER, GREG LARSON OR SILICON GRAPHICS BE LIABLE + * FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef LOGLUV_SUPPORT + +/* + * TIFF Library. + * LogLuv compression support for high dynamic range images. + * + * Contributed by Greg Larson. + * + * LogLuv image support uses the TIFF library to store 16 or 10-bit + * log luminance values with 8 bits each of u and v or a 14-bit index. + * + * The codec can take as input and produce as output 32-bit IEEE float values + * as well as 16-bit integer values. A 16-bit luminance is interpreted + * as a sign bit followed by a 15-bit integer that is converted + * to and from a linear magnitude using the transformation: + * + * L = 2^( (Le+.5)/256 - 64 ) # real from 15-bit + * + * Le = floor( 256*(log2(L) + 64) ) # 15-bit from real + * + * The actual conversion to world luminance units in candelas per sq. meter + * requires an additional multiplier, which is stored in the TIFFTAG_STONITS. + * This value is usually set such that a reasonable exposure comes from + * clamping decoded luminances above 1 to 1 in the displayed image. + * + * The 16-bit values for u and v may be converted to real values by dividing + * each by 32768. (This allows for negative values, which aren't useful as + * far as we know, but are left in case of future improvements in human + * color vision.) + * + * Conversion from (u,v), which is actually the CIE (u',v') system for + * you color scientists, is accomplished by the following transformation: + * + * u = 4*x / (-2*x + 12*y + 3) + * v = 9*y / (-2*x + 12*y + 3) + * + * x = 9*u / (6*u - 16*v + 12) + * y = 4*v / (6*u - 16*v + 12) + * + * This process is greatly simplified by passing 32-bit IEEE floats + * for each of three CIE XYZ coordinates. The codec then takes care + * of conversion to and from LogLuv, though the application is still + * responsible for interpreting the TIFFTAG_STONITS calibration factor. + * + * By definition, a CIE XYZ vector of [1 1 1] corresponds to a neutral white + * point of (x,y)=(1/3,1/3). However, most color systems assume some other + * white point, such as D65, and an absolute color conversion to XYZ then + * to another color space with a different white point may introduce an + * unwanted color cast to the image. It is often desirable, therefore, to + * perform a white point conversion that maps the input white to [1 1 1] + * in XYZ, then record the original white point using the TIFFTAG_WHITEPOINT + * tag value. A decoder that demands absolute color calibration may use + * this white point tag to get back the original colors, but usually it + * will be ignored and the new white point will be used instead that + * matches the output color space. + * + * Pixel information is compressed into one of two basic encodings, depending + * on the setting of the compression tag, which is one of COMPRESSION_SGILOG + * or COMPRESSION_SGILOG24. For COMPRESSION_SGILOG, greyscale data is + * stored as: + * + * 1 15 + * |-+---------------| + * + * COMPRESSION_SGILOG color data is stored as: + * + * 1 15 8 8 + * |-+---------------|--------+--------| + * S Le ue ve + * + * For the 24-bit COMPRESSION_SGILOG24 color format, the data is stored as: + * + * 10 14 + * |----------|--------------| + * Le' Ce + * + * There is no sign bit in the 24-bit case, and the (u,v) chromaticity is + * encoded as an index for optimal color resolution. The 10 log bits are + * defined by the following conversions: + * + * L = 2^((Le'+.5)/64 - 12) # real from 10-bit + * + * Le' = floor( 64*(log2(L) + 12) ) # 10-bit from real + * + * The 10 bits of the smaller format may be converted into the 15 bits of + * the larger format by multiplying by 4 and adding 13314. Obviously, + * a smaller range of magnitudes is covered (about 5 orders of magnitude + * instead of 38), and the lack of a sign bit means that negative luminances + * are not allowed. (Well, they aren't allowed in the real world, either, + * but they are useful for certain types of image processing.) + * + * The desired user format is controlled by the setting the internal + * pseudo tag TIFFTAG_SGILOGDATAFMT to one of: + * SGILOGDATAFMT_FLOAT = IEEE 32-bit float XYZ values + * SGILOGDATAFMT_16BIT = 16-bit integer encodings of logL, u and v + * Raw data i/o is also possible using: + * SGILOGDATAFMT_RAW = 32-bit unsigned integer with encoded pixel + * In addition, the following decoding is provided for ease of display: + * SGILOGDATAFMT_8BIT = 8-bit default RGB gamma-corrected values + * + * For grayscale images, we provide the following data formats: + * SGILOGDATAFMT_FLOAT = IEEE 32-bit float Y values + * SGILOGDATAFMT_16BIT = 16-bit integer w/ encoded luminance + * SGILOGDATAFMT_8BIT = 8-bit gray monitor values + * + * Note that the COMPRESSION_SGILOG applies a simple run-length encoding + * scheme by separating the logL, u and v bytes for each row and applying + * a PackBits type of compression. Since the 24-bit encoding is not + * adaptive, the 32-bit color format takes less space in many cases. + * + * Further control is provided over the conversion from higher-resolution + * formats to final encoded values through the pseudo tag + * TIFFTAG_SGILOGENCODE: + * SGILOGENCODE_NODITHER = do not dither encoded values + * SGILOGENCODE_RANDITHER = apply random dithering during encoding + * + * The default value of this tag is SGILOGENCODE_NODITHER for + * COMPRESSION_SGILOG to maximize run-length encoding and + * SGILOGENCODE_RANDITHER for COMPRESSION_SGILOG24 to turn + * quantization errors into noise. + */ + +#include +#include +#include +#include + +/* + * State block for each open TIFF + * file using LogLuv compression/decompression. + */ +typedef struct logLuvState LogLuvState; + +struct logLuvState { + int user_datafmt; /* user data format */ + int encode_meth; /* encoding method */ + int pixel_size; /* bytes per pixel */ + + tidata_t* tbuf; /* translation buffer */ + int tbuflen; /* buffer length */ + void (*tfunc)(LogLuvState*, tidata_t, int); + + TIFFVSetMethod vgetparent; /* super-class method */ + TIFFVSetMethod vsetparent; /* super-class method */ +}; + +#define DecoderState(tif) ((LogLuvState*) (tif)->tif_data) +#define EncoderState(tif) ((LogLuvState*) (tif)->tif_data) + +#define N(a) (sizeof(a)/sizeof(a[0])) +#define SGILOGDATAFMT_UNKNOWN -1 + +#define MINRUN 4 /* minimum run length */ + +/* + * Decode a string of 16-bit gray pixels. + */ +static int +LogL16Decode(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s) +{ + LogLuvState* sp = DecoderState(tif); + int shft, i, npixels; + u_char* bp; + int16* tp; + int16 b; + int cc, rc; + + assert(s == 0); + assert(sp != NULL); + + npixels = occ / sp->pixel_size; + + if (sp->user_datafmt == SGILOGDATAFMT_16BIT) + tp = (int16*) op; + else { + assert(sp->tbuflen >= npixels); + tp = (int16*) sp->tbuf; + } + _TIFFmemset((tdata_t) tp, 0, npixels*sizeof (tp[0])); + + bp = (u_char*) tif->tif_rawcp; + cc = tif->tif_rawcc; + /* get each byte string */ + for (shft = 2*8; (shft -= 8) >= 0; ) { + for (i = 0; i < npixels && cc > 0; ) + if (*bp >= 128) { /* run */ + rc = *bp++ + (2-128); + b = (int16)*bp++ << shft; + cc -= 2; + while (rc--) + tp[i++] |= b; + } else { /* non-run */ + rc = *bp++; /* nul is noop */ + while (--cc && rc--) + tp[i++] |= (int16)*bp++ << shft; + } + if (i != npixels) { + TIFFError(tif->tif_name, + "LogL16Decode: Not enough data at row %d (short %d pixels)", + tif->tif_row, npixels - i); + tif->tif_rawcp = (tidata_t) bp; + tif->tif_rawcc = cc; + return (0); + } + } + (*sp->tfunc)(sp, op, npixels); + tif->tif_rawcp = (tidata_t) bp; + tif->tif_rawcc = cc; + return (1); +} + +/* + * Decode a string of 24-bit pixels. + */ +static int +LogLuvDecode24(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s) +{ + LogLuvState* sp = DecoderState(tif); + int cc, i, npixels; + u_char* bp; + uint32* tp; + + assert(s == 0); + assert(sp != NULL); + + npixels = occ / sp->pixel_size; + + if (sp->user_datafmt == SGILOGDATAFMT_RAW) + tp = (uint32 *)op; + else { + assert(sp->tbuflen >= npixels); + tp = (uint32 *) sp->tbuf; + } + /* copy to array of uint32 */ + bp = (u_char*) tif->tif_rawcp; + cc = tif->tif_rawcc; + for (i = 0; i < npixels && cc > 0; i++) { + tp[i] = bp[0] << 16 | bp[1] << 8 | bp[2]; + bp += 3; + cc -= 3; + } + tif->tif_rawcp = (tidata_t) bp; + tif->tif_rawcc = cc; + if (i != npixels) { + TIFFError(tif->tif_name, + "LogLuvDecode24: Not enough data at row %d (short %d pixels)", + tif->tif_row, npixels - i); + return (0); + } + (*sp->tfunc)(sp, op, npixels); + return (1); +} + +/* + * Decode a string of 32-bit pixels. + */ +static int +LogLuvDecode32(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s) +{ + LogLuvState* sp; + int shft, i, npixels; + u_char* bp; + uint32* tp; + uint32 b; + int cc, rc; + + assert(s == 0); + sp = DecoderState(tif); + assert(sp != NULL); + + npixels = occ / sp->pixel_size; + + if (sp->user_datafmt == SGILOGDATAFMT_RAW) + tp = (uint32*) op; + else { + assert(sp->tbuflen >= npixels); + tp = (uint32*) sp->tbuf; + } + _TIFFmemset((tdata_t) tp, 0, npixels*sizeof (tp[0])); + + bp = (u_char*) tif->tif_rawcp; + cc = tif->tif_rawcc; + /* get each byte string */ + for (shft = 4*8; (shft -= 8) >= 0; ) { + for (i = 0; i < npixels && cc > 0; ) + if (*bp >= 128) { /* run */ + rc = *bp++ + (2-128); + b = (uint32)*bp++ << shft; + cc -= 2; + while (rc--) + tp[i++] |= b; + } else { /* non-run */ + rc = *bp++; /* nul is noop */ + while (--cc && rc--) + tp[i++] |= (uint32)*bp++ << shft; + } + if (i != npixels) { + TIFFError(tif->tif_name, + "LogLuvDecode32: Not enough data at row %d (short %d pixels)", + tif->tif_row, npixels - i); + tif->tif_rawcp = (tidata_t) bp; + tif->tif_rawcc = cc; + return (0); + } + } + (*sp->tfunc)(sp, op, npixels); + tif->tif_rawcp = (tidata_t) bp; + tif->tif_rawcc = cc; + return (1); +} + +/* + * Decode a strip of pixels. We break it into rows to + * maintain synchrony with the encode algorithm, which + * is row by row. + */ +static int +LogLuvDecodeStrip(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + tsize_t rowlen = TIFFScanlineSize(tif); + + assert(cc%rowlen == 0); + while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s)) + bp += rowlen, cc -= rowlen; + return (cc == 0); +} + +/* + * Decode a tile of pixels. We break it into rows to + * maintain synchrony with the encode algorithm, which + * is row by row. + */ +static int +LogLuvDecodeTile(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + tsize_t rowlen = TIFFTileRowSize(tif); + + assert(cc%rowlen == 0); + while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s)) + bp += rowlen, cc -= rowlen; + return (cc == 0); +} + +/* + * Encode a row of 16-bit pixels. + */ +static int +LogL16Encode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + LogLuvState* sp = EncoderState(tif); + int shft, i, j, npixels; + tidata_t op; + int16* tp; + int16 b; + int occ, rc=0, mask, beg; + + assert(s == 0); + assert(sp != NULL); + npixels = cc / sp->pixel_size; + + if (sp->user_datafmt == SGILOGDATAFMT_16BIT) + tp = (int16*) bp; + else { + tp = (int16*) sp->tbuf; + assert(sp->tbuflen >= npixels); + (*sp->tfunc)(sp, bp, npixels); + } + /* compress each byte string */ + op = tif->tif_rawcp; + occ = tif->tif_rawdatasize - tif->tif_rawcc; + for (shft = 2*8; (shft -= 8) >= 0; ) + for (i = 0; i < npixels; i += rc) { + if (occ < 4) { + tif->tif_rawcp = op; + tif->tif_rawcc = tif->tif_rawdatasize - occ; + if (!TIFFFlushData1(tif)) + return (-1); + op = tif->tif_rawcp; + occ = tif->tif_rawdatasize - tif->tif_rawcc; + } + mask = 0xff << shft; /* find next run */ + for (beg = i; beg < npixels; beg += rc) { + b = tp[beg] & mask; + rc = 1; + while (rc < 127+2 && beg+rc < npixels && + (tp[beg+rc] & mask) == b) + rc++; + if (rc >= MINRUN) + break; /* long enough */ + } + if (beg-i > 1 && beg-i < MINRUN) { + b = tp[i] & mask; /* check short run */ + j = i+1; + while ((tp[j++] & mask) == b) + if (j == beg) { + *op++ = 128-2+j-i; + *op++ = b >> shft; + occ -= 2; + i = beg; + break; + } + } + while (i < beg) { /* write out non-run */ + if ((j = beg-i) > 127) j = 127; + if (occ < j+3) { + tif->tif_rawcp = op; + tif->tif_rawcc = tif->tif_rawdatasize - occ; + if (!TIFFFlushData1(tif)) + return (-1); + op = tif->tif_rawcp; + occ = tif->tif_rawdatasize - tif->tif_rawcc; + } + *op++ = j; occ--; + while (j--) { + *op++ = tp[i++] >> shft & 0xff; + occ--; + } + } + if (rc >= MINRUN) { /* write out run */ + *op++ = 128-2+rc; + *op++ = tp[beg] >> shft & 0xff; + occ -= 2; + } else + rc = 0; + } + tif->tif_rawcp = op; + tif->tif_rawcc = tif->tif_rawdatasize - occ; + + return (0); +} + +/* + * Encode a row of 24-bit pixels. + */ +static int +LogLuvEncode24(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + LogLuvState* sp = EncoderState(tif); + int i, npixels, occ; + tidata_t op; + uint32* tp; + + assert(s == 0); + assert(sp != NULL); + npixels = cc / sp->pixel_size; + + if (sp->user_datafmt == SGILOGDATAFMT_RAW) + tp = (uint32*) bp; + else { + tp = (uint32*) sp->tbuf; + assert(sp->tbuflen >= npixels); + (*sp->tfunc)(sp, bp, npixels); + } + /* write out encoded pixels */ + op = tif->tif_rawcp; + occ = tif->tif_rawdatasize - tif->tif_rawcc; + for (i = npixels; i--; ) { + if (occ < 3) { + tif->tif_rawcp = op; + tif->tif_rawcc = tif->tif_rawdatasize - occ; + if (!TIFFFlushData1(tif)) + return (-1); + op = tif->tif_rawcp; + occ = tif->tif_rawdatasize - tif->tif_rawcc; + } + *op++ = (tidataval_t)(*tp >> 16); + *op++ = (tidataval_t)(*tp >> 8 & 0xff); + *op++ = (tidataval_t)(*tp++ & 0xff); + occ -= 3; + } + tif->tif_rawcp = op; + tif->tif_rawcc = tif->tif_rawdatasize - occ; + + return (0); +} + +/* + * Encode a row of 32-bit pixels. + */ +static int +LogLuvEncode32(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + LogLuvState* sp = EncoderState(tif); + int shft, i, j, npixels; + tidata_t op; + uint32* tp; + uint32 b; + int occ, rc=0, mask, beg; + + assert(s == 0); + assert(sp != NULL); + + npixels = cc / sp->pixel_size; + + if (sp->user_datafmt == SGILOGDATAFMT_RAW) + tp = (uint32*) bp; + else { + tp = (uint32*) sp->tbuf; + assert(sp->tbuflen >= npixels); + (*sp->tfunc)(sp, bp, npixels); + } + /* compress each byte string */ + op = tif->tif_rawcp; + occ = tif->tif_rawdatasize - tif->tif_rawcc; + for (shft = 4*8; (shft -= 8) >= 0; ) + for (i = 0; i < npixels; i += rc) { + if (occ < 4) { + tif->tif_rawcp = op; + tif->tif_rawcc = tif->tif_rawdatasize - occ; + if (!TIFFFlushData1(tif)) + return (-1); + op = tif->tif_rawcp; + occ = tif->tif_rawdatasize - tif->tif_rawcc; + } + mask = 0xff << shft; /* find next run */ + for (beg = i; beg < npixels; beg += rc) { + b = tp[beg] & mask; + rc = 1; + while (rc < 127+2 && beg+rc < npixels && + (tp[beg+rc] & mask) == b) + rc++; + if (rc >= MINRUN) + break; /* long enough */ + } + if (beg-i > 1 && beg-i < MINRUN) { + b = tp[i] & mask; /* check short run */ + j = i+1; + while ((tp[j++] & mask) == b) + if (j == beg) { + *op++ = (tidataval_t)(128-2+j-i); + *op++ = (tidataval_t)(b >> shft); + occ -= 2; + i = beg; + break; + } + } + while (i < beg) { /* write out non-run */ + if ((j = beg-i) > 127) j = 127; + if (occ < j+3) { + tif->tif_rawcp = op; + tif->tif_rawcc = tif->tif_rawdatasize - occ; + if (!TIFFFlushData1(tif)) + return (-1); + op = tif->tif_rawcp; + occ = tif->tif_rawdatasize - tif->tif_rawcc; + } + *op++ = j; occ--; + while (j--) { + *op++ = (tidataval_t)(tp[i++] >> shft & 0xff); + occ--; + } + } + if (rc >= MINRUN) { /* write out run */ + *op++ = 128-2+rc; + *op++ = (tidataval_t)(tp[beg] >> shft & 0xff); + occ -= 2; + } else + rc = 0; + } + tif->tif_rawcp = op; + tif->tif_rawcc = tif->tif_rawdatasize - occ; + + return (0); +} + +/* + * Encode a strip of pixels. We break it into rows to + * avoid encoding runs across row boundaries. + */ +static int +LogLuvEncodeStrip(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + tsize_t rowlen = TIFFScanlineSize(tif); + + assert(cc%rowlen == 0); + while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 0) + bp += rowlen, cc -= rowlen; + return (cc == 0); +} + +/* + * Encode a tile of pixels. We break it into rows to + * avoid encoding runs across row boundaries. + */ +static int +LogLuvEncodeTile(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + tsize_t rowlen = TIFFTileRowSize(tif); + + assert(cc%rowlen == 0); + while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 0) + bp += rowlen, cc -= rowlen; + return (cc == 0); +} + +/* + * Encode/Decode functions for converting to and from user formats. + */ + +#include "uvcode.h" + +#ifndef UVSCALE +#define U_NEU 0.210526316 +#define V_NEU 0.473684211 +#define UVSCALE 410. +#endif + +#ifndef M_LN2 +#define M_LN2 0.69314718055994530942 +#endif +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif +#define log2(x) ((1./M_LN2)*log(x)) +#define exp2(x) exp(M_LN2*(x)) + +#define itrunc(x,m) ((m)==SGILOGENCODE_NODITHER ? \ + (int)(x) : \ + (int)((x) + rand()*(1./RAND_MAX) - .5)) + +#if !LOGLUV_PUBLIC +static +#endif +double +LogL16toY(int p16) /* compute luminance from 16-bit LogL */ +{ + int Le = p16 & 0x7fff; + double Y; + + if (!Le) + return (0.); + Y = exp(M_LN2/256.*(Le+.5) - M_LN2*64.); + return (!(p16 & 0x8000) ? Y : -Y); +} + +#if !LOGLUV_PUBLIC +static +#endif +int +LogL16fromY(double Y, int em) /* get 16-bit LogL from Y */ +{ + if (Y >= 1.8371976e19) + return (0x7fff); + if (Y <= -1.8371976e19) + return (0xffff); + if (Y > 5.4136769e-20) + return itrunc(256.*(log2(Y) + 64.), em); + if (Y < -5.4136769e-20) + return (~0x7fff | itrunc(256.*(log2(-Y) + 64.), em)); + return (0); +} + +static void +L16toY(LogLuvState* sp, tidata_t op, int n) +{ + int16* l16 = (int16*) sp->tbuf; + float* yp = (float*) op; + + while (n-- > 0) + *yp++ = (float)LogL16toY(*l16++); +} + +static void +L16toGry(LogLuvState* sp, tidata_t op, int n) +{ + int16* l16 = (int16*) sp->tbuf; + uint8* gp = (uint8*) op; + + while (n-- > 0) { + double Y = LogL16toY(*l16++); + *gp++ = (Y <= 0.) ? 0 : (Y >= 1.) ? 255 : (int)(256.*sqrt(Y)); + } +} + +static void +L16fromY(LogLuvState* sp, tidata_t op, int n) +{ + int16* l16 = (int16*) sp->tbuf; + float* yp = (float*) op; + + while (n-- > 0) + *l16++ = LogL16fromY(*yp++, sp->encode_meth); +} + +#if !LOGLUV_PUBLIC +static +#endif +void +XYZtoRGB24(float xyz[3], uint8 rgb[3]) +{ + double r, g, b; + /* assume CCIR-709 primaries */ + r = 2.690*xyz[0] + -1.276*xyz[1] + -0.414*xyz[2]; + g = -1.022*xyz[0] + 1.978*xyz[1] + 0.044*xyz[2]; + b = 0.061*xyz[0] + -0.224*xyz[1] + 1.163*xyz[2]; + /* assume 2.0 gamma for speed */ + /* could use integer sqrt approx., but this is probably faster */ + rgb[0] = (r <= 0.) ? 0 : (r >= 1.) ? 255 : (int)(256.*sqrt(r)); + rgb[1] = (g <= 0.) ? 0 : (g >= 1.) ? 255 : (int)(256.*sqrt(g)); + rgb[2] = (b <= 0.) ? 0 : (b >= 1.) ? 255 : (int)(256.*sqrt(b)); +} + +#if !LOGLUV_PUBLIC +static +#endif +double +LogL10toY(int p10) /* compute luminance from 10-bit LogL */ +{ + if (p10 == 0) + return (0.); + return (exp(M_LN2/64.*(p10+.5) - M_LN2*12.)); +} + +#if !LOGLUV_PUBLIC +static +#endif +int +LogL10fromY(double Y, int em) /* get 10-bit LogL from Y */ +{ + if (Y >= 15.742) + return (0x3ff); + else if (Y <= .00024283) + return (0); + else + return itrunc(64.*(log2(Y) + 12.), em); +} + +#define NANGLES 100 +#define uv2ang(u, v) ( (NANGLES*.499999999/M_PI) \ + * atan2((v)-V_NEU,(u)-U_NEU) + .5*NANGLES ) + +static int +oog_encode(double u, double v) /* encode out-of-gamut chroma */ +{ + static int oog_table[NANGLES]; + static int initialized = 0; + register int i; + + if (!initialized) { /* set up perimeter table */ + double eps[NANGLES], ua, va, ang, epsa; + int ui, vi, ustep; + for (i = NANGLES; i--; ) + eps[i] = 2.; + for (vi = UV_NVS; vi--; ) { + va = UV_VSTART + (vi+.5)*UV_SQSIZ; + ustep = uv_row[vi].nus-1; + if (vi == UV_NVS-1 || vi == 0 || ustep <= 0) + ustep = 1; + for (ui = uv_row[vi].nus-1; ui >= 0; ui -= ustep) { + ua = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ; + ang = uv2ang(ua, va); + i = (int) ang; + epsa = fabs(ang - (i+.5)); + if (epsa < eps[i]) { + oog_table[i] = uv_row[vi].ncum + ui; + eps[i] = epsa; + } + } + } + for (i = NANGLES; i--; ) /* fill any holes */ + if (eps[i] > 1.5) { + int i1, i2; + for (i1 = 1; i1 < NANGLES/2; i1++) + if (eps[(i+i1)%NANGLES] < 1.5) + break; + for (i2 = 1; i2 < NANGLES/2; i2++) + if (eps[(i+NANGLES-i2)%NANGLES] < 1.5) + break; + if (i1 < i2) + oog_table[i] = + oog_table[(i+i1)%NANGLES]; + else + oog_table[i] = + oog_table[(i+NANGLES-i2)%NANGLES]; + } + initialized = 1; + } + i = (int) uv2ang(u, v); /* look up hue angle */ + return (oog_table[i]); +} + +#undef uv2ang +#undef NANGLES + +#if !LOGLUV_PUBLIC +static +#endif +int +uv_encode(double u, double v, int em) /* encode (u',v') coordinates */ +{ + register int vi, ui; + + if (v < UV_VSTART) + return oog_encode(u, v); + vi = itrunc((v - UV_VSTART)*(1./UV_SQSIZ), em); + if (vi >= UV_NVS) + return oog_encode(u, v); + if (u < uv_row[vi].ustart) + return oog_encode(u, v); + ui = itrunc((u - uv_row[vi].ustart)*(1./UV_SQSIZ), em); + if (ui >= uv_row[vi].nus) + return oog_encode(u, v); + + return (uv_row[vi].ncum + ui); +} + +#if !LOGLUV_PUBLIC +static +#endif +int +uv_decode(double *up, double *vp, int c) /* decode (u',v') index */ +{ + int upper, lower; + register int ui, vi; + + if (c < 0 || c >= UV_NDIVS) + return (-1); + lower = 0; /* binary search */ + upper = UV_NVS; + while (upper - lower > 1) { + vi = (lower + upper) >> 1; + ui = c - uv_row[vi].ncum; + if (ui > 0) + lower = vi; + else if (ui < 0) + upper = vi; + else { + lower = vi; + break; + } + } + vi = lower; + ui = c - uv_row[vi].ncum; + *up = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ; + *vp = UV_VSTART + (vi+.5)*UV_SQSIZ; + return (0); +} + +#if !LOGLUV_PUBLIC +static +#endif +void +LogLuv24toXYZ(uint32 p, float XYZ[3]) +{ + int Ce; + double L, u, v, s, x, y; + /* decode luminance */ + L = LogL10toY(p>>14 & 0x3ff); + if (L <= 0.) { + XYZ[0] = XYZ[1] = XYZ[2] = 0.; + return; + } + /* decode color */ + Ce = p & 0x3fff; + if (uv_decode(&u, &v, Ce) < 0) { + u = U_NEU; v = V_NEU; + } + s = 1./(6.*u - 16.*v + 12.); + x = 9.*u * s; + y = 4.*v * s; + /* convert to XYZ */ + XYZ[0] = (float)(x/y * L); + XYZ[1] = (float)L; + XYZ[2] = (float)((1.-x-y)/y * L); +} + +#if !LOGLUV_PUBLIC +static +#endif +uint32 +LogLuv24fromXYZ(float XYZ[3], int em) +{ + int Le, Ce; + double u, v, s; + /* encode luminance */ + Le = LogL10fromY(XYZ[1], em); + /* encode color */ + s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2]; + if (!Le || s <= 0.) { + u = U_NEU; + v = V_NEU; + } else { + u = 4.*XYZ[0] / s; + v = 9.*XYZ[1] / s; + } + Ce = uv_encode(u, v, em); + if (Ce < 0) /* never happens */ + Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER); + /* combine encodings */ + return (Le << 14 | Ce); +} + +static void +Luv24toXYZ(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + float* xyz = (float*) op; + + while (n-- > 0) { + LogLuv24toXYZ(*luv, xyz); + xyz += 3; + luv++; + } +} + +static void +Luv24toLuv48(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + int16* luv3 = (int16*) op; + + while (n-- > 0) { + double u, v; + + *luv3++ = (int16)((*luv >> 12 & 0xffd) + 13314); + if (uv_decode(&u, &v, *luv&0x3fff) < 0) { + u = U_NEU; + v = V_NEU; + } + *luv3++ = (int16)(u * (1L<<15)); + *luv3++ = (int16)(v * (1L<<15)); + luv++; + } +} + +static void +Luv24toRGB(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + uint8* rgb = (uint8*) op; + + while (n-- > 0) { + float xyz[3]; + + LogLuv24toXYZ(*luv++, xyz); + XYZtoRGB24(xyz, rgb); + rgb += 3; + } +} + +static void +Luv24fromXYZ(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + float* xyz = (float*) op; + + while (n-- > 0) { + *luv++ = LogLuv24fromXYZ(xyz, sp->encode_meth); + xyz += 3; + } +} + +static void +Luv24fromLuv48(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + int16* luv3 = (int16*) op; + + while (n-- > 0) { + int Le, Ce; + + if (luv3[0] <= 0) + Le = 0; + else if (luv3[0] >= (1<<12)+3314) + Le = (1<<10) - 1; + else if (sp->encode_meth == SGILOGENCODE_NODITHER) + Le = (luv3[0]-3314) >> 2; + else + Le = itrunc(.25*(luv3[0]-3314.), sp->encode_meth); + + Ce = uv_encode((luv[1]+.5)/(1<<15), (luv[2]+.5)/(1<<15), + sp->encode_meth); + if (Ce < 0) /* never happens */ + Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER); + *luv++ = (uint32)Le << 14 | Ce; + luv3 += 3; + } +} + +#if !LOGLUV_PUBLIC +static +#endif +void +LogLuv32toXYZ(uint32 p, float XYZ[3]) +{ + double L, u, v, s, x, y; + /* decode luminance */ + L = LogL16toY((int)p >> 16); + if (L <= 0.) { + XYZ[0] = XYZ[1] = XYZ[2] = 0.; + return; + } + /* decode color */ + u = 1./UVSCALE * ((p>>8 & 0xff) + .5); + v = 1./UVSCALE * ((p & 0xff) + .5); + s = 1./(6.*u - 16.*v + 12.); + x = 9.*u * s; + y = 4.*v * s; + /* convert to XYZ */ + XYZ[0] = (float)(x/y * L); + XYZ[1] = (float)L; + XYZ[2] = (float)((1.-x-y)/y * L); +} + +#if !LOGLUV_PUBLIC +static +#endif +uint32 +LogLuv32fromXYZ(float XYZ[3], int em) +{ + unsigned int Le, ue, ve; + double u, v, s; + /* encode luminance */ + Le = (unsigned int)LogL16fromY(XYZ[1], em); + /* encode color */ + s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2]; + if (!Le || s <= 0.) { + u = U_NEU; + v = V_NEU; + } else { + u = 4.*XYZ[0] / s; + v = 9.*XYZ[1] / s; + } + if (u <= 0.) ue = 0; + else ue = itrunc(UVSCALE*u, em); + if (ue > 255) ue = 255; + if (v <= 0.) ve = 0; + else ve = itrunc(UVSCALE*v, em); + if (ve > 255) ve = 255; + /* combine encodings */ + return (Le << 16 | ue << 8 | ve); +} + +static void +Luv32toXYZ(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + float* xyz = (float*) op; + + while (n-- > 0) { + LogLuv32toXYZ(*luv++, xyz); + xyz += 3; + } +} + +static void +Luv32toLuv48(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + int16* luv3 = (int16*) op; + + while (n-- > 0) { + double u, v; + + *luv3++ = (int16)(*luv >> 16); + u = 1./UVSCALE * ((*luv>>8 & 0xff) + .5); + v = 1./UVSCALE * ((*luv & 0xff) + .5); + *luv3++ = (int16)(u * (1L<<15)); + *luv3++ = (int16)(v * (1L<<15)); + luv++; + } +} + +static void +Luv32toRGB(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + uint8* rgb = (uint8*) op; + + while (n-- > 0) { + float xyz[3]; + + LogLuv32toXYZ(*luv++, xyz); + XYZtoRGB24(xyz, rgb); + rgb += 3; + } +} + +static void +Luv32fromXYZ(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + float* xyz = (float*) op; + + while (n-- > 0) { + *luv++ = LogLuv32fromXYZ(xyz, sp->encode_meth); + xyz += 3; + } +} + +static void +Luv32fromLuv48(LogLuvState* sp, tidata_t op, int n) +{ + uint32* luv = (uint32*) sp->tbuf; + int16* luv3 = (int16*) op; + + if (sp->encode_meth == SGILOGENCODE_NODITHER) { + while (n-- > 0) { + *luv++ = (uint32)luv3[0] << 16 | + (luv3[1]*(uint32)(UVSCALE+.5) >> 7 & 0xff00) | + (luv3[2]*(uint32)(UVSCALE+.5) >> 15 & 0xff); + luv3 += 3; + } + return; + } + while (n-- > 0) { + *luv++ = (uint32)luv3[0] << 16 | + (itrunc(luv3[1]*(UVSCALE/(1<<15)), sp->encode_meth) << 8 & 0xff00) | + (itrunc(luv3[2]*(UVSCALE/(1<<15)), sp->encode_meth) & 0xff); + luv3 += 3; + } +} + +static void +_logLuvNop(LogLuvState* sp, tidata_t op, int n) +{ + (void) sp; (void) op; (void) n; +} + +static int +LogL16GuessDataFmt(TIFFDirectory *td) +{ +#define PACK(s,b,f) (((b)<<6)|((s)<<3)|(f)) + switch (PACK(td->td_samplesperpixel, td->td_bitspersample, td->td_sampleformat)) { + case PACK(1, 32, SAMPLEFORMAT_IEEEFP): + return (SGILOGDATAFMT_FLOAT); + case PACK(1, 16, SAMPLEFORMAT_VOID): + case PACK(1, 16, SAMPLEFORMAT_INT): + case PACK(1, 16, SAMPLEFORMAT_UINT): + return (SGILOGDATAFMT_16BIT); + case PACK(1, 8, SAMPLEFORMAT_VOID): + case PACK(1, 8, SAMPLEFORMAT_UINT): + return (SGILOGDATAFMT_8BIT); + } +#undef PACK + return (SGILOGDATAFMT_UNKNOWN); +} + +static int +LogL16InitState(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + LogLuvState* sp = DecoderState(tif); + static const char module[] = "LogL16InitState"; + + assert(sp != NULL); + assert(td->td_photometric == PHOTOMETRIC_LOGL); + + /* for some reason, we can't do this in TIFFInitLogL16 */ + if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN) + sp->user_datafmt = LogL16GuessDataFmt(td); + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + sp->pixel_size = sizeof (float); + break; + case SGILOGDATAFMT_16BIT: + sp->pixel_size = sizeof (int16); + break; + case SGILOGDATAFMT_8BIT: + sp->pixel_size = sizeof (uint8); + break; + default: + TIFFError(tif->tif_name, + "No support for converting user data format to LogL"); + return (0); + } + sp->tbuflen = td->td_imagewidth * td->td_rowsperstrip; + sp->tbuf = (tidata_t*) _TIFFmalloc(sp->tbuflen * sizeof (int16)); + if (sp->tbuf == NULL) { + TIFFError(module, "%s: No space for SGILog translation buffer", + tif->tif_name); + return (0); + } + return (1); +} + +static int +LogLuvGuessDataFmt(TIFFDirectory *td) +{ + int guess; + + /* + * If the user didn't tell us their datafmt, + * take our best guess from the bitspersample. + */ +#define PACK(a,b) (((a)<<3)|(b)) + switch (PACK(td->td_bitspersample, td->td_sampleformat)) { + case PACK(32, SAMPLEFORMAT_IEEEFP): + guess = SGILOGDATAFMT_FLOAT; + break; + case PACK(32, SAMPLEFORMAT_VOID): + case PACK(32, SAMPLEFORMAT_UINT): + case PACK(32, SAMPLEFORMAT_INT): + guess = SGILOGDATAFMT_RAW; + break; + case PACK(16, SAMPLEFORMAT_VOID): + case PACK(16, SAMPLEFORMAT_INT): + case PACK(16, SAMPLEFORMAT_UINT): + guess = SGILOGDATAFMT_16BIT; + break; + case PACK( 8, SAMPLEFORMAT_VOID): + case PACK( 8, SAMPLEFORMAT_UINT): + guess = SGILOGDATAFMT_8BIT; + break; + default: + guess = SGILOGDATAFMT_UNKNOWN; + break; +#undef PACK + } + /* + * Double-check samples per pixel. + */ + switch (td->td_samplesperpixel) { + case 1: + if (guess != SGILOGDATAFMT_RAW) + guess = SGILOGDATAFMT_UNKNOWN; + break; + case 3: + if (guess == SGILOGDATAFMT_RAW) + guess = SGILOGDATAFMT_UNKNOWN; + break; + default: + guess = SGILOGDATAFMT_UNKNOWN; + break; + } + return (guess); +} + +static int +LogLuvInitState(TIFF* tif) +{ + TIFFDirectory* td = &tif->tif_dir; + LogLuvState* sp = DecoderState(tif); + static const char module[] = "LogLuvInitState"; + + assert(sp != NULL); + assert(td->td_photometric == PHOTOMETRIC_LOGLUV); + + /* for some reason, we can't do this in TIFFInitLogLuv */ + if (td->td_planarconfig != PLANARCONFIG_CONTIG) { + TIFFError(module, + "SGILog compression cannot handle non-contiguous data"); + return (0); + } + if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN) + sp->user_datafmt = LogLuvGuessDataFmt(td); + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + sp->pixel_size = 3*sizeof (float); + break; + case SGILOGDATAFMT_16BIT: + sp->pixel_size = 3*sizeof (int16); + break; + case SGILOGDATAFMT_RAW: + sp->pixel_size = sizeof (uint32); + break; + case SGILOGDATAFMT_8BIT: + sp->pixel_size = 3*sizeof (uint8); + break; + default: + TIFFError(tif->tif_name, + "No support for converting user data format to LogLuv"); + return (0); + } + sp->tbuflen = td->td_imagewidth * td->td_rowsperstrip; + sp->tbuf = (tidata_t*) _TIFFmalloc(sp->tbuflen * sizeof (uint32)); + if (sp->tbuf == NULL) { + TIFFError(module, "%s: No space for SGILog translation buffer", + tif->tif_name); + return (0); + } + return (1); +} + +static int +LogLuvSetupDecode(TIFF* tif) +{ + LogLuvState* sp = DecoderState(tif); + TIFFDirectory* td = &tif->tif_dir; + + tif->tif_postdecode = _TIFFNoPostDecode; + switch (td->td_photometric) { + case PHOTOMETRIC_LOGLUV: + if (!LogLuvInitState(tif)) + break; + if (td->td_compression == COMPRESSION_SGILOG24) { + tif->tif_decoderow = LogLuvDecode24; + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + sp->tfunc = Luv24toXYZ; + break; + case SGILOGDATAFMT_16BIT: + sp->tfunc = Luv24toLuv48; + break; + case SGILOGDATAFMT_8BIT: + sp->tfunc = Luv24toRGB; + break; + } + } else { + tif->tif_decoderow = LogLuvDecode32; + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + sp->tfunc = Luv32toXYZ; + break; + case SGILOGDATAFMT_16BIT: + sp->tfunc = Luv32toLuv48; + break; + case SGILOGDATAFMT_8BIT: + sp->tfunc = Luv32toRGB; + break; + } + } + return (1); + case PHOTOMETRIC_LOGL: + if (!LogL16InitState(tif)) + break; + tif->tif_decoderow = LogL16Decode; + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + sp->tfunc = L16toY; + break; + case SGILOGDATAFMT_8BIT: + sp->tfunc = L16toGry; + break; + } + return (1); + default: + TIFFError(tif->tif_name, + "Inappropriate photometric interpretation %d for SGILog compression; %s", + td->td_photometric, "must be either LogLUV or LogL"); + break; + } + return (0); +} + +static int +LogLuvSetupEncode(TIFF* tif) +{ + LogLuvState* sp = EncoderState(tif); + TIFFDirectory* td = &tif->tif_dir; + + switch (td->td_photometric) { + case PHOTOMETRIC_LOGLUV: + if (!LogLuvInitState(tif)) + break; + if (td->td_compression == COMPRESSION_SGILOG24) { + tif->tif_encoderow = LogLuvEncode24; + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + sp->tfunc = Luv24fromXYZ; + break; + case SGILOGDATAFMT_16BIT: + sp->tfunc = Luv24fromLuv48; + break; + case SGILOGDATAFMT_RAW: + break; + default: + goto notsupported; + } + } else { + tif->tif_encoderow = LogLuvEncode32; + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + sp->tfunc = Luv32fromXYZ; + break; + case SGILOGDATAFMT_16BIT: + sp->tfunc = Luv32fromLuv48; + break; + case SGILOGDATAFMT_RAW: + break; + default: + goto notsupported; + } + } + break; + case PHOTOMETRIC_LOGL: + if (!LogL16InitState(tif)) + break; + tif->tif_encoderow = LogL16Encode; + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + sp->tfunc = L16fromY; + break; + case SGILOGDATAFMT_16BIT: + break; + default: + goto notsupported; + } + break; + default: + TIFFError(tif->tif_name, + "Inappropriate photometric interpretation %d for SGILog compression; %s", + td->td_photometric, "must be either LogLUV or LogL"); + break; + } + return (1); +notsupported: + TIFFError(tif->tif_name, + "SGILog compression supported only for %s, or raw data", + td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv"); + return (0); +} + +static void +LogLuvClose(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + + /* + * For consistency, we always want to write out the same + * bitspersample and sampleformat for our TIFF file, + * regardless of the data format being used by the application. + * Since this routine is called after tags have been set but + * before they have been recorded in the file, we reset them here. + */ + td->td_samplesperpixel = + (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3; + td->td_bitspersample = 16; + td->td_sampleformat = SAMPLEFORMAT_INT; +} + +static void +LogLuvCleanup(TIFF* tif) +{ + LogLuvState* sp = (LogLuvState *)tif->tif_data; + + if (sp) { + if (sp->tbuf) + _TIFFfree(sp->tbuf); + _TIFFfree(sp); + tif->tif_data = NULL; + } +} + +static int +LogLuvVSetField(TIFF* tif, ttag_t tag, va_list ap) +{ + LogLuvState* sp = DecoderState(tif); + int bps, fmt; + + switch (tag) { + case TIFFTAG_SGILOGDATAFMT: + sp->user_datafmt = va_arg(ap, int); + /* + * Tweak the TIFF header so that the rest of libtiff knows what + * size of data will be passed between app and library, and + * assume that the app knows what it is doing and is not + * confused by these header manipulations... + */ + switch (sp->user_datafmt) { + case SGILOGDATAFMT_FLOAT: + bps = 32, fmt = SAMPLEFORMAT_IEEEFP; + break; + case SGILOGDATAFMT_16BIT: + bps = 16, fmt = SAMPLEFORMAT_INT; + break; + case SGILOGDATAFMT_RAW: + bps = 32, fmt = SAMPLEFORMAT_UINT; + TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1); + break; + case SGILOGDATAFMT_8BIT: + bps = 8, fmt = SAMPLEFORMAT_UINT; + break; + default: + TIFFError(tif->tif_name, + "Unknown data format %d for LogLuv compression", + sp->user_datafmt); + return (0); + } + TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps); + TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, fmt); + /* + * Must recalculate sizes should bits/sample change. + */ + tif->tif_tilesize = TIFFTileSize(tif); + tif->tif_scanlinesize = TIFFScanlineSize(tif); + return (1); + case TIFFTAG_SGILOGENCODE: + sp->encode_meth = va_arg(ap, int); + if (sp->encode_meth != SGILOGENCODE_NODITHER && + sp->encode_meth != SGILOGENCODE_RANDITHER) { + TIFFError(tif->tif_name, + "Unknown encoding %d for LogLuv compression", + sp->encode_meth); + return (0); + } + return (1); + default: + return (*sp->vsetparent)(tif, tag, ap); + } +} + +static int +LogLuvVGetField(TIFF* tif, ttag_t tag, va_list ap) +{ + LogLuvState *sp = (LogLuvState *)tif->tif_data; + + switch (tag) { + case TIFFTAG_SGILOGDATAFMT: + *va_arg(ap, int*) = sp->user_datafmt; + return (1); + default: + return (*sp->vgetparent)(tif, tag, ap); + } +} + +static const TIFFFieldInfo LogLuvFieldInfo[] = { + { TIFFTAG_SGILOGDATAFMT, 0, 0, TIFF_SHORT, FIELD_PSEUDO, + TRUE, FALSE, "SGILogDataFmt"}, + { TIFFTAG_SGILOGENCODE, 0, 0, TIFF_SHORT, FIELD_PSEUDO, + TRUE, FALSE, "SGILogEncode"} +}; + +int +TIFFInitSGILog(TIFF* tif, int scheme) +{ + static const char module[] = "TIFFInitSGILog"; + LogLuvState* sp; + + assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG); + + /* + * Allocate state block so tag methods have storage to record values. + */ + tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (LogLuvState)); + if (tif->tif_data == NULL) + goto bad; + sp = (LogLuvState*) tif->tif_data; + _TIFFmemset((tdata_t)sp, 0, sizeof (*sp)); + sp->user_datafmt = SGILOGDATAFMT_UNKNOWN; + sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ? + SGILOGENCODE_RANDITHER : SGILOGENCODE_NODITHER; + sp->tfunc = _logLuvNop; + + /* + * Install codec methods. + * NB: tif_decoderow & tif_encoderow are filled + * in at setup time. + */ + tif->tif_setupdecode = LogLuvSetupDecode; + tif->tif_decodestrip = LogLuvDecodeStrip; + tif->tif_decodetile = LogLuvDecodeTile; + tif->tif_setupencode = LogLuvSetupEncode; + tif->tif_encodestrip = LogLuvEncodeStrip; + tif->tif_encodetile = LogLuvEncodeTile; + tif->tif_close = LogLuvClose; + tif->tif_cleanup = LogLuvCleanup; + + /* override SetField so we can handle our private pseudo-tag */ + _TIFFMergeFieldInfo(tif, LogLuvFieldInfo, N(LogLuvFieldInfo)); + sp->vgetparent = tif->tif_vgetfield; + tif->tif_vgetfield = LogLuvVGetField; /* hook for codec tags */ + sp->vsetparent = tif->tif_vsetfield; + tif->tif_vsetfield = LogLuvVSetField; /* hook for codec tags */ + + return (1); +bad: + TIFFError(module, "%s: No space for LogLuv state block", tif->tif_name); + return (0); +} +#endif /* LOGLUV_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_lzw.c b/SlnkDWFImpl/CxImage/tiff/tif_lzw.c new file mode 100644 index 0000000..3235521 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_lzw.c @@ -0,0 +1,1019 @@ +/* $Header: /cvsroot/libtiff-lzw-compression-kit/tif_lzw.c,v 1.2 2001/09/25 02:14:31 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef LZW_SUPPORT +/* + * TIFF Library. + * Rev 5.0 Lempel-Ziv & Welch Compression Support + * + * This code is derived from the compress program whose code is + * derived from software contributed to Berkeley by James A. Woods, + * derived from original work by Spencer Thomas and Joseph Orost. + * + * The original Berkeley copyright notice appears below in its entirety. + */ +#include "tif_predict.h" + +#include +#include + +/* + * NB: The 5.0 spec describes a different algorithm than Aldus + * implements. Specifically, Aldus does code length transitions + * one code earlier than should be done (for real LZW). + * Earlier versions of this library implemented the correct + * LZW algorithm, but emitted codes in a bit order opposite + * to the TIFF spec. Thus, to maintain compatibility w/ Aldus + * we interpret MSB-LSB ordered codes to be images written w/ + * old versions of this library, but otherwise adhere to the + * Aldus "off by one" algorithm. + * + * Future revisions to the TIFF spec are expected to "clarify this issue". + */ +#define LZW_COMPAT /* include backwards compatibility code */ +/* + * Each strip of data is supposed to be terminated by a CODE_EOI. + * If the following #define is included, the decoder will also + * check for end-of-strip w/o seeing this code. This makes the + * library more robust, but also slower. + */ +#define LZW_CHECKEOS /* include checks for strips w/o EOI code */ + +#define MAXCODE(n) ((1L<<(n))-1) +/* + * The TIFF spec specifies that encoded bit + * strings range from 9 to 12 bits. + */ +#define BITS_MIN 9 /* start with 9 bits */ +#define BITS_MAX 12 /* max of 12 bit strings */ +/* predefined codes */ +#define CODE_CLEAR 256 /* code to clear string table */ +#define CODE_EOI 257 /* end-of-information code */ +#define CODE_FIRST 258 /* first free code entry */ +#define CODE_MAX MAXCODE(BITS_MAX) +#define HSIZE 9001L /* 91% occupancy */ +#define HSHIFT (13-8) +#ifdef LZW_COMPAT +/* NB: +1024 is for compatibility with old files */ +#define CSIZE (MAXCODE(BITS_MAX)+1024L) +#else +#define CSIZE (MAXCODE(BITS_MAX)+1L) +#endif + +/* + * State block for each open TIFF file using LZW + * compression/decompression. Note that the predictor + * state block must be first in this data structure. + */ +typedef struct { + TIFFPredictorState predict; /* predictor super class */ + + u_short nbits; /* # of bits/code */ + u_short maxcode; /* maximum code for lzw_nbits */ + u_short free_ent; /* next free entry in hash table */ + long nextdata; /* next bits of i/o */ + long nextbits; /* # of valid bits in lzw_nextdata */ + + int rw_mode; /* preserve rw_mode from init */ +} LZWBaseState; + +#define lzw_nbits base.nbits +#define lzw_maxcode base.maxcode +#define lzw_free_ent base.free_ent +#define lzw_nextdata base.nextdata +#define lzw_nextbits base.nextbits + +/* + * Decoding-specific state. + */ +typedef struct code_ent { + struct code_ent *next; + u_short length; /* string len, including this token */ + u_char value; /* data value */ + u_char firstchar; /* first token of string */ +} code_t; + +typedef int (*decodeFunc)(TIFF*, tidata_t, tsize_t, tsample_t); + +typedef struct { + LZWBaseState base; + long dec_nbitsmask; /* lzw_nbits 1 bits, right adjusted */ + long dec_restart; /* restart count */ +#ifdef LZW_CHECKEOS + long dec_bitsleft; /* available bits in raw data */ +#endif + decodeFunc dec_decode; /* regular or backwards compatible */ + code_t* dec_codep; /* current recognized code */ + code_t* dec_oldcodep; /* previously recognized code */ + code_t* dec_free_entp; /* next free entry */ + code_t* dec_maxcodep; /* max available entry */ + code_t* dec_codetab; /* kept separate for small machines */ +} LZWDecodeState; + +/* + * Encoding-specific state. + */ +typedef uint16 hcode_t; /* codes fit in 16 bits */ +typedef struct { + long hash; + hcode_t code; +} hash_t; + +typedef struct { + LZWBaseState base; + int enc_oldcode; /* last code encountered */ + long enc_checkpoint; /* point at which to clear table */ +#define CHECK_GAP 10000 /* enc_ratio check interval */ + long enc_ratio; /* current compression ratio */ + long enc_incount; /* (input) data bytes encoded */ + long enc_outcount; /* encoded (output) bytes */ + tidata_t enc_rawlimit; /* bound on tif_rawdata buffer */ + hash_t* enc_hashtab; /* kept separate for small machines */ +} LZWEncodeState; + +#define LZWState(tif) ((LZWBaseState*) (tif)->tif_data) +#define DecoderState(tif) ((LZWDecodeState*) LZWState(tif)) +#define EncoderState(tif) ((LZWEncodeState*) LZWState(tif)) + +static int LZWDecode(TIFF*, tidata_t, tsize_t, tsample_t); +#ifdef LZW_COMPAT +static int LZWDecodeCompat(TIFF*, tidata_t, tsize_t, tsample_t); +#endif +static void cl_hash(LZWEncodeState*); + +/* + * LZW Decoder. + */ + +#ifdef LZW_CHECKEOS +/* + * This check shouldn't be necessary because each + * strip is suppose to be terminated with CODE_EOI. + */ +#define NextCode(_tif, _sp, _bp, _code, _get) { \ + if ((_sp)->dec_bitsleft < nbits) { \ + TIFFWarning(_tif->tif_name, \ + "LZWDecode: Strip %d not terminated with EOI code", \ + _tif->tif_curstrip); \ + _code = CODE_EOI; \ + } else { \ + _get(_sp,_bp,_code); \ + (_sp)->dec_bitsleft -= nbits; \ + } \ +} +#else +#define NextCode(tif, sp, bp, code, get) get(sp, bp, code) +#endif + +static int +LZWSetupDecode(TIFF* tif) +{ + LZWDecodeState* sp = DecoderState(tif); + static const char module[] = " LZWSetupDecode"; + int code; + + assert(sp != NULL); + if (sp->dec_codetab == NULL) { + sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t)); + if (sp->dec_codetab == NULL) { + TIFFError(module, "No space for LZW code table"); + return (0); + } + /* + * Pre-load the table. + */ + code = 255; + do { + sp->dec_codetab[code].value = code; + sp->dec_codetab[code].firstchar = code; + sp->dec_codetab[code].length = 1; + sp->dec_codetab[code].next = NULL; + } while (code--); + } + return (1); +} + +/* + * Setup state for decoding a strip. + */ +static int +LZWPreDecode(TIFF* tif, tsample_t s) +{ + LZWDecodeState *sp = DecoderState(tif); + + (void) s; + assert(sp != NULL); + /* + * Check for old bit-reversed codes. + */ + if (tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) { +#ifdef LZW_COMPAT + if (!sp->dec_decode) { + TIFFWarning(tif->tif_name, + "Old-style LZW codes, convert file"); + /* + * Override default decoding methods with + * ones that deal with the old coding. + * Otherwise the predictor versions set + * above will call the compatibility routines + * through the dec_decode method. + */ + tif->tif_decoderow = LZWDecodeCompat; + tif->tif_decodestrip = LZWDecodeCompat; + tif->tif_decodetile = LZWDecodeCompat; + /* + * If doing horizontal differencing, must + * re-setup the predictor logic since we + * switched the basic decoder methods... + */ + (*tif->tif_setupdecode)(tif); + sp->dec_decode = LZWDecodeCompat; + } + sp->lzw_maxcode = MAXCODE(BITS_MIN); +#else /* !LZW_COMPAT */ + if (!sp->dec_decode) { + TIFFError(tif->tif_name, + "Old-style LZW codes not supported"); + sp->dec_decode = LZWDecode; + } + return (0); +#endif/* !LZW_COMPAT */ + } else { + sp->lzw_maxcode = MAXCODE(BITS_MIN)-1; + sp->dec_decode = LZWDecode; + } + sp->lzw_nbits = BITS_MIN; + sp->lzw_nextbits = 0; + sp->lzw_nextdata = 0; + + sp->dec_restart = 0; + sp->dec_nbitsmask = MAXCODE(BITS_MIN); +#ifdef LZW_CHECKEOS + sp->dec_bitsleft = tif->tif_rawcc << 3; +#endif + sp->dec_free_entp = sp->dec_codetab + CODE_FIRST; + /* + * Zero entries that are not yet filled in. We do + * this to guard against bogus input data that causes + * us to index into undefined entries. If you can + * come up with a way to safely bounds-check input codes + * while decoding then you can remove this operation. + */ + _TIFFmemset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t)); + sp->dec_oldcodep = &sp->dec_codetab[-1]; + sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1]; + return (1); +} + +/* + * Decode a "hunk of data". + */ +#define GetNextCode(sp, bp, code) { \ + nextdata = (nextdata<<8) | *(bp)++; \ + nextbits += 8; \ + if (nextbits < nbits) { \ + nextdata = (nextdata<<8) | *(bp)++; \ + nextbits += 8; \ + } \ + code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask); \ + nextbits -= nbits; \ +} + +static void +codeLoop(TIFF* tif) +{ + TIFFError(tif->tif_name, + "LZWDecode: Bogus encoding, loop in the code table; scanline %d", + tif->tif_row); +} + +static int +LZWDecode(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s) +{ + LZWDecodeState *sp = DecoderState(tif); + char *op = (char*) op0; + long occ = (long) occ0; + char *tp; + u_char *bp; + hcode_t code; + int len; + long nbits, nextbits, nextdata, nbitsmask; + code_t *codep, *free_entp, *maxcodep, *oldcodep; + + (void) s; + assert(sp != NULL); + /* + * Restart interrupted output operation. + */ + if (sp->dec_restart) { + long residue; + + codep = sp->dec_codep; + residue = codep->length - sp->dec_restart; + if (residue > occ) { + /* + * Residue from previous decode is sufficient + * to satisfy decode request. Skip to the + * start of the decoded string, place decoded + * values in the output buffer, and return. + */ + sp->dec_restart += occ; + do { + codep = codep->next; + } while (--residue > occ && codep); + if (codep) { + tp = op + occ; + do { + *--tp = codep->value; + codep = codep->next; + } while (--occ && codep); + } + return (1); + } + /* + * Residue satisfies only part of the decode request. + */ + op += residue, occ -= residue; + tp = op; + do { + int t; + --tp; + t = codep->value; + codep = codep->next; + *tp = t; + } while (--residue && codep); + sp->dec_restart = 0; + } + + bp = (u_char *)tif->tif_rawcp; + nbits = sp->lzw_nbits; + nextdata = sp->lzw_nextdata; + nextbits = sp->lzw_nextbits; + nbitsmask = sp->dec_nbitsmask; + oldcodep = sp->dec_oldcodep; + free_entp = sp->dec_free_entp; + maxcodep = sp->dec_maxcodep; + + while (occ > 0) { + NextCode(tif, sp, bp, code, GetNextCode); + if (code == CODE_EOI) + break; + if (code == CODE_CLEAR) { + free_entp = sp->dec_codetab + CODE_FIRST; + nbits = BITS_MIN; + nbitsmask = MAXCODE(BITS_MIN); + maxcodep = sp->dec_codetab + nbitsmask-1; + NextCode(tif, sp, bp, code, GetNextCode); + if (code == CODE_EOI) + break; + *op++ = (char)code, occ--; + oldcodep = sp->dec_codetab + code; + continue; + } + codep = sp->dec_codetab + code; + + /* + * Add the new entry to the code table. + */ + assert(&sp->dec_codetab[0] <= free_entp && free_entp < &sp->dec_codetab[CSIZE]); + free_entp->next = oldcodep; + free_entp->firstchar = free_entp->next->firstchar; + free_entp->length = free_entp->next->length+1; + free_entp->value = (codep < free_entp) ? + codep->firstchar : free_entp->firstchar; + if (++free_entp > maxcodep) { + if (++nbits > BITS_MAX) /* should not happen */ + nbits = BITS_MAX; + nbitsmask = MAXCODE(nbits); + maxcodep = sp->dec_codetab + nbitsmask-1; + } + oldcodep = codep; + if (code >= 256) { + /* + * Code maps to a string, copy string + * value to output (written in reverse). + */ + if (codep->length > occ) { + /* + * String is too long for decode buffer, + * locate portion that will fit, copy to + * the decode buffer, and setup restart + * logic for the next decoding call. + */ + sp->dec_codep = codep; + do { + codep = codep->next; + } while (codep && codep->length > occ); + if (codep) { + sp->dec_restart = occ; + tp = op + occ; + do { + *--tp = codep->value; + codep = codep->next; + } while (--occ && codep); + if (codep) + codeLoop(tif); + } + break; + } + len = codep->length; + tp = op + len; + do { + int t; + --tp; + t = codep->value; + codep = codep->next; + *tp = t; + } while (codep && tp > op); + if (codep) { + codeLoop(tif); + break; + } + op += len, occ -= len; + } else + *op++ = (char)code, occ--; + } + + tif->tif_rawcp = (tidata_t) bp; + sp->lzw_nbits = (u_short) nbits; + sp->lzw_nextdata = nextdata; + sp->lzw_nextbits = nextbits; + sp->dec_nbitsmask = nbitsmask; + sp->dec_oldcodep = oldcodep; + sp->dec_free_entp = free_entp; + sp->dec_maxcodep = maxcodep; + + if (occ > 0) { + TIFFError(tif->tif_name, + "LZWDecode: Not enough data at scanline %d (short %d bytes)", + tif->tif_row, occ); + return (0); + } + return (1); +} + +#ifdef LZW_COMPAT +/* + * Decode a "hunk of data" for old images. + */ +#define GetNextCodeCompat(sp, bp, code) { \ + nextdata |= (u_long) *(bp)++ << nextbits; \ + nextbits += 8; \ + if (nextbits < nbits) { \ + nextdata |= (u_long) *(bp)++ << nextbits; \ + nextbits += 8; \ + } \ + code = (hcode_t)(nextdata & nbitsmask); \ + nextdata >>= nbits; \ + nextbits -= nbits; \ +} + +static int +LZWDecodeCompat(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s) +{ + LZWDecodeState *sp = DecoderState(tif); + char *op = (char*) op0; + long occ = (long) occ0; + char *tp; + u_char *bp; + int code, nbits; + long nextbits, nextdata, nbitsmask; + code_t *codep, *free_entp, *maxcodep, *oldcodep; + + (void) s; + assert(sp != NULL); + /* + * Restart interrupted output operation. + */ + if (sp->dec_restart) { + long residue; + + codep = sp->dec_codep; + residue = codep->length - sp->dec_restart; + if (residue > occ) { + /* + * Residue from previous decode is sufficient + * to satisfy decode request. Skip to the + * start of the decoded string, place decoded + * values in the output buffer, and return. + */ + sp->dec_restart += occ; + do { + codep = codep->next; + } while (--residue > occ); + tp = op + occ; + do { + *--tp = codep->value; + codep = codep->next; + } while (--occ); + return (1); + } + /* + * Residue satisfies only part of the decode request. + */ + op += residue, occ -= residue; + tp = op; + do { + *--tp = codep->value; + codep = codep->next; + } while (--residue); + sp->dec_restart = 0; + } + + bp = (u_char *)tif->tif_rawcp; + nbits = sp->lzw_nbits; + nextdata = sp->lzw_nextdata; + nextbits = sp->lzw_nextbits; + nbitsmask = sp->dec_nbitsmask; + oldcodep = sp->dec_oldcodep; + free_entp = sp->dec_free_entp; + maxcodep = sp->dec_maxcodep; + + while (occ > 0) { + NextCode(tif, sp, bp, code, GetNextCodeCompat); + if (code == CODE_EOI) + break; + if (code == CODE_CLEAR) { + free_entp = sp->dec_codetab + CODE_FIRST; + nbits = BITS_MIN; + nbitsmask = MAXCODE(BITS_MIN); + maxcodep = sp->dec_codetab + nbitsmask; + NextCode(tif, sp, bp, code, GetNextCodeCompat); + if (code == CODE_EOI) + break; + *op++ = code, occ--; + oldcodep = sp->dec_codetab + code; + continue; + } + codep = sp->dec_codetab + code; + + /* + * Add the new entry to the code table. + */ + assert(&sp->dec_codetab[0] <= free_entp && free_entp < &sp->dec_codetab[CSIZE]); + free_entp->next = oldcodep; + free_entp->firstchar = free_entp->next->firstchar; + free_entp->length = free_entp->next->length+1; + free_entp->value = (codep < free_entp) ? + codep->firstchar : free_entp->firstchar; + if (++free_entp > maxcodep) { + if (++nbits > BITS_MAX) /* should not happen */ + nbits = BITS_MAX; + nbitsmask = MAXCODE(nbits); + maxcodep = sp->dec_codetab + nbitsmask; + } + oldcodep = codep; + if (code >= 256) { + /* + * Code maps to a string, copy string + * value to output (written in reverse). + */ + if (codep->length > occ) { + /* + * String is too long for decode buffer, + * locate portion that will fit, copy to + * the decode buffer, and setup restart + * logic for the next decoding call. + */ + sp->dec_codep = codep; + do { + codep = codep->next; + } while (codep->length > occ); + sp->dec_restart = occ; + tp = op + occ; + do { + *--tp = codep->value; + codep = codep->next; + } while (--occ); + break; + } + op += codep->length, occ -= codep->length; + tp = op; + do { + *--tp = codep->value; + } while( (codep = codep->next) != NULL); + } else + *op++ = code, occ--; + } + + tif->tif_rawcp = (tidata_t) bp; + sp->lzw_nbits = nbits; + sp->lzw_nextdata = nextdata; + sp->lzw_nextbits = nextbits; + sp->dec_nbitsmask = nbitsmask; + sp->dec_oldcodep = oldcodep; + sp->dec_free_entp = free_entp; + sp->dec_maxcodep = maxcodep; + + if (occ > 0) { + TIFFError(tif->tif_name, + "LZWDecodeCompat: Not enough data at scanline %d (short %d bytes)", + tif->tif_row, occ); + return (0); + } + return (1); +} +#endif /* LZW_COMPAT */ + +/* + * LZW Encoding. + */ + +static int +LZWSetupEncode(TIFF* tif) +{ + LZWEncodeState* sp = EncoderState(tif); + static const char module[] = "LZWSetupEncode"; + + assert(sp != NULL); + sp->enc_hashtab = (hash_t*) _TIFFmalloc(HSIZE*sizeof (hash_t)); + if (sp->enc_hashtab == NULL) { + TIFFError(module, "No space for LZW hash table"); + return (0); + } + return (1); +} + +/* + * Reset encoding state at the start of a strip. + */ +static int +LZWPreEncode(TIFF* tif, tsample_t s) +{ + LZWEncodeState *sp = EncoderState(tif); + + (void) s; + assert(sp != NULL); + sp->lzw_nbits = BITS_MIN; + sp->lzw_maxcode = MAXCODE(BITS_MIN); + sp->lzw_free_ent = CODE_FIRST; + sp->lzw_nextbits = 0; + sp->lzw_nextdata = 0; + sp->enc_checkpoint = CHECK_GAP; + sp->enc_ratio = 0; + sp->enc_incount = 0; + sp->enc_outcount = 0; + /* + * The 4 here insures there is space for 2 max-sized + * codes in LZWEncode and LZWPostDecode. + */ + sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4; + cl_hash(sp); /* clear hash table */ + sp->enc_oldcode = (hcode_t) -1; /* generates CODE_CLEAR in LZWEncode */ + return (1); +} + +#define CALCRATIO(sp, rat) { \ + if (incount > 0x007fffff) { /* NB: shift will overflow */\ + rat = outcount >> 8; \ + rat = (rat == 0 ? 0x7fffffff : incount/rat); \ + } else \ + rat = (incount<<8) / outcount; \ +} +#define PutNextCode(op, c) { \ + nextdata = (nextdata << nbits) | c; \ + nextbits += nbits; \ + *op++ = (u_char)(nextdata >> (nextbits-8)); \ + nextbits -= 8; \ + if (nextbits >= 8) { \ + *op++ = (u_char)(nextdata >> (nextbits-8)); \ + nextbits -= 8; \ + } \ + outcount += nbits; \ +} + +/* + * Encode a chunk of pixels. + * + * Uses an open addressing double hashing (no chaining) on the + * prefix code/next character combination. We do a variant of + * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's + * relatively-prime secondary probe. Here, the modular division + * first probe is gives way to a faster exclusive-or manipulation. + * Also do block compression with an adaptive reset, whereby the + * code table is cleared when the compression ratio decreases, + * but after the table fills. The variable-length output codes + * are re-sized at this point, and a CODE_CLEAR is generated + * for the decoder. + */ +static int +LZWEncode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + register LZWEncodeState *sp = EncoderState(tif); + register long fcode; + register hash_t *hp; + register int h, c; + hcode_t ent; + long disp; + long incount, outcount, checkpoint; + long nextdata, nextbits; + int free_ent, maxcode, nbits; + tidata_t op, limit; + + (void) s; + if (sp == NULL) + return (0); + /* + * Load local state. + */ + incount = sp->enc_incount; + outcount = sp->enc_outcount; + checkpoint = sp->enc_checkpoint; + nextdata = sp->lzw_nextdata; + nextbits = sp->lzw_nextbits; + free_ent = sp->lzw_free_ent; + maxcode = sp->lzw_maxcode; + nbits = sp->lzw_nbits; + op = tif->tif_rawcp; + limit = sp->enc_rawlimit; + ent = sp->enc_oldcode; + + if (ent == (hcode_t) -1 && cc > 0) { + /* + * NB: This is safe because it can only happen + * at the start of a strip where we know there + * is space in the data buffer. + */ + PutNextCode(op, CODE_CLEAR); + ent = *bp++; cc--; incount++; + } + while (cc > 0) { + c = *bp++; cc--; incount++; + fcode = ((long)c << BITS_MAX) + ent; + h = (c << HSHIFT) ^ ent; /* xor hashing */ +#ifdef _WINDOWS + /* + * Check hash index for an overflow. + */ + if (h >= HSIZE) + h -= HSIZE; +#endif + hp = &sp->enc_hashtab[h]; + if (hp->hash == fcode) { + ent = hp->code; + continue; + } + if (hp->hash >= 0) { + /* + * Primary hash failed, check secondary hash. + */ + disp = HSIZE - h; + if (h == 0) + disp = 1; + do { + /* + * Avoid pointer arithmetic 'cuz of + * wraparound problems with segments. + */ + if ((h -= disp) < 0) + h += HSIZE; + hp = &sp->enc_hashtab[h]; + if (hp->hash == fcode) { + ent = hp->code; + goto hit; + } + } while (hp->hash >= 0); + } + /* + * New entry, emit code and add to table. + */ + /* + * Verify there is space in the buffer for the code + * and any potential Clear code that might be emitted + * below. The value of limit is setup so that there + * are at least 4 bytes free--room for 2 codes. + */ + if (op > limit) { + tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata); + TIFFFlushData1(tif); + op = tif->tif_rawdata; + } + PutNextCode(op, ent); + ent = c; + hp->code = free_ent++; + hp->hash = fcode; + if (free_ent == CODE_MAX-1) { + /* table is full, emit clear code and reset */ + cl_hash(sp); + sp->enc_ratio = 0; + incount = 0; + outcount = 0; + free_ent = CODE_FIRST; + PutNextCode(op, CODE_CLEAR); + nbits = BITS_MIN; + maxcode = MAXCODE(BITS_MIN); + } else { + /* + * If the next entry is going to be too big for + * the code size, then increase it, if possible. + */ + if (free_ent > maxcode) { + nbits++; + assert(nbits <= BITS_MAX); + maxcode = (int) MAXCODE(nbits); + } else if (incount >= checkpoint) { + long rat; + /* + * Check compression ratio and, if things seem + * to be slipping, clear the hash table and + * reset state. The compression ratio is a + * 24+8-bit fractional number. + */ + checkpoint = incount+CHECK_GAP; + CALCRATIO(sp, rat); + if (rat <= sp->enc_ratio) { + cl_hash(sp); + sp->enc_ratio = 0; + incount = 0; + outcount = 0; + free_ent = CODE_FIRST; + PutNextCode(op, CODE_CLEAR); + nbits = BITS_MIN; + maxcode = MAXCODE(BITS_MIN); + } else + sp->enc_ratio = rat; + } + } + hit: + ; + } + + /* + * Restore global state. + */ + sp->enc_incount = incount; + sp->enc_outcount = outcount; + sp->enc_checkpoint = checkpoint; + sp->enc_oldcode = ent; + sp->lzw_nextdata = nextdata; + sp->lzw_nextbits = nextbits; + sp->lzw_free_ent = free_ent; + sp->lzw_maxcode = maxcode; + sp->lzw_nbits = nbits; + tif->tif_rawcp = op; + return (1); +} + +/* + * Finish off an encoded strip by flushing the last + * string and tacking on an End Of Information code. + */ +static int +LZWPostEncode(TIFF* tif) +{ + register LZWEncodeState *sp = EncoderState(tif); + tidata_t op = tif->tif_rawcp; + long nextbits = sp->lzw_nextbits; + long nextdata = sp->lzw_nextdata; + long outcount = sp->enc_outcount; + int nbits = sp->lzw_nbits; + + if (op > sp->enc_rawlimit) { + tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata); + TIFFFlushData1(tif); + op = tif->tif_rawdata; + } + if (sp->enc_oldcode != (hcode_t) -1) { + PutNextCode(op, sp->enc_oldcode); + sp->enc_oldcode = (hcode_t) -1; + } + PutNextCode(op, CODE_EOI); + if (nextbits > 0) + *op++ = (u_char)(nextdata << (8-nextbits)); + tif->tif_rawcc = (tsize_t)(op - tif->tif_rawdata); + return (1); +} + +/* + * Reset encoding hash table. + */ +static void +cl_hash(LZWEncodeState* sp) +{ + register hash_t *hp = &sp->enc_hashtab[HSIZE-1]; + register long i = HSIZE-8; + + do { + i -= 8; + hp[-7].hash = -1; + hp[-6].hash = -1; + hp[-5].hash = -1; + hp[-4].hash = -1; + hp[-3].hash = -1; + hp[-2].hash = -1; + hp[-1].hash = -1; + hp[ 0].hash = -1; + hp -= 8; + } while (i >= 0); + for (i += 8; i > 0; i--, hp--) + hp->hash = -1; +} + +static void +LZWCleanup(TIFF* tif) +{ + if (tif->tif_data) { + if (LZWState(tif)->rw_mode == O_RDONLY) { + if (DecoderState(tif)->dec_codetab) + _TIFFfree(DecoderState(tif)->dec_codetab); + } else { + if (EncoderState(tif)->enc_hashtab) + _TIFFfree(EncoderState(tif)->enc_hashtab); + } + _TIFFfree(tif->tif_data); + tif->tif_data = NULL; + } +} + +int +TIFFInitLZW(TIFF* tif, int scheme) +{ + assert(scheme == COMPRESSION_LZW); + /* + * Allocate state block so tag methods have storage to record values. + */ + if (tif->tif_mode == O_RDONLY) { + tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (LZWDecodeState)); + if (tif->tif_data == NULL) + goto bad; + DecoderState(tif)->dec_codetab = NULL; + DecoderState(tif)->dec_decode = NULL; + } else { + tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (LZWEncodeState)); + if (tif->tif_data == NULL) + goto bad; + EncoderState(tif)->enc_hashtab = NULL; + } + + LZWState(tif)->rw_mode = tif->tif_mode; + + /* + * Install codec methods. + */ + tif->tif_setupdecode = LZWSetupDecode; + tif->tif_predecode = LZWPreDecode; + tif->tif_decoderow = LZWDecode; + tif->tif_decodestrip = LZWDecode; + tif->tif_decodetile = LZWDecode; + tif->tif_setupencode = LZWSetupEncode; + tif->tif_preencode = LZWPreEncode; + tif->tif_postencode = LZWPostEncode; + tif->tif_encoderow = LZWEncode; + tif->tif_encodestrip = LZWEncode; + tif->tif_encodetile = LZWEncode; + tif->tif_cleanup = LZWCleanup; + /* + * Setup predictor setup. + */ + (void) TIFFPredictorInit(tif); + return (1); +bad: + TIFFError("TIFFInitLZW", "No space for LZW state block"); + return (0); +} + +/* + * Copyright (c) 1985, 1986 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * James A. Woods, derived from original work by Spencer Thomas + * and Joseph Orost. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by the University of California, Berkeley. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ +#endif /* LZW_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_next.c b/SlnkDWFImpl/CxImage/tiff/tif_next.c new file mode 100644 index 0000000..af965fa --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_next.c @@ -0,0 +1,142 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_next.c,v 1.2 1999/11/27 21:43:28 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef NEXT_SUPPORT +/* + * TIFF Library. + * + * NeXT 2-bit Grey Scale Compression Algorithm Support + */ + +#define SETPIXEL(op, v) { \ + switch (npixels++ & 3) { \ + case 0: op[0] = (v) << 6; break; \ + case 1: op[0] |= (v) << 4; break; \ + case 2: op[0] |= (v) << 2; break; \ + case 3: *op++ |= (v); break; \ + } \ +} + +#define LITERALROW 0x00 +#define LITERALSPAN 0x40 +#define WHITE ((1<<2)-1) + +static int +NeXTDecode(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s) +{ + register u_char *bp, *op; + register tsize_t cc; + register int n; + tidata_t row; + tsize_t scanline; + + (void) s; + /* + * Each scanline is assumed to start off as all + * white (we assume a PhotometricInterpretation + * of ``min-is-black''). + */ + for (op = buf, cc = occ; cc-- > 0;) + *op++ = 0xff; + + bp = (u_char *)tif->tif_rawcp; + cc = tif->tif_rawcc; + scanline = tif->tif_scanlinesize; + for (row = buf; (long)occ > 0; occ -= scanline, row += scanline) { + n = *bp++, cc--; + switch (n) { + case LITERALROW: + /* + * The entire scanline is given as literal values. + */ + if (cc < scanline) + goto bad; + _TIFFmemcpy(row, bp, scanline); + bp += scanline; + cc -= scanline; + break; + case LITERALSPAN: { + int off; + /* + * The scanline has a literal span + * that begins at some offset. + */ + off = (bp[0] * 256) + bp[1]; + n = (bp[2] * 256) + bp[3]; + if (cc < 4+n) + goto bad; + _TIFFmemcpy(row+off, bp+4, n); + bp += 4+n; + cc -= 4+n; + break; + } + default: { + register int npixels = 0, grey; + u_long imagewidth = tif->tif_dir.td_imagewidth; + + /* + * The scanline is composed of a sequence + * of constant color ``runs''. We shift + * into ``run mode'' and interpret bytes + * as codes of the form + * until we've filled the scanline. + */ + op = row; + for (;;) { + grey = (n>>6) & 0x3; + n &= 0x3f; + while (n-- > 0) + SETPIXEL(op, grey); + if (npixels >= (int) imagewidth) + break; + if (cc == 0) + goto bad; + n = *bp++, cc--; + } + break; + } + } + } + tif->tif_rawcp = (tidata_t) bp; + tif->tif_rawcc = cc; + return (1); +bad: + TIFFError(tif->tif_name, "NeXTDecode: Not enough data for scanline %ld", + (long) tif->tif_row); + return (0); +} + +int +TIFFInitNeXT(TIFF* tif, int scheme) +{ + (void) scheme; + tif->tif_decoderow = NeXTDecode; + tif->tif_decodestrip = NeXTDecode; + tif->tif_decodetile = NeXTDecode; + return (1); +} +#endif /* NEXT_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_ojpeg.c b/SlnkDWFImpl/CxImage/tiff/tif_ojpeg.c new file mode 100644 index 0000000..d1483be --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_ojpeg.c @@ -0,0 +1,2042 @@ +#include "tiffiop.h" +#ifdef OJPEG_SUPPORT + +/* JPEG Compression support, as per the original TIFF 6.0 specification. + + WARNING: KLUDGE ALERT! The type of JPEG encapsulation defined by the TIFF + Version 6.0 specification is now totally obsolete and + deprecated for new applications and images. This file is an unsupported hack + that was created solely in order to read (but NOT write!) a few old, + unconverted images still present on some users' computer systems. The code + isn't pretty or robust, and it won't read every "old format" JPEG-in-TIFF + file (see Samuel Leffler's draft "TIFF Technical Note No. 2" for a long and + incomplete list of known problems), but it seems to work well enough in the + few cases of practical interest to the author; so, "caveat emptor"! This + file should NEVER be enhanced to write new images using anything other than + the latest approved JPEG-in-TIFF encapsulation method, implemented by the + "tif_jpeg.c" file elsewhere in this library. + + This file interfaces with Release 6B of the JPEG Library written by theu + Independent JPEG Group, which you can find on the Internet at: + ftp.uu.net:/graphics/jpeg/. + + Contributed by Scott Marovich with considerable help + from Charles Auer to unravel the mysteries of image files + created by Microsoft's Wang Imaging application. +*/ +#include +#include +#ifdef FAR +#undef FAR /* Undefine FAR to avoid conflict with JPEG definition */ +#endif +#define JPEG_INTERNALS /* Include "jpegint.h" for "DSTATE_*" symbols */ +#undef INLINE +#include "../jpeg/jpeglib.h" +#undef JPEG_INTERNALS + +/* Hack for Microsoft's Wang Imaging for Windows output files */ +extern void jpeg_reset_huff_decode(j_decompress_ptr,float *); + +/* On some machines, it may be worthwhile to use "_setjmp()" or "sigsetjmp()" + instead of "setjmp()". These macros make it easier: +*/ +#define SETJMP(jbuf)setjmp(jbuf) +#define LONGJMP(jbuf,code)longjmp(jbuf,code) +#define JMP_BUF jmp_buf + +#define TIFFTAG_WANG_PAGECONTROL 32934 + +/* Bit-vector offsets for keeping track of TIFF records that we've parsed. */ + +#define FIELD_JPEGPROC FIELD_CODEC +#define FIELD_JPEGIFOFFSET (FIELD_CODEC+1) +#define FIELD_JPEGIFBYTECOUNT (FIELD_CODEC+2) +#define FIELD_JPEGRESTARTINTERVAL (FIELD_CODEC+3) +#define FIELD_JPEGTABLES (FIELD_CODEC+4) /* New, post-6.0 JPEG-in-TIFF tag! */ +#define FIELD_JPEGLOSSLESSPREDICTORS (FIELD_CODEC+5) +#define FIELD_JPEGPOINTTRANSFORM (FIELD_CODEC+6) +#define FIELD_JPEGQTABLES (FIELD_CODEC+7) +#define FIELD_JPEGDCTABLES (FIELD_CODEC+8) +#define FIELD_JPEGACTABLES (FIELD_CODEC+9) +#define FIELD_WANG_PAGECONTROL (FIELD_CODEC+10) +#define FIELD_JPEGCOLORMODE (FIELD_CODEC+11) + +typedef struct jpeg_destination_mgr jpeg_destination_mgr; +typedef struct jpeg_source_mgr jpeg_source_mgr; +typedef struct jpeg_error_mgr jpeg_error_mgr; + +/* State variable for each open TIFF file that uses "libjpeg" for JPEG + decompression. (Note: This file should NEVER perform JPEG compression + except in the manner implemented by the "tif_jpeg.c" file, elsewhere in this + library; see comments above.) JPEG Library internal state is recorded in a + "jpeg_{de}compress_struct", while a "jpeg_common_struct" records a few items + common to both compression and expansion. The "cinfo" field containing JPEG + Library state MUST be the 1st member of our own state variable, so that we + can safely "cast" pointers back and forth. +*/ +typedef struct /* This module's private, per-image state variable */ + { + union /* JPEG Library state variable; this MUST be our 1st field! */ + { + /* struct jpeg_compress_struct c; */ + struct jpeg_decompress_struct d; + struct jpeg_common_struct comm; + } cinfo; + jpeg_error_mgr err; /* JPEG Library error manager */ + JMP_BUF exit_jmpbuf; /* ...for catching JPEG Library failures */ +# ifdef never + + /* (The following two fields could be a "union", but they're small enough that + it's not worth the effort.) + */ + jpeg_destination_mgr dest; /* Destination for compressed data */ +# endif + jpeg_source_mgr src; /* Source of expanded data */ + JSAMPARRAY ds_buffer[MAX_COMPONENTS]; /* ->Temporary downsampling buffers */ + TIFF *tif; /* Reverse pointer, needed by some code */ + TIFFVGetMethod vgetparent; /* "Super class" methods... */ + TIFFVSetMethod vsetparent; + TIFFStripMethod defsparent; + TIFFTileMethod deftparent; + void *jpegtables; /* ->"New" JPEG tables, if we synthesized any */ + uint32 is_WANG, /* <=> Microsoft Wang Imaging for Windows output file? */ + jpegtables_length; /* Length of "new" JPEG tables, if they exist */ + tsize_t bytesperline; /* No. of decompressed Bytes per scan line */ + int jpegquality, /* Compression quality level */ + jpegtablesmode, /* What to put in JPEGTables */ + samplesperclump, + scancount; /* No. of scan lines accumulated */ + uint16 h_sampling, /* Luminance sampling factors */ + v_sampling, + photometric; /* Copy of "PhotometricInterpretation" tag value */ + u_char jpegcolormode; /* Who performs RGB <-> YCbCr conversion? */ + /* JPEGCOLORMODE_RAW <=> TIFF Library does conversion */ + /* JPEGCOLORMODE_RGB <=> JPEG Library does conversion */ + } OJPEGState; +#define OJState(tif)((OJPEGState*)(tif)->tif_data) + +static const TIFFFieldInfo ojpegFieldInfo[]=/* JPEG-specific TIFF-record tags */ + { + + /* This is the current JPEG-in-TIFF metadata-encapsulation tag, and its + treatment in this file is idiosyncratic. It should never appear in a + "source" image conforming to the TIFF Version 6.0 specification, so we + arrange to report an error if it appears. But in order to support possible + future conversion of "old" JPEG-in-TIFF encapsulations to "new" ones, we + might wish to synthesize an equivalent value to be returned by the TIFF + Library's "getfield" method. So, this table tells the TIFF Library to pass + these records to us in order to filter them below. + */ + { + TIFFTAG_JPEGTABLES ,TIFF_VARIABLE,TIFF_VARIABLE, + TIFF_UNDEFINED,FIELD_JPEGTABLES ,FALSE,TRUE ,"JPEGTables" + }, + + /* These tags are defined by the TIFF Version 6.0 specification and are now + obsolete. This module reads them from an old "source" image, but it never + writes them to a new "destination" image. + */ + { + TIFFTAG_JPEGPROC ,1 ,1 , + TIFF_SHORT ,FIELD_JPEGPROC ,FALSE,FALSE,"JPEGProc" + }, + { + TIFFTAG_JPEGIFOFFSET ,1 ,1 , + TIFF_LONG ,FIELD_JPEGIFOFFSET ,FALSE,FALSE,"JPEGInterchangeFormat" + }, + { + TIFFTAG_JPEGIFBYTECOUNT ,1 ,1 , + TIFF_LONG ,FIELD_JPEGIFBYTECOUNT ,FALSE,FALSE,"JPEGInterchangeFormatLength" + }, + { + TIFFTAG_JPEGRESTARTINTERVAL ,1 ,1 , + TIFF_SHORT ,FIELD_JPEGRESTARTINTERVAL ,FALSE,FALSE,"JPEGRestartInterval" + }, + { + TIFFTAG_JPEGLOSSLESSPREDICTORS,TIFF_VARIABLE,TIFF_VARIABLE, + TIFF_SHORT ,FIELD_JPEGLOSSLESSPREDICTORS,FALSE,TRUE ,"JPEGLosslessPredictors" + }, + { + TIFFTAG_JPEGPOINTTRANSFORM ,TIFF_VARIABLE,TIFF_VARIABLE, + TIFF_SHORT ,FIELD_JPEGPOINTTRANSFORM ,FALSE,TRUE ,"JPEGPointTransforms" + }, + { + TIFFTAG_JPEGQTABLES ,TIFF_VARIABLE,TIFF_VARIABLE, + TIFF_LONG ,FIELD_JPEGQTABLES ,FALSE,TRUE ,"JPEGQTables" + }, + { + TIFFTAG_JPEGDCTABLES ,TIFF_VARIABLE,TIFF_VARIABLE, + TIFF_LONG ,FIELD_JPEGDCTABLES ,FALSE,TRUE ,"JPEGDCTables" + }, + { + TIFFTAG_JPEGACTABLES ,TIFF_VARIABLE,TIFF_VARIABLE, + TIFF_LONG ,FIELD_JPEGACTABLES ,FALSE,TRUE ,"JPEGACTables" + }, + { + TIFFTAG_WANG_PAGECONTROL ,TIFF_VARIABLE,1 , + TIFF_LONG ,FIELD_WANG_PAGECONTROL ,FALSE,FALSE,"WANG PageControl" + }, + + /* This is a pseudo tag intended for internal use only by the TIFF Library and + its clients, which should never appear in an input/output image file. It + specifies whether the TIFF Library will perform YCbCr<->RGB color-space + conversion (JPEGCOLORMODE_RAW <=> 0) or ask the JPEG Library to do it + (JPEGCOLORMODE_RGB <=> 1). + */ + { + TIFFTAG_JPEGCOLORMODE ,0 ,0 , + TIFF_ANY ,FIELD_PSEUDO ,FALSE,FALSE,"JPEGColorMode" + } + }; +static const char JPEGLib_name[]={"JPEG Library"}, + bad_bps[]={"%u BitsPerSample not allowed for JPEG"}, +# ifdef never + no_write_frac[]={"fractional scan line discarded"}, +# endif + no_read_frac[]={"fractional scan line not read"}, + no_jtable_space[]={"No space for JPEGTables"}; + +/* The following diagnostic subroutines interface with and replace default + subroutines in the JPEG Library. Our basic strategy is to use "setjmp()"/ + "longjmp()" in order to return control to the TIFF Library when the JPEG + library detects an error, and to use TIFF Library subroutines for displaying + diagnostic messages to a client application. +*/ +static void +TIFFojpeg_error_exit(register j_common_ptr cinfo) + { char buffer[JMSG_LENGTH_MAX]; + + (*cinfo->err->format_message)(cinfo,buffer); + TIFFError(JPEGLib_name,buffer); /* Display error message */ + jpeg_abort(cinfo); /* Clean up JPEG Library state */ + LONGJMP(((OJPEGState *)cinfo)->exit_jmpbuf,1); /* Return to TIFF client */ + } + +static void +TIFFojpeg_output_message(register j_common_ptr cinfo) + { char buffer[JMSG_LENGTH_MAX]; + + /* This subroutine is invoked only for warning messages, since the JPEG + Library's "error_exit" method does its own thing and "trace_level" is never + set > 0. + */ + (*cinfo->err->format_message)(cinfo,buffer); + TIFFWarning(JPEGLib_name,buffer); + } + +/* The following subroutines, which also interface with the JPEG Library, exist + mainly in limit the side effects of "setjmp()" and convert JPEG normal/error + conditions into TIFF Library return codes. +*/ +#define CALLJPEG(sp,fail,op)(SETJMP((sp)->exit_jmpbuf)?(fail):(op)) +#define CALLVJPEG(sp,op)CALLJPEG(sp,0,((op),1)) +#ifdef never + +static int +TIFFojpeg_create_compress(register OJPEGState *sp) + { + sp->cinfo.c.err = jpeg_std_error(&sp->err); /* Initialize error handling */ + sp->err.error_exit = TIFFojpeg_error_exit; + sp->err.output_message = TIFFojpeg_output_message; + return CALLVJPEG(sp,jpeg_create_compress(&sp->cinfo.c)); + } + +static int +TIFFojpeg_finish_compress(register OJPEGState *sp) + {return CALLVJPEG(sp,jpeg_finish_compress(&sp->cinfo.c));} + +static int +TIFFojpeg_set_colorspace(register OJPEGState *sp,J_COLOR_SPACE colorspace) + {return CALLVJPEG(sp,jpeg_set_colorspace(&sp->cinfo.c,colorspace));} + +static int +TIFFojpeg_set_defaults(register OJPEGState *sp) + {return CALLVJPEG(sp,jpeg_set_defaults(&sp->cinfo.c));} + +static int +TIFFojpeg_set_quality(register OJPEGState *sp,int quality,boolean force_baseline) + {return CALLVJPEG(sp,jpeg_set_quality(&sp->cinfo.c,quality,force_baseline));} + +static int +TIFFojpeg_start_compress(register OJPEGState *sp,boolean write_all_tables) + {return CALLVJPEG(sp,jpeg_start_compress(&sp->cinfo.c,write_all_tables));} + +static int +TIFFojpeg_suppress_tables(register OJPEGState *sp,boolean suppress) + {return CALLVJPEG(sp,jpeg_suppress_tables(&sp->cinfo.c,suppress));} + +static int +TIFFojpeg_write_raw_data(register OJPEGState *sp,JSAMPIMAGE data,int num_lines) + { return + CALLJPEG(sp,-1,(int)jpeg_write_raw_data(&sp->cinfo.c,data,(JDIMENSION)num_lines)); + } + +static int +TIFFojpeg_write_scanlines(register OJPEGState *sp,JSAMPARRAY scanlines, + int num_lines) + { return + CALLJPEG(sp,-1,(int)jpeg_write_scanlines(&sp->cinfo.c,scanlines,(JDIMENSION)num_lines)); + } + +static int +TIFFojpeg_write_tables(register OJPEGState *sp) + {return CALLVJPEG(sp,jpeg_write_tables(&sp->cinfo.c));} +#else /* well, hardly ever */ + +static int +_notSupported(register TIFF *tif) + { const TIFFCodec *c = TIFFFindCODEC(tif->tif_dir.td_compression); + + TIFFError(tif->tif_name,"%s compression is not supported",c->name); + return 0; + } +#endif /* never */ + +static int +TIFFojpeg_abort(register OJPEGState *sp) + {return CALLVJPEG(sp,jpeg_abort(&sp->cinfo.comm));} + +static JSAMPARRAY +TIFFojpeg_alloc_sarray(register OJPEGState *sp,int pool_id, + JDIMENSION samplesperrow,JDIMENSION numrows) + { return + CALLJPEG(sp,0,(*sp->cinfo.comm.mem->alloc_sarray)(&sp->cinfo.comm,pool_id,samplesperrow, numrows)); + } + +static int +TIFFojpeg_create_decompress(register OJPEGState *sp) + { + sp->cinfo.d.err = jpeg_std_error(&sp->err); /* Initialize error handling */ + sp->err.error_exit = TIFFojpeg_error_exit; + sp->err.output_message = TIFFojpeg_output_message; + return CALLVJPEG(sp,jpeg_create_decompress(&sp->cinfo.d)); + } + +static int +TIFFojpeg_destroy(register OJPEGState *sp) + {return CALLVJPEG(sp,jpeg_destroy(&sp->cinfo.comm));} + +static int +TIFFojpeg_finish_decompress(register OJPEGState *sp) + {return CALLJPEG(sp,-1,(int)jpeg_finish_decompress(&sp->cinfo.d));} + +static int +TIFFojpeg_read_header(register OJPEGState *sp,boolean require_image) + {return CALLJPEG(sp,-1,jpeg_read_header(&sp->cinfo.d,require_image));} + +static int +TIFFojpeg_read_raw_data(register OJPEGState *sp,JSAMPIMAGE data,int max_lines) + { + return + CALLJPEG(sp,-1,(int)jpeg_read_raw_data(&sp->cinfo.d,data,(JDIMENSION)max_lines)); + } + +static int +TIFFojpeg_read_scanlines(register OJPEGState *sp,JSAMPARRAY scanlines, + int max_lines) + { return + CALLJPEG(sp,-1,(int)jpeg_read_scanlines(&sp->cinfo.d,scanlines,(JDIMENSION)max_lines)); + } + +static int +TIFFojpeg_start_decompress(register OJPEGState *sp) + {return CALLVJPEG(sp,jpeg_start_decompress(&sp->cinfo.d));} +#ifdef never + +/* The following subroutines comprise a JPEG Library "destination" data manager + by directing compressed data from the JPEG Library to a TIFF Library output + buffer. +*/ +static void +std_init_destination(register j_compress_ptr cinfo){} /* "Dummy" stub */ + +static boolean +std_empty_output_buffer(register j_compress_ptr cinfo) + { +# define sp ((OJPEGState *)cinfo) + register TIFF *tif = sp->tif; + + tif->tif_rawcc = tif->tif_rawdatasize; /* Entire buffer has been filled */ + TIFFFlushData1(tif); + sp->dest.next_output_byte = (JOCTET *)tif->tif_rawdata; + sp->dest.free_in_buffer = (size_t)tif->tif_rawdatasize; + return TRUE; +# undef sp + } + +static void +std_term_destination(register j_compress_ptr cinfo) + { +# define sp ((OJPEGState *)cinfo) + register TIFF *tif = sp->tif; + + /* NB: The TIFF Library does the final buffer flush. */ + tif->tif_rawcp = (tidata_t)sp->dest.next_output_byte; + tif->tif_rawcc = tif->tif_rawdatasize - (tsize_t)sp->dest.free_in_buffer; +# undef sp + } + +/*ARGSUSED*/ static void +TIFFojpeg_data_dest(register OJPEGState *sp,TIFF *tif) + { + sp->cinfo.c.dest = &sp->dest; + sp->dest.init_destination = std_init_destination; + sp->dest.empty_output_buffer = std_empty_output_buffer; + sp->dest.term_destination = std_term_destination; + } + + +/* Alternate destination manager to output JPEGTables field: */ + +static void +tables_init_destination(register j_compress_ptr cinfo) + { +# define sp ((OJPEGState *)cinfo) + /* The "jpegtables_length" field is the allocated buffer size while building */ + sp->dest.next_output_byte = (JOCTET *)sp->jpegtables; + sp->dest.free_in_buffer = (size_t)sp->jpegtables_length; +# undef sp + } + +static boolean +tables_empty_output_buffer(register j_compress_ptr cinfo) + { void *newbuf; +# define sp ((OJPEGState *)cinfo) + + /* The entire buffer has been filled, so enlarge it by 1000 bytes. */ + if (!( newbuf = _TIFFrealloc( (tdata_t)sp->jpegtables + , (tsize_t)(sp->jpegtables_length + 1000) + ) + ) + ) ERREXIT1(cinfo,JERR_OUT_OF_MEMORY,100); + sp->dest.next_output_byte = (JOCTET *)newbuf + sp->jpegtables_length; + sp->dest.free_in_buffer = (size_t)1000; + sp->jpegtables = newbuf; + sp->jpegtables_length += 1000; + return TRUE; +# undef sp + } + +static void +tables_term_destination(register j_compress_ptr cinfo) + { +# define sp ((OJPEGState *)cinfo) + /* Set tables length to no. of Bytes actually emitted. */ + sp->jpegtables_length -= sp->dest.free_in_buffer; +# undef sp + } + +/*ARGSUSED*/ static int +TIFFojpeg_tables_dest(register OJPEGState *sp, TIFF *tif) + { + + /* Allocate a working buffer for building tables. The initial size is 1000 + Bytes, which is usually adequate. + */ + if (sp->jpegtables) _TIFFfree(sp->jpegtables); + if (!(sp->jpegtables = (void*) + _TIFFmalloc((tsize_t)(sp->jpegtables_length = 1000)) + ) + ) + { + sp->jpegtables_length = 0; + TIFFError("TIFFojpeg_tables_dest",no_jtable_space); + return 0; + }; + sp->cinfo.c.dest = &sp->dest; + sp->dest.init_destination = tables_init_destination; + sp->dest.empty_output_buffer = tables_empty_output_buffer; + sp->dest.term_destination = tables_term_destination; + return 1; + } +#endif /* never */ + +/* The following subroutines comprise a JPEG Library "source" data manager by + by directing compressed data to the JPEG Library from a TIFF Library input + buffer. +*/ +static void +std_init_source(register j_decompress_ptr cinfo) + { +# define sp ((OJPEGState *)cinfo) + register TIFF *tif = sp->tif; + + if (sp->src.bytes_in_buffer == 0) + { + sp->src.next_input_byte = (const JOCTET *)tif->tif_rawdata; + sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc; + }; +# undef sp + } + +static boolean +std_fill_input_buffer(register j_decompress_ptr cinfo) + { static const JOCTET dummy_EOI[2]={0xFF,JPEG_EOI}; +# define sp ((OJPEGState *)cinfo) + + /* Control should never get here, since an entire strip/tile is read into + memory before the decompressor is called; thus, data should have been + supplied by the "init_source" method. ...But, sometimes things fail. + */ + WARNMS(cinfo,JWRN_JPEG_EOF); + sp->src.next_input_byte = dummy_EOI; /* Insert a fake EOI marker */ + sp->src.bytes_in_buffer = sizeof dummy_EOI; + return TRUE; +# undef sp + } + +static void +std_skip_input_data(register j_decompress_ptr cinfo,long num_bytes) + { +# define sp ((OJPEGState *)cinfo) + + if (num_bytes > 0) + if (num_bytes > (long)sp->src.bytes_in_buffer) /* oops: buffer overrun */ + (void)std_fill_input_buffer(cinfo); + else + { + sp->src.next_input_byte += (size_t)num_bytes; + sp->src.bytes_in_buffer -= (size_t)num_bytes; + } +# undef sp + } + +/*ARGSUSED*/ static void +std_term_source(register j_decompress_ptr cinfo){} /* "Dummy" stub */ + +/* Allocate temporary I/O buffers for downsampled data, using values computed in + "jpeg_start_{de}compress()". We use the JPEG Library's allocator so that + buffers will be released automatically when done with a strip/tile. This is + also a handy place to compute samplesperclump, bytesperline, etc. +*/ +static int +alloc_downsampled_buffers(TIFF *tif,jpeg_component_info *comp_info, + int num_components) + { register OJPEGState *sp = OJState(tif); + + sp->samplesperclump = 0; + if (num_components > 0) + { int ci = 0; + register jpeg_component_info *compptr = comp_info; + + do + { JSAMPARRAY buf; + + sp->samplesperclump += + compptr->h_samp_factor * compptr->v_samp_factor; + if (!(buf = TIFFojpeg_alloc_sarray( sp + , JPOOL_IMAGE + , compptr->width_in_blocks*DCTSIZE + , compptr->v_samp_factor *DCTSIZE + ) + ) + ) return 0; + sp->ds_buffer[ci] = buf; + } + while (++compptr,++ci < num_components); + }; + return 1; + } +#ifdef never + +/* JPEG Encoding begins here. */ + +static void +unsuppress_quant_table(register OJPEGState *sp,int tblno) + { register JQUANT_TBL *qtbl; + + if (qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) qtbl->sent_table = FALSE; + } + +static void +unsuppress_huff_table(register OJPEGState *sp,register int tblno) + { register JHUFF_TBL *htbl; + + if ( (htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) + || (htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) + ) htbl->sent_table = FALSE; + } + +static int +prepare_JPEGTables(register TIFF *tif) + { register OJPEGState *sp = OJState(tif); + + /* Initialize quantization tables for the current quality setting, and mark for + output only the tables that we want. Note that chrominance tables are + currently used only with YCbCr. + */ + if ( !TIFFojpeg_set_quality(sp,sp->jpegquality,FALSE); + || !TIFFojpeg_suppress_tables(sp,TRUE) + ) return 0; + if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) + { + unsuppress_quant_table(sp,0); + if (sp->photometric == PHOTOMETRIC_YCBCR) unsuppress_quant_table(sp,1); + } + if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) + { + unsuppress_huff_table(sp,0); + if (sp->photometric == PHOTOMETRIC_YCBCR) unsuppress_huff_table(sp,1); + }; + return TIFFojpeg_tables_dest(sp,tif) && TIFFojpeg_write_tables(sp); + } + +static int +OJPEGSetupEncode(register TIFF *tif) + { static const char module[]={"OJPEGSetupEncode"}; + register OJPEGState *sp = OJState(tif); +# define td (&tif->tif_dir) + + /* Verify miscellaneous parameters. This will need work if the TIFF Library + ever supports different depths for different components, or if the JPEG + Library ever supports run-time depth selection. Neither seems imminent. + */ + if (td->td_bitspersample != BITS_IN_JSAMPLE) + { + TIFFError(module,bad_bps,td->td_bitspersample); + return 0; + }; + + /* Initialize all JPEG parameters to default values. Note that the JPEG + Library's "jpeg_set_defaults()" method needs legal values for the + "in_color_space" and "input_components" fields. + */ + sp->cinfo.c.in_color_space = JCS_UNKNOWN; + sp->cinfo.c.input_components = 1; + if (!TIFFojpeg_set_defaults(sp)) return 0; + switch (sp->photometric = td->td_photometric) /* set per-file parameters */ + { + case PHOTOMETRIC_YCBCR: + sp->h_sampling = td->td_ycbcrsubsampling[0]; + sp->v_sampling = td->td_ycbcrsubsampling[1]; +# ifdef COLORIMETRY_SUPPORT + + /* A ReferenceBlackWhite field MUST be present, since the default value + is inapproriate for YCbCr. Fill in the proper value if application + didn't set it. + */ + if (!TIFFFieldSet(tif,FIELD_REFBLACKWHITE)) + { float refbw[6]; + long top = 1L << td->td_bitspersample; + + refbw[0] = 0; + refbw[1] = (float)(top-1L); + refbw[2] = (float)(top>>1); + refbw[3] = refbw[1]; + refbw[4] = refbw[2]; + refbw[5] = refbw[1]; + TIFFSetField(tif,TIFFTAG_REFERENCEBLACKWHITE,refbw); + }; +# endif /* COLORIMETRY_SUPPORT */ + break; + case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */ + case PHOTOMETRIC_MASK: + TIFFError(module,"PhotometricInterpretation %d not allowed for JPEG", + (int)sp->photometric); + return 0; + + /* TIFF 6.0 forbids subsampling of all other color spaces */ + + default: sp->h_sampling = sp->v_sampling = 1; + }; + sp->cinfo.c.data_precision = td->td_bitspersample; + if (isTiled(tif)) + { + if (td->td_tilelength % (sp->v_sampling*DCTSIZE)) + { + TIFFError(module,"JPEG tile height must be multiple of %d", + sp->v_sampling*DCTSIZE); + return 0; + }; + if (td->td_tilewidth % (sp->h_sampling*DCTSIZE)) + { + TIFFError(module,"JPEG tile width must be multiple of %d", + sp->h_sampling*DCTSIZE); + return 0; + } + } + else + if ( td->td_rowsperstrip < td->td_imagelength + && (td->td_rowsperstrip % (sp->v_sampling*DCTSIZE)) + ) + { + TIFFError(module,"RowsPerStrip must be multiple of %d for JPEG", + sp->v_sampling*DCTSIZE); + return 0; + }; + if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) + { /* create a JPEGTables field */ + + if (!prepare_JPEGTables(tif)) return 0; + + /* Mark the field "present". We can't use "TIFFSetField()" because + "BEENWRITING" is already set! + */ + TIFFSetFieldBit(tif,FIELD_JPEGTABLES); + tif->tif_flags |= TIFF_DIRTYDIRECT; + } + else + /* We do not support application-supplied JPEG tables, so mark the field + "not present". + */ + TIFFClrFieldBit(tif,FIELD_JPEGTABLES); + TIFFojpeg_data_dest(sp,tif); /* send JPEG output to TIFF Library's buffer */ + return 1; +# undef td + } + +/*ARGSUSED*/ static int +OJPEGEncode(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s) + { register OJPEGState *sp = OJState(tif); + + /* Encode a chunk of pixels, where returned data is NOT down-sampled (the + standard case). The data is expected to be written in scan-line multiples. + */ + if (cc % sp->bytesperline) TIFFWarning(tif->tif_name,no_write_frac); + cc /= sp->bytesperline; + while (--cc >= 0) + { JSAMPROW bufptr = (JSAMPROW)buf; + + if (TIFFojpeg_write_scanlines(sp,&bufptr,1) != 1) return 0; + ++tif->tif_row; + buf += sp->bytesperline; + }; + return 1; + } + +/*ARGSUSED*/ static int +OJPEGEncodeRaw(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s) + { register OJPEGState *sp = OJState(tif); + + /* Encode a chunk of pixels, where returned data is down-sampled as per the + sampling factors. The data is expected to be written in scan-line + multiples. + */ + if (cc % sp->bytesperline) TIFFWarning(tif->tif_name,no_write_frac); + cc /= sp->bytesperline; + while (--cc >= 0) + { + if (sp->cinfo.c.num_components > 0) + { int ci = 0, clumpoffset = 0; + register jpeg_component_info *compptr = sp->cinfo.c.comp_info; + + /* The fastest way to separate the data is to make 1 pass over the scan + line for each row of each component. + */ + do + { int ypos = 0; + + do + { int padding; + register JSAMPLE *inptr = (JSAMPLE*)buf + clumpoffset, + *outptr = + sp->ds_buffer[ci][sp->scancount*compptr->v_samp_factor+ypos]; + /* Cb,Cr both have sampling factors 1, so this is correct */ + register int clumps_per_line = + sp->cinfo.c.comp_info[1].downsampled_width, + xpos; + + padding = (int) + ( compptr->width_in_blocks * DCTSIZE + - clumps_per_line * compptr->h_samp_factor + ); + if (compptr->h_samp_factor == 1) /* Cb & Cr fast path */ + do + { + *outptr++ = inptr[0]; + inptr += sp->samplesperclump; + } + while (--clumps_per_line > 0); + else /* general case */ + do + { + xpos = 0; + do *outptr++ = inptr[xpos]; + while (++xpos < compptr->h_samp_factor); + inptr += sp->samplesperclump; + } + while (--clumps_per_line > 0); + xpos = 0; /* Pad each scan line as needed */ + do outptr[0]=outptr[-1]; while (++outptr,++xpos < padding); + clumpoffset += compptr->h_samp_factor; + } + while (++ypos < compptr->v_samp_factor); + } + while (++compptr,++ci < sp->cinfo.c.num_components); + }; + if (++sp->scancount >= DCTSIZE) + { int n = sp->cinfo.c.max_v_samp_factor*DCTSIZE; + + if (TIFFojpeg_write_raw_data(sp,sp->ds_buffer,n) != n) return 0; + sp->scancount = 0; + }; + ++tif->tif_row++ + buf += sp->bytesperline; + }; + return 1; + } + +static int +OJPEGPreEncode(register TIFF *tif,tsample_t s) + { static const char module[]={"OJPEGPreEncode"}; + uint32 segment_width, segment_height; + int downsampled_input = FALSE; + register OJPEGState *sp = OJState(tif); +# define td (&tif->tif_dir) + + /* Set encoding state at the start of a strip or tile. */ + + if (td->td_planarconfig == PLANARCONFIG_CONTIG) + { + sp->cinfo.c.input_components = td->td_samplesperpixel; + if (sp->photometric == PHOTOMETRIC_YCBCR) + { + if (sp->jpegcolormode == JPEGCOLORMODE_RGB) + sp->cinfo.c.in_color_space = JCS_RGB; + else + { + sp->cinfo.c.in_color_space = JCS_YCbCr; + if (sp->h_sampling != 1 || sp->v_sampling != 1) + downsampled_input = TRUE; + }; + if (!TIFFojpeg_set_colorspace(sp,JCS_YCbCr)) return 0; + + /* Set Y sampling factors; we assume "jpeg_set_colorspace()" set the + rest to 1. + */ + sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling; + sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling; + } + else + { + sp->cinfo.c.in_color_space = JCS_UNKNOWN; + if (!TIFFojpeg_set_colorspace(sp,JCS_UNKNOWN)) return 0; + /* "jpeg_set_colorspace()" set all sampling factors to 1. */ + } + } + else + { + sp->cinfo.c.input_components = 1; + sp->cinfo.c.in_color_space = JCS_UNKNOWN; + if (!TIFFojpeg_set_colorspace(sp,JCS_UNKNOWN)) return 0; + sp->cinfo.c.comp_info[0].component_id = s; + /* "jpeg_set_colorspace()" set all sampling factors to 1. */ + if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) + sp->cinfo.c.comp_info[0].quant_tbl_no = + sp->cinfo.c.comp_info[0].dc_tbl_no = + sp->cinfo.c.comp_info[0].ac_tbl_no = 1; + }; + if (isTiled(tif)) + { + segment_width = td->td_tilewidth; + segment_height = td->td_tilelength; + sp->bytesperline = TIFFTileRowSize(tif); + } + else + { + segment_width = td->td_imagewidth; + segment_height = td->td_imagelength - tif->tif_row; + if (segment_height > td->td_rowsperstrip) + segment_height = td->td_rowsperstrip; + sp->bytesperline = TIFFScanlineSize(tif); + }; + if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) + { + + /* Scale the expected strip/tile size to match a downsampled component. */ + + segment_width = TIFFhowmany(segment_width,sp->h_sampling); + segment_height = TIFFhowmany(segment_height,sp->v_sampling); + }; + if (segment_width > 65535 || segment_height > 65535) + { + TIFFError(module,"Strip/tile too large for JPEG"); + return 0; + }; + sp->cinfo.c.image_width = segment_width; + sp->cinfo.c.image_height = segment_height; + sp->cinfo.c.write_JFIF_header = /* Don't write extraneous markers */ + sp->cinfo.c.write_Adobe_marker = FALSE; + if (!(sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) /* setup table handling */ + { + if (!TIFFojpeg_set_quality(sp,sp->jpegquality,FALSE)) return 0; + unsuppress_quant_table(sp,0); + unsuppress_quant_table(sp,1); + }; + sp->cinfo.c.optimize_coding = !(sp->jpegtablesmode & JPEGTABLESMODE_HUFF); + tif->tif_encoderow = tif->tif_encodestrip = tif->tif_encodetile = + (sp->cinfo.c.raw_data_in = downsampled_input) + ? OJPEGEncodeRaw : OJPEGEncode; + if ( !TIFFojpeg_start_compress(sp,FALSE) /* start JPEG compressor */ + || downsampled_input /* allocate downsampled-data buffers */ + && !alloc_downsampled_buffers(tif,sp->cinfo.c.comp_info, + sp->cinfo.c.num_components) + ) return 0; + sp->scancount = 0; + return 1; +# undef td + } + +static int +OJPEGPostEncode(register TIFF *tif) + { register OJPEGState *sp = OJState(tif); + + /* Finish up at the end of a strip or tile. */ + + if (sp->scancount > 0) /* emit partial buffer of down-sampled data */ + { + if (sp->scancount < DCTSIZE && sp->cinfo.c.num_components > 0) + { int ci = 0, n; /* Pad the data vertically */ + register jpeg_component_info *compptr = sp->cinfo.c.comp_info; + + do + { tsize_t row_width = + compptr->width_in_blocks*DCTSIZE*sizeof(JSAMPLE); + int ypos = sp->scancount*compptr->v_samp_factor; + + do _TIFFmemcpy( (tdata_t)sp->ds_buffer[ci][ypos] + , (tdata_t)sp->ds_buffer[ci][ypos-1] + , row_width + ); + while (++ypos < compptr->v_samp_factor*DCTSIZE); + } + while (++compptr,++ci < sp->cinfo.c.num_components); + }; + n = sp->cinfo.c.max_v_samp_factor*DCTSIZE; + if (TIFFojpeg_write_raw_data(sp,sp->ds_buffer,n) != n) return 0; + }; + return TIFFojpeg_finish_compress(sp); + } +#endif /* never */ + +/* JPEG Decoding begins here. */ + +static int +OJPEGSetupDecode(register TIFF *tif) + { static const char module[]={"OJPEGSetupDecode"}; + register OJPEGState *sp = OJState(tif); +# define td (&tif->tif_dir) + + /* Verify miscellaneous parameters. This will need work if the TIFF Library + ever supports different depths for different components, or if the JPEG + Library ever supports run-time depth selection. Neither seems imminent. + */ + if (td->td_bitspersample != BITS_IN_JSAMPLE) + { + TIFFError(module,bad_bps,td->td_bitspersample); + return 0; + }; + + /* Almost all old JPEG-in-TIFF encapsulations use 8 bits per sample, but the + following is just a "sanity check", since "OJPEGPreDecode()" actually + depends upon this assumption in certain cases. + */ + if (td->td_bitspersample != 8) + { + TIFFError(module,"Cannot decompress %u bits per sample"); + return 0; + }; + + /* Grab parameters that are same for all strips/tiles. */ + + if ((sp->photometric = td->td_photometric) == PHOTOMETRIC_YCBCR) + { + sp->h_sampling = td->td_ycbcrsubsampling[0]; + sp->v_sampling = td->td_ycbcrsubsampling[1]; + } + else /* TIFF 6.0 forbids subsampling of all other color spaces */ + sp->h_sampling = sp->v_sampling = 1; + sp->cinfo.d.src = &sp->src; + sp->src.init_source = std_init_source; + sp->src.fill_input_buffer = std_fill_input_buffer; + sp->src.skip_input_data = std_skip_input_data; + sp->src.resync_to_restart = jpeg_resync_to_restart; + sp->src.term_source = std_term_source; + tif->tif_postdecode = _TIFFNoPostDecode; /* Override Byte-swapping */ + return 1; +# undef td + } + +/*ARGSUSED*/ static int +OJPEGDecode(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s) + { static float zeroes[6]; + tsize_t nrows; + register OJPEGState *sp = OJState(tif); + + /* BEWARE OF KLUDGE: If our input file was produced by Microsoft's Wang + Imaging for Windows application, the DC coefficients of + each JPEG image component (Y,Cb,Cr) must be reset at the beginning of each + TIFF "strip", and any JPEG data bits remaining in the decoder's input buffer + must be discarded, up to the next input-Byte storage boundary. To do so, we + create an "ad hoc" interface in the "jdhuff.c" module of IJG JPEG Library + Version 6, and we invoke that interface here before decoding each "strip". + */ + if (sp->is_WANG) jpeg_reset_huff_decode(&sp->cinfo.d,zeroes); + + /* Decode a chunk of pixels, where returned data is NOT down-sampled (the + standard case). The data is expected to be read in scan-line multiples. + */ + if (nrows = sp->cinfo.d.image_height) + { unsigned int bytesperline = isTiled(tif) + ? TIFFTileRowSize(tif) + : TIFFScanlineSize(tif); + + /* WARNING: Unlike "OJPEGDecodeRaw()", below, the no. of Bytes in each + decoded row is calculated here as "bytesperline" instead of + using "sp->bytesperline", which might be a little smaller. This can + occur for an old tiled image whose width isn't a multiple of 8 pixels. + That's illegal according to the TIFF Version 6 specification, but some + test files, like "zackthecat.tif", were built that way. In those cases, + we want to embed the image's true width in our caller's buffer (which is + presumably allocated according to the expected tile width) by + effectively "padding" it with unused Bytes at the end of each row. + */ + do + { JSAMPROW bufptr = (JSAMPROW)buf; + + if (TIFFojpeg_read_scanlines(sp,&bufptr,1) != 1) return 0; + buf += bytesperline; + ++tif->tif_row; + } + while ((cc -= bytesperline) > 0 && --nrows > 0); + }; + return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height + || TIFFojpeg_finish_decompress(sp); + } + +/*ARGSUSED*/ static int +OJPEGDecodeRaw(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s) + { static float zeroes[6]; + tsize_t nrows; + register OJPEGState *sp = OJState(tif); + + /* BEWARE OF KLUDGE: If our input file was produced by Microsoft's Wang + Imaging for Windows application, the DC coefficients of + each JPEG image component (Y,Cb,Cr) must be reset at the beginning of each + TIFF "strip", and any JPEG data bits remaining in the decoder's input buffer + must be discarded, up to the next input-Byte storage boundary. To do so, we + create an "ad hoc" interface in the "jdhuff.c" module of IJG JPEG Library + Version 6, and we invoke that interface here before decoding each "strip". + */ + if (sp->is_WANG) jpeg_reset_huff_decode(&sp->cinfo.d,zeroes); + + /* Decode a chunk of pixels, where returned data is down-sampled as per the + sampling factors. The data is expected to be read in scan-line multiples. + */ + if (nrows = sp->cinfo.d.image_height) + do + { + if (sp->scancount >= DCTSIZE) /* reload downsampled-data buffer */ + { int n = sp->cinfo.d.max_v_samp_factor*DCTSIZE; + + if (TIFFojpeg_read_raw_data(sp,sp->ds_buffer,n) != n) return 0; + sp->scancount = 0; + }; + if (sp->cinfo.d.num_components > 0) + { int ci = 0, clumpoffset = 0; + register jpeg_component_info *compptr = sp->cinfo.d.comp_info; + + /* The fastest way to separate the data is: make 1 pass over the scan + line for each row of each component. + */ + do + { int ypos = 0; + + if (compptr->h_samp_factor == 1) /* Cb & Cr fast path */ + do + { register JSAMPLE *inptr = + sp->ds_buffer[ci][sp->scancount*compptr->v_samp_factor+ypos], + *outptr = (JSAMPLE *)buf + clumpoffset; + /* Cb & Cr have sampling factors = 1, so this is correct */ + register int clumps_per_line = + sp->cinfo.d.comp_info[1].downsampled_width; + + do *outptr = *inptr++; + while ( (outptr += sp->samplesperclump) + , --clumps_per_line > 0 + ); + } + while ( (clumpoffset += compptr->h_samp_factor) + , ++ypos < compptr->v_samp_factor + ); + else /* general case */ + do + { register JSAMPLE *inptr = + sp->ds_buffer[ci][sp->scancount*compptr->v_samp_factor+ypos], + *outptr = (JSAMPLE *)buf + clumpoffset; + /* Cb & Cr have sampling factors = 1, so this is correct */ + register int clumps_per_line = + sp->cinfo.d.comp_info[1].downsampled_width; + + do + { register int xpos = 0; + + do outptr[xpos] = *inptr++; + while (++xpos < compptr->h_samp_factor); + } + while ( (outptr += sp->samplesperclump) + , --clumps_per_line > 0 + ); + } + while ( (clumpoffset += compptr->h_samp_factor) + , ++ypos < compptr->v_samp_factor + ); + } + while (++compptr,++ci < sp->cinfo.d.num_components); + }; + ++sp->scancount; + buf += sp->bytesperline; + ++tif->tif_row; + } + while ((cc -= sp->bytesperline) > 0 && --nrows > 0); + return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height + || TIFFojpeg_finish_decompress(sp); + } + +/* "OJPEGPreDecode()" temporarily forces the JPEG Library to use the following + subroutine as a "dummy" input reader, to fool it into thinking that it has + read the image's 1st "Start of Scan" (SOS) marker and initialize accordingly. +*/ +/*ARGSUSED*/ METHODDEF(int) +fake_SOS_marker(j_decompress_ptr cinfo){return JPEG_REACHED_SOS;} + +/*ARGSUSED*/ METHODDEF(int) +suspend(j_decompress_ptr cinfo){return JPEG_SUSPENDED;} + +/*ARGSUSED*/ static int +OJPEGPreDecode(register TIFF *tif,tsample_t s) + { static const char bad_factors[]={"Improper JPEG sampling factors"}, + module[]={"OJPEGPreDecode"}; + uint32 segment_width, segment_height; + int downsampled_output = FALSE, + is_JFIF; /* <=> JFIF image? */ + J_COLOR_SPACE in_color_space = JCS_UNKNOWN; /* Image's input color space */ + register OJPEGState *sp = OJState(tif); +# define td (&tif->tif_dir) + + tif->tif_predecode = _TIFFNoPreCode; /* Don't call us again */ + + /* BOGOSITY ALERT! MicroSoft's Wang Imaging for Windows application produces + images containing "JPEGInterchangeFormat[Length]" TIFF + records that resemble JFIF-in-TIFF encapsulations but, in fact, violate the + TIFF Version 6 specification in several ways; nevertheless, we try to handle + them gracefully because there are apparently a lot of them around. The + purported "JFIF" data stream in one of these files vaguely resembles a JPEG + "tables only" data stream, except that there's no trailing EOI marker. The + rest of the JPEG data stream lies in a discontiguous file region, identified + by the 0th Strip offset (which is *also* illegal!), where it begins with an + SOS marker and apparently continues to the end of the file. There is no + trailing EOI marker here, either. + */ + is_JFIF = !sp->is_WANG && TIFFFieldSet(tif,FIELD_JPEGIFOFFSET); + + /* Set up to decode a strip or tile. Start by resetting decoder state left + over from any previous strip/tile, in case our client application didn't + read all of that data. Then read the JPEG header data. + */ + if (!TIFFojpeg_abort(sp)) return 0; + + /* Do a preliminary translation of the image's (input) color space from its + TIFF representation to JPEG Library representation. We might have to fix + this up after calling "TIFFojpeg_read_header()", which tries to establish + its own JPEG Library defaults. While we're here, initialize some other + decompression parameters that won't be overridden. + */ + if (td->td_planarconfig == PLANARCONFIG_CONTIG) + { + if (sp->h_sampling != 1 || sp->v_sampling != 1) + downsampled_output = TRUE; /* Tentative default */ + switch (sp->photometric) /* default color-space translation */ + { + case PHOTOMETRIC_MINISBLACK: in_color_space = JCS_GRAYSCALE; + break; + case PHOTOMETRIC_RGB : in_color_space = JCS_RGB; + break; + case PHOTOMETRIC_SEPARATED : in_color_space = JCS_CMYK; + break; + case PHOTOMETRIC_YCBCR : in_color_space = JCS_YCbCr; + /* JPEG Library converts YCbCr to RGB? */ + if ( sp->jpegcolormode + == JPEGCOLORMODE_RGB + ) downsampled_output = FALSE; + } + }; + segment_width = td->td_imagewidth; + segment_height = td->td_imagelength - tif->tif_row; + if (isTiled(tif)) + { + if (sp->is_WANG) /* we don't know how to handle it */ + { + TIFFError(module,"Tiled Wang image not supported"); + return 0; + }; + + /* BOGOSITY ALERT! "TIFFTileRowSize()" seems to work fine for modern JPEG- + in-TIFF encapsulations where the image width--like the + tile width--is a multiple of 8 or 16 pixels. But image widths and + heights are aren't restricted to 8- or 16-bit multiples, and we need + the exact Byte count of decompressed scan lines when we call the JPEG + Library. At least one old file ("zackthecat.tif") in the TIFF Library + test suite has widths and heights slightly less than the tile sizes, and + it apparently used the bogus computation below to determine the number + of Bytes per scan line (was this due to an old, broken version of + "TIFFhowmany()"?). Before we get here, "OJPEGSetupDecode()" verified + that our image uses 8-bit samples, so the following check appears to + return the correct answer in all known cases tested to date. + */ + if (is_JFIF || (segment_width & 7) == 0) + sp->bytesperline = TIFFTileRowSize(tif); /* Normal case */ + else + { + /* Was the file-encoder's segment-width calculation bogus? */ + segment_width = (segment_width/sp->h_sampling + 1) * sp->h_sampling; + sp->bytesperline = segment_width * td->td_samplesperpixel; + } + } + else sp->bytesperline = TIFFVStripSize(tif,1); + if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) + { + + /* Scale the expected strip/tile size to match a downsampled component. */ + + segment_width = TIFFhowmany(segment_width,sp->h_sampling); + segment_height = TIFFhowmany(segment_height,sp->v_sampling); + }; + + /* BEWARE OF KLUDGE: If we have JPEG Interchange File Format (JFIF) image, + then we want to read "metadata" in the bit-stream's + header and validate it against corresponding information in TIFF records. + But if we have a *really old* JPEG file that's not JFIF, then we simply + assign TIFF-record values to JPEG Library variables without checking. + */ + if (is_JFIF) /* JFIF image */ + { unsigned char *end_of_data; + register unsigned char *p; + + /* WARNING: Although the image file contains a JFIF bit stream, it might + also contain some old TIFF records causing "OJPEGVSetField()" + to have allocated quantization or Huffman decoding tables. But when the + JPEG Library reads and parses the JFIF header below, it reallocate these + tables anew without checking for "dangling" pointers, thereby causing a + memory "leak". We have enough information to potentially deallocate the + old tables here, but unfortunately JPEG Library Version 6B uses a "pool" + allocator for small objects, with no deallocation procedure; instead, it + reclaims a whole pool when an image is closed/destroyed, so well-behaved + TIFF client applications (i.e., those which close their JPEG images as + soon as they're no longer needed) will waste memory for a short time but + recover it eventually. But ill-behaved TIFF clients (i.e., those which + keep many JPEG images open gratuitously) can exhaust memory prematurely. + If the JPEG Library ever implements a deallocation procedure, insert + this clean-up code: + */ +# ifdef someday + if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) /* free quant. tables */ + { register int i = 0; + + do + { register JQUANT_TBL *q; + + if (q = sp->cinfo.d.quant_tbl_ptrs[i]) + { + jpeg_free_small(&sp->cinfo.comm,q,sizeof *q); + sp->cinfo.d.quant_tbl_ptrs[i] = 0; + } + } + while (++i < NUM_QUANT_TBLS); + }; + if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) /* free Huffman tables */ + { register int i = 0; + + do + { register JHUFF_TBL *h; + + if (h = sp->cinfo.d.dc_huff_tbl_ptrs[i]) + { + jpeg_free_small(&sp->cinfo.comm,h,sizeof *h); + sp->cinfo.d.dc_huff_tbl_ptrs[i] = 0; + }; + if (h = sp->cinfo.d.ac_huff_tbl_ptrs[i]) + { + jpeg_free_small(&sp->cinfo.comm,h,sizeof *h); + sp->cinfo.d.ac_huff_tbl_ptrs[i] = 0; + } + } + while (++i < NUM_HUFF_TBLS); + }; +# endif /* someday */ + + /* Since we might someday wish to try rewriting "old format" JPEG-in-TIFF + encapsulations in "new format" files, try to synthesize the value of a + modern "JPEGTables" TIFF record by scanning the JPEG data from just past + the "Start of Information" (SOI) marker until something other than a + legitimate "table" marker is found, as defined in ISO DIS 10918-1 + Appending B.2.4; namely: + + -- Define Quantization Table (DQT) + -- Define Huffman Table (DHT) + -- Define Arithmetic Coding table (DAC) + -- Define Restart Interval (DRI) + -- Comment (COM) + -- Application data (APPn) + + For convenience, we also accept "Expansion" (EXP) markers, although they + are apparently not a part of normal "table" data. + */ + sp->jpegtables = p = (unsigned char *)sp->src.next_input_byte; + end_of_data = p + sp->src.bytes_in_buffer; + p += 2; + while (p < end_of_data && p[0] == 0xFF) + switch (p[1]) + { + default : goto L; + case 0xC0: /* SOF0 */ + case 0xC1: /* SOF1 */ + case 0xC2: /* SOF2 */ + case 0xC3: /* SOF3 */ + case 0xC4: /* DHT */ + case 0xC5: /* SOF5 */ + case 0xC6: /* SOF6 */ + case 0xC7: /* SOF7 */ + case 0xC9: /* SOF9 */ + case 0xCA: /* SOF10 */ + case 0xCB: /* SOF11 */ + case 0xCC: /* DAC */ + case 0xCD: /* SOF13 */ + case 0xCE: /* SOF14 */ + case 0xCF: /* SOF15 */ + case 0xDB: /* DQT */ + case 0xDD: /* DRI */ + case 0xDF: /* EXP */ + case 0xE0: /* APP0 */ + case 0xE1: /* APP1 */ + case 0xE2: /* APP2 */ + case 0xE3: /* APP3 */ + case 0xE4: /* APP4 */ + case 0xE5: /* APP5 */ + case 0xE6: /* APP6 */ + case 0xE7: /* APP7 */ + case 0xE8: /* APP8 */ + case 0xE9: /* APP9 */ + case 0xEA: /* APP10 */ + case 0xEB: /* APP11 */ + case 0xEC: /* APP12 */ + case 0xED: /* APP13 */ + case 0xEE: /* APP14 */ + case 0xEF: /* APP15 */ + case 0xFE: /* COM */ + p += (p[2] << 8 | p[3]) + 2; + }; + L: if (p - (unsigned char *)sp->jpegtables > 2) /* fake "JPEGTables" */ + { + + /* In case our client application asks, pretend that this image file + contains a modern "JPEGTables" TIFF record by copying to a buffer + the initial part of the JFIF bit-stream that we just scanned, from + the SOI marker through the "metadata" tables, then append an EOI + marker and flag the "JPEGTables" TIFF record as "present". + */ + sp->jpegtables_length = p - (unsigned char*)sp->jpegtables + 2; + p = sp->jpegtables; + if (!(sp->jpegtables = _TIFFmalloc(sp->jpegtables_length))) + { + TIFFError(module,no_jtable_space); + return 0; + }; + _TIFFmemcpy(sp->jpegtables,p,sp->jpegtables_length-2); + p = (unsigned char *)sp->jpegtables + sp->jpegtables_length; + p[-2] = 0xFF; p[-1] = JPEG_EOI; /* Append EOI marker */ + TIFFSetFieldBit(tif,FIELD_JPEGTABLES); + tif->tif_flags |= TIFF_DIRTYDIRECT; + } + else sp->jpegtables = 0; /* Don't simulate "JPEGTables" */ + if (TIFFojpeg_read_header(sp,TRUE) != JPEG_HEADER_OK) return 0; + if ( sp->cinfo.d.image_width != segment_width + || sp->cinfo.d.image_height != segment_height + ) + { + TIFFError(module,"Improper JPEG strip/tile size"); + return 0; + }; + if ( ( td->td_planarconfig == PLANARCONFIG_CONTIG + ? td->td_samplesperpixel + : 1 + ) != sp->cinfo.d.num_components + ) + { + TIFFError(module,"Improper JPEG component count"); + return 0; + }; + if (sp->cinfo.d.data_precision != td->td_bitspersample) + { + TIFFError(module,"Improper JPEG data precision"); + return 0; + }; + /*if (td->td_planarconfig == PLANARCONFIG_CONTIG) + { int ci; + + // Component 0 should have expected sampling factors. + + if ( sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling + || sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling + ) + { + TIFFError(module,bad_factors); + return 0; + }; + ci = 1; // The rest should have sampling factors 1,1 + do if ( sp->cinfo.d.comp_info[ci].h_samp_factor != 1 + || sp->cinfo.d.comp_info[ci].v_samp_factor != 1 + ) + { + TIFFError(module,bad_factors); + return 0; + } + while (++ci < sp->cinfo.d.num_components); + } + else + + // PLANARCONFIG_SEPARATE's single component should have sampling factors + + if ( sp->cinfo.d.comp_info[0].h_samp_factor != 1 + || sp->cinfo.d.comp_info[0].v_samp_factor != 1 + ) + { + TIFFError(module,bad_factors); + return 0; + } + */ + } + else /* not JFIF image */ + { int (*save)(j_decompress_ptr cinfo) = sp->cinfo.d.marker->read_markers; + register int i; + + /* We're not assuming that this file's JPEG bit stream has any header + "metadata", so fool the JPEG Library into thinking that we read a + "Start of Input" (SOI) marker and a "Start of Frame" (SOFx) marker, then + force it to read a simulated "Start of Scan" (SOS) marker when we call + "TIFFojpeg_read_header()" below. This should cause the JPEG Library to + establish reasonable defaults. + */ + sp->cinfo.d.marker->saw_SOI = /* Pretend we saw SOI marker */ + sp->cinfo.d.marker->saw_SOF = TRUE; /* Pretend we saw SOF marker */ + sp->cinfo.d.marker->read_markers = + sp->is_WANG ? suspend : fake_SOS_marker; + sp->cinfo.d.global_state = DSTATE_INHEADER; + sp->cinfo.d.Se = DCTSIZE2-1; /* Suppress JPEG Library warning */ + sp->cinfo.d.image_width = segment_width; + sp->cinfo.d.image_height = segment_height; + sp->cinfo.d.data_precision = td->td_bitspersample; + + /* The following color-space initialization, including the complicated + "switch"-statement below, essentially duplicates the logic used by the + JPEG Library's "jpeg_init_colorspace()" subroutine during compression. + */ + sp->cinfo.d.num_components = td->td_planarconfig == PLANARCONFIG_CONTIG + ? td->td_samplesperpixel + : 1; + sp->cinfo.d.comp_info = (jpeg_component_info *) + (*sp->cinfo.d.mem->alloc_small) + ( &sp->cinfo.comm + , JPOOL_IMAGE + , sp->cinfo.d.num_components * sizeof *sp->cinfo.d.comp_info + ); + i = 0; + do + { + sp->cinfo.d.comp_info[i].component_index = i; + sp->cinfo.d.comp_info[i].component_needed = TRUE; + sp->cinfo.d.cur_comp_info[i] = &sp->cinfo.d.comp_info[i]; + } + while (++i < sp->cinfo.d.num_components); + switch (in_color_space) + { + case JCS_UNKNOWN : + i = 0; + do + { + sp->cinfo.d.comp_info[i].component_id = i; + sp->cinfo.d.comp_info[i].h_samp_factor = + sp->cinfo.d.comp_info[i].v_samp_factor = 1; + } + while (++i < sp->cinfo.d.num_components); + break; + case JCS_GRAYSCALE: + sp->cinfo.d.comp_info[0].component_id = + sp->cinfo.d.comp_info[0].h_samp_factor = + sp->cinfo.d.comp_info[0].v_samp_factor = 1; + break; + case JCS_RGB : + sp->cinfo.d.comp_info[0].component_id = 'R'; + sp->cinfo.d.comp_info[1].component_id = 'G'; + sp->cinfo.d.comp_info[2].component_id = 'B'; + i = 0; + do sp->cinfo.d.comp_info[i].h_samp_factor = + sp->cinfo.d.comp_info[i].v_samp_factor = 1; + while (++i < sp->cinfo.d.num_components); + break; + case JCS_CMYK : + sp->cinfo.d.comp_info[0].component_id = 'C'; + sp->cinfo.d.comp_info[1].component_id = 'Y'; + sp->cinfo.d.comp_info[2].component_id = 'M'; + sp->cinfo.d.comp_info[3].component_id = 'K'; + i = 0; + do sp->cinfo.d.comp_info[i].h_samp_factor = + sp->cinfo.d.comp_info[i].v_samp_factor = 1; + while (++i < sp->cinfo.d.num_components); + break; + case JCS_YCbCr : + i = 0; + do + { + sp->cinfo.d.comp_info[i].component_id = i+1; + sp->cinfo.d.comp_info[i].h_samp_factor = + sp->cinfo.d.comp_info[i].v_samp_factor = 1; + sp->cinfo.d.comp_info[i].quant_tbl_no = + sp->cinfo.d.comp_info[i].dc_tbl_no = + sp->cinfo.d.comp_info[i].ac_tbl_no = i > 0; + } + while (++i < sp->cinfo.d.num_components); + sp->cinfo.d.comp_info[0].h_samp_factor = sp->h_sampling; + sp->cinfo.d.comp_info[0].v_samp_factor = sp->v_sampling; + }; + sp->cinfo.d.comps_in_scan = sp->cinfo.d.num_components; + i = TIFFojpeg_read_header(sp,(unsigned char)(!sp->is_WANG)); + sp->cinfo.d.marker->read_markers = save; /* Restore input method */ + if (sp->is_WANG) /* Microsoft Wang Imaging for Windows file */ + { + if (i != JPEG_SUSPENDED) return 0; + + /* BOGOSITY ALERT! Files generated by Microsoft's Wang Imaging + application are a special--and, technically + illegal--case. A JPEG SOS marker and rest of the data stream should + be located at the end of the file, in a position identified by the + 0th Strip offset. + */ + i = td->td_nstrips - 1; + sp->src.next_input_byte = tif->tif_base + td->td_stripoffset[0]; + sp->src.bytes_in_buffer = td->td_stripoffset[i] - + td->td_stripoffset[0] + td->td_stripbytecount[i]; + i = TIFFojpeg_read_header(sp,TRUE); + }; + if (i != JPEG_HEADER_OK) return 0; + }; + + /* The JPEG Library doesn't seem to be as smart as we are about choosing + suitable default input- and output color spaces for decompression, so fix + things up here. + */ + sp->cinfo.d.out_color_space = + ((sp->cinfo.d.jpeg_color_space = in_color_space) == JCS_YCbCr) + ? (sp->jpegcolormode == JPEGCOLORMODE_RGB ? JCS_RGB : JCS_YCbCr) + : JCS_UNKNOWN; /* Suppress color-space handling */ + tif->tif_decoderow = tif->tif_decodestrip = tif->tif_decodetile = + (sp->cinfo.d.raw_data_out = downsampled_output) + ? OJPEGDecodeRaw : OJPEGDecode; + if (!TIFFojpeg_start_decompress(sp)) return 0; /* Start JPEG decompressor */ + if (downsampled_output) /* allocate downsampled-data buffers */ + { + if (!alloc_downsampled_buffers(tif,sp->cinfo.d.comp_info, + sp->cinfo.d.num_components) + ) return 0; + sp->scancount = DCTSIZE; /* mark buffer empty */ + }; + return 1; +# undef td + } + +static int +OJPEGVSetField(register TIFF *tif,ttag_t tag,va_list ap) + { uint32 v32; + register OJPEGState *sp = OJState(tif); +# define td (&tif->tif_dir) + + switch (tag) + { +# ifdef COLORIMETRY_SUPPORT + + /* If a "ReferenceBlackWhite" TIFF tag appears in the file explicitly, undo + any modified default definition that we might have installed below, then + install the real one. + */ + case TIFFTAG_REFERENCEBLACKWHITE : if (td->td_refblackwhite) + { + _TIFFfree(td->td_refblackwhite); + td->td_refblackwhite = 0; + }; +# endif /* COLORIMETRY_SUPPORT */ + default : return + (*sp->vsetparent)(tif,tag,ap); +# ifdef COLORIMETRY_SUPPORT + + /* BEWARE OF KLUDGE: Some old-format JPEG-in-TIFF files, including those + created by Microsoft's Wang Imaging application, + illegally omit a "ReferenceBlackWhite" TIFF tag, even though the TIFF + specification's default is intended for the RGB color space and is in- + appropriate for the YCbCr color space ordinarily used for JPEG images. + Since many TIFF client applications request the value of this tag + immediately after a TIFF image directory is parsed, and before any other + code in this module receives control, we are forced to fix this problem + very early in image-file processing. Fortunately, legal TIFF files are + supposed to store their tags in numeric order, so a mandatory + "PhotometricInterpretation" tag should always appear before an optional + "ReferenceBlackWhite" tag. So, we slyly peek ahead when we discover the + desired photometry, by installing modified black and white reference + levels. + */ + case TIFFTAG_PHOTOMETRIC : + if ( (v32 = (*sp->vsetparent)(tif,tag,ap)) + && td->td_photometric == PHOTOMETRIC_YCBCR + ) + if (td->td_refblackwhite = _TIFFmalloc(6*sizeof(float))) + { register long top = 1 << td->td_bitspersample; + + td->td_refblackwhite[0] = 0; + td->td_refblackwhite[1] = td->td_refblackwhite[3] = + td->td_refblackwhite[5] = (float)(top - 1); + td->td_refblackwhite[2] = td->td_refblackwhite[4] = (float)(top >> 1); + } + else + { + TIFFError(tif->tif_name,"Cannot define default reference black and white levels"); + v32 = 0; + }; + return v32; +# endif /* COLORIMETRY_SUPPORT */ + + /* BEWARE OF KLUDGE: According to Charles Auer , if our + input is a multi-image (multi-directory) JPEG-in-TIFF + file created by Microsoft's Wang Imaging application, for some reason + the first directory excludes the vendor-specific "WANG PageControl" tag + (32934) that we check below, so the only other way to identify these + directories is apparently to look for a software-identification tag with + the substring, "Wang Labs". Single-image files can apparently pass both + tests, which causes no harm here, but what a mess this is! + */ + case TIFFTAG_SOFTWARE : if ( (v32 = (*sp->vsetparent) + (tif,tag,ap) + ) + && strstr( td->td_software + , "Wang Labs" + ) + ) sp->is_WANG = 1; + return v32; + case TIFFTAG_JPEGPROC : + case TIFFTAG_JPEGIFOFFSET : + case TIFFTAG_JPEGIFBYTECOUNT : + case TIFFTAG_JPEGRESTARTINTERVAL : + case TIFFTAG_JPEGLOSSLESSPREDICTORS: + case TIFFTAG_JPEGPOINTTRANSFORM : + case TIFFTAG_JPEGQTABLES : + case TIFFTAG_JPEGDCTABLES : + case TIFFTAG_JPEGACTABLES : + case TIFFTAG_WANG_PAGECONTROL : + case TIFFTAG_JPEGCOLORMODE : ; + }; + v32 = va_arg(ap,uint32); /* No. of values in this TIFF record */ + + /* BEWARE: The following actions apply only if we are reading a "source" TIFF + image to be decompressed for a client application program. If we + ever enhance this file's CODEC to write "destination" JPEG-in-TIFF images, + we'll need an "if"- and another "switch"-statement below, because we'll + probably want to store these records' values in some different places. Most + of these need not be parsed here in order to decode JPEG bit stream, so we + set boolean flags to note that they have been seen, but we otherwise ignore + them. + */ + switch (tag) + { JHUFF_TBL **h; + //float *refbw; + + /* Validate the JPEG-process code. */ + + case TIFFTAG_JPEGPROC : + switch (v32) + { + default: TIFFError(tif->tif_name,"Unknown JPEG process"); + return 0; + case 14: TIFFError(JPEGLib_name, + "Does not support lossless Huffman coding"); + return 0; + case 1: ; + }; + break; + + /* The TIFF Version 6.0 specification says that if the value of a TIFF + "JPEGInterchangeFormat" record is 0, then we are to behave as if this + record were absent; i.e., the data does *not* represent a JPEG Inter- + change Format File (JFIF), so don't even set the boolean "I've been + here" flag below. Otherwise, the field's value represents the file + offset of the JPEG SOI marker. + */ + case TIFFTAG_JPEGIFOFFSET : + if (v32) + { + sp->src.next_input_byte = tif->tif_base + v32; + break; + }; + return 1; + case TIFFTAG_JPEGIFBYTECOUNT : + sp->src.bytes_in_buffer = v32; + break; + + /* The TIFF Version 6.0 specification says that if the JPEG "Restart" + marker interval is 0, then the data has no "Restart" markers; i.e., we + must behave as if this TIFF record were absent. So, don't even set the + boolean "I've been here" flag below. + */ + case TIFFTAG_JPEGRESTARTINTERVAL : + if (v32) + { + sp->cinfo.d.restart_interval = v32; + break; + }; + return 1; + + /* We have a vector of offsets to quantization tables, so load 'em! */ + + case TIFFTAG_JPEGQTABLES : + if (v32) + { uint32 *v; + int i; + + if (v32 > NUM_QUANT_TBLS) + { + TIFFError(tif->tif_name,"Too many quantization tables"); + return 0; + }; + i = 0; + v = va_arg(ap,uint32 *); + do /* read quantization table */ + { register UINT8 *from = tif->tif_base + *v++; + register UINT16 *to = (sp->cinfo.d.quant_tbl_ptrs[i] = + jpeg_alloc_quant_table(&sp->cinfo.comm) + )->quantval; + register int j = DCTSIZE2; + + do *to++ = *from++; while (--j > 0); + } + while (++i < (int)v32); + sp->jpegtablesmode |= JPEGTABLESMODE_QUANT; + }; + break; + + /* We have a vector of offsets to DC Huffman tables, so load 'em! */ + + case TIFFTAG_JPEGDCTABLES : + h = sp->cinfo.d.dc_huff_tbl_ptrs; + goto L; + + /* We have a vector of offsets to AC Huffman tables, so load 'em! */ + + case TIFFTAG_JPEGACTABLES : + h = sp->cinfo.d.ac_huff_tbl_ptrs; + L: if (v32) + { uint32 *v; + int i; + + if (v32 > NUM_HUFF_TBLS) + { + TIFFError(tif->tif_name,"Too many Huffman tables"); + return 0; + }; + v = va_arg(ap,uint32 *); + i = 0; + do /* copy each Huffman table */ + { int size = 0; + register UINT8 *from = tif->tif_base + *v++, + *to = (*h++ = + jpeg_alloc_huff_table(&sp->cinfo.comm) + )->bits; + register int j = sizeof (*h)->bits; + + /* WARNING: This code relies on the fact that an image file not + "memory mapped" was read entirely into a single + buffer by "TIFFInitOJPEG()", so we can do a fast memory-to- + memory copy here. Each table consists of 16 Bytes, which are + suffixed to a 0 Byte when copied, followed by a variable + number of Bytes whose length is the sum of the first 16. + */ + *to++ = 0; + while (--j > 0) size += *to++ = *from++; /* Copy 16 Bytes */ + if (size > sizeof (*h)->huffval/sizeof *(*h)->huffval) + { + TIFFError(tif->tif_name,"Huffman table too big"); + return 0; + }; + if ((j = size) > 0) do *to++ = *from++; while (--j > 0); + while (++size <= sizeof (*h)->huffval/sizeof *(*h)->huffval) + *to++ = 0; /* Zero the rest of the table for cleanliness */ + } + while (++i < (int)v32); + sp->jpegtablesmode |= JPEGTABLESMODE_HUFF; + }; + break; + + /* The following vendor-specific TIFF tag occurs in (highly illegal) files + generated by MicroSoft's Wang Imaging for Windows application. These + can apparently have several "pages", in which case this tag specifies + the offset of a "page control" structure, which we don't currently know + how to handle. 0 indicates a 1-page image with no "page control", which + we make a feeble effort to handle. + */ + case TIFFTAG_WANG_PAGECONTROL : + if (v32 == 0) v32 = -1; + sp->is_WANG = v32; + tag = TIFFTAG_JPEGPROC+FIELD_WANG_PAGECONTROL-FIELD_JPEGPROC; + break; + + /* This pseudo tag indicates whether we think that our caller is supposed + to do YCbCr<->RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or + whether we must ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1). + */ + case TIFFTAG_JPEGCOLORMODE : + sp->jpegcolormode = (unsigned char)v32; + + /* Mark the image to indicate whether returned data is up-sampled, so + that "TIFF{Strip,Tile}Size()" reflect the true amount of data present. + */ + v32 = tif->tif_flags; /* Save flags temporarily */ + tif->tif_flags &= ~TIFF_UPSAMPLED; + if (td->td_planarconfig == PLANARCONFIG_CONTIG) + if ( td->td_photometric == PHOTOMETRIC_YCBCR + && sp->jpegcolormode == JPEGCOLORMODE_RGB + ) tif->tif_flags |= TIFF_UPSAMPLED; + else + if ( (td->td_ycbcrsubsampling[1]<<16|td->td_ycbcrsubsampling[0]) + != (1 << 16 | 1) + ) /* XXX what about up-sampling? */; + + /* If the up-sampling state changed, re-calculate tile size. */ + + if ((tif->tif_flags ^ v32) & TIFF_UPSAMPLED) + { + tif->tif_tilesize = TIFFTileSize(tif); + tif->tif_flags |= TIFF_DIRTYDIRECT; + }; + return 1; + }; + TIFFSetFieldBit(tif,tag-TIFFTAG_JPEGPROC+FIELD_JPEGPROC); + return 1; +# undef td + } + +static int +OJPEGVGetField(register TIFF *tif,ttag_t tag,va_list ap) + { register OJPEGState *sp = OJState(tif); + + switch (tag) + { + + /* If this file has managed to synthesize a set of consolidated "metadata" + tables for the current (post-TIFF Version 6.0 specification) JPEG-in- + TIFF encapsulation strategy, then tell our caller about them; otherwise, + keep mum. + */ + case TIFFTAG_JPEGTABLES : + if (sp->jpegtables_length) /* we have "new"-style JPEG tables */ + { + *va_arg(ap,uint32 *) = sp->jpegtables_length; + *va_arg(ap,char **) = sp->jpegtables; + return 1; + }; + + /* This pseudo tag indicates whether we think that our caller is supposed + to do YCbCr<->RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or + whether we must ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1). + */ + case TIFFTAG_JPEGCOLORMODE : + *va_arg(ap,uint32 *) = sp->jpegcolormode; + return 1; + + /* The following tags are defined by the TIFF Version 6.0 specification + and are obsolete. If our caller asks for information about them, do not + return anything, even if we parsed them in an old-format "source" image. + */ + case TIFFTAG_JPEGPROC : + case TIFFTAG_JPEGIFOFFSET : + case TIFFTAG_JPEGIFBYTECOUNT : + case TIFFTAG_JPEGRESTARTINTERVAL : + case TIFFTAG_JPEGLOSSLESSPREDICTORS: + case TIFFTAG_JPEGPOINTTRANSFORM : + case TIFFTAG_JPEGQTABLES : + case TIFFTAG_JPEGDCTABLES : + case TIFFTAG_JPEGACTABLES : return 0; + }; + return (*sp->vgetparent)(tif,tag,ap); + } + +/*ARGSUSED*/ static void +OJPEGPrintDir(register TIFF *tif,FILE *fd,long flags) + { register OJPEGState *sp = OJState(tif); + + if (sp->jpegtables_length) + fprintf(fd," JPEG Table Data: , %lu bytes\n", + sp->jpegtables_length); + } + +static uint32 +OJPEGDefaultStripSize(register TIFF *tif,register uint32 s) + { register OJPEGState *sp = OJState(tif); +# define td (&tif->tif_dir) + + if ((s = (*sp->defsparent)(tif,s)) < td->td_imagelength) + s = TIFFroundup(s,td->td_ycbcrsubsampling[1]*DCTSIZE); + return s; +# undef td + } + +static void +OJPEGDefaultTileSize(register TIFF *tif,register uint32 *tw,register uint32 *th) + { register OJPEGState *sp = OJState(tif); +# define td (&tif->tif_dir) + + (*sp->deftparent)(tif,tw,th); + *tw = TIFFroundup(*tw,td->td_ycbcrsubsampling[0]*DCTSIZE); + *th = TIFFroundup(*th,td->td_ycbcrsubsampling[1]*DCTSIZE); +# undef td + } + +static void +OJPEGCleanUp(register TIFF *tif) + { register OJPEGState *sp; + + if (sp = OJState(tif)) + { + TIFFojpeg_destroy(sp); /* Release JPEG Library variables */ + if (sp->jpegtables) _TIFFfree(sp->jpegtables); + + /* If the image file isn't "memory mapped" and we read it all into a + single, large memory buffer, free the buffer now. + */ + if (!isMapped(tif) && tif->tif_base) /* free whole-file buffer */ + { + _TIFFfree(tif->tif_base); + tif->tif_base = 0; + tif->tif_size = 0; + }; + _TIFFfree(sp); /* Release local variables */ + tif->tif_data = 0; + } + } + +int +TIFFInitOJPEG(register TIFF *tif,int scheme) + { register OJPEGState *sp; +# define td (&tif->tif_dir) +# ifndef never + + /* This module supports a decompression-only CODEC, which is intended strictly + for viewing old image files using the obsolete JPEG-in-TIFF encapsulation + specified by the TIFF Version 6.0 specification. It does not, and never + should, support compression for new images. If a client application asks us + to, refuse and complain loudly! + */ + if (tif->tif_mode != O_RDONLY) return _notSupported(tif); +# endif /* never */ + if (!isMapped(tif)) + { + + /* BEWARE OF KLUDGE: If our host operating-system doesn't let an image + file be "memory mapped", then we want to read the + entire file into a single (possibly large) memory buffer as if it had + been "memory mapped". Although this is likely to waste space, because + analysis of the file's content might cause parts of it to be read into + smaller buffers duplicatively, it appears to be the lesser of several + evils. Very old JPEG-in-TIFF encapsulations aren't guaranteed to be + JFIF bit streams, or to have a TIFF "JPEGTables" record or much other + "metadata" to help us locate the decoding tables and entropy-coded data, + so we're likely do a lot of random-access grokking around, and we must + ultimately tell the JPEG Library to sequentially scan much of the file + anyway. This is all likely to be easier if we use "brute force" to + read the entire file, once, and don't use incremental disc I/O. If our + client application tries to process a file so big that we can't buffer + it entirely, then tough shit: we'll give up and exit! + */ + if (!(tif->tif_base = _TIFFmalloc(tif->tif_size=TIFFGetFileSize(tif)))) + { + TIFFError(tif->tif_name,"Cannot allocate file buffer"); + return 0; + }; + if (!SeekOK(tif,0) || !ReadOK(tif,tif->tif_base,tif->tif_size)) + { + TIFFError(tif->tif_name,"Cannot read file"); + return 0; + } + }; + + /* Allocate storage for this module's per-file variables. */ + + if (!(tif->tif_data = (tidata_t)_TIFFmalloc(sizeof *sp))) + { + TIFFError("TIFFInitOJPEG","No space for JPEG state block"); + return 0; + }; + (sp = OJState(tif))->tif = tif; /* Initialize reverse pointer */ + if (!TIFFojpeg_create_decompress(sp)) return 0; /* Init. JPEG Library */ + + /* If the image file doesn't have "JPEGInterchangeFormat[Length]" TIFF records + to guide us, we have few clues about where its encapsulated JPEG bit stream + is located, so establish intelligent defaults: If the Image File Directory + doesn't immediately follow the TIFF header, assume that the JPEG data lies + in between; otherwise, assume that it follows the Image File Directory. + */ + sp->src.next_input_byte = tif->tif_base + tif->tif_diroff; /* Default */ + if (tif->tif_header.tiff_diroff > sizeof tif->tif_header) + { + sp->src.bytes_in_buffer = tif->tif_header.tiff_diroff + - sizeof tif->tif_header; + sp->src.next_input_byte = sp->src.next_input_byte + - sp->src.bytes_in_buffer; + } + else /* this case is ugly! */ + { uint16 dircount; + + dircount = *(uint16 *)sp->src.next_input_byte; + if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); + sp->src.next_input_byte += dircount * sizeof(TIFFDirEntry) + + sizeof dircount; + sp->src.bytes_in_buffer = tif->tif_base + tif->tif_nextdiroff + - sp->src.next_input_byte; + }; + + /* Install CODEC-specific tag information and override default TIFF Library + "method" subroutines with our own, CODEC-specific methods. Like all good + members of an object-class, we save some of these subroutine pointers for + "fall back" in case our own methods fail. + */ + _TIFFMergeFieldInfo(tif,ojpegFieldInfo, + sizeof ojpegFieldInfo/sizeof *ojpegFieldInfo); + sp->defsparent = tif->tif_defstripsize; + sp->deftparent = tif->tif_deftilesize; + sp->vgetparent = tif->tif_vgetfield; + sp->vsetparent = tif->tif_vsetfield; + tif->tif_defstripsize = OJPEGDefaultStripSize; + tif->tif_deftilesize = OJPEGDefaultTileSize; + tif->tif_vgetfield = OJPEGVGetField; + tif->tif_vsetfield = OJPEGVSetField; + tif->tif_printdir = OJPEGPrintDir; +# ifdef never + tif->tif_setupencode = OJPEGSetupEncode; + tif->tif_preencode = OJPEGPreEncode; + tif->tif_postencode = OJPEGPostEncode; +# else /* well, hardly ever */ + tif->tif_setupencode = tif->tif_postencode = _notSupported; + tif->tif_preencode = (TIFFPreMethod)_notSupported; +# endif /* never */ + tif->tif_setupdecode = OJPEGSetupDecode; + tif->tif_predecode = OJPEGPreDecode; + tif->tif_cleanup = OJPEGCleanUp; + + /* Initialize other CODEC-specific variables requiring default values. */ + + tif->tif_flags |= TIFF_NOBITREV; /* No bit-reversal within data bytes */ + sp->is_WANG = 0; /* Assume not a Microsoft Wang Imaging file by default */ + sp->jpegtables = 0; /* No "new"-style JPEG tables synthesized yet */ + sp->jpegtables_length = 0; + sp->jpegquality = 75; /* Default IJG quality */ + sp->jpegcolormode = JPEGCOLORMODE_RAW; + sp->jpegtablesmode = 0; /* No tables found yet */ + return 1; +# undef td + } +#endif /* OJPEG_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_open.c b/SlnkDWFImpl/CxImage/tiff/tif_open.c new file mode 100644 index 0000000..23db306 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_open.c @@ -0,0 +1,495 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_open.c,v 1.6 2001/07/20 02:22:46 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + */ +#include "tiffiop.h" + +void _TIFFSetDefaultCompressionState(TIFF* tif); + +static const long typemask[13] = { + 0L, /* TIFF_NOTYPE */ + 0x000000ffL, /* TIFF_BYTE */ + 0xffffffffL, /* TIFF_ASCII */ + 0x0000ffffL, /* TIFF_SHORT */ + 0xffffffffL, /* TIFF_LONG */ + 0xffffffffL, /* TIFF_RATIONAL */ + 0x000000ffL, /* TIFF_SBYTE */ + 0x000000ffL, /* TIFF_UNDEFINED */ + 0x0000ffffL, /* TIFF_SSHORT */ + 0xffffffffL, /* TIFF_SLONG */ + 0xffffffffL, /* TIFF_SRATIONAL */ + 0xffffffffL, /* TIFF_FLOAT */ + 0xffffffffL, /* TIFF_DOUBLE */ +}; +static const int bigTypeshift[13] = { + 0, /* TIFF_NOTYPE */ + 24, /* TIFF_BYTE */ + 0, /* TIFF_ASCII */ + 16, /* TIFF_SHORT */ + 0, /* TIFF_LONG */ + 0, /* TIFF_RATIONAL */ + 24, /* TIFF_SBYTE */ + 24, /* TIFF_UNDEFINED */ + 16, /* TIFF_SSHORT */ + 0, /* TIFF_SLONG */ + 0, /* TIFF_SRATIONAL */ + 0, /* TIFF_FLOAT */ + 0, /* TIFF_DOUBLE */ +}; +static const int litTypeshift[13] = { + 0, /* TIFF_NOTYPE */ + 0, /* TIFF_BYTE */ + 0, /* TIFF_ASCII */ + 0, /* TIFF_SHORT */ + 0, /* TIFF_LONG */ + 0, /* TIFF_RATIONAL */ + 0, /* TIFF_SBYTE */ + 0, /* TIFF_UNDEFINED */ + 0, /* TIFF_SSHORT */ + 0, /* TIFF_SLONG */ + 0, /* TIFF_SRATIONAL */ + 0, /* TIFF_FLOAT */ + 0, /* TIFF_DOUBLE */ +}; + +/* + * Initialize the shift & mask tables, and the + * byte swapping state according to the file + * contents and the machine architecture. + */ +static void +TIFFInitOrder(TIFF* tif, int magic, int bigendian) +{ + tif->tif_typemask = typemask; + if (magic == TIFF_BIGENDIAN) { + tif->tif_typeshift = bigTypeshift; + if (!bigendian) + tif->tif_flags |= TIFF_SWAB; + } else { + tif->tif_typeshift = litTypeshift; + if (bigendian) + tif->tif_flags |= TIFF_SWAB; + } +} + +int +_TIFFgetMode(const char* mode, const char* module) +{ + int m = -1; + + switch (mode[0]) { + case 'r': + m = O_RDONLY; + if (mode[1] == '+') + m = O_RDWR; + break; + case 'w': + case 'a': + m = O_RDWR|O_CREAT; + if (mode[0] == 'w') + m |= O_TRUNC; + break; + default: + TIFFError(module, "\"%s\": Bad mode", mode); + break; + } + return (m); +} + +TIFF* +TIFFClientOpen( + const char* name, const char* mode, + thandle_t clientdata, + TIFFReadWriteProc readproc, + TIFFReadWriteProc writeproc, + TIFFSeekProc seekproc, + TIFFCloseProc closeproc, + TIFFSizeProc sizeproc, + TIFFMapFileProc mapproc, + TIFFUnmapFileProc unmapproc +) +{ + static const char module[] = "TIFFClientOpen"; + TIFF *tif; + int m, bigendian; + const char* cp; + + m = _TIFFgetMode(mode, module); + if (m == -1) + goto bad2; + tif = (TIFF *)_TIFFmalloc(sizeof (TIFF) + strlen(name) + 1); + if (tif == NULL) { + TIFFError(module, "%s: Out of memory (TIFF structure)", name); + goto bad2; + } + _TIFFmemset(tif, 0, sizeof (*tif)); + tif->tif_name = (char *)tif + sizeof (TIFF); + strcpy(tif->tif_name, name); + tif->tif_mode = m &~ (O_CREAT|O_TRUNC); + tif->tif_curdir = (tdir_t) -1; /* non-existent directory */ + tif->tif_curoff = 0; + tif->tif_curstrip = (tstrip_t) -1; /* invalid strip */ + tif->tif_row = (uint32) -1; /* read/write pre-increment */ + tif->tif_clientdata = clientdata; + tif->tif_readproc = readproc; + tif->tif_writeproc = writeproc; + tif->tif_seekproc = seekproc; + tif->tif_closeproc = closeproc; + tif->tif_sizeproc = sizeproc; + tif->tif_mapproc = mapproc; + tif->tif_unmapproc = unmapproc; + _TIFFSetDefaultCompressionState(tif); /* setup default state */ + /* + * Default is to return data MSB2LSB and enable the + * use of memory-mapped files and strip chopping when + * a file is opened read-only. + */ + tif->tif_flags = FILLORDER_MSB2LSB; + if (m == O_RDONLY ) + tif->tif_flags |= TIFF_MAPPED; + +#ifdef STRIPCHOP_DEFAULT + if (m == O_RDONLY || m == O_RDWR) + tif->tif_flags |= STRIPCHOP_DEFAULT; +#endif + + { union { int32 i; char c[4]; } u; u.i = 1; bigendian = u.c[0] == 0; } + /* + * Process library-specific flags in the open mode string. + * The following flags may be used to control intrinsic library + * behaviour that may or may not be desirable (usually for + * compatibility with some application that claims to support + * TIFF but only supports some braindead idea of what the + * vendor thinks TIFF is): + * + * 'l' use little-endian byte order for creating a file + * 'b' use big-endian byte order for creating a file + * 'L' read/write information using LSB2MSB bit order + * 'B' read/write information using MSB2LSB bit order + * 'H' read/write information using host bit order + * 'M' enable use of memory-mapped files when supported + * 'm' disable use of memory-mapped files + * 'C' enable strip chopping support when reading + * 'c' disable strip chopping support + * + * The use of the 'l' and 'b' flags is strongly discouraged. + * These flags are provided solely because numerous vendors, + * typically on the PC, do not correctly support TIFF; they + * only support the Intel little-endian byte order. This + * support is not configured by default because it supports + * the violation of the TIFF spec that says that readers *MUST* + * support both byte orders. It is strongly recommended that + * you not use this feature except to deal with busted apps + * that write invalid TIFF. And even in those cases you should + * bang on the vendors to fix their software. + * + * The 'L', 'B', and 'H' flags are intended for applications + * that can optimize operations on data by using a particular + * bit order. By default the library returns data in MSB2LSB + * bit order for compatibiltiy with older versions of this + * library. Returning data in the bit order of the native cpu + * makes the most sense but also requires applications to check + * the value of the FillOrder tag; something they probabyl do + * not do right now. + * + * The 'M' and 'm' flags are provided because some virtual memory + * systems exhibit poor behaviour when large images are mapped. + * These options permit clients to control the use of memory-mapped + * files on a per-file basis. + * + * The 'C' and 'c' flags are provided because the library support + * for chopping up large strips into multiple smaller strips is not + * application-transparent and as such can cause problems. The 'c' + * option permits applications that only want to look at the tags, + * for example, to get the unadulterated TIFF tag information. + */ + for (cp = mode; *cp; cp++) + switch (*cp) { + case 'b': + if ((m&O_CREAT) && !bigendian) + tif->tif_flags |= TIFF_SWAB; + break; + case 'l': + if ((m&O_CREAT) && bigendian) + tif->tif_flags |= TIFF_SWAB; + break; + case 'B': + tif->tif_flags = (tif->tif_flags &~ TIFF_FILLORDER) | + FILLORDER_MSB2LSB; + break; + case 'L': + tif->tif_flags = (tif->tif_flags &~ TIFF_FILLORDER) | + FILLORDER_LSB2MSB; + break; + case 'H': + tif->tif_flags = (tif->tif_flags &~ TIFF_FILLORDER) | + HOST_FILLORDER; + break; + case 'M': + if (m == O_RDONLY) + tif->tif_flags |= TIFF_MAPPED; + break; + case 'm': + if (m == O_RDONLY) + tif->tif_flags &= ~TIFF_MAPPED; + break; + case 'C': + if (m == O_RDONLY) + tif->tif_flags |= TIFF_STRIPCHOP; + break; + case 'c': + if (m == O_RDONLY) + tif->tif_flags &= ~TIFF_STRIPCHOP; + break; + } + /* + * Read in TIFF header. + */ + if (!ReadOK(tif, &tif->tif_header, sizeof (TIFFHeader))) { + if (tif->tif_mode == O_RDONLY) { + TIFFError(name, "Cannot read TIFF header"); + goto bad; + } + /* + * Setup header and write. + */ + tif->tif_header.tiff_magic = tif->tif_flags & TIFF_SWAB + ? (bigendian ? TIFF_LITTLEENDIAN : TIFF_BIGENDIAN) + : (bigendian ? TIFF_BIGENDIAN : TIFF_LITTLEENDIAN); + tif->tif_header.tiff_version = TIFF_VERSION; + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabShort(&tif->tif_header.tiff_version); + tif->tif_header.tiff_diroff = 0; /* filled in later */ + + /* + * This seek shouldn't be necessary, but I have had some + * crazy problems with a failed fseek() on Solaris leaving + * the current file pointer out of whack when an fwrite() + * is done. + */ + TIFFSeekFile( tif, 0, SEEK_SET ); + + if (!WriteOK(tif, &tif->tif_header, sizeof (TIFFHeader))) { + TIFFError(name, "Error writing TIFF header"); + goto bad; + } + /* + * Setup the byte order handling. + */ + TIFFInitOrder(tif, tif->tif_header.tiff_magic, bigendian); + /* + * Setup default directory. + */ + if (!TIFFDefaultDirectory(tif)) + goto bad; + tif->tif_diroff = 0; + return (tif); + } + /* + * Setup the byte order handling. + */ + if (tif->tif_header.tiff_magic != TIFF_BIGENDIAN && + tif->tif_header.tiff_magic != TIFF_LITTLEENDIAN) { + TIFFError(name, "Not a TIFF file, bad magic number %d (0x%x)", + tif->tif_header.tiff_magic, + tif->tif_header.tiff_magic); + goto bad; + } + TIFFInitOrder(tif, tif->tif_header.tiff_magic, bigendian); + /* + * Swap header if required. + */ + if (tif->tif_flags & TIFF_SWAB) { + TIFFSwabShort(&tif->tif_header.tiff_version); + TIFFSwabLong(&tif->tif_header.tiff_diroff); + } + /* + * Now check version (if needed, it's been byte-swapped). + * Note that this isn't actually a version number, it's a + * magic number that doesn't change (stupid). + */ + if (tif->tif_header.tiff_version != TIFF_VERSION) { + TIFFError(name, + "Not a TIFF file, bad version number %d (0x%x)", + tif->tif_header.tiff_version, + tif->tif_header.tiff_version); + goto bad; + } + tif->tif_flags |= TIFF_MYBUFFER; + tif->tif_rawcp = tif->tif_rawdata = 0; + tif->tif_rawdatasize = 0; + /* + * Setup initial directory. + */ + switch (mode[0]) { + case 'r': + tif->tif_nextdiroff = tif->tif_header.tiff_diroff; + /* + * Try to use a memory-mapped file if the client + * has not explicitly suppressed usage with the + * 'm' flag in the open mode (see above). + */ + if ((tif->tif_flags & TIFF_MAPPED) && + !TIFFMapFileContents(tif, (tdata_t*) &tif->tif_base, &tif->tif_size)) + tif->tif_flags &= ~TIFF_MAPPED; + if (TIFFReadDirectory(tif)) { + if( m != O_RDONLY + && tif->tif_dir.td_compression != COMPRESSION_NONE ) + { + TIFFError( name, + "Can't open a compressed TIFF file" + " with compression for update." ); + goto bad; + } + tif->tif_rawcc = -1; + tif->tif_flags |= TIFF_BUFFERSETUP; + return (tif); + } + break; + case 'a': + /* + * New directories are automatically append + * to the end of the directory chain when they + * are written out (see TIFFWriteDirectory). + */ + if (!TIFFDefaultDirectory(tif)) + goto bad; + return (tif); + } +bad: + tif->tif_mode = O_RDONLY; /* XXX avoid flush */ + TIFFClose(tif); + return ((TIFF*)0); +bad2: + (void) (*closeproc)(clientdata); + return ((TIFF*)0); +} + +/* + * Query functions to access private data. + */ + +/* + * Return open file's name. + */ +const char * +TIFFFileName(TIFF* tif) +{ + return (tif->tif_name); +} + +/* + * Return open file's I/O descriptor. + */ +int +TIFFFileno(TIFF* tif) +{ + return (tif->tif_fd); +} + +/* + * Return read/write mode. + */ +int +TIFFGetMode(TIFF* tif) +{ + return (tif->tif_mode); +} + +/* + * Return nonzero if file is organized in + * tiles; zero if organized as strips. + */ +int +TIFFIsTiled(TIFF* tif) +{ + return (isTiled(tif)); +} + +/* + * Return current row being read/written. + */ +uint32 +TIFFCurrentRow(TIFF* tif) +{ + return (tif->tif_row); +} + +/* + * Return index of the current directory. + */ +tdir_t +TIFFCurrentDirectory(TIFF* tif) +{ + return (tif->tif_curdir); +} + +/* + * Return current strip. + */ +tstrip_t +TIFFCurrentStrip(TIFF* tif) +{ + return (tif->tif_curstrip); +} + +/* + * Return current tile. + */ +ttile_t +TIFFCurrentTile(TIFF* tif) +{ + return (tif->tif_curtile); +} + +/* + * Return nonzero if the file has byte-swapped data. + */ +int +TIFFIsByteSwapped(TIFF* tif) +{ + return ((tif->tif_flags & TIFF_SWAB) != 0); +} + +/* + * Return nonzero if the data is returned up-sampled. + */ +int +TIFFIsUpSampled(TIFF* tif) +{ + return (isUpSampled(tif)); +} + +/* + * Return nonzero if the data is returned in MSB-to-LSB bit order. + */ +int +TIFFIsMSB2LSB(TIFF* tif) +{ + return (isFillOrder(tif, FILLORDER_MSB2LSB)); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_packbits.c b/SlnkDWFImpl/CxImage/tiff/tif_packbits.c new file mode 100644 index 0000000..b3ff2ee --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_packbits.c @@ -0,0 +1,291 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_packbits.c,v 1.5 2001/09/06 19:28:45 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef PACKBITS_SUPPORT +/* + * TIFF Library. + * + * PackBits Compression Algorithm Support + */ +#include +#include + +static int +PackBitsPreEncode(TIFF* tif, tsample_t s) +{ + (void) s; + /* + * Calculate the scanline/tile-width size in bytes. + */ + if (isTiled(tif)) + tif->tif_data = (tidata_t) TIFFTileRowSize(tif); + else + tif->tif_data = (tidata_t) TIFFScanlineSize(tif); + return (1); +} + +/* + * NB: tidata is the type representing *(tidata_t); + * if tidata_t is made signed then this type must + * be adjusted accordingly. + */ +typedef unsigned char tidata; + +/* + * Encode a run of pixels. + */ +static int +PackBitsEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s) +{ + u_char* bp = (u_char*) buf; + tidata_t op, ep, lastliteral; + long n, slop; + int b; + enum { BASE, LITERAL, RUN, LITERAL_RUN } state; + + (void) s; + op = tif->tif_rawcp; + ep = tif->tif_rawdata + tif->tif_rawdatasize; + state = BASE; + lastliteral = 0; + while (cc > 0) { + /* + * Find the longest string of identical bytes. + */ + b = *bp++, cc--, n = 1; + for (; cc > 0 && b == *bp; cc--, bp++) + n++; + again: + if (op + 2 >= ep) { /* insure space for new data */ + /* + * Be careful about writing the last + * literal. Must write up to that point + * and then copy the remainder to the + * front of the buffer. + */ + if (state == LITERAL || state == LITERAL_RUN) { + slop = op - lastliteral; + tif->tif_rawcc += lastliteral - tif->tif_rawcp; + if (!TIFFFlushData1(tif)) + return (-1); + op = tif->tif_rawcp; + while (slop-- > 0) + *op++ = *lastliteral++; + lastliteral = tif->tif_rawcp; + } else { + tif->tif_rawcc += op - tif->tif_rawcp; + if (!TIFFFlushData1(tif)) + return (-1); + op = tif->tif_rawcp; + } + } + switch (state) { + case BASE: /* initial state, set run/literal */ + if (n > 1) { + state = RUN; + if (n > 128) { + *op++ = (tidata) -127; + *op++ = b; + n -= 128; + goto again; + } + *op++ = (tidataval_t)(-(n-1)); + *op++ = b; + } else { + lastliteral = op; + *op++ = 0; + *op++ = b; + state = LITERAL; + } + break; + case LITERAL: /* last object was literal string */ + if (n > 1) { + state = LITERAL_RUN; + if (n > 128) { + *op++ = (tidata) -127; + *op++ = b; + n -= 128; + goto again; + } + *op++ = (tidataval_t)(-(n-1)); /* encode run */ + *op++ = b; + } else { /* extend literal */ + if (++(*lastliteral) == 127) + state = BASE; + *op++ = b; + } + break; + case RUN: /* last object was run */ + if (n > 1) { + if (n > 128) { + *op++ = (tidata) -127; + *op++ = b; + n -= 128; + goto again; + } + *op++ = (tidataval_t)(-(n-1)); + *op++ = b; + } else { + lastliteral = op; + *op++ = 0; + *op++ = b; + state = LITERAL; + } + break; + case LITERAL_RUN: /* literal followed by a run */ + /* + * Check to see if previous run should + * be converted to a literal, in which + * case we convert literal-run-literal + * to a single literal. + */ + if (n == 1 && op[-2] == (tidata) -1 && + *lastliteral < 126) { + state = (((*lastliteral) += 2) == 127 ? + BASE : LITERAL); + op[-2] = op[-1]; /* replicate */ + } else + state = RUN; + goto again; + } + } + tif->tif_rawcc += op - tif->tif_rawcp; + tif->tif_rawcp = op; + return (1); +} + +/* + * Encode a rectangular chunk of pixels. We break it up + * into row-sized pieces to insure that encoded runs do + * not span rows. Otherwise, there can be problems with + * the decoder if data is read, for example, by scanlines + * when it was encoded by strips. + */ +static int +PackBitsEncodeChunk(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + tsize_t rowsize = (tsize_t) tif->tif_data; + + assert(rowsize > 0); + +#ifdef YCBCR_SUPPORT + /* + * YCBCR data isn't really separable into rows, so we + * might as well encode the whole tile/strip as one chunk. + */ + if( tif->tif_dir.td_photometric == PHOTOMETRIC_YCBCR ) + rowsize = (tsize_t) tif->tif_data; +#endif + + while ((long)cc > 0) { + int chunk = rowsize; + + if( cc < chunk ) + chunk = cc; + + if (PackBitsEncode(tif, bp, chunk, s) < 0) + return (-1); + bp += chunk; + cc -= chunk; + } + return (1); +} + +static int +PackBitsDecode(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s) +{ + char *bp; + tsize_t cc; + long n; + int b; + + (void) s; + bp = (char*) tif->tif_rawcp; + cc = tif->tif_rawcc; + while (cc > 0 && (long)occ > 0) { + n = (long) *bp++, cc--; + /* + * Watch out for compilers that + * don't sign extend chars... + */ + if (n >= 128) + n -= 256; + if (n < 0) { /* replicate next byte -n+1 times */ + if (n == -128) /* nop */ + continue; + n = -n + 1; + if( occ < n ) + { + TIFFWarning(tif->tif_name, + "PackBitsDecode: discarding %d bytes " + "to avoid buffer overrun", + n - occ); + n = occ; + } + occ -= n; + b = *bp++, cc--; + while (n-- > 0) + *op++ = b; + } else { /* copy next n+1 bytes literally */ + if (occ < n + 1) + { + TIFFWarning(tif->tif_name, + "PackBitsDecode: discarding %d bytes " + "to avoid buffer overrun", + n - occ + 1); + n = occ - 1; + } + _TIFFmemcpy(op, bp, ++n); + op += n; occ -= n; + bp += n; cc -= n; + } + } + tif->tif_rawcp = (tidata_t) bp; + tif->tif_rawcc = cc; + if (occ > 0) { + TIFFError(tif->tif_name, + "PackBitsDecode: Not enough data for scanline %ld", + (long) tif->tif_row); + return (0); + } + return (1); +} + +int +TIFFInitPackBits(TIFF* tif, int scheme) +{ + (void) scheme; + tif->tif_decoderow = PackBitsDecode; + tif->tif_decodestrip = PackBitsDecode; + tif->tif_decodetile = PackBitsDecode; + tif->tif_preencode = PackBitsPreEncode; + tif->tif_encoderow = PackBitsEncode; + tif->tif_encodestrip = PackBitsEncodeChunk; + tif->tif_encodetile = PackBitsEncodeChunk; + return (1); +} +#endif /* PACKBITS_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_pixarlog.c b/SlnkDWFImpl/CxImage/tiff/tif_pixarlog.c new file mode 100644 index 0000000..3bc0a28 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_pixarlog.c @@ -0,0 +1,1309 @@ +/* + * Copyright (c) 1996-1997 Sam Leffler + * Copyright (c) 1996 Pixar + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Pixar, Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Pixar, Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL PIXAR, SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef PIXARLOG_SUPPORT + +/* + * TIFF Library. + * PixarLog Compression Support + * + * Contributed by Dan McCoy. + * + * PixarLog film support uses the TIFF library to store companded + * 11 bit values into a tiff file, which are compressed using the + * zip compressor. + * + * The codec can take as input and produce as output 32-bit IEEE float values + * as well as 16-bit or 8-bit unsigned integer values. + * + * On writing any of the above are converted into the internal + * 11-bit log format. In the case of 8 and 16 bit values, the + * input is assumed to be unsigned linear color values that represent + * the range 0-1. In the case of IEEE values, the 0-1 range is assumed to + * be the normal linear color range, in addition over 1 values are + * accepted up to a value of about 25.0 to encode "hot" hightlights and such. + * The encoding is lossless for 8-bit values, slightly lossy for the + * other bit depths. The actual color precision should be better + * than the human eye can perceive with extra room to allow for + * error introduced by further image computation. As with any quantized + * color format, it is possible to perform image calculations which + * expose the quantization error. This format should certainly be less + * susceptable to such errors than standard 8-bit encodings, but more + * susceptable than straight 16-bit or 32-bit encodings. + * + * On reading the internal format is converted to the desired output format. + * The program can request which format it desires by setting the internal + * pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values: + * PIXARLOGDATAFMT_FLOAT = provide IEEE float values. + * PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values + * PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values + * + * alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer + * values with the difference that if there are exactly three or four channels + * (rgb or rgba) it swaps the channel order (bgr or abgr). + * + * PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly + * packed in 16-bit values. However no tools are supplied for interpreting + * these values. + * + * "hot" (over 1.0) areas written in floating point get clamped to + * 1.0 in the integer data types. + * + * When the file is closed after writing, the bit depth and sample format + * are set always to appear as if 8-bit data has been written into it. + * That way a naive program unaware of the particulars of the encoding + * gets the format it is most likely able to handle. + * + * The codec does it's own horizontal differencing step on the coded + * values so the libraries predictor stuff should be turned off. + * The codec also handle byte swapping the encoded values as necessary + * since the library does not have the information necessary + * to know the bit depth of the raw unencoded buffer. + * + */ + +#include "tif_predict.h" +#include "zlib.h" +#include "zutil.h" + +#include +#include +#include +#include + +/* Tables for converting to/from 11 bit coded values */ + +#define TSIZE 2048 /* decode table size (11-bit tokens) */ +#define TSIZEP1 2049 /* Plus one for slop */ +#define ONE 1250 /* token value of 1.0 exactly */ +#define RATIO 1.004 /* nominal ratio for log part */ + +#define CODE_MASK 0x7ff /* 11 bits. */ + +static float Fltsize; +static float LogK1, LogK2; + +#define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); } + +static void +horizontalAccumulateF(uint16 *wp, int n, int stride, float *op, + float *ToLinearF) +{ + register unsigned int cr, cg, cb, ca, mask; + register float t0, t1, t2, t3; + + if (n >= stride) { + mask = CODE_MASK; + if (stride == 3) { + t0 = ToLinearF[cr = wp[0]]; + t1 = ToLinearF[cg = wp[1]]; + t2 = ToLinearF[cb = wp[2]]; + op[0] = t0; + op[1] = t1; + op[2] = t2; + n -= 3; + while (n > 0) { + wp += 3; + op += 3; + n -= 3; + t0 = ToLinearF[(cr += wp[0]) & mask]; + t1 = ToLinearF[(cg += wp[1]) & mask]; + t2 = ToLinearF[(cb += wp[2]) & mask]; + op[0] = t0; + op[1] = t1; + op[2] = t2; + } + } else if (stride == 4) { + t0 = ToLinearF[cr = wp[0]]; + t1 = ToLinearF[cg = wp[1]]; + t2 = ToLinearF[cb = wp[2]]; + t3 = ToLinearF[ca = wp[3]]; + op[0] = t0; + op[1] = t1; + op[2] = t2; + op[3] = t3; + n -= 4; + while (n > 0) { + wp += 4; + op += 4; + n -= 4; + t0 = ToLinearF[(cr += wp[0]) & mask]; + t1 = ToLinearF[(cg += wp[1]) & mask]; + t2 = ToLinearF[(cb += wp[2]) & mask]; + t3 = ToLinearF[(ca += wp[3]) & mask]; + op[0] = t0; + op[1] = t1; + op[2] = t2; + op[3] = t3; + } + } else { + REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++) + n -= stride; + while (n > 0) { + REPEAT(stride, + wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++) + n -= stride; + } + } + } +} + +static void +horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op, + float *ToLinearF) +{ + register unsigned int cr, cg, cb, ca, mask; + register float t0, t1, t2, t3; + +#define SCALE12 2048.0 +#define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071) + + if (n >= stride) { + mask = CODE_MASK; + if (stride == 3) { + t0 = ToLinearF[cr = wp[0]] * SCALE12; + t1 = ToLinearF[cg = wp[1]] * SCALE12; + t2 = ToLinearF[cb = wp[2]] * SCALE12; + op[0] = CLAMP12(t0); + op[1] = CLAMP12(t1); + op[2] = CLAMP12(t2); + n -= 3; + while (n > 0) { + wp += 3; + op += 3; + n -= 3; + t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; + t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; + t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; + op[0] = CLAMP12(t0); + op[1] = CLAMP12(t1); + op[2] = CLAMP12(t2); + } + } else if (stride == 4) { + t0 = ToLinearF[cr = wp[0]] * SCALE12; + t1 = ToLinearF[cg = wp[1]] * SCALE12; + t2 = ToLinearF[cb = wp[2]] * SCALE12; + t3 = ToLinearF[ca = wp[3]] * SCALE12; + op[0] = CLAMP12(t0); + op[1] = CLAMP12(t1); + op[2] = CLAMP12(t2); + op[3] = CLAMP12(t3); + n -= 4; + while (n > 0) { + wp += 4; + op += 4; + n -= 4; + t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; + t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; + t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; + t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12; + op[0] = CLAMP12(t0); + op[1] = CLAMP12(t1); + op[2] = CLAMP12(t2); + op[3] = CLAMP12(t3); + } + } else { + REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12; + *op = CLAMP12(t0); wp++; op++) + n -= stride; + while (n > 0) { + REPEAT(stride, + wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12; + *op = CLAMP12(t0); wp++; op++) + n -= stride; + } + } + } +} + +static void +horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op, + uint16 *ToLinear16) +{ + register unsigned int cr, cg, cb, ca, mask; + + if (n >= stride) { + mask = CODE_MASK; + if (stride == 3) { + op[0] = ToLinear16[cr = wp[0]]; + op[1] = ToLinear16[cg = wp[1]]; + op[2] = ToLinear16[cb = wp[2]]; + n -= 3; + while (n > 0) { + wp += 3; + op += 3; + n -= 3; + op[0] = ToLinear16[(cr += wp[0]) & mask]; + op[1] = ToLinear16[(cg += wp[1]) & mask]; + op[2] = ToLinear16[(cb += wp[2]) & mask]; + } + } else if (stride == 4) { + op[0] = ToLinear16[cr = wp[0]]; + op[1] = ToLinear16[cg = wp[1]]; + op[2] = ToLinear16[cb = wp[2]]; + op[3] = ToLinear16[ca = wp[3]]; + n -= 4; + while (n > 0) { + wp += 4; + op += 4; + n -= 4; + op[0] = ToLinear16[(cr += wp[0]) & mask]; + op[1] = ToLinear16[(cg += wp[1]) & mask]; + op[2] = ToLinear16[(cb += wp[2]) & mask]; + op[3] = ToLinear16[(ca += wp[3]) & mask]; + } + } else { + REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++) + n -= stride; + while (n > 0) { + REPEAT(stride, + wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++) + n -= stride; + } + } + } +} + +/* + * Returns the log encoded 11-bit values with the horizontal + * differencing undone. + */ +static void +horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op) +{ + register unsigned int cr, cg, cb, ca, mask; + + if (n >= stride) { + mask = CODE_MASK; + if (stride == 3) { + op[0] = cr = wp[0]; op[1] = cg = wp[1]; op[2] = cb = wp[2]; + n -= 3; + while (n > 0) { + wp += 3; + op += 3; + n -= 3; + op[0] = (cr += wp[0]) & mask; + op[1] = (cg += wp[1]) & mask; + op[2] = (cb += wp[2]) & mask; + } + } else if (stride == 4) { + op[0] = cr = wp[0]; op[1] = cg = wp[1]; + op[2] = cb = wp[2]; op[3] = ca = wp[3]; + n -= 4; + while (n > 0) { + wp += 4; + op += 4; + n -= 4; + op[0] = (cr += wp[0]) & mask; + op[1] = (cg += wp[1]) & mask; + op[2] = (cb += wp[2]) & mask; + op[3] = (ca += wp[3]) & mask; + } + } else { + REPEAT(stride, *op = *wp&mask; wp++; op++) + n -= stride; + while (n > 0) { + REPEAT(stride, + wp[stride] += *wp; *op = *wp&mask; wp++; op++) + n -= stride; + } + } + } +} + +static void +horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op, + unsigned char *ToLinear8) +{ + register unsigned int cr, cg, cb, ca, mask; + + if (n >= stride) { + mask = CODE_MASK; + if (stride == 3) { + op[0] = ToLinear8[cr = wp[0]]; + op[1] = ToLinear8[cg = wp[1]]; + op[2] = ToLinear8[cb = wp[2]]; + n -= 3; + while (n > 0) { + n -= 3; + wp += 3; + op += 3; + op[0] = ToLinear8[(cr += wp[0]) & mask]; + op[1] = ToLinear8[(cg += wp[1]) & mask]; + op[2] = ToLinear8[(cb += wp[2]) & mask]; + } + } else if (stride == 4) { + op[0] = ToLinear8[cr = wp[0]]; + op[1] = ToLinear8[cg = wp[1]]; + op[2] = ToLinear8[cb = wp[2]]; + op[3] = ToLinear8[ca = wp[3]]; + n -= 4; + while (n > 0) { + n -= 4; + wp += 4; + op += 4; + op[0] = ToLinear8[(cr += wp[0]) & mask]; + op[1] = ToLinear8[(cg += wp[1]) & mask]; + op[2] = ToLinear8[(cb += wp[2]) & mask]; + op[3] = ToLinear8[(ca += wp[3]) & mask]; + } + } else { + REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) + n -= stride; + while (n > 0) { + REPEAT(stride, + wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) + n -= stride; + } + } + } +} + + +static void +horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op, + unsigned char *ToLinear8) +{ + register unsigned int cr, cg, cb, ca, mask; + register unsigned char t0, t1, t2, t3; + + if (n >= stride) { + mask = CODE_MASK; + if (stride == 3) { + op[0] = 0; + t1 = ToLinear8[cb = wp[2]]; + t2 = ToLinear8[cg = wp[1]]; + t3 = ToLinear8[cr = wp[0]]; + op[1] = t1; + op[2] = t2; + op[3] = t3; + n -= 3; + while (n > 0) { + n -= 3; + wp += 3; + op += 4; + op[0] = 0; + t1 = ToLinear8[(cb += wp[2]) & mask]; + t2 = ToLinear8[(cg += wp[1]) & mask]; + t3 = ToLinear8[(cr += wp[0]) & mask]; + op[1] = t1; + op[2] = t2; + op[3] = t3; + } + } else if (stride == 4) { + t0 = ToLinear8[ca = wp[3]]; + t1 = ToLinear8[cb = wp[2]]; + t2 = ToLinear8[cg = wp[1]]; + t3 = ToLinear8[cr = wp[0]]; + op[0] = t0; + op[1] = t1; + op[2] = t2; + op[3] = t3; + n -= 4; + while (n > 0) { + n -= 4; + wp += 4; + op += 4; + t0 = ToLinear8[(ca += wp[3]) & mask]; + t1 = ToLinear8[(cb += wp[2]) & mask]; + t2 = ToLinear8[(cg += wp[1]) & mask]; + t3 = ToLinear8[(cr += wp[0]) & mask]; + op[0] = t0; + op[1] = t1; + op[2] = t2; + op[3] = t3; + } + } else { + REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) + n -= stride; + while (n > 0) { + REPEAT(stride, + wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) + n -= stride; + } + } + } +} + +/* + * State block for each open TIFF + * file using PixarLog compression/decompression. + */ +typedef struct { + TIFFPredictorState predict; + z_stream stream; + uint16 *tbuf; + uint16 stride; + int state; + int user_datafmt; + int quality; +#define PLSTATE_INIT 1 + + TIFFVSetMethod vgetparent; /* super-class method */ + TIFFVSetMethod vsetparent; /* super-class method */ + + float *ToLinearF; + uint16 *ToLinear16; + unsigned char *ToLinear8; + uint16 *FromLT2; + uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ + uint16 *From8; + +} PixarLogState; + +static int +PixarLogMakeTables(PixarLogState *sp) +{ + +/* + * We make several tables here to convert between various external + * representations (float, 16-bit, and 8-bit) and the internal + * 11-bit companded representation. The 11-bit representation has two + * distinct regions. A linear bottom end up through .018316 in steps + * of about .000073, and a region of constant ratio up to about 25. + * These floating point numbers are stored in the main table ToLinearF. + * All other tables are derived from this one. The tables (and the + * ratios) are continuous at the internal seam. + */ + + int nlin, lt2size; + int i, j; + double b, c, linstep, max; + double k, v, dv, r, lr2, r2; + float *ToLinearF; + uint16 *ToLinear16; + unsigned char *ToLinear8; + uint16 *FromLT2; + uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ + uint16 *From8; + + c = log(RATIO); + nlin = 1./c; /* nlin must be an integer */ + c = 1./nlin; + b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */ + linstep = b*c*exp(1.); + + LogK1 = 1./c; /* if (v >= 2) token = k1*log(v*k2) */ + LogK2 = 1./b; + lt2size = (2./linstep)+1; + FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16)); + From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16)); + From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16)); + ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float)); + ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16)); + ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char)); + if (FromLT2 == NULL || From14 == NULL || From8 == NULL || + ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) { + if (FromLT2) _TIFFfree(FromLT2); + if (From14) _TIFFfree(From14); + if (From8) _TIFFfree(From8); + if (ToLinearF) _TIFFfree(ToLinearF); + if (ToLinear16) _TIFFfree(ToLinear16); + if (ToLinear8) _TIFFfree(ToLinear8); + sp->FromLT2 = NULL; + sp->From14 = NULL; + sp->From8 = NULL; + sp->ToLinearF = NULL; + sp->ToLinear16 = NULL; + sp->ToLinear8 = NULL; + return 0; + } + + j = 0; + + for (i = 0; i < nlin; i++) { + v = i * linstep; + ToLinearF[j++] = v; + } + + for (i = nlin; i < TSIZE; i++) + ToLinearF[j++] = b*exp(c*i); + + ToLinearF[2048] = ToLinearF[2047]; + + for (i = 0; i < TSIZEP1; i++) { + v = ToLinearF[i]*65535.0 + 0.5; + ToLinear16[i] = (v > 65535.0) ? 65535 : v; + v = ToLinearF[i]*255.0 + 0.5; + ToLinear8[i] = (v > 255.0) ? 255 : v; + } + + j = 0; + for (i = 0; i < lt2size; i++) { + if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1]) + j++; + FromLT2[i] = j; + } + + /* + * Since we lose info anyway on 16-bit data, we set up a 14-bit + * table and shift 16-bit values down two bits on input. + * saves a little table space. + */ + j = 0; + for (i = 0; i < 16384; i++) { + while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1]) + j++; + From14[i] = j; + } + + j = 0; + for (i = 0; i < 256; i++) { + while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1]) + j++; + From8[i] = j; + } + + Fltsize = lt2size/2; + + sp->ToLinearF = ToLinearF; + sp->ToLinear16 = ToLinear16; + sp->ToLinear8 = ToLinear8; + sp->FromLT2 = FromLT2; + sp->From14 = From14; + sp->From8 = From8; + + return 1; +} + +#define DecoderState(tif) ((PixarLogState*) (tif)->tif_data) +#define EncoderState(tif) ((PixarLogState*) (tif)->tif_data) + +static int PixarLogEncode(TIFF*, tidata_t, tsize_t, tsample_t); +static int PixarLogDecode(TIFF*, tidata_t, tsize_t, tsample_t); + +#define N(a) (sizeof(a)/sizeof(a[0])) +#define PIXARLOGDATAFMT_UNKNOWN -1 + +static int +PixarLogGuessDataFmt(TIFFDirectory *td) +{ + int guess = PIXARLOGDATAFMT_UNKNOWN; + int format = td->td_sampleformat; + + /* If the user didn't tell us his datafmt, + * take our best guess from the bitspersample. + */ + switch (td->td_bitspersample) { + case 32: + if (format == SAMPLEFORMAT_IEEEFP) + guess = PIXARLOGDATAFMT_FLOAT; + break; + case 16: + if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) + guess = PIXARLOGDATAFMT_16BIT; + break; + case 12: + if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT) + guess = PIXARLOGDATAFMT_12BITPICIO; + break; + case 11: + if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) + guess = PIXARLOGDATAFMT_11BITLOG; + break; + case 8: + if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) + guess = PIXARLOGDATAFMT_8BIT; + break; + } + + return guess; +} + +static int +PixarLogSetupDecode(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + PixarLogState* sp = DecoderState(tif); + static const char module[] = "PixarLogSetupDecode"; + + assert(sp != NULL); + + /* Make sure no byte swapping happens on the data + * after decompression. */ + tif->tif_postdecode = _TIFFNoPostDecode; + + /* for some reason, we can't do this in TIFFInitPixarLog */ + + sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? + td->td_samplesperpixel : 1); + sp->tbuf = (uint16 *) _TIFFmalloc(sp->stride * + td->td_imagewidth * td->td_rowsperstrip * sizeof(uint16)); + if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) + sp->user_datafmt = PixarLogGuessDataFmt(td); + if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { + TIFFError(module, + "PixarLog compression can't handle bits depth/data format combination (depth: %d)", + td->td_bitspersample); + return (0); + } + + if (inflateInit(&sp->stream) != Z_OK) { + TIFFError(module, "%s: %s", tif->tif_name, sp->stream.msg); + return (0); + } else { + sp->state |= PLSTATE_INIT; + return (1); + } +} + +/* + * Setup state for decoding a strip. + */ +static int +PixarLogPreDecode(TIFF* tif, tsample_t s) +{ + TIFFDirectory *td = &tif->tif_dir; + PixarLogState* sp = DecoderState(tif); + + (void) s; + assert(sp != NULL); + sp->stream.next_in = tif->tif_rawdata; + sp->stream.avail_in = tif->tif_rawcc; + return (inflateReset(&sp->stream) == Z_OK); +} + +static int +PixarLogDecode(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s) +{ + TIFFDirectory *td = &tif->tif_dir; + PixarLogState* sp = DecoderState(tif); + static const char module[] = "PixarLogDecode"; + int i, nsamples, llen; + uint16 *up; + + switch (sp->user_datafmt) { + case PIXARLOGDATAFMT_FLOAT: + nsamples = occ / sizeof(float); /* XXX float == 32 bits */ + break; + case PIXARLOGDATAFMT_16BIT: + case PIXARLOGDATAFMT_12BITPICIO: + case PIXARLOGDATAFMT_11BITLOG: + nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */ + break; + case PIXARLOGDATAFMT_8BIT: + case PIXARLOGDATAFMT_8BITABGR: + nsamples = occ; + break; + default: + TIFFError(tif->tif_name, + "%d bit input not supported in PixarLog", + td->td_bitspersample); + return 0; + } + + llen = sp->stride * td->td_imagewidth; + + (void) s; + assert(sp != NULL); + sp->stream.next_out = (unsigned char *) sp->tbuf; + sp->stream.avail_out = nsamples * sizeof(uint16); + do { + int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); + if (state == Z_STREAM_END) { + break; /* XXX */ + } + if (state == Z_DATA_ERROR) { + TIFFError(module, + "%s: Decoding error at scanline %d, %s", + tif->tif_name, tif->tif_row, sp->stream.msg); + if (inflateSync(&sp->stream) != Z_OK) + return (0); + continue; + } + if (state != Z_OK) { + TIFFError(module, "%s: zlib error: %s", + tif->tif_name, sp->stream.msg); + return (0); + } + } while (sp->stream.avail_out > 0); + + /* hopefully, we got all the bytes we needed */ + if (sp->stream.avail_out != 0) { + TIFFError(module, + "%s: Not enough data at scanline %d (short %d bytes)", + tif->tif_name, tif->tif_row, sp->stream.avail_out); + return (0); + } + + up = sp->tbuf; + /* Swap bytes in the data if from a different endian machine. */ + if (tif->tif_flags & TIFF_SWAB) + TIFFSwabArrayOfShort(up, nsamples); + + for (i = 0; i < nsamples; i += llen, up += llen) { + switch (sp->user_datafmt) { + case PIXARLOGDATAFMT_FLOAT: + horizontalAccumulateF(up, llen, sp->stride, + (float *)op, sp->ToLinearF); + op += llen * sizeof(float); + break; + case PIXARLOGDATAFMT_16BIT: + horizontalAccumulate16(up, llen, sp->stride, + (uint16 *)op, sp->ToLinear16); + op += llen * sizeof(uint16); + break; + case PIXARLOGDATAFMT_12BITPICIO: + horizontalAccumulate12(up, llen, sp->stride, + (int16 *)op, sp->ToLinearF); + op += llen * sizeof(int16); + break; + case PIXARLOGDATAFMT_11BITLOG: + horizontalAccumulate11(up, llen, sp->stride, + (uint16 *)op); + op += llen * sizeof(uint16); + break; + case PIXARLOGDATAFMT_8BIT: + horizontalAccumulate8(up, llen, sp->stride, + (unsigned char *)op, sp->ToLinear8); + op += llen * sizeof(unsigned char); + break; + case PIXARLOGDATAFMT_8BITABGR: + horizontalAccumulate8abgr(up, llen, sp->stride, + (unsigned char *)op, sp->ToLinear8); + op += llen * sizeof(unsigned char); + break; + default: + TIFFError(tif->tif_name, + "PixarLogDecode: unsupported bits/sample: %d", + td->td_bitspersample); + return (0); + } + } + + return (1); +} + +static int +PixarLogSetupEncode(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + PixarLogState* sp = EncoderState(tif); + static const char module[] = "PixarLogSetupEncode"; + + assert(sp != NULL); + + /* for some reason, we can't do this in TIFFInitPixarLog */ + + sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? + td->td_samplesperpixel : 1); + sp->tbuf = (uint16 *) _TIFFmalloc(sp->stride * + td->td_imagewidth * td->td_rowsperstrip * sizeof(uint16)); + if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) + sp->user_datafmt = PixarLogGuessDataFmt(td); + if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { + TIFFError(module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample); + return (0); + } + + if (deflateInit(&sp->stream, sp->quality) != Z_OK) { + TIFFError(module, "%s: %s", tif->tif_name, sp->stream.msg); + return (0); + } else { + sp->state |= PLSTATE_INIT; + return (1); + } +} + +/* + * Reset encoding state at the start of a strip. + */ +static int +PixarLogPreEncode(TIFF* tif, tsample_t s) +{ + TIFFDirectory *td = &tif->tif_dir; + PixarLogState *sp = EncoderState(tif); + + (void) s; + assert(sp != NULL); + sp->stream.next_out = tif->tif_rawdata; + sp->stream.avail_out = tif->tif_rawdatasize; + return (deflateReset(&sp->stream) == Z_OK); +} + +static void +horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2) +{ + + register int r1, g1, b1, a1, r2, g2, b2, a2, mask; + register float fltsize = Fltsize; + +#define CLAMP(v) ( (v<(float)0.) ? 0 \ + : (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \ + : (v>(float)24.2) ? 2047 \ + : LogK1*log(v*LogK2) + 0.5 ) + + mask = CODE_MASK; + if (n >= stride) { + if (stride == 3) { + r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); + b2 = wp[2] = CLAMP(ip[2]); + n -= 3; + while (n > 0) { + n -= 3; + wp += 3; + ip += 3; + r1 = CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1; + g1 = CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1; + b1 = CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1; + } + } else if (stride == 4) { + r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); + b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); + n -= 4; + while (n > 0) { + n -= 4; + wp += 4; + ip += 4; + r1 = CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1; + g1 = CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1; + b1 = CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1; + a1 = CLAMP(ip[3]); wp[3] = (a1-a2) & mask; a2 = a1; + } + } else { + ip += n - 1; /* point to last one */ + wp += n - 1; /* point to last one */ + n -= stride; + while (n > 0) { + REPEAT(stride, wp[0] = CLAMP(ip[0]); + wp[stride] -= wp[0]; + wp[stride] &= mask; + wp--; ip--) + n -= stride; + } + REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) + } + } +} + +static void +horizontalDifference16(unsigned short *ip, int n, int stride, + unsigned short *wp, uint16 *From14) +{ + register int r1, g1, b1, a1, r2, g2, b2, a2, mask; + +/* assumption is unsigned pixel values */ +#undef CLAMP +#define CLAMP(v) From14[(v) >> 2] + + mask = CODE_MASK; + if (n >= stride) { + if (stride == 3) { + r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); + b2 = wp[2] = CLAMP(ip[2]); + n -= 3; + while (n > 0) { + n -= 3; + wp += 3; + ip += 3; + r1 = CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1; + g1 = CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1; + b1 = CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1; + } + } else if (stride == 4) { + r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); + b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); + n -= 4; + while (n > 0) { + n -= 4; + wp += 4; + ip += 4; + r1 = CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1; + g1 = CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1; + b1 = CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1; + a1 = CLAMP(ip[3]); wp[3] = (a1-a2) & mask; a2 = a1; + } + } else { + ip += n - 1; /* point to last one */ + wp += n - 1; /* point to last one */ + n -= stride; + while (n > 0) { + REPEAT(stride, wp[0] = CLAMP(ip[0]); + wp[stride] -= wp[0]; + wp[stride] &= mask; + wp--; ip--) + n -= stride; + } + REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) + } + } +} + + +static void +horizontalDifference8(unsigned char *ip, int n, int stride, + unsigned short *wp, uint16 *From8) +{ + register int r1, g1, b1, a1, r2, g2, b2, a2, mask; + +#undef CLAMP +#define CLAMP(v) (From8[(v)]) + + mask = CODE_MASK; + if (n >= stride) { + if (stride == 3) { + r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); + b2 = wp[2] = CLAMP(ip[2]); + n -= 3; + while (n > 0) { + n -= 3; + r1 = CLAMP(ip[3]); wp[3] = (r1-r2) & mask; r2 = r1; + g1 = CLAMP(ip[4]); wp[4] = (g1-g2) & mask; g2 = g1; + b1 = CLAMP(ip[5]); wp[5] = (b1-b2) & mask; b2 = b1; + wp += 3; + ip += 3; + } + } else if (stride == 4) { + r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); + b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); + n -= 4; + while (n > 0) { + n -= 4; + r1 = CLAMP(ip[4]); wp[4] = (r1-r2) & mask; r2 = r1; + g1 = CLAMP(ip[5]); wp[5] = (g1-g2) & mask; g2 = g1; + b1 = CLAMP(ip[6]); wp[6] = (b1-b2) & mask; b2 = b1; + a1 = CLAMP(ip[7]); wp[7] = (a1-a2) & mask; a2 = a1; + wp += 4; + ip += 4; + } + } else { + wp += n + stride - 1; /* point to last one */ + ip += n + stride - 1; /* point to last one */ + n -= stride; + while (n > 0) { + REPEAT(stride, wp[0] = CLAMP(ip[0]); + wp[stride] -= wp[0]; + wp[stride] &= mask; + wp--; ip--) + n -= stride; + } + REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) + } + } +} + +/* + * Encode a chunk of pixels. + */ +static int +PixarLogEncode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + TIFFDirectory *td = &tif->tif_dir; + PixarLogState *sp = EncoderState(tif); + static const char module[] = "PixarLogEncode"; + int i, n, llen; + unsigned short * up; + + (void) s; + + switch (sp->user_datafmt) { + case PIXARLOGDATAFMT_FLOAT: + n = cc / sizeof(float); /* XXX float == 32 bits */ + break; + case PIXARLOGDATAFMT_16BIT: + case PIXARLOGDATAFMT_12BITPICIO: + case PIXARLOGDATAFMT_11BITLOG: + n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */ + break; + case PIXARLOGDATAFMT_8BIT: + case PIXARLOGDATAFMT_8BITABGR: + n = cc; + break; + default: + TIFFError(tif->tif_name, + "%d bit input not supported in PixarLog", + td->td_bitspersample); + return 0; + } + + llen = sp->stride * td->td_imagewidth; + + for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) { + switch (sp->user_datafmt) { + case PIXARLOGDATAFMT_FLOAT: + horizontalDifferenceF((float *)bp, llen, + sp->stride, up, sp->FromLT2); + bp += llen * sizeof(float); + break; + case PIXARLOGDATAFMT_16BIT: + horizontalDifference16((uint16 *)bp, llen, + sp->stride, up, sp->From14); + bp += llen * sizeof(uint16); + break; + case PIXARLOGDATAFMT_8BIT: + horizontalDifference8((unsigned char *)bp, llen, + sp->stride, up, sp->From8); + bp += llen * sizeof(unsigned char); + break; + default: + TIFFError(tif->tif_name, + "%d bit input not supported in PixarLog", + td->td_bitspersample); + return 0; + } + } + + sp->stream.next_in = (unsigned char *) sp->tbuf; + sp->stream.avail_in = n * sizeof(uint16); + + do { + if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) { + TIFFError(module, "%s: Encoder error: %s", + tif->tif_name, sp->stream.msg); + return (0); + } + if (sp->stream.avail_out == 0) { + tif->tif_rawcc = tif->tif_rawdatasize; + TIFFFlushData1(tif); + sp->stream.next_out = tif->tif_rawdata; + sp->stream.avail_out = tif->tif_rawdatasize; + } + } while (sp->stream.avail_in > 0); + return (1); +} + +/* + * Finish off an encoded strip by flushing the last + * string and tacking on an End Of Information code. + */ + +static int +PixarLogPostEncode(TIFF* tif) +{ + PixarLogState *sp = EncoderState(tif); + static const char module[] = "PixarLogPostEncode"; + int state; + + sp->stream.avail_in = 0; + + do { + state = deflate(&sp->stream, Z_FINISH); + switch (state) { + case Z_STREAM_END: + case Z_OK: + if (sp->stream.avail_out != tif->tif_rawdatasize) { + tif->tif_rawcc = + tif->tif_rawdatasize - sp->stream.avail_out; + TIFFFlushData1(tif); + sp->stream.next_out = tif->tif_rawdata; + sp->stream.avail_out = tif->tif_rawdatasize; + } + break; + default: + TIFFError(module, "%s: zlib error: %s", + tif->tif_name, sp->stream.msg); + return (0); + } + } while (state != Z_STREAM_END); + return (1); +} + +static void +PixarLogClose(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + + /* In a really sneaky maneuver, on close, we covertly modify both + * bitspersample and sampleformat in the directory to indicate + * 8-bit linear. This way, the decode "just works" even for + * readers that don't know about PixarLog, or how to set + * the PIXARLOGDATFMT pseudo-tag. + */ + td->td_bitspersample = 8; + td->td_sampleformat = SAMPLEFORMAT_UINT; +} + +static void +PixarLogCleanup(TIFF* tif) +{ + PixarLogState* sp = (PixarLogState*) tif->tif_data; + + if (sp) { + if (sp->FromLT2) _TIFFfree(sp->FromLT2); + if (sp->From14) _TIFFfree(sp->From14); + if (sp->From8) _TIFFfree(sp->From8); + if (sp->ToLinearF) _TIFFfree(sp->ToLinearF); + if (sp->ToLinear16) _TIFFfree(sp->ToLinear16); + if (sp->ToLinear8) _TIFFfree(sp->ToLinear8); + if (sp->state&PLSTATE_INIT) { + if (tif->tif_mode == O_RDONLY) + inflateEnd(&sp->stream); + else + deflateEnd(&sp->stream); + } + if (sp->tbuf) + _TIFFfree(sp->tbuf); + _TIFFfree(sp); + tif->tif_data = NULL; + } +} + +static int +PixarLogVSetField(TIFF* tif, ttag_t tag, va_list ap) +{ + PixarLogState *sp = (PixarLogState *)tif->tif_data; + int result; + static const char module[] = "PixarLogVSetField"; + + switch (tag) { + case TIFFTAG_PIXARLOGQUALITY: + sp->quality = va_arg(ap, int); + if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) { + if (deflateParams(&sp->stream, + sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) { + TIFFError(module, "%s: zlib error: %s", + tif->tif_name, sp->stream.msg); + return (0); + } + } + return (1); + case TIFFTAG_PIXARLOGDATAFMT: + sp->user_datafmt = va_arg(ap, int); + /* Tweak the TIFF header so that the rest of libtiff knows what + * size of data will be passed between app and library, and + * assume that the app knows what it is doing and is not + * confused by these header manipulations... + */ + switch (sp->user_datafmt) { + case PIXARLOGDATAFMT_8BIT: + case PIXARLOGDATAFMT_8BITABGR: + TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); + TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); + break; + case PIXARLOGDATAFMT_11BITLOG: + TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); + TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); + break; + case PIXARLOGDATAFMT_12BITPICIO: + TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); + TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT); + break; + case PIXARLOGDATAFMT_16BIT: + TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); + TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); + break; + case PIXARLOGDATAFMT_FLOAT: + TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32); + TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP); + break; + } + /* + * Must recalculate sizes should bits/sample change. + */ + tif->tif_tilesize = TIFFTileSize(tif); + tif->tif_scanlinesize = TIFFScanlineSize(tif); + result = 1; /* NB: pseudo tag */ + break; + default: + result = (*sp->vsetparent)(tif, tag, ap); + } + return (result); +} + +static int +PixarLogVGetField(TIFF* tif, ttag_t tag, va_list ap) +{ + PixarLogState *sp = (PixarLogState *)tif->tif_data; + + switch (tag) { + case TIFFTAG_PIXARLOGQUALITY: + *va_arg(ap, int*) = sp->quality; + break; + case TIFFTAG_PIXARLOGDATAFMT: + *va_arg(ap, int*) = sp->user_datafmt; + break; + default: + return (*sp->vgetparent)(tif, tag, ap); + } + return (1); +} + +static const TIFFFieldInfo pixarlogFieldInfo[] = { + {TIFFTAG_PIXARLOGDATAFMT,0,0,TIFF_ANY, FIELD_PSEUDO,FALSE,FALSE,""}, + {TIFFTAG_PIXARLOGQUALITY,0,0,TIFF_ANY, FIELD_PSEUDO,FALSE,FALSE,""} +}; + +int +TIFFInitPixarLog(TIFF* tif, int scheme) +{ + PixarLogState* sp; + + assert(scheme == COMPRESSION_PIXARLOG); + + /* + * Allocate state block so tag methods have storage to record values. + */ + tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (PixarLogState)); + if (tif->tif_data == NULL) + goto bad; + sp = (PixarLogState*) tif->tif_data; + memset(sp, 0, sizeof (*sp)); + sp->stream.data_type = Z_BINARY; + sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN; + + /* + * Install codec methods. + */ + tif->tif_setupdecode = PixarLogSetupDecode; + tif->tif_predecode = PixarLogPreDecode; + tif->tif_decoderow = PixarLogDecode; + tif->tif_decodestrip = PixarLogDecode; + tif->tif_decodetile = PixarLogDecode; + tif->tif_setupencode = PixarLogSetupEncode; + tif->tif_preencode = PixarLogPreEncode; + tif->tif_postencode = PixarLogPostEncode; + tif->tif_encoderow = PixarLogEncode; + tif->tif_encodestrip = PixarLogEncode; + tif->tif_encodetile = PixarLogEncode; + tif->tif_close = PixarLogClose; + tif->tif_cleanup = PixarLogCleanup; + + /* Override SetField so we can handle our private pseudo-tag */ + _TIFFMergeFieldInfo(tif, pixarlogFieldInfo, N(pixarlogFieldInfo)); + sp->vgetparent = tif->tif_vgetfield; + tif->tif_vgetfield = PixarLogVGetField; /* hook for codec tags */ + sp->vsetparent = tif->tif_vsetfield; + tif->tif_vsetfield = PixarLogVSetField; /* hook for codec tags */ + + /* Default values for codec-specific fields */ + sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */ + sp->state = 0; + + /* we don't wish to use the predictor, + * the default is none, which predictor value 1 + */ + (void) TIFFPredictorInit(tif); + + /* + * build the companding tables + */ + PixarLogMakeTables(sp); + + return (1); +bad: + TIFFError("TIFFInitPixarLog", "No space for PixarLog state block"); + return (0); +} +#endif /* PIXARLOG_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_predict.c b/SlnkDWFImpl/CxImage/tiff/tif_predict.c new file mode 100644 index 0000000..53d6926 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_predict.c @@ -0,0 +1,461 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_predict.c,v 1.2 1999/11/27 21:43:28 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Predictor Tag Support (used by multiple codecs). + */ +#include "tiffiop.h" +#include "tif_predict.h" + +#include + +#define PredictorState(tif) ((TIFFPredictorState*) (tif)->tif_data) + +static void horAcc8(TIFF*, tidata_t, tsize_t); +static void horAcc16(TIFF*, tidata_t, tsize_t); +static void swabHorAcc16(TIFF*, tidata_t, tsize_t); +static void horDiff8(TIFF*, tidata_t, tsize_t); +static void horDiff16(TIFF*, tidata_t, tsize_t); +static int PredictorDecodeRow(TIFF*, tidata_t, tsize_t, tsample_t); +static int PredictorDecodeTile(TIFF*, tidata_t, tsize_t, tsample_t); +static int PredictorEncodeRow(TIFF*, tidata_t, tsize_t, tsample_t); +static int PredictorEncodeTile(TIFF*, tidata_t, tsize_t, tsample_t); + +static int +PredictorSetup(TIFF* tif) +{ + TIFFPredictorState* sp = PredictorState(tif); + TIFFDirectory* td = &tif->tif_dir; + + if (sp->predictor == 1) /* no differencing */ + return (1); + if (sp->predictor != 2) { + TIFFError(tif->tif_name, "\"Predictor\" value %d not supported", + sp->predictor); + return (0); + } + if (td->td_bitspersample != 8 && td->td_bitspersample != 16) { + TIFFError(tif->tif_name, + "Horizontal differencing \"Predictor\" not supported with %d-bit samples", + td->td_bitspersample); + return (0); + } + sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? + td->td_samplesperpixel : 1); + /* + * Calculate the scanline/tile-width size in bytes. + */ + if (isTiled(tif)) + sp->rowsize = TIFFTileRowSize(tif); + else + sp->rowsize = TIFFScanlineSize(tif); + return (1); +} + +static int +PredictorSetupDecode(TIFF* tif) +{ + TIFFPredictorState* sp = PredictorState(tif); + TIFFDirectory* td = &tif->tif_dir; + + if (!(*sp->setupdecode)(tif) || !PredictorSetup(tif)) + return (0); + if (sp->predictor == 2) { + switch (td->td_bitspersample) { + case 8: sp->pfunc = horAcc8; break; + case 16: sp->pfunc = horAcc16; break; + } + /* + * Override default decoding method with + * one that does the predictor stuff. + */ + sp->coderow = tif->tif_decoderow; + tif->tif_decoderow = PredictorDecodeRow; + sp->codestrip = tif->tif_decodestrip; + tif->tif_decodestrip = PredictorDecodeTile; + sp->codetile = tif->tif_decodetile; + tif->tif_decodetile = PredictorDecodeTile; + /* + * If the data is horizontally differenced + * 16-bit data that requires byte-swapping, + * then it must be byte swapped before the + * accumulation step. We do this with a + * special-purpose routine and override the + * normal post decoding logic that the library + * setup when the directory was read. + */ + if (tif->tif_flags&TIFF_SWAB) { + if (sp->pfunc == horAcc16) { + sp->pfunc = swabHorAcc16; + tif->tif_postdecode = _TIFFNoPostDecode; + } /* else handle 32-bit case... */ + } + } + return (1); +} + +static int +PredictorSetupEncode(TIFF* tif) +{ + TIFFPredictorState* sp = PredictorState(tif); + TIFFDirectory* td = &tif->tif_dir; + + if (!(*sp->setupencode)(tif) || !PredictorSetup(tif)) + return (0); + if (sp->predictor == 2) { + switch (td->td_bitspersample) { + case 8: sp->pfunc = horDiff8; break; + case 16: sp->pfunc = horDiff16; break; + } + /* + * Override default encoding method with + * one that does the predictor stuff. + */ + sp->coderow = tif->tif_encoderow; + tif->tif_encoderow = PredictorEncodeRow; + sp->codestrip = tif->tif_encodestrip; + tif->tif_encodestrip = PredictorEncodeTile; + sp->codetile = tif->tif_encodetile; + tif->tif_encodetile = PredictorEncodeTile; + } + return (1); +} + +#define REPEAT4(n, op) \ + switch (n) { \ + default: { int i; for (i = n-4; i > 0; i--) { op; } } \ + case 4: op; \ + case 3: op; \ + case 2: op; \ + case 1: op; \ + case 0: ; \ + } + +static void +horAcc8(TIFF* tif, tidata_t cp0, tsize_t cc) +{ + TIFFPredictorState* sp = PredictorState(tif); + tsize_t stride = sp->stride; + + char* cp = (char*) cp0; + if (cc > stride) { + cc -= stride; + /* + * Pipeline the most common cases. + */ + if (stride == 3) { + u_int cr = cp[0]; + u_int cg = cp[1]; + u_int cb = cp[2]; + do { + cc -= 3, cp += 3; + cp[0] = (cr += cp[0]); + cp[1] = (cg += cp[1]); + cp[2] = (cb += cp[2]); + } while ((int32) cc > 0); + } else if (stride == 4) { + u_int cr = cp[0]; + u_int cg = cp[1]; + u_int cb = cp[2]; + u_int ca = cp[3]; + do { + cc -= 4, cp += 4; + cp[0] = (cr += cp[0]); + cp[1] = (cg += cp[1]); + cp[2] = (cb += cp[2]); + cp[3] = (ca += cp[3]); + } while ((int32) cc > 0); + } else { + do { + REPEAT4(stride, cp[stride] += *cp; cp++) + cc -= stride; + } while ((int32) cc > 0); + } + } +} + +static void +swabHorAcc16(TIFF* tif, tidata_t cp0, tsize_t cc) +{ + TIFFPredictorState* sp = PredictorState(tif); + tsize_t stride = sp->stride; + uint16* wp = (uint16*) cp0; + tsize_t wc = cc / 2; + + if (wc > stride) { + TIFFSwabArrayOfShort(wp, wc); + wc -= stride; + do { + REPEAT4(stride, wp[stride] += wp[0]; wp++) + wc -= stride; + } while ((int32) wc > 0); + } +} + +static void +horAcc16(TIFF* tif, tidata_t cp0, tsize_t cc) +{ + tsize_t stride = PredictorState(tif)->stride; + uint16* wp = (uint16*) cp0; + tsize_t wc = cc / 2; + + if (wc > stride) { + wc -= stride; + do { + REPEAT4(stride, wp[stride] += wp[0]; wp++) + wc -= stride; + } while ((int32) wc > 0); + } +} + +/* + * Decode a scanline and apply the predictor routine. + */ +static int +PredictorDecodeRow(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s) +{ + TIFFPredictorState *sp = PredictorState(tif); + + assert(sp != NULL); + assert(sp->coderow != NULL); + assert(sp->pfunc != NULL); + if ((*sp->coderow)(tif, op0, occ0, s)) { + (*sp->pfunc)(tif, op0, occ0); + return (1); + } else + return (0); +} + +/* + * Decode a tile/strip and apply the predictor routine. + * Note that horizontal differencing must be done on a + * row-by-row basis. The width of a "row" has already + * been calculated at pre-decode time according to the + * strip/tile dimensions. + */ +static int +PredictorDecodeTile(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s) +{ + TIFFPredictorState *sp = PredictorState(tif); + + assert(sp != NULL); + assert(sp->codetile != NULL); + if ((*sp->codetile)(tif, op0, occ0, s)) { + tsize_t rowsize = sp->rowsize; + assert(rowsize > 0); + assert(sp->pfunc != NULL); + while ((long)occ0 > 0) { + (*sp->pfunc)(tif, op0, (tsize_t) rowsize); + occ0 -= rowsize; + op0 += rowsize; + } + return (1); + } else + return (0); +} + +static void +horDiff8(TIFF* tif, tidata_t cp0, tsize_t cc) +{ + TIFFPredictorState* sp = PredictorState(tif); + tsize_t stride = sp->stride; + char* cp = (char*) cp0; + + if (cc > stride) { + cc -= stride; + /* + * Pipeline the most common cases. + */ + if (stride == 3) { + int r1, g1, b1; + int r2 = cp[0]; + int g2 = cp[1]; + int b2 = cp[2]; + do { + r1 = cp[3]; cp[3] = r1-r2; r2 = r1; + g1 = cp[4]; cp[4] = g1-g2; g2 = g1; + b1 = cp[5]; cp[5] = b1-b2; b2 = b1; + cp += 3; + } while ((int32)(cc -= 3) > 0); + } else if (stride == 4) { + int r1, g1, b1, a1; + int r2 = cp[0]; + int g2 = cp[1]; + int b2 = cp[2]; + int a2 = cp[3]; + do { + r1 = cp[4]; cp[4] = r1-r2; r2 = r1; + g1 = cp[5]; cp[5] = g1-g2; g2 = g1; + b1 = cp[6]; cp[6] = b1-b2; b2 = b1; + a1 = cp[7]; cp[7] = a1-a2; a2 = a1; + cp += 4; + } while ((int32)(cc -= 4) > 0); + } else { + cp += cc - 1; + do { + REPEAT4(stride, cp[stride] -= cp[0]; cp--) + } while ((int32)(cc -= stride) > 0); + } + } +} + +static void +horDiff16(TIFF* tif, tidata_t cp0, tsize_t cc) +{ + TIFFPredictorState* sp = PredictorState(tif); + tsize_t stride = sp->stride; + int16 *wp = (int16*) cp0; + tsize_t wc = cc/2; + + if (wc > stride) { + wc -= stride; + wp += wc - 1; + do { + REPEAT4(stride, wp[stride] -= wp[0]; wp--) + wc -= stride; + } while ((int32) wc > 0); + } +} + +static int +PredictorEncodeRow(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + TIFFPredictorState *sp = PredictorState(tif); + + assert(sp != NULL); + assert(sp->pfunc != NULL); + assert(sp->coderow != NULL); +/* XXX horizontal differencing alters user's data XXX */ + (*sp->pfunc)(tif, bp, cc); + return ((*sp->coderow)(tif, bp, cc, s)); +} + +static int +PredictorEncodeTile(TIFF* tif, tidata_t bp0, tsize_t cc0, tsample_t s) +{ + TIFFPredictorState *sp = PredictorState(tif); + tsize_t cc = cc0, rowsize; + u_char* bp = bp0; + + assert(sp != NULL); + assert(sp->pfunc != NULL); + assert(sp->codetile != NULL); + rowsize = sp->rowsize; + assert(rowsize > 0); + while ((long)cc > 0) { + (*sp->pfunc)(tif, bp, (tsize_t) rowsize); + cc -= rowsize; + bp += rowsize; + } + return ((*sp->codetile)(tif, bp0, cc0, s)); +} + +#define FIELD_PREDICTOR (FIELD_CODEC+0) /* XXX */ + +static const TIFFFieldInfo predictFieldInfo[] = { + { TIFFTAG_PREDICTOR, 1, 1, TIFF_SHORT, FIELD_PREDICTOR, + FALSE, FALSE, "Predictor" }, +}; +#define N(a) (sizeof (a) / sizeof (a[0])) + +static int +PredictorVSetField(TIFF* tif, ttag_t tag, va_list ap) +{ + TIFFPredictorState *sp = PredictorState(tif); + + switch (tag) { + case TIFFTAG_PREDICTOR: + sp->predictor = (uint16) va_arg(ap, int); + TIFFSetFieldBit(tif, FIELD_PREDICTOR); + break; + default: + return (*sp->vsetparent)(tif, tag, ap); + } + tif->tif_flags |= TIFF_DIRTYDIRECT; + return (1); +} + +static int +PredictorVGetField(TIFF* tif, ttag_t tag, va_list ap) +{ + TIFFPredictorState *sp = PredictorState(tif); + + switch (tag) { + case TIFFTAG_PREDICTOR: + *va_arg(ap, uint16*) = sp->predictor; + break; + default: + return (*sp->vgetparent)(tif, tag, ap); + } + return (1); +} + +static void +PredictorPrintDir(TIFF* tif, FILE* fd, long flags) +{ + TIFFPredictorState* sp = PredictorState(tif); + + (void) flags; + if (TIFFFieldSet(tif,FIELD_PREDICTOR)) { + fprintf(fd, " Predictor: "); + switch (sp->predictor) { + case 1: fprintf(fd, "none "); break; + case 2: fprintf(fd, "horizontal differencing "); break; + } + fprintf(fd, "%u (0x%x)\n", sp->predictor, sp->predictor); + } + if (sp->printdir) + (*sp->printdir)(tif, fd, flags); +} + +int +TIFFPredictorInit(TIFF* tif) +{ + TIFFPredictorState* sp = PredictorState(tif); + + /* + * Merge codec-specific tag information and + * override parent get/set field methods. + */ + _TIFFMergeFieldInfo(tif, predictFieldInfo, N(predictFieldInfo)); + sp->vgetparent = tif->tif_vgetfield; + tif->tif_vgetfield = PredictorVGetField;/* hook for predictor tag */ + sp->vsetparent = tif->tif_vsetfield; + tif->tif_vsetfield = PredictorVSetField;/* hook for predictor tag */ + sp->printdir = tif->tif_printdir; + tif->tif_printdir = PredictorPrintDir; /* hook for predictor tag */ + + sp->setupdecode = tif->tif_setupdecode; + tif->tif_setupdecode = PredictorSetupDecode; + sp->setupencode = tif->tif_setupencode; + tif->tif_setupencode = PredictorSetupEncode; + + sp->predictor = 1; /* default value */ + sp->pfunc = NULL; /* no predictor routine */ + return (1); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_predict.h b/SlnkDWFImpl/CxImage/tiff/tif_predict.h new file mode 100644 index 0000000..0c46eec --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_predict.h @@ -0,0 +1,61 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_predict.h,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1995-1997 Sam Leffler + * Copyright (c) 1995-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _TIFFPREDICT_ +#define _TIFFPREDICT_ +/* + * ``Library-private'' Support for the Predictor Tag + */ + +/* + * Codecs that want to support the Predictor tag must place + * this structure first in their private state block so that + * the predictor code can cast tif_data to find its state. + */ +typedef struct { + int predictor; /* predictor tag value */ + int stride; /* sample stride over data */ + tsize_t rowsize; /* tile/strip row size */ + + TIFFPostMethod pfunc; /* horizontal differencer/accumulator */ + TIFFCodeMethod coderow; /* parent codec encode/decode row */ + TIFFCodeMethod codestrip; /* parent codec encode/decode strip */ + TIFFCodeMethod codetile; /* parent codec encode/decode tile */ + TIFFVGetMethod vgetparent; /* super-class method */ + TIFFVSetMethod vsetparent; /* super-class method */ + TIFFPrintMethod printdir; /* super-class method */ + TIFFBoolMethod setupdecode; /* super-class method */ + TIFFBoolMethod setupencode; /* super-class method */ +} TIFFPredictorState; + +#if defined(__cplusplus) +extern "C" { +#endif +extern int TIFFPredictorInit(TIFF*); +#if defined(__cplusplus) +} +#endif +#endif /* _TIFFPREDICT_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_print.c b/SlnkDWFImpl/CxImage/tiff/tif_print.c new file mode 100644 index 0000000..ba6fb89 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_print.c @@ -0,0 +1,527 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_print.c,v 1.5 2001/03/02 04:59:52 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Directory Printing Support + */ +#include "tiffiop.h" +#include + +#include + +static const char *photoNames[] = { + "min-is-white", /* PHOTOMETRIC_MINISWHITE */ + "min-is-black", /* PHOTOMETRIC_MINISBLACK */ + "RGB color", /* PHOTOMETRIC_RGB */ + "palette color (RGB from colormap)", /* PHOTOMETRIC_PALETTE */ + "transparency mask", /* PHOTOMETRIC_MASK */ + "separated", /* PHOTOMETRIC_SEPARATED */ + "YCbCr", /* PHOTOMETRIC_YCBCR */ + "7 (0x7)", + "CIE L*a*b*", /* PHOTOMETRIC_CIELAB */ +}; +#define NPHOTONAMES (sizeof (photoNames) / sizeof (photoNames[0])) + +static const char *orientNames[] = { + "0 (0x0)", + "row 0 top, col 0 lhs", /* ORIENTATION_TOPLEFT */ + "row 0 top, col 0 rhs", /* ORIENTATION_TOPRIGHT */ + "row 0 bottom, col 0 rhs", /* ORIENTATION_BOTRIGHT */ + "row 0 bottom, col 0 lhs", /* ORIENTATION_BOTLEFT */ + "row 0 lhs, col 0 top", /* ORIENTATION_LEFTTOP */ + "row 0 rhs, col 0 top", /* ORIENTATION_RIGHTTOP */ + "row 0 rhs, col 0 bottom", /* ORIENTATION_RIGHTBOT */ + "row 0 lhs, col 0 bottom", /* ORIENTATION_LEFTBOT */ +}; +#define NORIENTNAMES (sizeof (orientNames) / sizeof (orientNames[0])) + +/* + * Print the contents of the current directory + * to the specified stdio file stream. + */ +void +TIFFPrintDirectory(TIFF* tif, FILE* fd, long flags) +{ + register TIFFDirectory *td; + char *sep; + uint16 i; + long l, n; + + fprintf(fd, "TIFF Directory at offset 0x%lx\n", tif->tif_diroff); + td = &tif->tif_dir; + if (TIFFFieldSet(tif,FIELD_SUBFILETYPE)) { + fprintf(fd, " Subfile Type:"); + sep = " "; + if (td->td_subfiletype & FILETYPE_REDUCEDIMAGE) { + fprintf(fd, "%sreduced-resolution image", sep); + sep = "/"; + } + if (td->td_subfiletype & FILETYPE_PAGE) { + fprintf(fd, "%smulti-page document", sep); + sep = "/"; + } + if (td->td_subfiletype & FILETYPE_MASK) + fprintf(fd, "%stransparency mask", sep); + fprintf(fd, " (%lu = 0x%lx)\n", + (long) td->td_subfiletype, (long) td->td_subfiletype); + } + if (TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) { + fprintf(fd, " Image Width: %lu Image Length: %lu", + (u_long) td->td_imagewidth, (u_long) td->td_imagelength); + if (TIFFFieldSet(tif,FIELD_IMAGEDEPTH)) + fprintf(fd, " Image Depth: %lu", + (u_long) td->td_imagedepth); + fprintf(fd, "\n"); + } + + /* Begin Pixar */ + if (TIFFFieldSet(tif,FIELD_IMAGEFULLWIDTH) || + TIFFFieldSet(tif,FIELD_IMAGEFULLLENGTH)) { + fprintf(fd, " Pixar Full Image Width: %lu Full Image Length: %lu\n", + (u_long) td->td_imagefullwidth, + (u_long) td->td_imagefulllength); + } + if (TIFFFieldSet(tif,FIELD_TEXTUREFORMAT)) + _TIFFprintAsciiTag(fd, "Texture Format", td->td_textureformat); + if (TIFFFieldSet(tif,FIELD_WRAPMODES)) + _TIFFprintAsciiTag(fd, "Texture Wrap Modes", td->td_wrapmodes); + if (TIFFFieldSet(tif,FIELD_FOVCOT)) + fprintf(fd, " Field of View Cotangent: %g\n", td->td_fovcot); + if (TIFFFieldSet(tif,FIELD_MATRIX_WORLDTOSCREEN)) { + typedef float Matrix[4][4]; + Matrix* m = (Matrix*)td->td_matrixWorldToScreen; + + fprintf(fd, " Matrix NP:\n\t%g %g %g %g\n\t%g %g %g %g\n\t%g %g %g %g\n\t%g %g %g %g\n", + (*m)[0][0], (*m)[0][1], (*m)[0][2], (*m)[0][3], + (*m)[1][0], (*m)[1][1], (*m)[1][2], (*m)[1][3], + (*m)[2][0], (*m)[2][1], (*m)[2][2], (*m)[2][3], + (*m)[3][0], (*m)[3][1], (*m)[3][2], (*m)[3][3]); + } + if (TIFFFieldSet(tif,FIELD_MATRIX_WORLDTOCAMERA)) { + typedef float Matrix[4][4]; + Matrix* m = (Matrix*)td->td_matrixWorldToCamera; + + fprintf(fd, " Matrix Nl:\n\t%g %g %g %g\n\t%g %g %g %g\n\t%g %g %g %g\n\t%g %g %g %g\n", + (*m)[0][0], (*m)[0][1], (*m)[0][2], (*m)[0][3], + (*m)[1][0], (*m)[1][1], (*m)[1][2], (*m)[1][3], + (*m)[2][0], (*m)[2][1], (*m)[2][2], (*m)[2][3], + (*m)[3][0], (*m)[3][1], (*m)[3][2], (*m)[3][3]); + } + /* End Pixar */ + + if (TIFFFieldSet(tif,FIELD_TILEDIMENSIONS)) { + fprintf(fd, " Tile Width: %lu Tile Length: %lu", + (u_long) td->td_tilewidth, (u_long) td->td_tilelength); + if (TIFFFieldSet(tif,FIELD_TILEDEPTH)) + fprintf(fd, " Tile Depth: %lu", + (u_long) td->td_tiledepth); + fprintf(fd, "\n"); + } + if (TIFFFieldSet(tif,FIELD_RESOLUTION)) { + fprintf(fd, " Resolution: %g, %g", + td->td_xresolution, td->td_yresolution); + if (TIFFFieldSet(tif,FIELD_RESOLUTIONUNIT)) { + switch (td->td_resolutionunit) { + case RESUNIT_NONE: + fprintf(fd, " (unitless)"); + break; + case RESUNIT_INCH: + fprintf(fd, " pixels/inch"); + break; + case RESUNIT_CENTIMETER: + fprintf(fd, " pixels/cm"); + break; + default: + fprintf(fd, " (unit %u = 0x%x)", + td->td_resolutionunit, + td->td_resolutionunit); + break; + } + } + fprintf(fd, "\n"); + } + if (TIFFFieldSet(tif,FIELD_POSITION)) + fprintf(fd, " Position: %g, %g\n", + td->td_xposition, td->td_yposition); + if (TIFFFieldSet(tif,FIELD_BITSPERSAMPLE)) + fprintf(fd, " Bits/Sample: %u\n", td->td_bitspersample); + if (TIFFFieldSet(tif,FIELD_SAMPLEFORMAT)) { + fprintf(fd, " Sample Format: "); + switch (td->td_sampleformat) { + case SAMPLEFORMAT_VOID: + fprintf(fd, "void\n"); + break; + case SAMPLEFORMAT_INT: + fprintf(fd, "signed integer\n"); + break; + case SAMPLEFORMAT_UINT: + fprintf(fd, "unsigned integer\n"); + break; + case SAMPLEFORMAT_IEEEFP: + fprintf(fd, "IEEE floating point\n"); + break; + case SAMPLEFORMAT_COMPLEXINT: + fprintf(fd, "complex signed integer\n"); + break; + case SAMPLEFORMAT_COMPLEXIEEEFP: + fprintf(fd, "complex IEEE floating point\n"); + break; + default: + fprintf(fd, "%u (0x%x)\n", + td->td_sampleformat, td->td_sampleformat); + break; + } + } + if (TIFFFieldSet(tif,FIELD_COMPRESSION)) { + const TIFFCodec* c = TIFFFindCODEC(td->td_compression); + fprintf(fd, " Compression Scheme: "); + if (c) + fprintf(fd, "%s\n", c->name); + else + fprintf(fd, "%u (0x%x)\n", + td->td_compression, td->td_compression); + } + if (TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) { + fprintf(fd, " Photometric Interpretation: "); + if (td->td_photometric < NPHOTONAMES) + fprintf(fd, "%s\n", photoNames[td->td_photometric]); + else { + switch (td->td_photometric) { + case PHOTOMETRIC_LOGL: + fprintf(fd, "CIE Log2(L)\n"); + break; + case PHOTOMETRIC_LOGLUV: + fprintf(fd, "CIE Log2(L) (u',v')\n"); + break; + default: + fprintf(fd, "%u (0x%x)\n", + td->td_photometric, td->td_photometric); + break; + } + } + } + if (TIFFFieldSet(tif,FIELD_EXTRASAMPLES) && td->td_extrasamples) { + fprintf(fd, " Extra Samples: %u<", td->td_extrasamples); + sep = ""; + for (i = 0; i < td->td_extrasamples; i++) { + switch (td->td_sampleinfo[i]) { + case EXTRASAMPLE_UNSPECIFIED: + fprintf(fd, "%sunspecified", sep); + break; + case EXTRASAMPLE_ASSOCALPHA: + fprintf(fd, "%sassoc-alpha", sep); + break; + case EXTRASAMPLE_UNASSALPHA: + fprintf(fd, "%sunassoc-alpha", sep); + break; + default: + fprintf(fd, "%s%u (0x%x)", sep, + td->td_sampleinfo[i], td->td_sampleinfo[i]); + break; + } + sep = ", "; + } + fprintf(fd, ">\n"); + } + if (TIFFFieldSet(tif,FIELD_STONITS)) { + fprintf(fd, " Sample to Nits conversion factor: %.4e\n", + td->td_stonits); + } +#ifdef CMYK_SUPPORT + if (TIFFFieldSet(tif,FIELD_INKSET)) { + fprintf(fd, " Ink Set: "); + switch (td->td_inkset) { + case INKSET_CMYK: + fprintf(fd, "CMYK\n"); + break; + default: + fprintf(fd, "%u (0x%x)\n", + td->td_inkset, td->td_inkset); + break; + } + } + if (TIFFFieldSet(tif,FIELD_INKNAMES)) { + char* cp; + fprintf(fd, " Ink Names: "); + i = td->td_samplesperpixel; + sep = ""; + for (cp = td->td_inknames; i > 0; cp = strchr(cp,'\0')+1, i--) { + fprintf(fd, "%s", sep); + _TIFFprintAscii(fd, cp); + sep = ", "; + } + } + if (TIFFFieldSet(tif,FIELD_NUMBEROFINKS)) + fprintf(fd, " Number of Inks: %u\n", td->td_ninks); + if (TIFFFieldSet(tif,FIELD_DOTRANGE)) + fprintf(fd, " Dot Range: %u-%u\n", + td->td_dotrange[0], td->td_dotrange[1]); + if (TIFFFieldSet(tif,FIELD_TARGETPRINTER)) + _TIFFprintAsciiTag(fd, "Target Printer", td->td_targetprinter); +#endif + if (TIFFFieldSet(tif,FIELD_THRESHHOLDING)) { + fprintf(fd, " Thresholding: "); + switch (td->td_threshholding) { + case THRESHHOLD_BILEVEL: + fprintf(fd, "bilevel art scan\n"); + break; + case THRESHHOLD_HALFTONE: + fprintf(fd, "halftone or dithered scan\n"); + break; + case THRESHHOLD_ERRORDIFFUSE: + fprintf(fd, "error diffused\n"); + break; + default: + fprintf(fd, "%u (0x%x)\n", + td->td_threshholding, td->td_threshholding); + break; + } + } + if (TIFFFieldSet(tif,FIELD_FILLORDER)) { + fprintf(fd, " FillOrder: "); + switch (td->td_fillorder) { + case FILLORDER_MSB2LSB: + fprintf(fd, "msb-to-lsb\n"); + break; + case FILLORDER_LSB2MSB: + fprintf(fd, "lsb-to-msb\n"); + break; + default: + fprintf(fd, "%u (0x%x)\n", + td->td_fillorder, td->td_fillorder); + break; + } + } +#ifdef YCBCR_SUPPORT + if (TIFFFieldSet(tif,FIELD_YCBCRSUBSAMPLING)) + fprintf(fd, " YCbCr Subsampling: %u, %u\n", + td->td_ycbcrsubsampling[0], td->td_ycbcrsubsampling[1]); + if (TIFFFieldSet(tif,FIELD_YCBCRPOSITIONING)) { + fprintf(fd, " YCbCr Positioning: "); + switch (td->td_ycbcrpositioning) { + case YCBCRPOSITION_CENTERED: + fprintf(fd, "centered\n"); + break; + case YCBCRPOSITION_COSITED: + fprintf(fd, "cosited\n"); + break; + default: + fprintf(fd, "%u (0x%x)\n", + td->td_ycbcrpositioning, td->td_ycbcrpositioning); + break; + } + } + if (TIFFFieldSet(tif,FIELD_YCBCRCOEFFICIENTS)) + fprintf(fd, " YCbCr Coefficients: %g, %g, %g\n", + td->td_ycbcrcoeffs[0], + td->td_ycbcrcoeffs[1], + td->td_ycbcrcoeffs[2]); +#endif + if (TIFFFieldSet(tif,FIELD_HALFTONEHINTS)) + fprintf(fd, " Halftone Hints: light %u dark %u\n", + td->td_halftonehints[0], td->td_halftonehints[1]); + if (TIFFFieldSet(tif,FIELD_ARTIST)) + _TIFFprintAsciiTag(fd, "Artist", td->td_artist); + if (TIFFFieldSet(tif,FIELD_DATETIME)) + _TIFFprintAsciiTag(fd, "Date & Time", td->td_datetime); + if (TIFFFieldSet(tif,FIELD_HOSTCOMPUTER)) + _TIFFprintAsciiTag(fd, "Host Computer", td->td_hostcomputer); + if (TIFFFieldSet(tif,FIELD_SOFTWARE)) + _TIFFprintAsciiTag(fd, "Software", td->td_software); + if (TIFFFieldSet(tif,FIELD_COPYRIGHT)) + _TIFFprintAsciiTag(fd, "Copyright", td->td_copyright); + if (TIFFFieldSet(tif,FIELD_DOCUMENTNAME)) + _TIFFprintAsciiTag(fd, "Document Name", td->td_documentname); + if (TIFFFieldSet(tif,FIELD_IMAGEDESCRIPTION)) + _TIFFprintAsciiTag(fd, "Image Description", td->td_imagedescription); + if (TIFFFieldSet(tif,FIELD_MAKE)) + _TIFFprintAsciiTag(fd, "Make", td->td_make); + if (TIFFFieldSet(tif,FIELD_MODEL)) + _TIFFprintAsciiTag(fd, "Model", td->td_model); + if (TIFFFieldSet(tif,FIELD_ORIENTATION)) { + fprintf(fd, " Orientation: "); + if (td->td_orientation < NORIENTNAMES) + fprintf(fd, "%s\n", orientNames[td->td_orientation]); + else + fprintf(fd, "%u (0x%x)\n", + td->td_orientation, td->td_orientation); + } + if (TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL)) + fprintf(fd, " Samples/Pixel: %u\n", td->td_samplesperpixel); + if (TIFFFieldSet(tif,FIELD_ROWSPERSTRIP)) { + fprintf(fd, " Rows/Strip: "); + if (td->td_rowsperstrip == (uint32) -1) + fprintf(fd, "(infinite)\n"); + else + fprintf(fd, "%lu\n", (u_long) td->td_rowsperstrip); + } + if (TIFFFieldSet(tif,FIELD_MINSAMPLEVALUE)) + fprintf(fd, " Min Sample Value: %u\n", td->td_minsamplevalue); + if (TIFFFieldSet(tif,FIELD_MAXSAMPLEVALUE)) + fprintf(fd, " Max Sample Value: %u\n", td->td_maxsamplevalue); + if (TIFFFieldSet(tif,FIELD_SMINSAMPLEVALUE)) + fprintf(fd, " SMin Sample Value: %g\n", + td->td_sminsamplevalue); + if (TIFFFieldSet(tif,FIELD_SMAXSAMPLEVALUE)) + fprintf(fd, " SMax Sample Value: %g\n", + td->td_smaxsamplevalue); + if (TIFFFieldSet(tif,FIELD_PLANARCONFIG)) { + fprintf(fd, " Planar Configuration: "); + switch (td->td_planarconfig) { + case PLANARCONFIG_CONTIG: + fprintf(fd, "single image plane\n"); + break; + case PLANARCONFIG_SEPARATE: + fprintf(fd, "separate image planes\n"); + break; + default: + fprintf(fd, "%u (0x%x)\n", + td->td_planarconfig, td->td_planarconfig); + break; + } + } + if (TIFFFieldSet(tif,FIELD_PAGENAME)) + _TIFFprintAsciiTag(fd, "Page Name", td->td_pagename); + if (TIFFFieldSet(tif,FIELD_PAGENUMBER)) + fprintf(fd, " Page Number: %u-%u\n", + td->td_pagenumber[0], td->td_pagenumber[1]); + if (TIFFFieldSet(tif,FIELD_COLORMAP)) { + fprintf(fd, " Color Map: "); + if (flags & TIFFPRINT_COLORMAP) { + fprintf(fd, "\n"); + n = 1L<td_bitspersample; + for (l = 0; l < n; l++) + fprintf(fd, " %5lu: %5u %5u %5u\n", + l, + td->td_colormap[0][l], + td->td_colormap[1][l], + td->td_colormap[2][l]); + } else + fprintf(fd, "(present)\n"); + } +#ifdef COLORIMETRY_SUPPORT + if (TIFFFieldSet(tif,FIELD_WHITEPOINT)) + fprintf(fd, " White Point: %g-%g\n", + td->td_whitepoint[0], td->td_whitepoint[1]); + if (TIFFFieldSet(tif,FIELD_PRIMARYCHROMAS)) + fprintf(fd, " Primary Chromaticities: %g,%g %g,%g %g,%g\n", + td->td_primarychromas[0], td->td_primarychromas[1], + td->td_primarychromas[2], td->td_primarychromas[3], + td->td_primarychromas[4], td->td_primarychromas[5]); + if (TIFFFieldSet(tif,FIELD_REFBLACKWHITE)) { + fprintf(fd, " Reference Black/White:\n"); + for (i = 0; i < td->td_samplesperpixel; i++) + fprintf(fd, " %2d: %5g %5g\n", + i, + td->td_refblackwhite[2*i+0], + td->td_refblackwhite[2*i+1]); + } + if (TIFFFieldSet(tif,FIELD_TRANSFERFUNCTION)) { + fprintf(fd, " Transfer Function: "); + if (flags & TIFFPRINT_CURVES) { + fprintf(fd, "\n"); + n = 1L<td_bitspersample; + for (l = 0; l < n; l++) { + fprintf(fd, " %2lu: %5u", + l, td->td_transferfunction[0][l]); + for (i = 1; i < td->td_samplesperpixel; i++) + fprintf(fd, " %5u", + td->td_transferfunction[i][l]); + fputc('\n', fd); + } + } else + fprintf(fd, "(present)\n"); + } +#endif +#ifdef ICC_SUPPORT + if (TIFFFieldSet(tif,FIELD_ICCPROFILE)) + fprintf(fd, " ICC Profile: , %lu bytes\n", + (u_long) td->td_profileLength); +#endif +#ifdef PHOTOSHOP_SUPPORT + if (TIFFFieldSet(tif,FIELD_PHOTOSHOP)) + fprintf(fd, " Photoshop Data: , %lu bytes\n", + (u_long) td->td_photoshopLength); +#endif +#ifdef IPTC_SUPPORT + if (TIFFFieldSet(tif,FIELD_RICHTIFFIPTC)) + fprintf(fd, " RichTIFFIPTC Data: , %lu bytes\n", + (u_long) td->td_richtiffiptcLength); +#endif +#if SUBIFD_SUPPORT + if (TIFFFieldSet(tif, FIELD_SUBIFD)) { + fprintf(fd, " SubIFD Offsets:"); + for (i = 0; i < td->td_nsubifd; i++) + fprintf(fd, " %5lu", (long) td->td_subifd[i]); + fputc('\n', fd); + } +#endif + if (tif->tif_printdir) + (*tif->tif_printdir)(tif, fd, flags); + if ((flags & TIFFPRINT_STRIPS) && + TIFFFieldSet(tif,FIELD_STRIPOFFSETS)) { + tstrip_t s; + + fprintf(fd, " %lu %s:\n", + (long) td->td_nstrips, + isTiled(tif) ? "Tiles" : "Strips"); + for (s = 0; s < td->td_nstrips; s++) + fprintf(fd, " %3lu: [%8lu, %8lu]\n", + (u_long) s, + (u_long) td->td_stripoffset[s], + (u_long) td->td_stripbytecount[s]); + } +} + +void +_TIFFprintAscii(FILE* fd, const char* cp) +{ + for (; *cp != '\0'; cp++) { + const char* tp; + + if (isprint(*cp)) { + fputc(*cp, fd); + continue; + } + for (tp = "\tt\bb\rr\nn\vv"; *tp; tp++) + if (*tp++ == *cp) + break; + if (*tp) + fprintf(fd, "\\%c", *tp); + else + fprintf(fd, "\\%03o", *cp & 0xff); + } +} + +void +_TIFFprintAsciiTag(FILE* fd, const char* name, const char* value) +{ + fprintf(fd, " %s: \"", name); + _TIFFprintAscii(fd, value); + fprintf(fd, "\"\n"); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_read.c b/SlnkDWFImpl/CxImage/tiff/tif_read.c new file mode 100644 index 0000000..d375eb4 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_read.c @@ -0,0 +1,633 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_read.c,v 1.6 2000/08/14 16:21:54 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * Scanline-oriented Read Support + */ +#include "tiffiop.h" +#include +#include + +static int TIFFFillStrip(TIFF*, tstrip_t); +static int TIFFFillTile(TIFF*, ttile_t); +static int TIFFStartStrip(TIFF*, tstrip_t); +static int TIFFStartTile(TIFF*, ttile_t); +static int TIFFCheckRead(TIFF*, int); + +#define NOSTRIP ((tstrip_t) -1) /* undefined state */ +#define NOTILE ((ttile_t) -1) /* undefined state */ + +/* + * Seek to a random row+sample in a file. + */ +static int +TIFFSeek(TIFF* tif, uint32 row, tsample_t sample) +{ + register TIFFDirectory *td = &tif->tif_dir; + tstrip_t strip; + + if (row >= td->td_imagelength) { /* out of range */ + TIFFError(tif->tif_name, "%lu: Row out of range, max %lu", + (u_long) row, (u_long) td->td_imagelength); + return (0); + } + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { + if (sample >= td->td_samplesperpixel) { + TIFFError(tif->tif_name, + "%lu: Sample out of range, max %lu", + (u_long) sample, (u_long) td->td_samplesperpixel); + return (0); + } + strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip; + } else + strip = row / td->td_rowsperstrip; + if (strip != tif->tif_curstrip) { /* different strip, refill */ + if (!TIFFFillStrip(tif, strip)) + return (0); + } else if (row < tif->tif_row) { + /* + * Moving backwards within the same strip: backup + * to the start and then decode forward (below). + * + * NB: If you're planning on lots of random access within a + * strip, it's better to just read and decode the entire + * strip, and then access the decoded data in a random fashion. + */ + if (!TIFFStartStrip(tif, strip)) + return (0); + } + if (row != tif->tif_row) { + /* + * Seek forward to the desired row. + */ + if (!(*tif->tif_seek)(tif, row - tif->tif_row)) + return (0); + tif->tif_row = row; + } + return (1); +} + +int +TIFFReadScanline(TIFF* tif, tdata_t buf, uint32 row, tsample_t sample) +{ + int e; + + if (!TIFFCheckRead(tif, 0)) + return (-1); + if( (e = TIFFSeek(tif, row, sample)) != 0) { + /* + * Decompress desired row into user buffer. + */ + e = (*tif->tif_decoderow) + (tif, (tidata_t) buf, tif->tif_scanlinesize, sample); + tif->tif_row++; + if (e) + (*tif->tif_postdecode)(tif, (tidata_t) buf, + tif->tif_scanlinesize); + } + return (e > 0 ? 1 : -1); +} + +/* + * Read a strip of data and decompress the specified + * amount into the user-supplied buffer. + */ +tsize_t +TIFFReadEncodedStrip(TIFF* tif, tstrip_t strip, tdata_t buf, tsize_t size) +{ + TIFFDirectory *td = &tif->tif_dir; + uint32 nrows; + tsize_t stripsize; + tstrip_t sep_strip, strips_per_sep; + + if (!TIFFCheckRead(tif, 0)) + return (-1); + if (strip >= td->td_nstrips) { + TIFFError(tif->tif_name, "%ld: Strip out of range, max %ld", + (long) strip, (long) td->td_nstrips); + return (-1); + } + /* + * Calculate the strip size according to the number of + * rows in the strip (check for truncated last strip on any + * of the separations). + */ + if( td->td_rowsperstrip >= td->td_imagelength ) + strips_per_sep = 1; + else + strips_per_sep = (td->td_imagelength+td->td_rowsperstrip-1) + / td->td_rowsperstrip; + + sep_strip = strip % strips_per_sep; + + if (sep_strip != strips_per_sep-1 || + (nrows = td->td_imagelength % td->td_rowsperstrip) == 0) + nrows = td->td_rowsperstrip; + + stripsize = TIFFVStripSize(tif, nrows); + if (size == (tsize_t) -1) + size = stripsize; + else if (size > stripsize) + size = stripsize; + if (TIFFFillStrip(tif, strip) && (*tif->tif_decodestrip)(tif, + (tidata_t) buf, size, (tsample_t)(strip / td->td_stripsperimage))) { + (*tif->tif_postdecode)(tif, (tidata_t) buf, size); + return (size); + } else + return ((tsize_t) -1); +} + +static tsize_t +TIFFReadRawStrip1(TIFF* tif, + tstrip_t strip, tdata_t buf, tsize_t size, const char* module) +{ + TIFFDirectory *td = &tif->tif_dir; + + if (!isMapped(tif)) { + tsize_t cc; + + if (!SeekOK(tif, td->td_stripoffset[strip])) { + TIFFError(module, + "%s: Seek error at scanline %lu, strip %lu", + tif->tif_name, + (u_long) tif->tif_row, (u_long) strip); + return (-1); + } + cc = TIFFReadFile(tif, buf, size); + if (cc != size) { + TIFFError(module, + "%s: Read error at scanline %lu; got %lu bytes, expected %lu", + tif->tif_name, + (u_long) tif->tif_row, + (u_long) cc, + (u_long) size); + // return (-1); // To decode some nasty images + } + } else { + if (td->td_stripoffset[strip] + size > tif->tif_size) { + TIFFError(module, + "%s: Read error at scanline %lu, strip %lu; got %lu bytes, expected %lu", + tif->tif_name, + (u_long) tif->tif_row, + (u_long) strip, + (u_long) tif->tif_size - td->td_stripoffset[strip], + (u_long) size); + return (-1); + } + _TIFFmemcpy(buf, tif->tif_base + td->td_stripoffset[strip], size); + } + return (size); +} + +/* + * Read a strip of data from the file. + */ +tsize_t +TIFFReadRawStrip(TIFF* tif, tstrip_t strip, tdata_t buf, tsize_t size) +{ + static const char module[] = "TIFFReadRawStrip"; + TIFFDirectory *td = &tif->tif_dir; + tsize_t bytecount; + + if (!TIFFCheckRead(tif, 0)) + return ((tsize_t) -1); + if (strip >= td->td_nstrips) { + TIFFError(tif->tif_name, "%lu: Strip out of range, max %lu", + (u_long) strip, (u_long) td->td_nstrips); + return ((tsize_t) -1); + } + bytecount = td->td_stripbytecount[strip]; + if (bytecount <= 0) { + TIFFError(tif->tif_name, + "%lu: Invalid strip byte count, strip %lu", + (u_long) bytecount, (u_long) strip); + return ((tsize_t) -1); + } + if (size != (tsize_t)-1 && size < bytecount) + bytecount = size; + return (TIFFReadRawStrip1(tif, strip, buf, bytecount, module)); +} + +/* + * Read the specified strip and setup for decoding. + * The data buffer is expanded, as necessary, to + * hold the strip's data. + */ +static int +TIFFFillStrip(TIFF* tif, tstrip_t strip) +{ + static const char module[] = "TIFFFillStrip"; + TIFFDirectory *td = &tif->tif_dir; + tsize_t bytecount; + + bytecount = td->td_stripbytecount[strip]; + if (bytecount <= 0) { + TIFFError(tif->tif_name, + "%lu: Invalid strip byte count, strip %lu", + (u_long) bytecount, (u_long) strip); + return (0); + } + if (isMapped(tif) && + (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { + /* + * The image is mapped into memory and we either don't + * need to flip bits or the compression routine is going + * to handle this operation itself. In this case, avoid + * copying the raw data and instead just reference the + * data from the memory mapped file image. This assumes + * that the decompression routines do not modify the + * contents of the raw data buffer (if they try to, + * the application will get a fault since the file is + * mapped read-only). + */ + if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) + _TIFFfree(tif->tif_rawdata); + tif->tif_flags &= ~TIFF_MYBUFFER; + if ( td->td_stripoffset[strip] + bytecount > tif->tif_size) { + /* + * This error message might seem strange, but it's + * what would happen if a read were done instead. + */ + TIFFError(module, + "%s: Read error on strip %lu; got %lu bytes, expected %lu", + tif->tif_name, + (u_long) strip, + (u_long) tif->tif_size - td->td_stripoffset[strip], + (u_long) bytecount); + tif->tif_curstrip = NOSTRIP; + return (0); + } + tif->tif_rawdatasize = bytecount; + tif->tif_rawdata = tif->tif_base + td->td_stripoffset[strip]; + } else { + /* + * Expand raw data buffer, if needed, to + * hold data strip coming from file + * (perhaps should set upper bound on + * the size of a buffer we'll use?). + */ + if (bytecount > tif->tif_rawdatasize) { + tif->tif_curstrip = NOSTRIP; + if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { + TIFFError(module, + "%s: Data buffer too small to hold strip %lu", + tif->tif_name, (u_long) strip); + return (0); + } + if (!TIFFReadBufferSetup(tif, 0, + TIFFroundup(bytecount, 1024))) + return (0); + } + if (TIFFReadRawStrip1(tif, strip, (u_char *)tif->tif_rawdata, + bytecount, module) != bytecount) + return (0); + if (!isFillOrder(tif, td->td_fillorder) && + (tif->tif_flags & TIFF_NOBITREV) == 0) + TIFFReverseBits(tif->tif_rawdata, bytecount); + } + return (TIFFStartStrip(tif, strip)); +} + +/* + * Tile-oriented Read Support + * Contributed by Nancy Cam (Silicon Graphics). + */ + +/* + * Read and decompress a tile of data. The + * tile is selected by the (x,y,z,s) coordinates. + */ +tsize_t +TIFFReadTile(TIFF* tif, + tdata_t buf, uint32 x, uint32 y, uint32 z, tsample_t s) +{ + if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s)) + return (-1); + return (TIFFReadEncodedTile(tif, + TIFFComputeTile(tif, x, y, z, s), buf, (tsize_t) -1)); +} + +/* + * Read a tile of data and decompress the specified + * amount into the user-supplied buffer. + */ +tsize_t +TIFFReadEncodedTile(TIFF* tif, ttile_t tile, tdata_t buf, tsize_t size) +{ + TIFFDirectory *td = &tif->tif_dir; + tsize_t tilesize = tif->tif_tilesize; + + if (!TIFFCheckRead(tif, 1)) + return (-1); + if (tile >= td->td_nstrips) { + TIFFError(tif->tif_name, "%ld: Tile out of range, max %ld", + (long) tile, (u_long) td->td_nstrips); + return (-1); + } + if (size == (tsize_t) -1) + size = tilesize; + else if (size > tilesize) + size = tilesize; + if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif, + (tidata_t) buf, size, (tsample_t)(tile/td->td_stripsperimage))) { + (*tif->tif_postdecode)(tif, (tidata_t) buf, size); + return (size); + } else + return (-1); +} + +static tsize_t +TIFFReadRawTile1(TIFF* tif, + ttile_t tile, tdata_t buf, tsize_t size, const char* module) +{ + TIFFDirectory *td = &tif->tif_dir; + + if (!isMapped(tif)) { + tsize_t cc; + + if (!SeekOK(tif, td->td_stripoffset[tile])) { + TIFFError(module, + "%s: Seek error at row %ld, col %ld, tile %ld", + tif->tif_name, + (long) tif->tif_row, + (long) tif->tif_col, + (long) tile); + return ((tsize_t) -1); + } + cc = TIFFReadFile(tif, buf, size); + if (cc != size) { + TIFFError(module, + "%s: Read error at row %ld, col %ld; got %lu bytes, expected %lu", + tif->tif_name, + (long) tif->tif_row, + (long) tif->tif_col, + (u_long) cc, + (u_long) size); + return ((tsize_t) -1); + } + } else { + if (td->td_stripoffset[tile] + size > tif->tif_size) { + TIFFError(module, + "%s: Read error at row %ld, col %ld, tile %ld; got %lu bytes, expected %lu", + tif->tif_name, + (long) tif->tif_row, + (long) tif->tif_col, + (long) tile, + (u_long) tif->tif_size - td->td_stripoffset[tile], + (u_long) size); + return ((tsize_t) -1); + } + _TIFFmemcpy(buf, tif->tif_base + td->td_stripoffset[tile], size); + } + return (size); +} + +/* + * Read a tile of data from the file. + */ +tsize_t +TIFFReadRawTile(TIFF* tif, ttile_t tile, tdata_t buf, tsize_t size) +{ + static const char module[] = "TIFFReadRawTile"; + TIFFDirectory *td = &tif->tif_dir; + tsize_t bytecount; + + if (!TIFFCheckRead(tif, 1)) + return ((tsize_t) -1); + if (tile >= td->td_nstrips) { + TIFFError(tif->tif_name, "%lu: Tile out of range, max %lu", + (u_long) tile, (u_long) td->td_nstrips); + return ((tsize_t) -1); + } + bytecount = td->td_stripbytecount[tile]; + if (size != (tsize_t) -1 && size < bytecount) + bytecount = size; + return (TIFFReadRawTile1(tif, tile, buf, bytecount, module)); +} + +/* + * Read the specified tile and setup for decoding. + * The data buffer is expanded, as necessary, to + * hold the tile's data. + */ +static int +TIFFFillTile(TIFF* tif, ttile_t tile) +{ + static const char module[] = "TIFFFillTile"; + TIFFDirectory *td = &tif->tif_dir; + tsize_t bytecount; + + bytecount = td->td_stripbytecount[tile]; + if (bytecount <= 0) { + TIFFError(tif->tif_name, + "%lu: Invalid tile byte count, tile %lu", + (u_long) bytecount, (u_long) tile); + return (0); + } + if (isMapped(tif) && + (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { + /* + * The image is mapped into memory and we either don't + * need to flip bits or the compression routine is going + * to handle this operation itself. In this case, avoid + * copying the raw data and instead just reference the + * data from the memory mapped file image. This assumes + * that the decompression routines do not modify the + * contents of the raw data buffer (if they try to, + * the application will get a fault since the file is + * mapped read-only). + */ + if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) + _TIFFfree(tif->tif_rawdata); + tif->tif_flags &= ~TIFF_MYBUFFER; + if ( td->td_stripoffset[tile] + bytecount > tif->tif_size) { + tif->tif_curtile = NOTILE; + return (0); + } + tif->tif_rawdatasize = bytecount; + tif->tif_rawdata = tif->tif_base + td->td_stripoffset[tile]; + } else { + /* + * Expand raw data buffer, if needed, to + * hold data tile coming from file + * (perhaps should set upper bound on + * the size of a buffer we'll use?). + */ + if (bytecount > tif->tif_rawdatasize) { + tif->tif_curtile = NOTILE; + if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { + TIFFError(module, + "%s: Data buffer too small to hold tile %ld", + tif->tif_name, (long) tile); + return (0); + } + if (!TIFFReadBufferSetup(tif, 0, + TIFFroundup(bytecount, 1024))) + return (0); + } + if (TIFFReadRawTile1(tif, tile, (u_char *)tif->tif_rawdata, + bytecount, module) != bytecount) + return (0); + if (!isFillOrder(tif, td->td_fillorder) && + (tif->tif_flags & TIFF_NOBITREV) == 0) + TIFFReverseBits(tif->tif_rawdata, bytecount); + } + return (TIFFStartTile(tif, tile)); +} + +/* + * Setup the raw data buffer in preparation for + * reading a strip of raw data. If the buffer + * is specified as zero, then a buffer of appropriate + * size is allocated by the library. Otherwise, + * the client must guarantee that the buffer is + * large enough to hold any individual strip of + * raw data. + */ +int +TIFFReadBufferSetup(TIFF* tif, tdata_t bp, tsize_t size) +{ + static const char module[] = "TIFFReadBufferSetup"; + + if (tif->tif_rawdata) { + if (tif->tif_flags & TIFF_MYBUFFER) + _TIFFfree(tif->tif_rawdata); + tif->tif_rawdata = NULL; + } + if (bp) { + tif->tif_rawdatasize = size; + tif->tif_rawdata = (tidata_t) bp; + tif->tif_flags &= ~TIFF_MYBUFFER; + } else { + tif->tif_rawdatasize = TIFFroundup(size, 1024); + tif->tif_rawdata = (tidata_t) _TIFFmalloc(tif->tif_rawdatasize); + tif->tif_flags |= TIFF_MYBUFFER; + } + if (tif->tif_rawdata == NULL) { + TIFFError(module, + "%s: No space for data buffer at scanline %ld", + tif->tif_name, (long) tif->tif_row); + tif->tif_rawdatasize = 0; + return (0); + } + return (1); +} + +/* + * Set state to appear as if a + * strip has just been read in. + */ +static int +TIFFStartStrip(TIFF* tif, tstrip_t strip) +{ + TIFFDirectory *td = &tif->tif_dir; + + if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { + if (!(*tif->tif_setupdecode)(tif)) + return (0); + tif->tif_flags |= TIFF_CODERSETUP; + } + tif->tif_curstrip = strip; + tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; + tif->tif_rawcp = tif->tif_rawdata; + tif->tif_rawcc = td->td_stripbytecount[strip]; + return ((*tif->tif_predecode)(tif, + (tsample_t)(strip / td->td_stripsperimage))); +} + +/* + * Set state to appear as if a + * tile has just been read in. + */ +static int +TIFFStartTile(TIFF* tif, ttile_t tile) +{ + TIFFDirectory *td = &tif->tif_dir; + + if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { + if (!(*tif->tif_setupdecode)(tif)) + return (0); + tif->tif_flags |= TIFF_CODERSETUP; + } + tif->tif_curtile = tile; + tif->tif_row = + (tile % TIFFhowmany(td->td_imagewidth, td->td_tilewidth)) * + td->td_tilelength; + tif->tif_col = + (tile % TIFFhowmany(td->td_imagelength, td->td_tilelength)) * + td->td_tilewidth; + tif->tif_rawcp = tif->tif_rawdata; + tif->tif_rawcc = td->td_stripbytecount[tile]; + return ((*tif->tif_predecode)(tif, + (tsample_t)(tile/td->td_stripsperimage))); +} + +static int +TIFFCheckRead(TIFF* tif, int tiles) +{ + if (tif->tif_mode == O_WRONLY) { + TIFFError(tif->tif_name, "File not open for reading"); + return (0); + } + if (tiles ^ isTiled(tif)) { + TIFFError(tif->tif_name, tiles ? + "Can not read tiles from a stripped image" : + "Can not read scanlines from a tiled image"); + return (0); + } + return (1); +} + +void +_TIFFNoPostDecode(TIFF* tif, tidata_t buf, tsize_t cc) +{ + (void) tif; (void) buf; (void) cc; +} + +void +_TIFFSwab16BitData(TIFF* tif, tidata_t buf, tsize_t cc) +{ + (void) tif; + assert((cc & 1) == 0); + TIFFSwabArrayOfShort((uint16*) buf, cc/2); +} + +void +_TIFFSwab32BitData(TIFF* tif, tidata_t buf, tsize_t cc) +{ + (void) tif; + assert((cc & 3) == 0); + TIFFSwabArrayOfLong((uint32*) buf, cc/4); +} + +void +_TIFFSwab64BitData(TIFF* tif, tidata_t buf, tsize_t cc) +{ + (void) tif; + assert((cc & 7) == 0); + TIFFSwabArrayOfDouble((double*) buf, cc/8); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_strip.c b/SlnkDWFImpl/CxImage/tiff/tif_strip.c new file mode 100644 index 0000000..177f213 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_strip.c @@ -0,0 +1,192 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_strip.c,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1991-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Strip-organized Image Support Routines. + */ +#include "tiffiop.h" + +/* + * Compute which strip a (row,sample) value is in. + */ +tstrip_t +TIFFComputeStrip(TIFF* tif, uint32 row, tsample_t sample) +{ + TIFFDirectory *td = &tif->tif_dir; + tstrip_t strip; + + strip = row / td->td_rowsperstrip; + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { + if (sample >= td->td_samplesperpixel) { + TIFFError(tif->tif_name, + "%u: Sample out of range, max %u", + sample, td->td_samplesperpixel); + return ((tstrip_t) 0); + } + strip += sample*td->td_stripsperimage; + } + return (strip); +} + +/* + * Compute how many strips are in an image. + */ +tstrip_t +TIFFNumberOfStrips(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + tstrip_t nstrips; + + nstrips = (td->td_rowsperstrip == (uint32) -1 ? + (td->td_imagelength != 0 ? 1 : 0) : + TIFFhowmany(td->td_imagelength, td->td_rowsperstrip)); + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) + nstrips *= td->td_samplesperpixel; + return (nstrips); +} + +/* + * Compute the # bytes in a variable height, row-aligned strip. + */ +tsize_t +TIFFVStripSize(TIFF* tif, uint32 nrows) +{ + TIFFDirectory *td = &tif->tif_dir; + + if (nrows == (uint32) -1) + nrows = td->td_imagelength; +#ifdef YCBCR_SUPPORT + if (td->td_planarconfig == PLANARCONFIG_CONTIG && + td->td_photometric == PHOTOMETRIC_YCBCR && + !isUpSampled(tif)) { + /* + * Packed YCbCr data contain one Cb+Cr for every + * HorizontalSampling*VerticalSampling Y values. + * Must also roundup width and height when calculating + * since images that are not a multiple of the + * horizontal/vertical subsampling area include + * YCbCr data for the extended image. + */ + tsize_t w = + TIFFroundup(td->td_imagewidth, td->td_ycbcrsubsampling[0]); + tsize_t scanline = TIFFhowmany(w*td->td_bitspersample, 8); + tsize_t samplingarea = + td->td_ycbcrsubsampling[0]*td->td_ycbcrsubsampling[1]; + nrows = TIFFroundup(nrows, td->td_ycbcrsubsampling[1]); + /* NB: don't need TIFFhowmany here 'cuz everything is rounded */ + return ((tsize_t) + (nrows*scanline + 2*(nrows*scanline / samplingarea))); + } else +#endif + return ((tsize_t)(nrows * TIFFScanlineSize(tif))); +} + +/* + * Compute the # bytes in a (row-aligned) strip. + * + * Note that if RowsPerStrip is larger than the + * recorded ImageLength, then the strip size is + * truncated to reflect the actual space required + * to hold the strip. + */ +tsize_t +TIFFStripSize(TIFF* tif) +{ + TIFFDirectory* td = &tif->tif_dir; + uint32 rps = td->td_rowsperstrip; + if (rps > td->td_imagelength) + rps = td->td_imagelength; + return (TIFFVStripSize(tif, rps)); +} + +/* + * Compute a default strip size based on the image + * characteristics and a requested value. If the + * request is <1 then we choose a strip size according + * to certain heuristics. + */ +uint32 +TIFFDefaultStripSize(TIFF* tif, uint32 request) +{ + return (*tif->tif_defstripsize)(tif, request); +} + +uint32 +_TIFFDefaultStripSize(TIFF* tif, uint32 s) +{ + if ((int32) s < 1) { + /* + * If RowsPerStrip is unspecified, try to break the + * image up into strips that are approximately 8Kbytes. + */ + tsize_t scanline = TIFFScanlineSize(tif); + s = (uint32)(8*1024) / (scanline == 0 ? 1 : scanline); + if (s == 0) /* very wide images */ + s = 1; + } + return (s); +} + +/* + * Return the number of bytes to read/write in a call to + * one of the scanline-oriented i/o routines. Note that + * this number may be 1/samples-per-pixel if data is + * stored as separate planes. + */ +tsize_t +TIFFScanlineSize(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + tsize_t scanline; + + scanline = td->td_bitspersample * td->td_imagewidth; + if (td->td_planarconfig == PLANARCONFIG_CONTIG) + scanline *= td->td_samplesperpixel; + return ((tsize_t) TIFFhowmany(scanline, 8)); +} + +/* + * Return the number of bytes required to store a complete + * decoded and packed raster scanline (as opposed to the + * I/O size returned by TIFFScanlineSize which may be less + * if data is store as separate planes). + */ +tsize_t +TIFFRasterScanlineSize(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + tsize_t scanline; + + scanline = td->td_bitspersample * td->td_imagewidth; + if (td->td_planarconfig == PLANARCONFIG_CONTIG) { + scanline *= td->td_samplesperpixel; + return ((tsize_t) TIFFhowmany(scanline, 8)); + } else + return ((tsize_t) + TIFFhowmany(scanline, 8)*td->td_samplesperpixel); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_swab.c b/SlnkDWFImpl/CxImage/tiff/tif_swab.c new file mode 100644 index 0000000..3eca80d --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_swab.c @@ -0,0 +1,217 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_swab.c,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library Bit & Byte Swapping Support. + * + * XXX We assume short = 16-bits and long = 32-bits XXX + */ +#include "tiffiop.h" + +#ifndef TIFFSwabShort +void +TIFFSwabShort(uint16* wp) +{ + register u_char* cp = (u_char*) wp; + int t; + + t = cp[1]; cp[1] = cp[0]; cp[0] = t; +} +#endif + +#ifndef TIFFSwabLong +void +TIFFSwabLong(uint32* lp) +{ + register u_char* cp = (u_char*) lp; + int t; + + t = cp[3]; cp[3] = cp[0]; cp[0] = t; + t = cp[2]; cp[2] = cp[1]; cp[1] = t; +} +#endif + +#ifndef TIFFSwabArrayOfShort +void +TIFFSwabArrayOfShort(uint16* wp, register u_long n) +{ + register u_char* cp; + register int t; + + /* XXX unroll loop some */ + while (n-- > 0) { + cp = (u_char*) wp; + t = cp[1]; cp[1] = cp[0]; cp[0] = t; + wp++; + } +} +#endif + +#ifndef TIFFSwabArrayOfLong +void +TIFFSwabArrayOfLong(register uint32* lp, register u_long n) +{ + register unsigned char *cp; + register int t; + + /* XXX unroll loop some */ + while (n-- > 0) { + cp = (unsigned char *)lp; + t = cp[3]; cp[3] = cp[0]; cp[0] = t; + t = cp[2]; cp[2] = cp[1]; cp[1] = t; + lp++; + } +} +#endif + +#ifndef TIFFSwabDouble +void +TIFFSwabDouble(double *dp) +{ + register uint32* lp = (uint32*) dp; + uint32 t; + + TIFFSwabArrayOfLong(lp, 2); + t = lp[0]; lp[0] = lp[1]; lp[1] = t; +} +#endif + +#ifndef TIFFSwabArrayOfDouble +void +TIFFSwabArrayOfDouble(double* dp, register u_long n) +{ + register uint32* lp = (uint32*) dp; + register uint32 t; + + TIFFSwabArrayOfLong(lp, n + n); + while (n-- > 0) { + t = lp[0]; lp[0] = lp[1]; lp[1] = t; + lp += 2; + } +} +#endif + +/* + * Bit reversal tables. TIFFBitRevTable[] gives + * the bit reversed value of . Used in various + * places in the library when the FillOrder requires + * bit reversal of byte values (e.g. CCITT Fax 3 + * encoding/decoding). TIFFNoBitRevTable is provided + * for algorithms that want an equivalent table that + * do not reverse bit values. + */ +static const unsigned char TIFFBitRevTable[256] = { + 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, + 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, + 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, + 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, + 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, + 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, + 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, + 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, + 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, + 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, + 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, + 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, + 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, + 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, + 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, + 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, + 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, + 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, + 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, + 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, + 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, + 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, + 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, + 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, + 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, + 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, + 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, + 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, + 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, + 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, + 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, + 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff +}; +static const unsigned char TIFFNoBitRevTable[256] = { + 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, 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, 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, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, + 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, + 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, + 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, + 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, + 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, +}; + +const unsigned char* +TIFFGetBitRevTable(int reversed) +{ + return (reversed ? TIFFBitRevTable : TIFFNoBitRevTable); +} + +void +TIFFReverseBits(register u_char* cp, register u_long n) +{ + for (; n > 8; n -= 8) { + cp[0] = TIFFBitRevTable[cp[0]]; + cp[1] = TIFFBitRevTable[cp[1]]; + cp[2] = TIFFBitRevTable[cp[2]]; + cp[3] = TIFFBitRevTable[cp[3]]; + cp[4] = TIFFBitRevTable[cp[4]]; + cp[5] = TIFFBitRevTable[cp[5]]; + cp[6] = TIFFBitRevTable[cp[6]]; + cp[7] = TIFFBitRevTable[cp[7]]; + cp += 8; + } + while (n-- > 0) + *cp = TIFFBitRevTable[*cp], cp++; +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_thunder.c b/SlnkDWFImpl/CxImage/tiff/tif_thunder.c new file mode 100644 index 0000000..e99c43c --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_thunder.c @@ -0,0 +1,154 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_thunder.c,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef THUNDER_SUPPORT +/* + * TIFF Library. + * + * ThunderScan 4-bit Compression Algorithm Support + */ + +/* + * ThunderScan uses an encoding scheme designed for + * 4-bit pixel values. Data is encoded in bytes, with + * each byte split into a 2-bit code word and a 6-bit + * data value. The encoding gives raw data, runs of + * pixels, or pixel values encoded as a delta from the + * previous pixel value. For the latter, either 2-bit + * or 3-bit delta values are used, with the deltas packed + * into a single byte. + */ +#define THUNDER_DATA 0x3f /* mask for 6-bit data */ +#define THUNDER_CODE 0xc0 /* mask for 2-bit code word */ +/* code values */ +#define THUNDER_RUN 0x00 /* run of pixels w/ encoded count */ +#define THUNDER_2BITDELTAS 0x40 /* 3 pixels w/ encoded 2-bit deltas */ +#define DELTA2_SKIP 2 /* skip code for 2-bit deltas */ +#define THUNDER_3BITDELTAS 0x80 /* 2 pixels w/ encoded 3-bit deltas */ +#define DELTA3_SKIP 4 /* skip code for 3-bit deltas */ +#define THUNDER_RAW 0xc0 /* raw data encoded */ + +static const int twobitdeltas[4] = { 0, 1, 0, -1 }; +static const int threebitdeltas[8] = { 0, 1, 2, 3, 0, -3, -2, -1 }; + +#define SETPIXEL(op, v) { \ + lastpixel = (v) & 0xf; \ + if (npixels++ & 1) \ + *op++ |= lastpixel; \ + else \ + op[0] = lastpixel << 4; \ +} + +static int +ThunderDecode(TIFF* tif, tidata_t op, tsize_t maxpixels) +{ + register u_char *bp; + register tsize_t cc; + u_int lastpixel; + tsize_t npixels; + + bp = (u_char *)tif->tif_rawcp; + cc = tif->tif_rawcc; + lastpixel = 0; + npixels = 0; + while (cc > 0 && npixels < maxpixels) { + int n, delta; + + n = *bp++, cc--; + switch (n & THUNDER_CODE) { + case THUNDER_RUN: /* pixel run */ + /* + * Replicate the last pixel n times, + * where n is the lower-order 6 bits. + */ + if (npixels & 1) { + op[0] |= lastpixel; + lastpixel = *op++; npixels++; n--; + } else + lastpixel |= lastpixel << 4; + npixels += n; + for (; n > 0; n -= 2) + *op++ = lastpixel; + if (n == -1) + *--op &= 0xf0; + lastpixel &= 0xf; + break; + case THUNDER_2BITDELTAS: /* 2-bit deltas */ + if ((delta = ((n >> 4) & 3)) != DELTA2_SKIP) + SETPIXEL(op, lastpixel + twobitdeltas[delta]); + if ((delta = ((n >> 2) & 3)) != DELTA2_SKIP) + SETPIXEL(op, lastpixel + twobitdeltas[delta]); + if ((delta = (n & 3)) != DELTA2_SKIP) + SETPIXEL(op, lastpixel + twobitdeltas[delta]); + break; + case THUNDER_3BITDELTAS: /* 3-bit deltas */ + if ((delta = ((n >> 3) & 7)) != DELTA3_SKIP) + SETPIXEL(op, lastpixel + threebitdeltas[delta]); + if ((delta = (n & 7)) != DELTA3_SKIP) + SETPIXEL(op, lastpixel + threebitdeltas[delta]); + break; + case THUNDER_RAW: /* raw data */ + SETPIXEL(op, n); + break; + } + } + tif->tif_rawcp = (tidata_t) bp; + tif->tif_rawcc = cc; + if (npixels != maxpixels) { + TIFFError(tif->tif_name, + "ThunderDecode: %s data at scanline %ld (%lu != %lu)", + npixels < maxpixels ? "Not enough" : "Too much", + (long) tif->tif_row, (long) npixels, (long) maxpixels); + return (0); + } + return (1); +} + +static int +ThunderDecodeRow(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s) +{ + tidata_t row = buf; + + (void) s; + while ((long)occ > 0) { + if (!ThunderDecode(tif, row, tif->tif_dir.td_imagewidth)) + return (0); + occ -= tif->tif_scanlinesize; + row += tif->tif_scanlinesize; + } + return (1); +} + +int +TIFFInitThunderScan(TIFF* tif, int scheme) +{ + (void) scheme; + tif->tif_decoderow = ThunderDecodeRow; + tif->tif_decodestrip = ThunderDecodeRow; + return (1); +} +#endif /* THUNDER_SUPPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tif_tile.c b/SlnkDWFImpl/CxImage/tiff/tif_tile.c new file mode 100644 index 0000000..8f1d038 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_tile.c @@ -0,0 +1,219 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_tile.c,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1991-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Tiled Image Support Routines. + */ +#include "tiffiop.h" + +/* + * Compute which tile an (x,y,z,s) value is in. + */ +ttile_t +TIFFComputeTile(TIFF* tif, uint32 x, uint32 y, uint32 z, tsample_t s) +{ + TIFFDirectory *td = &tif->tif_dir; + uint32 dx = td->td_tilewidth; + uint32 dy = td->td_tilelength; + uint32 dz = td->td_tiledepth; + ttile_t tile = 1; + + if (td->td_imagedepth == 1) + z = 0; + if (dx == (uint32) -1) + dx = td->td_imagewidth; + if (dy == (uint32) -1) + dy = td->td_imagelength; + if (dz == (uint32) -1) + dz = td->td_imagedepth; + if (dx != 0 && dy != 0 && dz != 0) { + uint32 xpt = TIFFhowmany(td->td_imagewidth, dx); + uint32 ypt = TIFFhowmany(td->td_imagelength, dy); + uint32 zpt = TIFFhowmany(td->td_imagedepth, dz); + + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) + tile = (xpt*ypt*zpt)*s + + (xpt*ypt)*(z/dz) + + xpt*(y/dy) + + x/dx; + else + tile = (xpt*ypt)*(z/dz) + xpt*(y/dy) + x/dx + s; + } + return (tile); +} + +/* + * Check an (x,y,z,s) coordinate + * against the image bounds. + */ +int +TIFFCheckTile(TIFF* tif, uint32 x, uint32 y, uint32 z, tsample_t s) +{ + TIFFDirectory *td = &tif->tif_dir; + + if (x >= td->td_imagewidth) { + TIFFError(tif->tif_name, "Col %ld out of range, max %lu", + (long) x, (u_long) td->td_imagewidth); + return (0); + } + if (y >= td->td_imagelength) { + TIFFError(tif->tif_name, "Row %ld out of range, max %lu", + (long) y, (u_long) td->td_imagelength); + return (0); + } + if (z >= td->td_imagedepth) { + TIFFError(tif->tif_name, "Depth %ld out of range, max %lu", + (long) z, (u_long) td->td_imagedepth); + return (0); + } + if (td->td_planarconfig == PLANARCONFIG_SEPARATE && + s >= td->td_samplesperpixel) { + TIFFError(tif->tif_name, "Sample %d out of range, max %u", + (int) s, td->td_samplesperpixel); + return (0); + } + return (1); +} + +/* + * Compute how many tiles are in an image. + */ +ttile_t +TIFFNumberOfTiles(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + uint32 dx = td->td_tilewidth; + uint32 dy = td->td_tilelength; + uint32 dz = td->td_tiledepth; + ttile_t ntiles; + + if (dx == (uint32) -1) + dx = td->td_imagewidth; + if (dy == (uint32) -1) + dy = td->td_imagelength; + if (dz == (uint32) -1) + dz = td->td_imagedepth; + ntiles = (dx == 0 || dy == 0 || dz == 0) ? 0 : + (TIFFhowmany(td->td_imagewidth, dx) * + TIFFhowmany(td->td_imagelength, dy) * + TIFFhowmany(td->td_imagedepth, dz)); + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) + ntiles *= td->td_samplesperpixel; + return (ntiles); +} + +/* + * Compute the # bytes in each row of a tile. + */ +tsize_t +TIFFTileRowSize(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + tsize_t rowsize; + + if (td->td_tilelength == 0 || td->td_tilewidth == 0) + return ((tsize_t) 0); + rowsize = td->td_bitspersample * td->td_tilewidth; + if (td->td_planarconfig == PLANARCONFIG_CONTIG) + rowsize *= td->td_samplesperpixel; + return ((tsize_t) TIFFhowmany(rowsize, 8)); +} + +/* + * Compute the # bytes in a variable length, row-aligned tile. + */ +tsize_t +TIFFVTileSize(TIFF* tif, uint32 nrows) +{ + TIFFDirectory *td = &tif->tif_dir; + tsize_t tilesize; + + if (td->td_tilelength == 0 || td->td_tilewidth == 0 || + td->td_tiledepth == 0) + return ((tsize_t) 0); +#ifdef YCBCR_SUPPORT + if (td->td_planarconfig == PLANARCONFIG_CONTIG && + td->td_photometric == PHOTOMETRIC_YCBCR && + !isUpSampled(tif)) { + /* + * Packed YCbCr data contain one Cb+Cr for every + * HorizontalSampling*VerticalSampling Y values. + * Must also roundup width and height when calculating + * since images that are not a multiple of the + * horizontal/vertical subsampling area include + * YCbCr data for the extended image. + */ + tsize_t w = + TIFFroundup(td->td_tilewidth, td->td_ycbcrsubsampling[0]); + tsize_t rowsize = TIFFhowmany(w*td->td_bitspersample, 8); + tsize_t samplingarea = + td->td_ycbcrsubsampling[0]*td->td_ycbcrsubsampling[1]; + nrows = TIFFroundup(nrows, td->td_ycbcrsubsampling[1]); + /* NB: don't need TIFFhowmany here 'cuz everything is rounded */ + tilesize = nrows*rowsize + 2*(nrows*rowsize / samplingarea); + } else +#endif + tilesize = nrows * TIFFTileRowSize(tif); + return ((tsize_t)(tilesize * td->td_tiledepth)); +} + +/* + * Compute the # bytes in a row-aligned tile. + */ +tsize_t +TIFFTileSize(TIFF* tif) +{ + return (TIFFVTileSize(tif, tif->tif_dir.td_tilelength)); +} + +/* + * Compute a default tile size based on the image + * characteristics and a requested value. If a + * request is <1 then we choose a size according + * to certain heuristics. + */ +void +TIFFDefaultTileSize(TIFF* tif, uint32* tw, uint32* th) +{ + (*tif->tif_deftilesize)(tif, tw, th); +} + +void +_TIFFDefaultTileSize(TIFF* tif, uint32* tw, uint32* th) +{ + (void) tif; + if (*(int32*) tw < 1) + *tw = 256; + if (*(int32*) th < 1) + *th = 256; + /* roundup to a multiple of 16 per the spec */ + if (*tw & 0xf) + *tw = TIFFroundup(*tw, 16); + if (*th & 0xf) + *th = TIFFroundup(*th, 16); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_version.c b/SlnkDWFImpl/CxImage/tiff/tif_version.c new file mode 100644 index 0000000..5275b22 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_version.c @@ -0,0 +1,33 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_version.c,v 1.2 2000/11/13 14:42:38 warmerda Exp $ */ +/* + * Copyright (c) 1992-1997 Sam Leffler + * Copyright (c) 1992-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ +#include "tiffiop.h" + +static const char TIFFVersion[] = "LibTIFF 3.5.7"; + +const char* +TIFFGetVersion(void) +{ + return (TIFFVersion); +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_warning.c b/SlnkDWFImpl/CxImage/tiff/tif_warning.c new file mode 100644 index 0000000..250376d --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_warning.c @@ -0,0 +1,49 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_warning.c,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + */ +#include "tiffiop.h" + +TIFFErrorHandler +TIFFSetWarningHandler(TIFFErrorHandler handler) +{ + TIFFErrorHandler prev = _TIFFwarningHandler; + _TIFFwarningHandler = handler; + return (prev); +} + +void +TIFFWarning(const char* module, const char* fmt, ...) +{ + if (_TIFFwarningHandler) { + va_list ap; + va_start(ap, fmt); + (*_TIFFwarningHandler)(module, fmt, ap); + va_end(ap); + } +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_write.c b/SlnkDWFImpl/CxImage/tiff/tif_write.c new file mode 100644 index 0000000..ddad523 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_write.c @@ -0,0 +1,659 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_write.c,v 1.5 2000/02/11 19:28:17 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Scanline-oriented Write Support + */ +#include "tiffiop.h" +#include +#include + +#define REWRITE_HACK + +#define STRIPINCR 20 /* expansion factor on strip array */ + +#define WRITECHECKSTRIPS(tif, module) \ + (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module)) +#define WRITECHECKTILES(tif, module) \ + (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module)) +#define BUFFERCHECK(tif) \ + ((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \ + TIFFWriteBufferSetup((tif), NULL, (tsize_t) -1)) + +static int TIFFGrowStrips(TIFF*, int, const char*); +static int TIFFAppendToStrip(TIFF*, tstrip_t, tidata_t, tsize_t); +static int TIFFSetupStrips(TIFF*); + +int +TIFFWriteScanline(TIFF* tif, tdata_t buf, uint32 row, tsample_t sample) +{ + static const char module[] = "TIFFWriteScanline"; + register TIFFDirectory *td; + int status, imagegrew = 0; + tstrip_t strip; + + if (!WRITECHECKSTRIPS(tif, module)) + return (-1); + /* + * Handle delayed allocation of data buffer. This + * permits it to be sized more intelligently (using + * directory information). + */ + if (!BUFFERCHECK(tif)) + return (-1); + td = &tif->tif_dir; + /* + * Extend image length if needed + * (but only for PlanarConfig=1). + */ + if (row >= td->td_imagelength) { /* extend image */ + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { + TIFFError(tif->tif_name, + "Can not change \"ImageLength\" when using separate planes"); + return (-1); + } + td->td_imagelength = row+1; + imagegrew = 1; + } + /* + * Calculate strip and check for crossings. + */ + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { + if (sample >= td->td_samplesperpixel) { + TIFFError(tif->tif_name, + "%d: Sample out of range, max %d", + sample, td->td_samplesperpixel); + return (-1); + } + strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip; + } else + strip = row / td->td_rowsperstrip; + if (strip != tif->tif_curstrip) { + /* + * Changing strips -- flush any data present. + */ + if (!TIFFFlushData(tif)) + return (-1); + tif->tif_curstrip = strip; + /* + * Watch out for a growing image. The value of + * strips/image will initially be 1 (since it + * can't be deduced until the imagelength is known). + */ + if (strip >= td->td_stripsperimage && imagegrew) + td->td_stripsperimage = + TIFFhowmany(td->td_imagelength,td->td_rowsperstrip); + tif->tif_row = + (strip % td->td_stripsperimage) * td->td_rowsperstrip; + if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { + if (!(*tif->tif_setupencode)(tif)) + return (-1); + tif->tif_flags |= TIFF_CODERSETUP; + } + if (!(*tif->tif_preencode)(tif, sample)) + return (-1); + tif->tif_flags |= TIFF_POSTENCODE; + } + /* + * Check strip array to make sure there's space. + * We don't support dynamically growing files that + * have data organized in separate bitplanes because + * it's too painful. In that case we require that + * the imagelength be set properly before the first + * write (so that the strips array will be fully + * allocated above). + */ + if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module)) + return (-1); + /* + * Ensure the write is either sequential or at the + * beginning of a strip (or that we can randomly + * access the data -- i.e. no encoding). + */ + if (row != tif->tif_row) { + if (row < tif->tif_row) { + /* + * Moving backwards within the same strip: + * backup to the start and then decode + * forward (below). + */ + tif->tif_row = (strip % td->td_stripsperimage) * + td->td_rowsperstrip; + tif->tif_rawcp = tif->tif_rawdata; + } + /* + * Seek forward to the desired row. + */ + if (!(*tif->tif_seek)(tif, row - tif->tif_row)) + return (-1); + tif->tif_row = row; + } + status = (*tif->tif_encoderow)(tif, (tidata_t) buf, + tif->tif_scanlinesize, sample); + tif->tif_row++; + return (status); +} + +/* + * Encode the supplied data and write it to the + * specified strip. There must be space for the + * data; we don't check if strips overlap! + * + * NB: Image length must be setup before writing. + */ +tsize_t +TIFFWriteEncodedStrip(TIFF* tif, tstrip_t strip, tdata_t data, tsize_t cc) +{ + static const char module[] = "TIFFWriteEncodedStrip"; + TIFFDirectory *td = &tif->tif_dir; + tsample_t sample; + + if (!WRITECHECKSTRIPS(tif, module)) + return ((tsize_t) -1); + /* + * Check strip array to make sure there's space. + * We don't support dynamically growing files that + * have data organized in separate bitplanes because + * it's too painful. In that case we require that + * the imagelength be set properly before the first + * write (so that the strips array will be fully + * allocated above). + */ + if (strip >= td->td_nstrips) { + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { + TIFFError(tif->tif_name, + "Can not grow image by strips when using separate planes"); + return ((tsize_t) -1); + } + if (!TIFFGrowStrips(tif, 1, module)) + return ((tsize_t) -1); + td->td_stripsperimage = + TIFFhowmany(td->td_imagelength, td->td_rowsperstrip); + } + /* + * Handle delayed allocation of data buffer. This + * permits it to be sized according to the directory + * info. + */ + if (!BUFFERCHECK(tif)) + return ((tsize_t) -1); + tif->tif_curstrip = strip; + tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; + if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { + if (!(*tif->tif_setupencode)(tif)) + return ((tsize_t) -1); + tif->tif_flags |= TIFF_CODERSETUP; + } + +#ifdef REWRITE_HACK + tif->tif_rawcc = 0; + tif->tif_rawcp = tif->tif_rawdata; + + if( td->td_stripbytecount[strip] > 0 ) + { + /* if we are writing over existing tiles, zero length. */ + td->td_stripbytecount[strip] = 0; + + /* this forces TIFFAppendToStrip() to do a seek */ + tif->tif_curoff = 0; + } +#endif + + tif->tif_flags &= ~TIFF_POSTENCODE; + sample = (tsample_t)(strip / td->td_stripsperimage); + if (!(*tif->tif_preencode)(tif, sample)) + return ((tsize_t) -1); + if (!(*tif->tif_encodestrip)(tif, (tidata_t) data, cc, sample)) + return ((tsize_t) 0); + if (!(*tif->tif_postencode)(tif)) + return ((tsize_t) -1); + if (!isFillOrder(tif, td->td_fillorder) && + (tif->tif_flags & TIFF_NOBITREV) == 0) + TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc); + if (tif->tif_rawcc > 0 && + !TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc)) + return ((tsize_t) -1); + tif->tif_rawcc = 0; + tif->tif_rawcp = tif->tif_rawdata; + return (cc); +} + +/* + * Write the supplied data to the specified strip. + * There must be space for the data; we don't check + * if strips overlap! + * + * NB: Image length must be setup before writing. + */ +tsize_t +TIFFWriteRawStrip(TIFF* tif, tstrip_t strip, tdata_t data, tsize_t cc) +{ + static const char module[] = "TIFFWriteRawStrip"; + TIFFDirectory *td = &tif->tif_dir; + + if (!WRITECHECKSTRIPS(tif, module)) + return ((tsize_t) -1); + /* + * Check strip array to make sure there's space. + * We don't support dynamically growing files that + * have data organized in separate bitplanes because + * it's too painful. In that case we require that + * the imagelength be set properly before the first + * write (so that the strips array will be fully + * allocated above). + */ + if (strip >= td->td_nstrips) { + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { + TIFFError(tif->tif_name, + "Can not grow image by strips when using separate planes"); + return ((tsize_t) -1); + } + /* + * Watch out for a growing image. The value of + * strips/image will initially be 1 (since it + * can't be deduced until the imagelength is known). + */ + if (strip >= td->td_stripsperimage) + td->td_stripsperimage = + TIFFhowmany(td->td_imagelength,td->td_rowsperstrip); + if (!TIFFGrowStrips(tif, 1, module)) + return ((tsize_t) -1); + } + tif->tif_curstrip = strip; + tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; + return (TIFFAppendToStrip(tif, strip, (tidata_t) data, cc) ? + cc : (tsize_t) -1); +} + +/* + * Write and compress a tile of data. The + * tile is selected by the (x,y,z,s) coordinates. + */ +tsize_t +TIFFWriteTile(TIFF* tif, + tdata_t buf, uint32 x, uint32 y, uint32 z, tsample_t s) +{ + if (!TIFFCheckTile(tif, x, y, z, s)) + return (-1); + /* + * NB: A tile size of -1 is used instead of tif_tilesize knowing + * that TIFFWriteEncodedTile will clamp this to the tile size. + * This is done because the tile size may not be defined until + * after the output buffer is setup in TIFFWriteBufferSetup. + */ + return (TIFFWriteEncodedTile(tif, + TIFFComputeTile(tif, x, y, z, s), buf, (tsize_t) -1)); +} + +/* + * Encode the supplied data and write it to the + * specified tile. There must be space for the + * data. The function clamps individual writes + * to a tile to the tile size, but does not (and + * can not) check that multiple writes to the same + * tile do not write more than tile size data. + * + * NB: Image length must be setup before writing; this + * interface does not support automatically growing + * the image on each write (as TIFFWriteScanline does). + */ +tsize_t +TIFFWriteEncodedTile(TIFF* tif, ttile_t tile, tdata_t data, tsize_t cc) +{ + static const char module[] = "TIFFWriteEncodedTile"; + TIFFDirectory *td; + tsample_t sample; + + if (!WRITECHECKTILES(tif, module)) + return ((tsize_t) -1); + td = &tif->tif_dir; + if (tile >= td->td_nstrips) { + TIFFError(module, "%s: Tile %lu out of range, max %lu", + tif->tif_name, (u_long) tile, (u_long) td->td_nstrips); + return ((tsize_t) -1); + } + /* + * Handle delayed allocation of data buffer. This + * permits it to be sized more intelligently (using + * directory information). + */ + if (!BUFFERCHECK(tif)) + return ((tsize_t) -1); + tif->tif_curtile = tile; + +#ifdef REWRITE_HACK + tif->tif_rawcc = 0; + tif->tif_rawcp = tif->tif_rawdata; + + if( td->td_stripbytecount[tile] > 0 ) + { + /* if we are writing over existing tiles, zero length. */ + td->td_stripbytecount[tile] = 0; + + /* this forces TIFFAppendToStrip() to do a seek */ + tif->tif_curoff = 0; + } +#endif + + /* + * Compute tiles per row & per column to compute + * current row and column + */ + tif->tif_row = (tile % TIFFhowmany(td->td_imagelength, td->td_tilelength)) + * td->td_tilelength; + tif->tif_col = (tile % TIFFhowmany(td->td_imagewidth, td->td_tilewidth)) + * td->td_tilewidth; + + if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { + if (!(*tif->tif_setupencode)(tif)) + return ((tsize_t) -1); + tif->tif_flags |= TIFF_CODERSETUP; + } + tif->tif_flags &= ~TIFF_POSTENCODE; + sample = (tsample_t)(tile/td->td_stripsperimage); + if (!(*tif->tif_preencode)(tif, sample)) + return ((tsize_t) -1); + /* + * Clamp write amount to the tile size. This is mostly + * done so that callers can pass in some large number + * (e.g. -1) and have the tile size used instead. + */ + if ( cc < 1 || cc > tif->tif_tilesize) + cc = tif->tif_tilesize; + if (!(*tif->tif_encodetile)(tif, (tidata_t) data, cc, sample)) + return ((tsize_t) 0); + if (!(*tif->tif_postencode)(tif)) + return ((tsize_t) -1); + if (!isFillOrder(tif, td->td_fillorder) && + (tif->tif_flags & TIFF_NOBITREV) == 0) + TIFFReverseBits((u_char *)tif->tif_rawdata, tif->tif_rawcc); + if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile, + tif->tif_rawdata, tif->tif_rawcc)) + return ((tsize_t) -1); + tif->tif_rawcc = 0; + tif->tif_rawcp = tif->tif_rawdata; + return (cc); +} + +/* + * Write the supplied data to the specified strip. + * There must be space for the data; we don't check + * if strips overlap! + * + * NB: Image length must be setup before writing; this + * interface does not support automatically growing + * the image on each write (as TIFFWriteScanline does). + */ +tsize_t +TIFFWriteRawTile(TIFF* tif, ttile_t tile, tdata_t data, tsize_t cc) +{ + static const char module[] = "TIFFWriteRawTile"; + + if (!WRITECHECKTILES(tif, module)) + return ((tsize_t) -1); + if (tile >= tif->tif_dir.td_nstrips) { + TIFFError(module, "%s: Tile %lu out of range, max %lu", + tif->tif_name, (u_long) tile, + (u_long) tif->tif_dir.td_nstrips); + return ((tsize_t) -1); + } + return (TIFFAppendToStrip(tif, tile, (tidata_t) data, cc) ? + cc : (tsize_t) -1); +} + +#define isUnspecified(tif, f) \ + (TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0) + +static int +TIFFSetupStrips(TIFF* tif) +{ + TIFFDirectory* td = &tif->tif_dir; + + if (isTiled(tif)) + td->td_stripsperimage = + isUnspecified(tif, FIELD_TILEDIMENSIONS) ? + td->td_samplesperpixel : TIFFNumberOfTiles(tif); + else + td->td_stripsperimage = + isUnspecified(tif, FIELD_ROWSPERSTRIP) ? + td->td_samplesperpixel : TIFFNumberOfStrips(tif); + td->td_nstrips = td->td_stripsperimage; + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) + td->td_stripsperimage /= td->td_samplesperpixel; + td->td_stripoffset = (uint32 *) + _TIFFmalloc(td->td_nstrips * sizeof (uint32)); + td->td_stripbytecount = (uint32 *) + _TIFFmalloc(td->td_nstrips * sizeof (uint32)); + if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL) + return (0); + /* + * Place data at the end-of-file + * (by setting offsets to zero). + */ + _TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint32)); + _TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint32)); + TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS); + TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); + return (1); +} +#undef isUnspecified + +/* + * Verify file is writable and that the directory + * information is setup properly. In doing the latter + * we also "freeze" the state of the directory so + * that important information is not changed. + */ +int +TIFFWriteCheck(TIFF* tif, int tiles, const char* module) +{ + if (tif->tif_mode == O_RDONLY) { + TIFFError(module, "%s: File not open for writing", + tif->tif_name); + return (0); + } + if (tiles ^ isTiled(tif)) { + TIFFError(tif->tif_name, tiles ? + "Can not write tiles to a stripped image" : + "Can not write scanlines to a tiled image"); + return (0); + } + /* + * On the first write verify all the required information + * has been setup and initialize any data structures that + * had to wait until directory information was set. + * Note that a lot of our work is assumed to remain valid + * because we disallow any of the important parameters + * from changing after we start writing (i.e. once + * TIFF_BEENWRITING is set, TIFFSetField will only allow + * the image's length to be changed). + */ + if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { + TIFFError(module, + "%s: Must set \"ImageWidth\" before writing data", + tif->tif_name); + return (0); + } + if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { + TIFFError(module, + "%s: Must set \"PlanarConfiguration\" before writing data", + tif->tif_name); + return (0); + } + if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) { + tif->tif_dir.td_nstrips = 0; + TIFFError(module, "%s: No space for %s arrays", + tif->tif_name, isTiled(tif) ? "tile" : "strip"); + return (0); + } + tif->tif_tilesize = TIFFTileSize(tif); + tif->tif_scanlinesize = TIFFScanlineSize(tif); + tif->tif_flags |= TIFF_BEENWRITING; + return (1); +} + +/* + * Setup the raw data buffer used for encoding. + */ +int +TIFFWriteBufferSetup(TIFF* tif, tdata_t bp, tsize_t size) +{ + static const char module[] = "TIFFWriteBufferSetup"; + + if (tif->tif_rawdata) { + if (tif->tif_flags & TIFF_MYBUFFER) { + _TIFFfree(tif->tif_rawdata); + tif->tif_flags &= ~TIFF_MYBUFFER; + } + tif->tif_rawdata = NULL; + } + if (size == (tsize_t) -1) { + size = (isTiled(tif) ? + tif->tif_tilesize : tif->tif_scanlinesize); + /* + * Make raw data buffer at least 8K + */ + if (size < 8*1024) + size = 8*1024; + bp = NULL; /* NB: force malloc */ + } + if (bp == NULL) { + bp = _TIFFmalloc(size); + if (bp == NULL) { + TIFFError(module, "%s: No space for output buffer", + tif->tif_name); + return (0); + } + tif->tif_flags |= TIFF_MYBUFFER; + } else + tif->tif_flags &= ~TIFF_MYBUFFER; + tif->tif_rawdata = (tidata_t) bp; + tif->tif_rawdatasize = size; + tif->tif_rawcc = 0; + tif->tif_rawcp = tif->tif_rawdata; + tif->tif_flags |= TIFF_BUFFERSETUP; + return (1); +} + +/* + * Grow the strip data structures by delta strips. + */ +static int +TIFFGrowStrips(TIFF* tif, int delta, const char* module) +{ + TIFFDirectory *td = &tif->tif_dir; + + assert(td->td_planarconfig == PLANARCONFIG_CONTIG); + td->td_stripoffset = (uint32*)_TIFFrealloc(td->td_stripoffset, + (td->td_nstrips + delta) * sizeof (uint32)); + td->td_stripbytecount = (uint32*)_TIFFrealloc(td->td_stripbytecount, + (td->td_nstrips + delta) * sizeof (uint32)); + if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL) { + td->td_nstrips = 0; + TIFFError(module, "%s: No space to expand strip arrays", + tif->tif_name); + return (0); + } + _TIFFmemset(td->td_stripoffset+td->td_nstrips, 0, delta*sizeof (uint32)); + _TIFFmemset(td->td_stripbytecount+td->td_nstrips, 0, delta*sizeof (uint32)); + td->td_nstrips += delta; + return (1); +} + +/* + * Append the data to the specified strip. + * + * NB: We don't check that there's space in the + * file (i.e. that strips do not overlap). + */ +static int +TIFFAppendToStrip(TIFF* tif, tstrip_t strip, tidata_t data, tsize_t cc) +{ + TIFFDirectory *td = &tif->tif_dir; + static const char module[] = "TIFFAppendToStrip"; + + if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) { + /* + * No current offset, set the current strip. + */ + if (td->td_stripoffset[strip] != 0) { + if (!SeekOK(tif, td->td_stripoffset[strip])) { + TIFFError(module, + "%s: Seek error at scanline %lu", + tif->tif_name, (u_long) tif->tif_row); + return (0); + } + } else + td->td_stripoffset[strip] = + TIFFSeekFile(tif, (toff_t) 0, SEEK_END); + tif->tif_curoff = td->td_stripoffset[strip]; + } + if (!WriteOK(tif, data, cc)) { + TIFFError(module, "%s: Write error at scanline %lu", + tif->tif_name, (u_long) tif->tif_row); + return (0); + } + tif->tif_curoff += cc; + td->td_stripbytecount[strip] += cc; + return (1); +} + +/* + * Internal version of TIFFFlushData that can be + * called by ``encodestrip routines'' w/o concern + * for infinite recursion. + */ +int +TIFFFlushData1(TIFF* tif) +{ + if (tif->tif_rawcc > 0) { + if (!isFillOrder(tif, tif->tif_dir.td_fillorder) && + (tif->tif_flags & TIFF_NOBITREV) == 0) + TIFFReverseBits((u_char *)tif->tif_rawdata, + tif->tif_rawcc); + if (!TIFFAppendToStrip(tif, + isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip, + tif->tif_rawdata, tif->tif_rawcc)) + return (0); + tif->tif_rawcc = 0; + tif->tif_rawcp = tif->tif_rawdata; + } + return (1); +} + +/* + * Set the current write offset. This should only be + * used to set the offset to a known previous location + * (very carefully), or to 0 so that the next write gets + * appended to the end of the file. + */ +void +TIFFSetWriteOffset(TIFF* tif, toff_t off) +{ + tif->tif_curoff = off; +} diff --git a/SlnkDWFImpl/CxImage/tiff/tif_zip.c b/SlnkDWFImpl/CxImage/tiff/tif_zip.c new file mode 100644 index 0000000..018ae06 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tif_zip.c @@ -0,0 +1,367 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_zip.c,v 1.2 1999/12/07 17:11:38 mwelles Exp $ */ + +/* + * Copyright (c) 1995-1997 Sam Leffler + * Copyright (c) 1995-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tiffiop.h" +#ifdef ZIP_SUPPORT +/* + * TIFF Library. + * + * ZIP (aka Deflate) Compression Support + * + * This file is simply an interface to the zlib library written by + * Jean-loup Gailly and Mark Adler. You must use version 1.0 or later + * of the library: this code assumes the 1.0 API and also depends on + * the ability to write the zlib header multiple times (one per strip) + * which was not possible with versions prior to 0.95. Note also that + * older versions of this codec avoided this bug by supressing the header + * entirely. This means that files written with the old library cannot + * be read; they should be converted to a different compression scheme + * and then reconverted. + * + * The data format used by the zlib library is described in the files + * zlib-3.1.doc, deflate-1.1.doc and gzip-4.1.doc, available in the + * directory ftp://ftp.uu.net/pub/archiving/zip/doc. The library was + * last found at ftp://ftp.uu.net/pub/archiving/zip/zlib/zlib-0.99.tar.gz. + */ +#include "tif_predict.h" +#include "zlib.h" + +#include +#include + +/* + * Sigh, ZLIB_VERSION is defined as a string so there's no + * way to do a proper check here. Instead we guess based + * on the presence of #defines that were added between the + * 0.95 and 1.0 distributions. + */ +#if !defined(Z_NO_COMPRESSION) || !defined(Z_DEFLATED) +#error "Antiquated ZLIB software; you must use version 1.0 or later" +#endif + +/* + * State block for each open TIFF + * file using ZIP compression/decompression. + */ +typedef struct { + TIFFPredictorState predict; + z_stream stream; + int zipquality; /* compression level */ + int state; /* state flags */ +#define ZSTATE_INIT 0x1 /* zlib setup successfully */ + + TIFFVGetMethod vgetparent; /* super-class method */ + TIFFVSetMethod vsetparent; /* super-class method */ +} ZIPState; + +#define ZState(tif) ((ZIPState*) (tif)->tif_data) +#define DecoderState(tif) ZState(tif) +#define EncoderState(tif) ZState(tif) + +static int ZIPEncode(TIFF*, tidata_t, tsize_t, tsample_t); +static int ZIPDecode(TIFF*, tidata_t, tsize_t, tsample_t); + +static int +ZIPSetupDecode(TIFF* tif) +{ + ZIPState* sp = DecoderState(tif); + static const char module[] = "ZIPSetupDecode"; + + assert(sp != NULL); + if (inflateInit(&sp->stream) != Z_OK) { + TIFFError(module, "%s: %s", tif->tif_name, sp->stream.msg); + return (0); + } else { + sp->state |= ZSTATE_INIT; + return (1); + } +} + +/* + * Setup state for decoding a strip. + */ +static int +ZIPPreDecode(TIFF* tif, tsample_t s) +{ + ZIPState* sp = DecoderState(tif); + + (void) s; + assert(sp != NULL); + sp->stream.next_in = tif->tif_rawdata; + sp->stream.avail_in = tif->tif_rawcc; + return (inflateReset(&sp->stream) == Z_OK); +} + +static int +ZIPDecode(TIFF* tif, tidata_t op, tsize_t occ, tsample_t s) +{ + ZIPState* sp = DecoderState(tif); + static const char module[] = "ZIPDecode"; + + (void) s; + assert(sp != NULL); + sp->stream.next_out = op; + sp->stream.avail_out = occ; + do { + int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); + if (state == Z_STREAM_END) + break; + if (state == Z_DATA_ERROR) { + TIFFError(module, + "%s: Decoding error at scanline %d, %s", + tif->tif_name, tif->tif_row, sp->stream.msg); + if (inflateSync(&sp->stream) != Z_OK) + return (0); + continue; + } + if (state != Z_OK) { + TIFFError(module, "%s: zlib error: %s", + tif->tif_name, sp->stream.msg); + return (0); + } + } while (sp->stream.avail_out > 0); + if (sp->stream.avail_out != 0) { + TIFFError(module, + "%s: Not enough data at scanline %d (short %d bytes)", + tif->tif_name, tif->tif_row, sp->stream.avail_out); + return (0); + } + return (1); +} + +static int +ZIPSetupEncode(TIFF* tif) +{ + ZIPState* sp = EncoderState(tif); + static const char module[] = "ZIPSetupEncode"; + + assert(sp != NULL); + if (deflateInit(&sp->stream, sp->zipquality) != Z_OK) { + TIFFError(module, "%s: %s", tif->tif_name, sp->stream.msg); + return (0); + } else { + sp->state |= ZSTATE_INIT; + return (1); + } +} + +/* + * Reset encoding state at the start of a strip. + */ +static int +ZIPPreEncode(TIFF* tif, tsample_t s) +{ + ZIPState *sp = EncoderState(tif); + + (void) s; + assert(sp != NULL); + sp->stream.next_out = tif->tif_rawdata; + sp->stream.avail_out = tif->tif_rawdatasize; + return (deflateReset(&sp->stream) == Z_OK); +} + +/* + * Encode a chunk of pixels. + */ +static int +ZIPEncode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) +{ + ZIPState *sp = EncoderState(tif); + static const char module[] = "ZIPEncode"; + + (void) s; + sp->stream.next_in = bp; + sp->stream.avail_in = cc; + do { + if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) { + TIFFError(module, "%s: Encoder error: %s", + tif->tif_name, sp->stream.msg); + return (0); + } + if (sp->stream.avail_out == 0) { + tif->tif_rawcc = tif->tif_rawdatasize; + TIFFFlushData1(tif); + sp->stream.next_out = tif->tif_rawdata; + sp->stream.avail_out = tif->tif_rawdatasize; + } + } while (sp->stream.avail_in > 0); + return (1); +} + +/* + * Finish off an encoded strip by flushing the last + * string and tacking on an End Of Information code. + */ +static int +ZIPPostEncode(TIFF* tif) +{ + ZIPState *sp = EncoderState(tif); + static const char module[] = "ZIPPostEncode"; + int state; + + sp->stream.avail_in = 0; + do { + state = deflate(&sp->stream, Z_FINISH); + switch (state) { + case Z_STREAM_END: + case Z_OK: + if ((int)sp->stream.avail_out != tif->tif_rawdatasize) { + tif->tif_rawcc = + tif->tif_rawdatasize - sp->stream.avail_out; + TIFFFlushData1(tif); + sp->stream.next_out = tif->tif_rawdata; + sp->stream.avail_out = tif->tif_rawdatasize; + } + break; + default: + TIFFError(module, "%s: zlib error: %s", + tif->tif_name, sp->stream.msg); + return (0); + } + } while (state != Z_STREAM_END); + return (1); +} + +static void +ZIPCleanup(TIFF* tif) +{ + ZIPState* sp = ZState(tif); + if (sp) { + if (sp->state&ZSTATE_INIT) { + /* NB: avoid problems in the library */ + if (tif->tif_mode == O_RDONLY) + inflateEnd(&sp->stream); + else + deflateEnd(&sp->stream); + } + _TIFFfree(sp); + tif->tif_data = NULL; + } +} + +static int +ZIPVSetField(TIFF* tif, ttag_t tag, va_list ap) +{ + ZIPState* sp = ZState(tif); + static const char module[] = "ZIPVSetField"; + + switch (tag) { + case TIFFTAG_ZIPQUALITY: + sp->zipquality = va_arg(ap, int); + if (tif->tif_mode != O_RDONLY && (sp->state&ZSTATE_INIT)) { + if (deflateParams(&sp->stream, + sp->zipquality, Z_DEFAULT_STRATEGY) != Z_OK) { + TIFFError(module, "%s: zlib error: %s", + tif->tif_name, sp->stream.msg); + return (0); + } + } + return (1); + default: + return (*sp->vsetparent)(tif, tag, ap); + } + /*NOTREACHED*/ +} + +static int +ZIPVGetField(TIFF* tif, ttag_t tag, va_list ap) +{ + ZIPState* sp = ZState(tif); + + switch (tag) { + case TIFFTAG_ZIPQUALITY: + *va_arg(ap, int*) = sp->zipquality; + break; + default: + return (*sp->vgetparent)(tif, tag, ap); + } + return (1); +} + +static const TIFFFieldInfo zipFieldInfo[] = { + { TIFFTAG_ZIPQUALITY, 0, 0, TIFF_ANY, FIELD_PSEUDO, + TRUE, FALSE, "" }, +}; +#define N(a) (sizeof (a) / sizeof (a[0])) + +int +TIFFInitZIP(TIFF* tif, int scheme) +{ + ZIPState* sp; + + assert( (scheme == COMPRESSION_DEFLATE) || (scheme == COMPRESSION_ADOBE_DEFLATE)); + + /* + * Allocate state block so tag methods have storage to record values. + */ + tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (ZIPState)); + if (tif->tif_data == NULL) + goto bad; + sp = ZState(tif); + sp->stream.zalloc = NULL; + sp->stream.zfree = NULL; + sp->stream.opaque = NULL; + sp->stream.data_type = Z_BINARY; + + /* + * Merge codec-specific tag information and + * override parent get/set field methods. + */ + _TIFFMergeFieldInfo(tif, zipFieldInfo, N(zipFieldInfo)); + sp->vgetparent = tif->tif_vgetfield; + tif->tif_vgetfield = ZIPVGetField; /* hook for codec tags */ + sp->vsetparent = tif->tif_vsetfield; + tif->tif_vsetfield = ZIPVSetField; /* hook for codec tags */ + + /* Default values for codec-specific fields */ + sp->zipquality = Z_DEFAULT_COMPRESSION; /* default comp. level */ + sp->state = 0; + + /* + * Install codec methods. + */ + tif->tif_setupdecode = ZIPSetupDecode; + tif->tif_predecode = ZIPPreDecode; + tif->tif_decoderow = ZIPDecode; + tif->tif_decodestrip = ZIPDecode; + tif->tif_decodetile = ZIPDecode; + tif->tif_setupencode = ZIPSetupEncode; + tif->tif_preencode = ZIPPreEncode; + tif->tif_postencode = ZIPPostEncode; + tif->tif_encoderow = ZIPEncode; + tif->tif_encodestrip = ZIPEncode; + tif->tif_encodetile = ZIPEncode; + tif->tif_cleanup = ZIPCleanup; + /* + * Setup predictor setup. + */ + (void) TIFFPredictorInit(tif); + return (1); +bad: + TIFFError("TIFFInitZIP", "No space for ZIP state block"); + return (0); +} +#endif /* ZIP_SUPORT */ diff --git a/SlnkDWFImpl/CxImage/tiff/tiff.h b/SlnkDWFImpl/CxImage/tiff/tiff.h new file mode 100644 index 0000000..b74f5c5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tiff.h @@ -0,0 +1,468 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tiff.h,v 1.10 2001/11/02 17:25:52 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _TIFF_ +#define _TIFF_ +/* + * Tag Image File Format (TIFF) + * + * Based on Rev 6.0 from: + * Developer's Desk + * Aldus Corporation + * 411 First Ave. South + * Suite 200 + * Seattle, WA 98104 + * 206-622-5500 + */ +#define TIFF_VERSION 42 + +#define TIFF_BIGENDIAN 0x4d4d +#define TIFF_LITTLEENDIAN 0x4949 + +/* + * The so called TIFF types conflict with definitions from inttypes.h + * included from sys/types.h on AIX (at least using VisualAge compiler). + * We try to work around this by detecting this case. Defining + * _TIFF_DATA_TYPEDEFS_ short circuits the later definitions in tiff.h, and + * we will in the holes not provided for by inttypes.h. + * + * See http://bugzilla.remotesensing.org/show_bug.cgi?id=39 + */ +#if defined(_H_INTTYPES) && defined(_ALL_SOURCE) + +#define _TIFF_DATA_TYPEDEFS_ +typedef unsigned char uint8; +typedef unsigned short uint16; +typedef unsigned int uint32; + +#endif + +/* + * Intrinsic data types required by the file format: + * + * 8-bit quantities int8/uint8 + * 16-bit quantities int16/uint16 + * 32-bit quantities int32/uint32 + * strings unsigned char* + */ +#ifndef _TIFF_DATA_TYPEDEFS_ +#define _TIFF_DATA_TYPEDEFS_ + +#ifdef __STDC__ +typedef signed char int8; /* NB: non-ANSI compilers may not grok */ +#else +typedef char int8; +#endif +typedef unsigned char uint8; +typedef short int16; +typedef unsigned short uint16; /* sizeof (uint16) must == 2 */ +#if defined(__alpha) || (defined(_MIPS_SZLONG) && _MIPS_SZLONG == 64) || defined(__LP64__) +typedef int int32; +typedef unsigned int uint32; /* sizeof (uint32) must == 4 */ +#else +typedef long int32; +typedef unsigned long uint32; /* sizeof (uint32) must == 4 */ +#endif +#endif /* _TIFF_DATA_TYPEDEFS_ */ + +/* For TIFFReassignTagToIgnore */ +enum TIFFIgnoreSense /* IGNORE tag table */ +{ + TIS_STORE, + TIS_EXTRACT, + TIS_EMPTY +}; + +typedef struct { + uint16 tiff_magic; /* magic number (defines byte order) */ + uint16 tiff_version; /* TIFF version number */ + uint32 tiff_diroff; /* byte offset to first directory */ +} TIFFHeader; + +/* + * TIFF Image File Directories are comprised of + * a table of field descriptors of the form shown + * below. The table is sorted in ascending order + * by tag. The values associated with each entry + * are disjoint and may appear anywhere in the file + * (so long as they are placed on a word boundary). + * + * If the value is 4 bytes or less, then it is placed + * in the offset field to save space. If the value + * is less than 4 bytes, it is left-justified in the + * offset field. + */ +typedef struct { + uint16 tdir_tag; /* see below */ + uint16 tdir_type; /* data type; see below */ + uint32 tdir_count; /* number of items; length in spec */ + uint32 tdir_offset; /* byte offset to field data */ +} TIFFDirEntry; + +/* + * NB: In the comments below, + * - items marked with a + are obsoleted by revision 5.0, + * - items marked with a ! are introduced in revision 6.0. + * - items marked with a % are introduced post revision 6.0. + * - items marked with a $ are obsoleted by revision 6.0. + */ + +/* + * Tag data type information. + * + * Note: RATIONALs are the ratio of two 32-bit integer values. + */ +typedef enum { + TIFF_NOTYPE = 0, /* placeholder */ + TIFF_BYTE = 1, /* 8-bit unsigned integer */ + TIFF_ASCII = 2, /* 8-bit bytes w/ last byte null */ + TIFF_SHORT = 3, /* 16-bit unsigned integer */ + TIFF_LONG = 4, /* 32-bit unsigned integer */ + TIFF_RATIONAL = 5, /* 64-bit unsigned fraction */ + TIFF_SBYTE = 6, /* !8-bit signed integer */ + TIFF_UNDEFINED = 7, /* !8-bit untyped data */ + TIFF_SSHORT = 8, /* !16-bit signed integer */ + TIFF_SLONG = 9, /* !32-bit signed integer */ + TIFF_SRATIONAL = 10, /* !64-bit signed fraction */ + TIFF_FLOAT = 11, /* !32-bit IEEE floating point */ + TIFF_DOUBLE = 12 /* !64-bit IEEE floating point */ +} TIFFDataType; + +/* + * TIFF Tag Definitions. + */ +#define TIFFTAG_SUBFILETYPE 254 /* subfile data descriptor */ +#define FILETYPE_REDUCEDIMAGE 0x1 /* reduced resolution version */ +#define FILETYPE_PAGE 0x2 /* one page of many */ +#define FILETYPE_MASK 0x4 /* transparency mask */ +#define TIFFTAG_OSUBFILETYPE 255 /* +kind of data in subfile */ +#define OFILETYPE_IMAGE 1 /* full resolution image data */ +#define OFILETYPE_REDUCEDIMAGE 2 /* reduced size image data */ +#define OFILETYPE_PAGE 3 /* one page of many */ +#define TIFFTAG_IMAGEWIDTH 256 /* image width in pixels */ +#define TIFFTAG_IMAGELENGTH 257 /* image height in pixels */ +#define TIFFTAG_BITSPERSAMPLE 258 /* bits per channel (sample) */ +#define TIFFTAG_COMPRESSION 259 /* data compression technique */ +#define COMPRESSION_NONE 1 /* dump mode */ +#define COMPRESSION_CCITTRLE 2 /* CCITT modified Huffman RLE */ +#define COMPRESSION_CCITTFAX3 3 /* CCITT Group 3 fax encoding */ +#define COMPRESSION_CCITT_T4 3 /* CCITT T.4 (TIFF 6 name) */ +#define COMPRESSION_CCITTFAX4 4 /* CCITT Group 4 fax encoding */ +#define COMPRESSION_CCITT_T6 4 /* CCITT T.6 (TIFF 6 name) */ +#define COMPRESSION_LZW 5 /* Lempel-Ziv & Welch */ +#define COMPRESSION_OJPEG 6 /* !6.0 JPEG */ +#define COMPRESSION_JPEG 7 /* %JPEG DCT compression */ +#define COMPRESSION_NEXT 32766 /* NeXT 2-bit RLE */ +#define COMPRESSION_CCITTRLEW 32771 /* #1 w/ word alignment */ +#define COMPRESSION_PACKBITS 32773 /* Macintosh RLE */ +#define COMPRESSION_THUNDERSCAN 32809 /* ThunderScan RLE */ +/* codes 32895-32898 are reserved for ANSI IT8 TIFF/IT */ +#define COMPRESSION_DCS 32947 /* Kodak DCS encoding */ +#define COMPRESSION_JBIG 34661 /* ISO JBIG */ +#define COMPRESSION_SGILOG 34676 /* SGI Log Luminance RLE */ +#define COMPRESSION_SGILOG24 34677 /* SGI Log 24-bit packed */ +#define TIFFTAG_PHOTOMETRIC 262 /* photometric interpretation */ +#define PHOTOMETRIC_MINISWHITE 0 /* min value is white */ +#define PHOTOMETRIC_MINISBLACK 1 /* min value is black */ +#define PHOTOMETRIC_RGB 2 /* RGB color model */ +#define PHOTOMETRIC_PALETTE 3 /* color map indexed */ +#define PHOTOMETRIC_MASK 4 /* $holdout mask */ +#define PHOTOMETRIC_SEPARATED 5 /* !color separations */ +#define PHOTOMETRIC_YCBCR 6 /* !CCIR 601 */ +#define PHOTOMETRIC_CIELAB 8 /* !1976 CIE L*a*b* */ +#define PHOTOMETRIC_ITULAB 10 /* ITU L*a*b* */ +#define PHOTOMETRIC_LOGL 32844 /* CIE Log2(L) */ +#define PHOTOMETRIC_LOGLUV 32845 /* CIE Log2(L) (u',v') */ +#define TIFFTAG_THRESHHOLDING 263 /* +thresholding used on data */ +#define THRESHHOLD_BILEVEL 1 /* b&w art scan */ +#define THRESHHOLD_HALFTONE 2 /* or dithered scan */ +#define THRESHHOLD_ERRORDIFFUSE 3 /* usually floyd-steinberg */ +#define TIFFTAG_CELLWIDTH 264 /* +dithering matrix width */ +#define TIFFTAG_CELLLENGTH 265 /* +dithering matrix height */ +#define TIFFTAG_FILLORDER 266 /* data order within a byte */ +#define FILLORDER_MSB2LSB 1 /* most significant -> least */ +#define FILLORDER_LSB2MSB 2 /* least significant -> most */ +#define TIFFTAG_DOCUMENTNAME 269 /* name of doc. image is from */ +#define TIFFTAG_IMAGEDESCRIPTION 270 /* info about image */ +#define TIFFTAG_MAKE 271 /* scanner manufacturer name */ +#define TIFFTAG_MODEL 272 /* scanner model name/number */ +#define TIFFTAG_STRIPOFFSETS 273 /* offsets to data strips */ +#define TIFFTAG_ORIENTATION 274 /* +image orientation */ +#define ORIENTATION_TOPLEFT 1 /* row 0 top, col 0 lhs */ +#define ORIENTATION_TOPRIGHT 2 /* row 0 top, col 0 rhs */ +#define ORIENTATION_BOTRIGHT 3 /* row 0 bottom, col 0 rhs */ +#define ORIENTATION_BOTLEFT 4 /* row 0 bottom, col 0 lhs */ +#define ORIENTATION_LEFTTOP 5 /* row 0 lhs, col 0 top */ +#define ORIENTATION_RIGHTTOP 6 /* row 0 rhs, col 0 top */ +#define ORIENTATION_RIGHTBOT 7 /* row 0 rhs, col 0 bottom */ +#define ORIENTATION_LEFTBOT 8 /* row 0 lhs, col 0 bottom */ +#define TIFFTAG_SAMPLESPERPIXEL 277 /* samples per pixel */ +#define TIFFTAG_ROWSPERSTRIP 278 /* rows per strip of data */ +#define TIFFTAG_STRIPBYTECOUNTS 279 /* bytes counts for strips */ +#define TIFFTAG_MINSAMPLEVALUE 280 /* +minimum sample value */ +#define TIFFTAG_MAXSAMPLEVALUE 281 /* +maximum sample value */ +#define TIFFTAG_XRESOLUTION 282 /* pixels/resolution in x */ +#define TIFFTAG_YRESOLUTION 283 /* pixels/resolution in y */ +#define TIFFTAG_PLANARCONFIG 284 /* storage organization */ +#define PLANARCONFIG_CONTIG 1 /* single image plane */ +#define PLANARCONFIG_SEPARATE 2 /* separate planes of data */ +#define TIFFTAG_PAGENAME 285 /* page name image is from */ +#define TIFFTAG_XPOSITION 286 /* x page offset of image lhs */ +#define TIFFTAG_YPOSITION 287 /* y page offset of image lhs */ +#define TIFFTAG_FREEOFFSETS 288 /* +byte offset to free block */ +#define TIFFTAG_FREEBYTECOUNTS 289 /* +sizes of free blocks */ +#define TIFFTAG_GRAYRESPONSEUNIT 290 /* $gray scale curve accuracy */ +#define GRAYRESPONSEUNIT_10S 1 /* tenths of a unit */ +#define GRAYRESPONSEUNIT_100S 2 /* hundredths of a unit */ +#define GRAYRESPONSEUNIT_1000S 3 /* thousandths of a unit */ +#define GRAYRESPONSEUNIT_10000S 4 /* ten-thousandths of a unit */ +#define GRAYRESPONSEUNIT_100000S 5 /* hundred-thousandths */ +#define TIFFTAG_GRAYRESPONSECURVE 291 /* $gray scale response curve */ +#define TIFFTAG_GROUP3OPTIONS 292 /* 32 flag bits */ +#define TIFFTAG_T4OPTIONS 292 /* TIFF 6.0 proper name alias */ +#define GROUP3OPT_2DENCODING 0x1 /* 2-dimensional coding */ +#define GROUP3OPT_UNCOMPRESSED 0x2 /* data not compressed */ +#define GROUP3OPT_FILLBITS 0x4 /* fill to byte boundary */ +#define TIFFTAG_GROUP4OPTIONS 293 /* 32 flag bits */ +#define TIFFTAG_T6OPTIONS 293 /* TIFF 6.0 proper name */ +#define GROUP4OPT_UNCOMPRESSED 0x2 /* data not compressed */ +#define TIFFTAG_RESOLUTIONUNIT 296 /* units of resolutions */ +#define RESUNIT_NONE 1 /* no meaningful units */ +#define RESUNIT_INCH 2 /* english */ +#define RESUNIT_CENTIMETER 3 /* metric */ +#define TIFFTAG_PAGENUMBER 297 /* page numbers of multi-page */ +#define TIFFTAG_COLORRESPONSEUNIT 300 /* $color curve accuracy */ +#define COLORRESPONSEUNIT_10S 1 /* tenths of a unit */ +#define COLORRESPONSEUNIT_100S 2 /* hundredths of a unit */ +#define COLORRESPONSEUNIT_1000S 3 /* thousandths of a unit */ +#define COLORRESPONSEUNIT_10000S 4 /* ten-thousandths of a unit */ +#define COLORRESPONSEUNIT_100000S 5 /* hundred-thousandths */ +#define TIFFTAG_TRANSFERFUNCTION 301 /* !colorimetry info */ +#define TIFFTAG_SOFTWARE 305 /* name & release */ +#define TIFFTAG_DATETIME 306 /* creation date and time */ +#define TIFFTAG_ARTIST 315 /* creator of image */ +#define TIFFTAG_HOSTCOMPUTER 316 /* machine where created */ +#define TIFFTAG_PREDICTOR 317 /* prediction scheme w/ LZW */ +#define TIFFTAG_WHITEPOINT 318 /* image white point */ +#define TIFFTAG_PRIMARYCHROMATICITIES 319 /* !primary chromaticities */ +#define TIFFTAG_COLORMAP 320 /* RGB map for pallette image */ +#define TIFFTAG_HALFTONEHINTS 321 /* !highlight+shadow info */ +#define TIFFTAG_TILEWIDTH 322 /* !rows/data tile */ +#define TIFFTAG_TILELENGTH 323 /* !cols/data tile */ +#define TIFFTAG_TILEOFFSETS 324 /* !offsets to data tiles */ +#define TIFFTAG_TILEBYTECOUNTS 325 /* !byte counts for tiles */ +#define TIFFTAG_BADFAXLINES 326 /* lines w/ wrong pixel count */ +#define TIFFTAG_CLEANFAXDATA 327 /* regenerated line info */ +#define CLEANFAXDATA_CLEAN 0 /* no errors detected */ +#define CLEANFAXDATA_REGENERATED 1 /* receiver regenerated lines */ +#define CLEANFAXDATA_UNCLEAN 2 /* uncorrected errors exist */ +#define TIFFTAG_CONSECUTIVEBADFAXLINES 328 /* max consecutive bad lines */ +#define TIFFTAG_SUBIFD 330 /* subimage descriptors */ +#define TIFFTAG_INKSET 332 /* !inks in separated image */ +#define INKSET_CMYK 1 /* !cyan-magenta-yellow-black */ +#define TIFFTAG_INKNAMES 333 /* !ascii names of inks */ +#define TIFFTAG_NUMBEROFINKS 334 /* !number of inks */ +#define TIFFTAG_DOTRANGE 336 /* !0% and 100% dot codes */ +#define TIFFTAG_TARGETPRINTER 337 /* !separation target */ +#define TIFFTAG_EXTRASAMPLES 338 /* !info about extra samples */ +#define EXTRASAMPLE_UNSPECIFIED 0 /* !unspecified data */ +#define EXTRASAMPLE_ASSOCALPHA 1 /* !associated alpha data */ +#define EXTRASAMPLE_UNASSALPHA 2 /* !unassociated alpha data */ +#define TIFFTAG_SAMPLEFORMAT 339 /* !data sample format */ +#define SAMPLEFORMAT_UINT 1 /* !unsigned integer data */ +#define SAMPLEFORMAT_INT 2 /* !signed integer data */ +#define SAMPLEFORMAT_IEEEFP 3 /* !IEEE floating point data */ +#define SAMPLEFORMAT_VOID 4 /* !untyped data */ +#define SAMPLEFORMAT_COMPLEXINT 5 /* !complex signed int */ +#define SAMPLEFORMAT_COMPLEXIEEEFP 6 /* !complex ieee floating */ +#define TIFFTAG_SMINSAMPLEVALUE 340 /* !variable MinSampleValue */ +#define TIFFTAG_SMAXSAMPLEVALUE 341 /* !variable MaxSampleValue */ +#define TIFFTAG_JPEGTABLES 347 /* %JPEG table stream */ +/* + * Tags 512-521 are obsoleted by Technical Note #2 + * which specifies a revised JPEG-in-TIFF scheme. + */ +#define TIFFTAG_JPEGPROC 512 /* !JPEG processing algorithm */ +#define JPEGPROC_BASELINE 1 /* !baseline sequential */ +#define JPEGPROC_LOSSLESS 14 /* !Huffman coded lossless */ +#define TIFFTAG_JPEGIFOFFSET 513 /* !pointer to SOI marker */ +#define TIFFTAG_JPEGIFBYTECOUNT 514 /* !JFIF stream length */ +#define TIFFTAG_JPEGRESTARTINTERVAL 515 /* !restart interval length */ +#define TIFFTAG_JPEGLOSSLESSPREDICTORS 517 /* !lossless proc predictor */ +#define TIFFTAG_JPEGPOINTTRANSFORM 518 /* !lossless point transform */ +#define TIFFTAG_JPEGQTABLES 519 /* !Q matrice offsets */ +#define TIFFTAG_JPEGDCTABLES 520 /* !DCT table offsets */ +#define TIFFTAG_JPEGACTABLES 521 /* !AC coefficient offsets */ +#define TIFFTAG_YCBCRCOEFFICIENTS 529 /* !RGB -> YCbCr transform */ +#define TIFFTAG_YCBCRSUBSAMPLING 530 /* !YCbCr subsampling factors */ +#define TIFFTAG_YCBCRPOSITIONING 531 /* !subsample positioning */ +#define YCBCRPOSITION_CENTERED 1 /* !as in PostScript Level 2 */ +#define YCBCRPOSITION_COSITED 2 /* !as in CCIR 601-1 */ +#define TIFFTAG_REFERENCEBLACKWHITE 532 /* !colorimetry info */ +/* tags 32952-32956 are private tags registered to Island Graphics */ +#define TIFFTAG_REFPTS 32953 /* image reference points */ +#define TIFFTAG_REGIONTACKPOINT 32954 /* region-xform tack point */ +#define TIFFTAG_REGIONWARPCORNERS 32955 /* warp quadrilateral */ +#define TIFFTAG_REGIONAFFINE 32956 /* affine transformation mat */ +/* tags 32995-32999 are private tags registered to SGI */ +#define TIFFTAG_MATTEING 32995 /* $use ExtraSamples */ +#define TIFFTAG_DATATYPE 32996 /* $use SampleFormat */ +#define TIFFTAG_IMAGEDEPTH 32997 /* z depth of image */ +#define TIFFTAG_TILEDEPTH 32998 /* z depth/data tile */ +/* tags 33300-33309 are private tags registered to Pixar */ +/* + * TIFFTAG_PIXAR_IMAGEFULLWIDTH and TIFFTAG_PIXAR_IMAGEFULLLENGTH + * are set when an image has been cropped out of a larger image. + * They reflect the size of the original uncropped image. + * The TIFFTAG_XPOSITION and TIFFTAG_YPOSITION can be used + * to determine the position of the smaller image in the larger one. + */ +#define TIFFTAG_PIXAR_IMAGEFULLWIDTH 33300 /* full image size in x */ +#define TIFFTAG_PIXAR_IMAGEFULLLENGTH 33301 /* full image size in y */ + /* Tags 33302-33306 are used to identify special image modes and data + * used by Pixar's texture formats. + */ +#define TIFFTAG_PIXAR_TEXTUREFORMAT 33302 /* texture map format */ +#define TIFFTAG_PIXAR_WRAPMODES 33303 /* s & t wrap modes */ +#define TIFFTAG_PIXAR_FOVCOT 33304 /* cotan(fov) for env. maps */ +#define TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN 33305 +#define TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA 33306 +/* tag 33405 is a private tag registered to Eastman Kodak */ +#define TIFFTAG_WRITERSERIALNUMBER 33405 /* device serial number */ +/* tag 33432 is listed in the 6.0 spec w/ unknown ownership */ +#define TIFFTAG_COPYRIGHT 33432 /* copyright string */ +/* IPTC TAG from RichTIFF specifications */ +#define TIFFTAG_RICHTIFFIPTC 33723 +/* 34016-34029 are reserved for ANSI IT8 TIFF/IT */ +#define TIFFTAG_STONITS 37439 /* Sample value to Nits */ +/* tag 34929 is a private tag registered to FedEx */ +#define TIFFTAG_FEDEX_EDR 34929 /* unknown use */ +/* tag 65535 is an undefined tag used by Eastman Kodak */ +#define TIFFTAG_DCSHUESHIFTVALUES 65535 /* hue shift correction data */ + +/* + * The following are ``pseudo tags'' that can be + * used to control codec-specific functionality. + * These tags are not written to file. Note that + * these values start at 0xffff+1 so that they'll + * never collide with Aldus-assigned tags. + * + * If you want your private pseudo tags ``registered'' + * (i.e. added to this file), send mail to sam@sgi.com + * with the appropriate C definitions to add. + */ +#define TIFFTAG_FAXMODE 65536 /* Group 3/4 format control */ +#define FAXMODE_CLASSIC 0x0000 /* default, include RTC */ +#define FAXMODE_NORTC 0x0001 /* no RTC at end of data */ +#define FAXMODE_NOEOL 0x0002 /* no EOL code at end of row */ +#define FAXMODE_BYTEALIGN 0x0004 /* byte align row */ +#define FAXMODE_WORDALIGN 0x0008 /* word align row */ +#define FAXMODE_CLASSF FAXMODE_NORTC /* TIFF Class F */ +#define TIFFTAG_JPEGQUALITY 65537 /* Compression quality level */ +/* Note: quality level is on the IJG 0-100 scale. Default value is 75 */ +#define TIFFTAG_JPEGCOLORMODE 65538 /* Auto RGB<=>YCbCr convert? */ +#define JPEGCOLORMODE_RAW 0x0000 /* no conversion (default) */ +#define JPEGCOLORMODE_RGB 0x0001 /* do auto conversion */ +#define TIFFTAG_JPEGTABLESMODE 65539 /* What to put in JPEGTables */ +#define JPEGTABLESMODE_QUANT 0x0001 /* include quantization tbls */ +#define JPEGTABLESMODE_HUFF 0x0002 /* include Huffman tbls */ +/* Note: default is JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF */ +#define TIFFTAG_FAXFILLFUNC 65540 /* G3/G4 fill function */ +#define TIFFTAG_PIXARLOGDATAFMT 65549 /* PixarLogCodec I/O data sz */ +#define PIXARLOGDATAFMT_8BIT 0 /* regular u_char samples */ +#define PIXARLOGDATAFMT_8BITABGR 1 /* ABGR-order u_chars */ +#define PIXARLOGDATAFMT_11BITLOG 2 /* 11-bit log-encoded (raw) */ +#define PIXARLOGDATAFMT_12BITPICIO 3 /* as per PICIO (1.0==2048) */ +#define PIXARLOGDATAFMT_16BIT 4 /* signed short samples */ +#define PIXARLOGDATAFMT_FLOAT 5 /* IEEE float samples */ +/* 65550-65556 are allocated to Oceana Matrix */ +#define TIFFTAG_DCSIMAGERTYPE 65550 /* imager model & filter */ +#define DCSIMAGERMODEL_M3 0 /* M3 chip (1280 x 1024) */ +#define DCSIMAGERMODEL_M5 1 /* M5 chip (1536 x 1024) */ +#define DCSIMAGERMODEL_M6 2 /* M6 chip (3072 x 2048) */ +#define DCSIMAGERFILTER_IR 0 /* infrared filter */ +#define DCSIMAGERFILTER_MONO 1 /* monochrome filter */ +#define DCSIMAGERFILTER_CFA 2 /* color filter array */ +#define DCSIMAGERFILTER_OTHER 3 /* other filter */ +#define TIFFTAG_DCSINTERPMODE 65551 /* interpolation mode */ +#define DCSINTERPMODE_NORMAL 0x0 /* whole image, default */ +#define DCSINTERPMODE_PREVIEW 0x1 /* preview of image (384x256) */ +#define TIFFTAG_DCSBALANCEARRAY 65552 /* color balance values */ +#define TIFFTAG_DCSCORRECTMATRIX 65553 /* color correction values */ +#define TIFFTAG_DCSGAMMA 65554 /* gamma value */ +#define TIFFTAG_DCSTOESHOULDERPTS 65555 /* toe & shoulder points */ +#define TIFFTAG_DCSCALIBRATIONFD 65556 /* calibration file desc */ +/* Note: quality level is on the ZLIB 1-9 scale. Default value is -1 */ +#define TIFFTAG_ZIPQUALITY 65557 /* compression quality level */ +#define TIFFTAG_PIXARLOGQUALITY 65558 /* PixarLog uses same scale */ +/* 65559 is allocated to Oceana Matrix */ +#define TIFFTAG_DCSCLIPRECTANGLE 65559 /* area of image to acquire */ +#define TIFFTAG_SGILOGDATAFMT 65560 /* SGILog user data format */ +#define SGILOGDATAFMT_FLOAT 0 /* IEEE float samples */ +#define SGILOGDATAFMT_16BIT 1 /* 16-bit samples */ +#define SGILOGDATAFMT_RAW 2 /* uninterpreted data */ +#define SGILOGDATAFMT_8BIT 3 /* 8-bit RGB monitor values */ +#define TIFFTAG_SGILOGENCODE 65561 /* SGILog data encoding control*/ +#define SGILOGENCODE_NODITHER 0 /* do not dither encoded values*/ +#define SGILOGENCODE_RANDITHER 1 /* randomly dither encd values */ +#endif /* _TIFF_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/tiffcomp.h b/SlnkDWFImpl/CxImage/tiff/tiffcomp.h new file mode 100644 index 0000000..a9e09f6 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tiffcomp.h @@ -0,0 +1,214 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tiffcomp.h,v 1.3 2000/11/13 14:23:53 warmerda Exp $ */ + +/* + * Copyright (c) 1990-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _COMPAT_ +#define _COMPAT_ +/* + * This file contains a hodgepodge of definitions and + * declarations that are needed to provide compatibility + * between the native system and the base implementation + * that the library assumes. + * + * NB: This file is a mess. + */ + +/* + * Setup basic type definitions and function declaratations. + */ + +/* + * Simplify Acorn RISC OS identifier (to avoid confusion with Acorn RISC iX + * and with defunct Unix Risc OS) + * No need to specify __arm - hey, Acorn might port the OS, no problem here! + */ +#ifdef __acornriscos +#undef __acornriscos +#endif +#if defined(__acorn) && defined(__riscos) +#define __acornriscos +#endif + +#if defined(__MWERKS__) || defined(THINK_C) +#include +#include +#endif + +#include + +#if defined(__PPCC__) || defined(__SC__) || defined(__MRC__) +#include +#elif !defined(__MWERKS__) && !defined(THINK_C) && !defined(__acornriscos) && !defined(applec) +#include +#endif + +#if defined(VMS) +#include +#include +#elif !defined(__acornriscos) +#include +#endif + +/* + * This maze of checks controls defines or not the + * target system has BSD-style typdedefs declared in + * an include file and/or whether or not to include + * to get the SEEK_* definitions. Some + * additional includes are also done to pull in the + * appropriate definitions we're looking for. + */ +#if defined(__MWERKS__) || defined(THINK_C) || defined(__PPCC__) || defined(__SC__) || defined(__MRC__) +#include +#define BSDTYPES +#define HAVE_UNISTD_H 0 +#elif (defined(_WINDOWS) || defined(__WIN32__) || defined(_Windows) || defined(_WIN32)) && !defined(unix) +#define BSDTYPES +#elif defined(OS2_16) || defined(OS2_32) +#define BSDTYPES +#elif defined(__acornriscos) +#include +#define BSDTYPES +#define HAVE_UNISTD_H 0 +#elif defined(VMS) +#define HAVE_UNISTD_H 0 +#else +#define HAVE_UNISTD_H 1 +#endif + +/* + * The library uses the ANSI C/POSIX SEEK_* + * definitions that should be defined in unistd.h + * (except on system where they are in stdio.h and + * there is no unistd.h). + */ +#if !defined(SEEK_SET) && HAVE_UNISTD_H +#include +#endif + +/* + * The library uses memset, memcpy, and memcmp. + * ANSI C and System V define these in string.h. + */ +#include + +/* + * The BSD typedefs are used throughout the library. + * If your system doesn't have them in , + * then define BSDTYPES in your Makefile. + */ +#if defined(BSDTYPES) +typedef unsigned char u_char; +typedef unsigned short u_short; +typedef unsigned int u_int; +typedef unsigned long u_long; +#endif + +/* + * dblparam_t is the type that a double precision + * floating point value will have on the parameter + * stack (when coerced by the compiler). + */ +/* Note: on MacPowerPC "extended" is undefined. So only use it for 68K-Macs */ +#if defined(__SC__) || defined(THINK_C) +typedef extended dblparam_t; +#else +typedef double dblparam_t; +#endif + +/* + * If your compiler supports inline functions, then + * set INLINE appropriately to get the known hotspots + * in the library expanded inline. + */ +#if defined(__GNUC__) +#if defined(__STRICT_ANSI__) +#define INLINE __inline__ +#else +#define INLINE inline +#endif +#else /* !__GNUC__ */ +#define INLINE +#endif + +/* + * GLOBALDATA is a macro that is used to define global variables + * private to the library. We use this indirection to hide + * brain-damage in VAXC (and GCC) under VAX/VMS. In these + * environments the macro places the variable in a non-shareable + * program section, which ought to be done by default (sigh!) + * + * Apparently DEC are aware of the problem as this behaviour is the + * default under VMS on AXP. + * + * The GNU C variant is untested. + */ +#if defined(VAX) && defined(VMS) +#if defined(VAXC) +#define GLOBALDATA(TYPE,NAME) extern noshare TYPE NAME +#endif +#if defined(__GNUC__) +#define GLOBALDATA(TYPE,NAME) extern TYPE NAME \ + asm("_$$PsectAttributes_NOSHR$$" #NAME) +#endif +#else /* !VAX/VMS */ +#define GLOBALDATA(TYPE,NAME) extern TYPE NAME +#endif + +#if defined(__acornriscos) +/* + * osfcn.h is part of C++Lib on Acorn C/C++, and as such can't be used + * on C alone. For that reason, the relevant functions are + * implemented in tif_acorn.c, and the elements from the header + * file are included here. + */ +#if defined(__cplusplus) +#include +#else +#define O_RDONLY 0 +#define O_WRONLY 1 +#define O_RDWR 2 +#define O_APPEND 8 +#define O_CREAT 0x200 +#define O_TRUNC 0x400 +typedef long off_t; +extern int open(const char *name, int flags, int mode); +extern int close(int fd); +extern int write(int fd, const char *buf, int nbytes); +extern int read(int fd, char *buf, int nbytes); +extern off_t lseek(int fd, off_t offset, int whence); +extern int creat(const char *path, int mode); +#endif /* __cplusplus */ +#endif /* __acornriscos */ + +/* Bit and byte order, the default is MSB to LSB */ +#ifdef VMS +#undef HOST_FILLORDER +#undef HOST_BIGENDIAN +#define HOST_FILLORDER FILLORDER_LSB2MSB +#define HOST_BIGENDIAN 0 +#endif + + +#endif /* _COMPAT_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/tiffconf.h b/SlnkDWFImpl/CxImage/tiff/tiffconf.h new file mode 100644 index 0000000..0c4acec --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tiffconf.h @@ -0,0 +1,146 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tiffconf.h,v 1.3 2001/05/12 03:59:50 warmerda Exp $ */ +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _TIFFCONF_ +#define _TIFFCONF_ +/* + * Library Configuration Definitions. + * + * This file defines the default configuration for the library. + * If the target system does not have make or a way to specify + * #defines on the command line, this file can be edited to + * configure the library. Otherwise, one can override portability + * and configuration-related definitions from a Makefile or command + * line by defining FEATURE_SUPPORT and COMPRESSION_SUPPORT (see below). + */ + +/* + * General portability-related defines: + * + * HAVE_IEEEFP define as 0 or 1 according to the floating point + * format suported by the machine + * BSDTYPES define this if your system does NOT define the + * usual 4BSD typedefs u_int et. al. + * HAVE_MMAP enable support for memory mapping read-only files; + * this is typically deduced by the configure script + * HOST_FILLORDER native cpu bit order: one of FILLORDER_MSB2LSB + * or FILLODER_LSB2MSB; this is typically set by the + * configure script + * HOST_BIGENDIAN native cpu byte order: 1 if big-endian (Motorola) + * or 0 if little-endian (Intel); this may be used + * in codecs to optimize code + * USE_64BIT_API set to 1 if tif_unix.c should use lseek64(), + * fstat64() and stat64 allowing 2-4GB files. + */ +#ifndef HAVE_IEEEFP +#define HAVE_IEEEFP 1 +#endif +#ifndef HOST_FILLORDER +#define HOST_FILLORDER FILLORDER_MSB2LSB +#endif +#ifndef HOST_BIGENDIAN +#define HOST_BIGENDIAN 1 +#endif + +#ifndef USE_64BIT_API +# define USE_64BIT_API 0 +#endif + +#ifndef FEATURE_SUPPORT +/* + * Feature support definitions: + * + * COLORIMETRY_SUPPORT enable support for 6.0 colorimetry tags + * YCBCR_SUPPORT enable support for 6.0 YCbCr tags + * CMYK_SUPPORT enable support for 6.0 CMYK tags + * ICC_SUPPORT enable support for ICC profile tag + * PHOTOSHOP_SUPPORT enable support for PHOTOSHOP resource tag + * IPTC_SUPPORT enable support for RichTIFF IPTC tag + */ +#define COLORIMETRY_SUPPORT +#define YCBCR_SUPPORT +#define CMYK_SUPPORT +#define ICC_SUPPORT +#define PHOTOSHOP_SUPPORT +#define IPTC_SUPPORT +#endif /* FEATURE_SUPPORT */ + +#ifndef COMPRESSION_SUPPORT +/* + * Compression support defines: + * + * CCITT_SUPPORT enable support for CCITT Group 3 & 4 algorithms + * PACKBITS_SUPPORT enable support for Macintosh PackBits algorithm + * LZW_SUPPORT enable support for LZW algorithm + * THUNDER_SUPPORT enable support for ThunderScan 4-bit RLE algorithm + * NEXT_SUPPORT enable support for NeXT 2-bit RLE algorithm + * OJPEG_SUPPORT enable support for 6.0-style JPEG DCT algorithms + * (requires IJG software) + * JPEG_SUPPORT enable support for post-6.0-style JPEG DCT algorithms + * (requires freely available IJG software, see tif_jpeg.c) + * ZIP_SUPPORT enable support for Deflate algorithm + * (requires freely available zlib software, see tif_zip.c) + * PIXARLOG_SUPPORT enable support for Pixar log-format algorithm + * LOGLUV_SUPPORT enable support for LogLuv high dynamic range encoding + */ +#define CCITT_SUPPORT +#define PACKBITS_SUPPORT +#define LZW_SUPPORT +#define THUNDER_SUPPORT +#define NEXT_SUPPORT +#define LOGLUV_SUPPORT +#define JPEG_SUPPORT +#define ZIP_SUPPORT +#define OJPEG_SUPPORT +#endif /* COMPRESSION_SUPPORT */ + +/* + * If JPEG compression is enabled then we must also include + * support for the colorimetry and YCbCr-related tags. + */ +#ifdef JPEG_SUPPORT +#ifndef YCBCR_SUPPORT +#define YCBCR_SUPPORT +#endif +#ifndef COLORIMETRY_SUPPORT +#define COLORIMETRY_SUPPORT +#endif +#endif /* JPEG_SUPPORT */ + +/* + * ``Orthogonal Features'' + * + * STRIPCHOP_DEFAULT default handling of strip chopping support (whether + * or not to convert single-strip uncompressed images + * to mutiple strips of ~8Kb--to reduce memory use) + * SUBIFD_SUPPORT enable support for SubIFD tag (thumbnails and such) + */ +#ifndef STRIPCHOP_DEFAULT +#define STRIPCHOP_DEFAULT TIFF_STRIPCHOP /* default is to enable */ +#endif +#ifndef SUBIFD_SUPPORT +#define SUBIFD_SUPPORT 1 /* enable SubIFD tag (330) support */ +#endif +#endif /* _TIFFCONF_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/tiffio.h b/SlnkDWFImpl/CxImage/tiff/tiffio.h new file mode 100644 index 0000000..87bc257 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tiffio.h @@ -0,0 +1,364 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tiffio.h,v 1.11 2001/09/26 17:42:18 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _TIFFIO_ +#define _TIFFIO_ + +/* + * TIFF I/O Library Definitions. + */ +#include "tiff.h" + +/* + * TIFF is defined as an incomplete type to hide the + * library's internal data structures from clients. + */ +typedef struct tiff TIFF; + +/* + * The following typedefs define the intrinsic size of + * data types used in the *exported* interfaces. These + * definitions depend on the proper definition of types + * in tiff.h. Note also that the varargs interface used + * to pass tag types and values uses the types defined in + * tiff.h directly. + * + * NB: ttag_t is unsigned int and not unsigned short because + * ANSI C requires that the type before the ellipsis be a + * promoted type (i.e. one of int, unsigned int, pointer, + * or double) and because we defined pseudo-tags that are + * outside the range of legal Aldus-assigned tags. + * NB: tsize_t is int32 and not uint32 because some functions + * return -1. + * NB: toff_t is not off_t for many reasons; TIFFs max out at + * 32-bit file offsets being the most important, and to ensure + * that it is unsigned, rather than signed. + */ +typedef uint32 ttag_t; /* directory tag */ +typedef uint16 tdir_t; /* directory index */ +typedef uint16 tsample_t; /* sample number */ +typedef uint32 tstrip_t; /* strip number */ +typedef uint32 ttile_t; /* tile number */ +typedef int32 tsize_t; /* i/o size in bytes */ +typedef void* tdata_t; /* image data ref */ +typedef uint32 toff_t; /* file offset */ + +#if !defined(__WIN32__) && (defined(_WIN32) || defined(WIN32)) +#define __WIN32__ +#endif + +/* + * On windows you should define USE_WIN32_FILEIO if you are using tif_win32.c + * or AVOID_WIN32_FILEIO if you are using something else (like tif_unix.c). + * + * By default tif_win32.c is assumed on windows if not using the cygwin + * environment. + */ + +#if defined(_WINDOWS) || defined(__WIN32__) || defined(_Windows) +# if !defined(__CYGWIN) && !defined(AVOID_WIN32_FILEIO) && !defined(USE_WIN32_FILIO) +# define USE_WIN32_FILEIO +# endif +#endif + +#if defined(USE_WIN32_FILEIO) +#include +#ifdef __WIN32__ +DECLARE_HANDLE(thandle_t); /* Win32 file handle */ +#else +typedef HFILE thandle_t; /* client data handle */ +#endif +#else +typedef void* thandle_t; /* client data handle */ +#endif + +#ifndef NULL +#define NULL 0 +#endif + +/* + * Flags to pass to TIFFPrintDirectory to control + * printing of data structures that are potentially + * very large. Bit-or these flags to enable printing + * multiple items. + */ +#define TIFFPRINT_NONE 0x0 /* no extra info */ +#define TIFFPRINT_STRIPS 0x1 /* strips/tiles info */ +#define TIFFPRINT_CURVES 0x2 /* color/gray response curves */ +#define TIFFPRINT_COLORMAP 0x4 /* colormap */ +#define TIFFPRINT_JPEGQTABLES 0x100 /* JPEG Q matrices */ +#define TIFFPRINT_JPEGACTABLES 0x200 /* JPEG AC tables */ +#define TIFFPRINT_JPEGDCTABLES 0x200 /* JPEG DC tables */ + +/* + * RGBA-style image support. + */ +typedef unsigned char TIFFRGBValue; /* 8-bit samples */ +typedef struct _TIFFRGBAImage TIFFRGBAImage; +/* + * The image reading and conversion routines invoke + * ``put routines'' to copy/image/whatever tiles of + * raw image data. A default set of routines are + * provided to convert/copy raw image data to 8-bit + * packed ABGR format rasters. Applications can supply + * alternate routines that unpack the data into a + * different format or, for example, unpack the data + * and draw the unpacked raster on the display. + */ +typedef void (*tileContigRoutine) + (TIFFRGBAImage*, uint32*, uint32, uint32, uint32, uint32, int32, int32, + unsigned char*); +typedef void (*tileSeparateRoutine) + (TIFFRGBAImage*, uint32*, uint32, uint32, uint32, uint32, int32, int32, + unsigned char*, unsigned char*, unsigned char*, unsigned char*); +/* + * RGBA-reader state. + */ +typedef struct { /* YCbCr->RGB support */ + TIFFRGBValue* clamptab; /* range clamping table */ + int* Cr_r_tab; + int* Cb_b_tab; + int32* Cr_g_tab; + int32* Cb_g_tab; + float coeffs[3]; /* cached for repeated use */ +} TIFFYCbCrToRGB; + +struct _TIFFRGBAImage { + TIFF* tif; /* image handle */ + int stoponerr; /* stop on read error */ + int isContig; /* data is packed/separate */ + int alpha; /* type of alpha data present */ + uint32 width; /* image width */ + uint32 height; /* image height */ + uint16 bitspersample; /* image bits/sample */ + uint16 samplesperpixel; /* image samples/pixel */ + uint16 orientation; /* image orientation */ + uint16 photometric; /* image photometric interp */ + uint16* redcmap; /* colormap pallete */ + uint16* greencmap; + uint16* bluecmap; + /* get image data routine */ + int (*get)(TIFFRGBAImage*, uint32*, uint32, uint32); + union { + void (*any)(TIFFRGBAImage*); + tileContigRoutine contig; + tileSeparateRoutine separate; + } put; /* put decoded strip/tile */ + TIFFRGBValue* Map; /* sample mapping array */ + uint32** BWmap; /* black&white map */ + uint32** PALmap; /* palette image map */ + TIFFYCbCrToRGB* ycbcr; /* YCbCr conversion state */ + + int row_offset; + int col_offset; +}; + +/* + * Macros for extracting components from the + * packed ABGR form returned by TIFFReadRGBAImage. + */ +#define TIFFGetR(abgr) ((abgr) & 0xff) +#define TIFFGetG(abgr) (((abgr) >> 8) & 0xff) +#define TIFFGetB(abgr) (((abgr) >> 16) & 0xff) +#define TIFFGetA(abgr) (((abgr) >> 24) & 0xff) + +/* + * A CODEC is a software package that implements decoding, + * encoding, or decoding+encoding of a compression algorithm. + * The library provides a collection of builtin codecs. + * More codecs may be registered through calls to the library + * and/or the builtin implementations may be overridden. + */ +typedef int (*TIFFInitMethod)(TIFF*, int); +typedef struct { + char* name; + uint16 scheme; + TIFFInitMethod init; +} TIFFCodec; + +#include +#include + +/* share internal LogLuv conversion routines? */ +#ifndef LOGLUV_PUBLIC +#define LOGLUV_PUBLIC 1 +#endif + +#if defined(__cplusplus) +extern "C" { +#endif +typedef void (*TIFFErrorHandler)(const char*, const char*, va_list); +typedef tsize_t (*TIFFReadWriteProc)(thandle_t, tdata_t, tsize_t); +typedef toff_t (*TIFFSeekProc)(thandle_t, toff_t, int); +typedef int (*TIFFCloseProc)(thandle_t); +typedef toff_t (*TIFFSizeProc)(thandle_t); +typedef int (*TIFFMapFileProc)(thandle_t, tdata_t*, toff_t*); +typedef void (*TIFFUnmapFileProc)(thandle_t, tdata_t, toff_t); +typedef void (*TIFFExtendProc)(TIFF*); + +extern const char* TIFFGetVersion(void); + +extern const TIFFCodec* TIFFFindCODEC(uint16); +extern TIFFCodec* TIFFRegisterCODEC(uint16, const char*, TIFFInitMethod); +extern void TIFFUnRegisterCODEC(TIFFCodec*); + +extern tdata_t _TIFFmalloc(tsize_t); +extern tdata_t _TIFFrealloc(tdata_t, tsize_t); +extern void _TIFFmemset(tdata_t, int, tsize_t); +extern void _TIFFmemcpy(tdata_t, const tdata_t, tsize_t); +extern int _TIFFmemcmp(const tdata_t, const tdata_t, tsize_t); +extern void _TIFFfree(tdata_t); + +extern void TIFFClose(TIFF*); +extern int TIFFFlush(TIFF*); +extern int TIFFFlushData(TIFF*); +extern int TIFFGetField(TIFF*, ttag_t, ...); +extern int TIFFVGetField(TIFF*, ttag_t, va_list); +extern int TIFFGetFieldDefaulted(TIFF*, ttag_t, ...); +extern int TIFFVGetFieldDefaulted(TIFF*, ttag_t, va_list); +extern int TIFFReadDirectory(TIFF*); +extern tsize_t TIFFScanlineSize(TIFF*); +extern tsize_t TIFFRasterScanlineSize(TIFF*); +extern tsize_t TIFFStripSize(TIFF*); +extern tsize_t TIFFVStripSize(TIFF*, uint32); +extern tsize_t TIFFTileRowSize(TIFF*); +extern tsize_t TIFFTileSize(TIFF*); +extern tsize_t TIFFVTileSize(TIFF*, uint32); +extern uint32 TIFFDefaultStripSize(TIFF*, uint32); +extern void TIFFDefaultTileSize(TIFF*, uint32*, uint32*); +extern int TIFFFileno(TIFF*); +extern int TIFFGetMode(TIFF*); +extern int TIFFIsTiled(TIFF*); +extern int TIFFIsByteSwapped(TIFF*); +extern int TIFFIsUpSampled(TIFF*); +extern int TIFFIsMSB2LSB(TIFF*); +extern uint32 TIFFCurrentRow(TIFF*); +extern tdir_t TIFFCurrentDirectory(TIFF*); +extern tdir_t TIFFNumberOfDirectories(TIFF*); +extern uint32 TIFFCurrentDirOffset(TIFF*); +extern tstrip_t TIFFCurrentStrip(TIFF*); +extern ttile_t TIFFCurrentTile(TIFF*); +extern int TIFFReadBufferSetup(TIFF*, tdata_t, tsize_t); +extern int TIFFWriteBufferSetup(TIFF*, tdata_t, tsize_t); +extern int TIFFWriteCheck(TIFF*, int, const char *); +extern int TIFFCreateDirectory(TIFF*); +extern int TIFFLastDirectory(TIFF*); +extern int TIFFSetDirectory(TIFF*, tdir_t); +extern int TIFFSetSubDirectory(TIFF*, uint32); +extern int TIFFUnlinkDirectory(TIFF*, tdir_t); +extern int TIFFSetField(TIFF*, ttag_t, ...); +extern int TIFFVSetField(TIFF*, ttag_t, va_list); +extern int TIFFWriteDirectory(TIFF *); +extern int TIFFRewriteDirectory(TIFF *); +extern int TIFFReassignTagToIgnore(enum TIFFIgnoreSense, int); + +#if defined(c_plusplus) || defined(__cplusplus) +extern void TIFFPrintDirectory(TIFF*, FILE*, long = 0); +extern int TIFFReadScanline(TIFF*, tdata_t, uint32, tsample_t = 0); +extern int TIFFWriteScanline(TIFF*, tdata_t, uint32, tsample_t = 0); +extern int TIFFReadRGBAImage(TIFF*, uint32, uint32, uint32*, int = 0); +#else +extern void TIFFPrintDirectory(TIFF*, FILE*, long); +extern int TIFFReadScanline(TIFF*, tdata_t, uint32, tsample_t); +extern int TIFFWriteScanline(TIFF*, tdata_t, uint32, tsample_t); +extern int TIFFReadRGBAImage(TIFF*, uint32, uint32, uint32*, int); +#endif + +extern int TIFFReadRGBAStrip(TIFF*, tstrip_t, uint32 * ); +extern int TIFFReadRGBATile(TIFF*, uint32, uint32, uint32 * ); +extern int TIFFRGBAImageOK(TIFF*, char [1024]); +extern int TIFFRGBAImageBegin(TIFFRGBAImage*, TIFF*, int, char [1024]); +extern int TIFFRGBAImageGet(TIFFRGBAImage*, uint32*, uint32, uint32); +extern void TIFFRGBAImageEnd(TIFFRGBAImage*); +extern TIFF* TIFFOpen(const char*, const char*); +extern TIFF* TIFFFdOpen(int, const char*, const char*); +extern TIFF* TIFFClientOpen(const char*, const char*, + thandle_t, + TIFFReadWriteProc, TIFFReadWriteProc, + TIFFSeekProc, TIFFCloseProc, + TIFFSizeProc, + TIFFMapFileProc, TIFFUnmapFileProc); +extern const char* TIFFFileName(TIFF*); +extern void TIFFError(const char*, const char*, ...); +extern void TIFFWarning(const char*, const char*, ...); +extern TIFFErrorHandler TIFFSetErrorHandler(TIFFErrorHandler); +extern TIFFErrorHandler TIFFSetWarningHandler(TIFFErrorHandler); +extern TIFFExtendProc TIFFSetTagExtender(TIFFExtendProc); +extern ttile_t TIFFComputeTile(TIFF*, uint32, uint32, uint32, tsample_t); +extern int TIFFCheckTile(TIFF*, uint32, uint32, uint32, tsample_t); +extern ttile_t TIFFNumberOfTiles(TIFF*); +extern tsize_t TIFFReadTile(TIFF*, + tdata_t, uint32, uint32, uint32, tsample_t); +extern tsize_t TIFFWriteTile(TIFF*, + tdata_t, uint32, uint32, uint32, tsample_t); +extern tstrip_t TIFFComputeStrip(TIFF*, uint32, tsample_t); +extern tstrip_t TIFFNumberOfStrips(TIFF*); +extern tsize_t TIFFReadEncodedStrip(TIFF*, tstrip_t, tdata_t, tsize_t); +extern tsize_t TIFFReadRawStrip(TIFF*, tstrip_t, tdata_t, tsize_t); +extern tsize_t TIFFReadEncodedTile(TIFF*, ttile_t, tdata_t, tsize_t); +extern tsize_t TIFFReadRawTile(TIFF*, ttile_t, tdata_t, tsize_t); +extern tsize_t TIFFWriteEncodedStrip(TIFF*, tstrip_t, tdata_t, tsize_t); +extern tsize_t TIFFWriteRawStrip(TIFF*, tstrip_t, tdata_t, tsize_t); +extern tsize_t TIFFWriteEncodedTile(TIFF*, ttile_t, tdata_t, tsize_t); +extern tsize_t TIFFWriteRawTile(TIFF*, ttile_t, tdata_t, tsize_t); +extern void TIFFSetWriteOffset(TIFF*, toff_t); +extern void TIFFSwabShort(uint16*); +extern void TIFFSwabLong(uint32*); +extern void TIFFSwabDouble(double*); +extern void TIFFSwabArrayOfShort(uint16*, unsigned long); +extern void TIFFSwabArrayOfLong(uint32*, unsigned long); +extern void TIFFSwabArrayOfDouble(double*, unsigned long); +extern void TIFFReverseBits(unsigned char *, unsigned long); +extern const unsigned char* TIFFGetBitRevTable(int); + +#ifdef LOGLUV_PUBLIC +#define U_NEU 0.210526316 +#define V_NEU 0.473684211 +#define UVSCALE 410. +extern double LogL16toY(int); +extern double LogL10toY(int); +extern void XYZtoRGB24(float*, uint8*); +extern int uv_decode(double*, double*, int); +extern void LogLuv24toXYZ(uint32, float*); +extern void LogLuv32toXYZ(uint32, float*); +#if defined(c_plusplus) || defined(__cplusplus) +extern int LogL16fromY(double, int = SGILOGENCODE_NODITHER); +extern int LogL10fromY(double, int = SGILOGENCODE_NODITHER); +extern int uv_encode(double, double, int = SGILOGENCODE_NODITHER); +extern uint32 LogLuv24fromXYZ(float*, int = SGILOGENCODE_NODITHER); +extern uint32 LogLuv32fromXYZ(float*, int = SGILOGENCODE_NODITHER); +#else +extern int LogL16fromY(double, int); +extern int LogL10fromY(double, int); +extern int uv_encode(double, double, int); +extern uint32 LogLuv24fromXYZ(float*, int); +extern uint32 LogLuv32fromXYZ(float*, int); +#endif +#endif /* LOGLUV_PUBLIC */ +#if defined(__cplusplus) +} +#endif +#endif /* _TIFFIO_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/tiffiop.h b/SlnkDWFImpl/CxImage/tiff/tiffiop.h new file mode 100644 index 0000000..9578953 --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/tiffiop.h @@ -0,0 +1,280 @@ +/* $Header: /cvsroot/osrs/libtiff/libtiff/tiffiop.h,v 1.3 2000/01/28 20:56:59 warmerda Exp $ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef _TIFFIOP_ +#define _TIFFIOP_ +/* + * ``Library-private'' definitions. + */ +/* + * UNIX systems should run the configure script to generate + * a port.h file that reflects the system capabilities. + * Doing this obviates all the dreck done in tiffcomp.h. + */ +#if defined(unix) || defined(__unix) +//#include "port.h" +#include "tiffconf.h" +#include "tiffcomp.h" +#else +#include "tiffconf.h" +#include "tiffcomp.h" +#endif +#include "tiffio.h" +#include "tif_dir.h" + +#ifndef TRUE +#define TRUE 1 +#define FALSE 0 +#endif + +/* + * Typedefs for ``method pointers'' used internally. + */ +typedef unsigned char tidataval_t; /* internal image data value type */ +typedef tidataval_t* tidata_t; /* reference to internal image data */ + +typedef void (*TIFFVoidMethod)(TIFF*); +typedef int (*TIFFBoolMethod)(TIFF*); +typedef int (*TIFFPreMethod)(TIFF*, tsample_t); +typedef int (*TIFFCodeMethod)(TIFF*, tidata_t, tsize_t, tsample_t); +typedef int (*TIFFSeekMethod)(TIFF*, uint32); +typedef void (*TIFFPostMethod)(TIFF*, tidata_t, tsize_t); +typedef int (*TIFFVSetMethod)(TIFF*, ttag_t, va_list); +typedef int (*TIFFVGetMethod)(TIFF*, ttag_t, va_list); +typedef void (*TIFFPrintMethod)(TIFF*, FILE*, long); +typedef uint32 (*TIFFStripMethod)(TIFF*, uint32); +typedef void (*TIFFTileMethod)(TIFF*, uint32*, uint32*); + +struct tiff { + char* tif_name; /* name of open file */ + int tif_fd; /* open file descriptor */ + int tif_mode; /* open mode (O_*) */ + uint32 tif_flags; +#define TIFF_FILLORDER 0x0003 /* natural bit fill order for machine */ +#define TIFF_DIRTYHEADER 0x0004 /* header must be written on close */ +#define TIFF_DIRTYDIRECT 0x0008 /* current directory must be written */ +#define TIFF_BUFFERSETUP 0x0010 /* data buffers setup */ +#define TIFF_CODERSETUP 0x0020 /* encoder/decoder setup done */ +#define TIFF_BEENWRITING 0x0040 /* written 1+ scanlines to file */ +#define TIFF_SWAB 0x0080 /* byte swap file information */ +#define TIFF_NOBITREV 0x0100 /* inhibit bit reversal logic */ +#define TIFF_MYBUFFER 0x0200 /* my raw data buffer; free on close */ +#define TIFF_ISTILED 0x0400 /* file is tile, not strip- based */ +#define TIFF_MAPPED 0x0800 /* file is mapped into memory */ +#define TIFF_POSTENCODE 0x1000 /* need call to postencode routine */ +#define TIFF_INSUBIFD 0x2000 /* currently writing a subifd */ +#define TIFF_UPSAMPLED 0x4000 /* library is doing data up-sampling */ +#define TIFF_STRIPCHOP 0x8000 /* enable strip chopping support */ + toff_t tif_diroff; /* file offset of current directory */ + toff_t tif_nextdiroff; /* file offset of following directory */ + TIFFDirectory tif_dir; /* internal rep of current directory */ + TIFFHeader tif_header; /* file's header block */ + tidata_t tif_clientdir; /* client TIFF directory */ + const int* tif_typeshift; /* data type shift counts */ + const long* tif_typemask; /* data type masks */ + uint32 tif_row; /* current scanline */ + tdir_t tif_curdir; /* current directory (index) */ + tstrip_t tif_curstrip; /* current strip for read/write */ + toff_t tif_curoff; /* current offset for read/write */ + toff_t tif_dataoff; /* current offset for writing dir */ +#if SUBIFD_SUPPORT + uint16 tif_nsubifd; /* remaining subifds to write */ + toff_t tif_subifdoff; /* offset for patching SubIFD link */ +#endif +/* tiling support */ + uint32 tif_col; /* current column (offset by row too) */ + ttile_t tif_curtile; /* current tile for read/write */ + tsize_t tif_tilesize; /* # of bytes in a tile */ +/* compression scheme hooks */ + TIFFBoolMethod tif_setupdecode;/* called once before predecode */ + TIFFPreMethod tif_predecode; /* pre- row/strip/tile decoding */ + TIFFBoolMethod tif_setupencode;/* called once before preencode */ + TIFFPreMethod tif_preencode; /* pre- row/strip/tile encoding */ + TIFFBoolMethod tif_postencode; /* post- row/strip/tile encoding */ + TIFFCodeMethod tif_decoderow; /* scanline decoding routine */ + TIFFCodeMethod tif_encoderow; /* scanline encoding routine */ + TIFFCodeMethod tif_decodestrip;/* strip decoding routine */ + TIFFCodeMethod tif_encodestrip;/* strip encoding routine */ + TIFFCodeMethod tif_decodetile; /* tile decoding routine */ + TIFFCodeMethod tif_encodetile; /* tile encoding routine */ + TIFFVoidMethod tif_close; /* cleanup-on-close routine */ + TIFFSeekMethod tif_seek; /* position within a strip routine */ + TIFFVoidMethod tif_cleanup; /* cleanup state routine */ + TIFFStripMethod tif_defstripsize;/* calculate/constrain strip size */ + TIFFTileMethod tif_deftilesize;/* calculate/constrain tile size */ + tidata_t tif_data; /* compression scheme private data */ +/* input/output buffering */ + tsize_t tif_scanlinesize;/* # of bytes in a scanline */ + tsize_t tif_scanlineskew;/* scanline skew for reading strips */ + tidata_t tif_rawdata; /* raw data buffer */ + tsize_t tif_rawdatasize;/* # of bytes in raw data buffer */ + tidata_t tif_rawcp; /* current spot in raw buffer */ + tsize_t tif_rawcc; /* bytes unread from raw buffer */ +/* memory-mapped file support */ + tidata_t tif_base; /* base of mapped file */ + toff_t tif_size; /* size of mapped file region (bytes) */ + TIFFMapFileProc tif_mapproc; /* map file method */ + TIFFUnmapFileProc tif_unmapproc;/* unmap file method */ +/* input/output callback methods */ + thandle_t tif_clientdata; /* callback parameter */ + TIFFReadWriteProc tif_readproc; /* read method */ + TIFFReadWriteProc tif_writeproc;/* write method */ + TIFFSeekProc tif_seekproc; /* lseek method */ + TIFFCloseProc tif_closeproc; /* close method */ + TIFFSizeProc tif_sizeproc; /* filesize method */ +/* post-decoding support */ + TIFFPostMethod tif_postdecode; /* post decoding routine */ +/* tag support */ + TIFFFieldInfo** tif_fieldinfo; /* sorted table of registered tags */ + int tif_nfields; /* # entries in registered tag table */ + TIFFVSetMethod tif_vsetfield; /* tag set routine */ + TIFFVGetMethod tif_vgetfield; /* tag get routine */ + TIFFPrintMethod tif_printdir; /* directory print routine */ +}; + +#define isPseudoTag(t) (t > 0xffff) /* is tag value normal or pseudo */ + +#define isTiled(tif) (((tif)->tif_flags & TIFF_ISTILED) != 0) +#define isMapped(tif) (((tif)->tif_flags & TIFF_MAPPED) != 0) +#define isFillOrder(tif, o) (((tif)->tif_flags & (o)) != 0) +#define isUpSampled(tif) (((tif)->tif_flags & TIFF_UPSAMPLED) != 0) +#define TIFFReadFile(tif, buf, size) \ + ((*(tif)->tif_readproc)((tif)->tif_clientdata,buf,size)) +#define TIFFWriteFile(tif, buf, size) \ + ((*(tif)->tif_writeproc)((tif)->tif_clientdata,buf,size)) +#define TIFFSeekFile(tif, off, whence) \ + ((*(tif)->tif_seekproc)((tif)->tif_clientdata,(toff_t)(off),whence)) +#define TIFFCloseFile(tif) \ + ((*(tif)->tif_closeproc)((tif)->tif_clientdata)) +#define TIFFGetFileSize(tif) \ + ((*(tif)->tif_sizeproc)((tif)->tif_clientdata)) +#define TIFFMapFileContents(tif, paddr, psize) \ + ((*(tif)->tif_mapproc)((tif)->tif_clientdata,paddr,psize)) +#define TIFFUnmapFileContents(tif, addr, size) \ + ((*(tif)->tif_unmapproc)((tif)->tif_clientdata,addr,size)) + +/* + * Default Read/Seek/Write definitions. + */ +#ifndef ReadOK +#define ReadOK(tif, buf, size) \ + (TIFFReadFile(tif, (tdata_t) buf, (tsize_t)(size)) == (tsize_t)(size)) +#endif +#ifndef SeekOK +#define SeekOK(tif, off) \ + (TIFFSeekFile(tif, (toff_t) off, SEEK_SET) == (toff_t) off) +#endif +#ifndef WriteOK +#define WriteOK(tif, buf, size) \ + (TIFFWriteFile(tif, (tdata_t) buf, (tsize_t) size) == (tsize_t) size) +#endif + +/* NB: the uint32 casts are to silence certain ANSI-C compilers */ +#define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) +#define TIFFroundup(x, y) (TIFFhowmany(x,y)*((uint32)(y))) + +#if defined(__cplusplus) +extern "C" { +#endif +extern int _TIFFgetMode(const char*, const char*); +extern int _TIFFNoRowEncode(TIFF*, tidata_t, tsize_t, tsample_t); +extern int _TIFFNoStripEncode(TIFF*, tidata_t, tsize_t, tsample_t); +extern int _TIFFNoTileEncode(TIFF*, tidata_t, tsize_t, tsample_t); +extern int _TIFFNoRowDecode(TIFF*, tidata_t, tsize_t, tsample_t); +extern int _TIFFNoStripDecode(TIFF*, tidata_t, tsize_t, tsample_t); +extern int _TIFFNoTileDecode(TIFF*, tidata_t, tsize_t, tsample_t); +extern void _TIFFNoPostDecode(TIFF*, tidata_t, tsize_t); +extern int _TIFFNoPreCode (TIFF*, tsample_t); +extern int _TIFFNoSeek(TIFF*, uint32); +extern void _TIFFSwab16BitData(TIFF*, tidata_t, tsize_t); +extern void _TIFFSwab32BitData(TIFF*, tidata_t, tsize_t); +extern void _TIFFSwab64BitData(TIFF*, tidata_t, tsize_t); +extern int TIFFFlushData1(TIFF*); +extern void TIFFFreeDirectory(TIFF*); +extern int TIFFDefaultDirectory(TIFF*); +extern int TIFFSetCompressionScheme(TIFF*, int); +extern int TIFFSetDefaultCompressionState(TIFF*); +extern uint32 _TIFFDefaultStripSize(TIFF*, uint32); +extern void _TIFFDefaultTileSize(TIFF*, uint32*, uint32*); + +extern void _TIFFsetByteArray(void**, void*, long); +extern void _TIFFsetString(char**, char*); +extern void _TIFFsetShortArray(uint16**, uint16*, long); +extern void _TIFFsetLongArray(uint32**, uint32*, long); +extern void _TIFFsetFloatArray(float**, float*, long); +extern void _TIFFsetDoubleArray(double**, double*, long); + +extern void _TIFFprintAscii(FILE*, const char*); +extern void _TIFFprintAsciiTag(FILE*, const char*, const char*); + +GLOBALDATA(TIFFErrorHandler,_TIFFwarningHandler); +GLOBALDATA(TIFFErrorHandler,_TIFFerrorHandler); + +extern int TIFFInitDumpMode(TIFF*, int); +#ifdef PACKBITS_SUPPORT +extern int TIFFInitPackBits(TIFF*, int); +#endif +#ifdef CCITT_SUPPORT +extern int TIFFInitCCITTRLE(TIFF*, int), TIFFInitCCITTRLEW(TIFF*, int); +extern int TIFFInitCCITTFax3(TIFF*, int), TIFFInitCCITTFax4(TIFF*, int); +#endif +#ifdef THUNDER_SUPPORT +extern int TIFFInitThunderScan(TIFF*, int); +#endif +#ifdef NEXT_SUPPORT +extern int TIFFInitNeXT(TIFF*, int); +#endif +#ifdef LZW_SUPPORT +extern int TIFFInitLZW(TIFF*, int); +#endif +#ifdef OJPEG_SUPPORT +extern int TIFFInitOJPEG(TIFF*, int); +#endif +#ifdef JPEG_SUPPORT +extern int TIFFInitJPEG(TIFF*, int); +#endif +#ifdef JBIG_SUPPORT +extern int TIFFInitJBIG(TIFF*, int); +#endif +#ifdef ZIP_SUPPORT +extern int TIFFInitZIP(TIFF*, int); +#endif +#ifdef PIXARLOG_SUPPORT +extern int TIFFInitPixarLog(TIFF*, int); +#endif +#ifdef LOGLUV_SUPPORT +extern int TIFFInitSGILog(TIFF*, int); +#endif +#ifdef VMS +extern const TIFFCodec _TIFFBuiltinCODECS[]; +#else +extern TIFFCodec _TIFFBuiltinCODECS[]; +#endif + +#if defined(__cplusplus) +} +#endif +#endif /* _TIFFIOP_ */ diff --git a/SlnkDWFImpl/CxImage/tiff/uvcode.h b/SlnkDWFImpl/CxImage/tiff/uvcode.h new file mode 100644 index 0000000..b2900bd --- /dev/null +++ b/SlnkDWFImpl/CxImage/tiff/uvcode.h @@ -0,0 +1,173 @@ +/* Version 1.0 generated April 7, 1997 by Greg Ward Larson, SGI */ +#define UV_SQSIZ (float)0.003500 +#define UV_NDIVS 16289 +#define UV_VSTART (float)0.016940 +#define UV_NVS 163 +static struct { + float ustart; + short nus, ncum; +} uv_row[UV_NVS] = { + (float)0.247663, 4, 0, + (float)0.243779, 6, 4, + (float)0.241684, 7, 10, + (float)0.237874, 9, 17, + (float)0.235906, 10, 26, + (float)0.232153, 12, 36, + (float)0.228352, 14, 48, + (float)0.226259, 15, 62, + (float)0.222371, 17, 77, + (float)0.220410, 18, 94, + (float)0.214710, 21, 112, + (float)0.212714, 22, 133, + (float)0.210721, 23, 155, + (float)0.204976, 26, 178, + (float)0.202986, 27, 204, + (float)0.199245, 29, 231, + (float)0.195525, 31, 260, + (float)0.193560, 32, 291, + (float)0.189878, 34, 323, + (float)0.186216, 36, 357, + (float)0.186216, 36, 393, + (float)0.182592, 38, 429, + (float)0.179003, 40, 467, + (float)0.175466, 42, 507, + (float)0.172001, 44, 549, + (float)0.172001, 44, 593, + (float)0.168612, 46, 637, + (float)0.168612, 46, 683, + (float)0.163575, 49, 729, + (float)0.158642, 52, 778, + (float)0.158642, 52, 830, + (float)0.158642, 52, 882, + (float)0.153815, 55, 934, + (float)0.153815, 55, 989, + (float)0.149097, 58, 1044, + (float)0.149097, 58, 1102, + (float)0.142746, 62, 1160, + (float)0.142746, 62, 1222, + (float)0.142746, 62, 1284, + (float)0.138270, 65, 1346, + (float)0.138270, 65, 1411, + (float)0.138270, 65, 1476, + (float)0.132166, 69, 1541, + (float)0.132166, 69, 1610, + (float)0.126204, 73, 1679, + (float)0.126204, 73, 1752, + (float)0.126204, 73, 1825, + (float)0.120381, 77, 1898, + (float)0.120381, 77, 1975, + (float)0.120381, 77, 2052, + (float)0.120381, 77, 2129, + (float)0.112962, 82, 2206, + (float)0.112962, 82, 2288, + (float)0.112962, 82, 2370, + (float)0.107450, 86, 2452, + (float)0.107450, 86, 2538, + (float)0.107450, 86, 2624, + (float)0.107450, 86, 2710, + (float)0.100343, 91, 2796, + (float)0.100343, 91, 2887, + (float)0.100343, 91, 2978, + (float)0.095126, 95, 3069, + (float)0.095126, 95, 3164, + (float)0.095126, 95, 3259, + (float)0.095126, 95, 3354, + (float)0.088276, 100, 3449, + (float)0.088276, 100, 3549, + (float)0.088276, 100, 3649, + (float)0.088276, 100, 3749, + (float)0.081523, 105, 3849, + (float)0.081523, 105, 3954, + (float)0.081523, 105, 4059, + (float)0.081523, 105, 4164, + (float)0.074861, 110, 4269, + (float)0.074861, 110, 4379, + (float)0.074861, 110, 4489, + (float)0.074861, 110, 4599, + (float)0.068290, 115, 4709, + (float)0.068290, 115, 4824, + (float)0.068290, 115, 4939, + (float)0.068290, 115, 5054, + (float)0.063573, 119, 5169, + (float)0.063573, 119, 5288, + (float)0.063573, 119, 5407, + (float)0.063573, 119, 5526, + (float)0.057219, 124, 5645, + (float)0.057219, 124, 5769, + (float)0.057219, 124, 5893, + (float)0.057219, 124, 6017, + (float)0.050985, 129, 6141, + (float)0.050985, 129, 6270, + (float)0.050985, 129, 6399, + (float)0.050985, 129, 6528, + (float)0.050985, 129, 6657, + (float)0.044859, 134, 6786, + (float)0.044859, 134, 6920, + (float)0.044859, 134, 7054, + (float)0.044859, 134, 7188, + (float)0.040571, 138, 7322, + (float)0.040571, 138, 7460, + (float)0.040571, 138, 7598, + (float)0.040571, 138, 7736, + (float)0.036339, 142, 7874, + (float)0.036339, 142, 8016, + (float)0.036339, 142, 8158, + (float)0.036339, 142, 8300, + (float)0.032139, 146, 8442, + (float)0.032139, 146, 8588, + (float)0.032139, 146, 8734, + (float)0.032139, 146, 8880, + (float)0.027947, 150, 9026, + (float)0.027947, 150, 9176, + (float)0.027947, 150, 9326, + (float)0.023739, 154, 9476, + (float)0.023739, 154, 9630, + (float)0.023739, 154, 9784, + (float)0.023739, 154, 9938, + (float)0.019504, 158, 10092, + (float)0.019504, 158, 10250, + (float)0.019504, 158, 10408, + (float)0.016976, 161, 10566, + (float)0.016976, 161, 10727, + (float)0.016976, 161, 10888, + (float)0.016976, 161, 11049, + (float)0.012639, 165, 11210, + (float)0.012639, 165, 11375, + (float)0.012639, 165, 11540, + (float)0.009991, 168, 11705, + (float)0.009991, 168, 11873, + (float)0.009991, 168, 12041, + (float)0.009016, 170, 12209, + (float)0.009016, 170, 12379, + (float)0.009016, 170, 12549, + (float)0.006217, 173, 12719, + (float)0.006217, 173, 12892, + (float)0.005097, 175, 13065, + (float)0.005097, 175, 13240, + (float)0.005097, 175, 13415, + (float)0.003909, 177, 13590, + (float)0.003909, 177, 13767, + (float)0.002340, 177, 13944, + (float)0.002389, 170, 14121, + (float)0.001068, 164, 14291, + (float)0.001653, 157, 14455, + (float)0.000717, 150, 14612, + (float)0.001614, 143, 14762, + (float)0.000270, 136, 14905, + (float)0.000484, 129, 15041, + (float)0.001103, 123, 15170, + (float)0.001242, 115, 15293, + (float)0.001188, 109, 15408, + (float)0.001011, 103, 15517, + (float)0.000709, 97, 15620, + (float)0.000301, 89, 15717, + (float)0.002416, 82, 15806, + (float)0.003251, 76, 15888, + (float)0.003246, 69, 15964, + (float)0.004141, 62, 16033, + (float)0.005963, 55, 16095, + (float)0.008839, 47, 16150, + (float)0.010490, 40, 16197, + (float)0.016994, 31, 16237, + (float)0.023659, 21, 16268, +}; diff --git a/SlnkDWFImpl/CxImage/zlib/ChangeLog b/SlnkDWFImpl/CxImage/zlib/ChangeLog new file mode 100644 index 0000000..e68e07b --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/ChangeLog @@ -0,0 +1,722 @@ + + ChangeLog file for zlib + +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 occuring 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() diff --git a/SlnkDWFImpl/CxImage/zlib/FAQ b/SlnkDWFImpl/CxImage/zlib/FAQ new file mode 100644 index 0000000..b638815 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/FAQ @@ -0,0 +1,315 @@ + + Frequently Asked Questions about zlib + + +If your question is not there, please check the zlib home page +http://www.zlib.org which may have more recent information. +The lastest zlib FAQ is at http://www.gzip.org/zlib/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://www.zlib.org. + + 3. Where can I get a Visual Basic interface to zlib? + + See + * http://www.winimage.com/zLibDll/ + * http://www.dogma.net/markn/articles/zlibtool/zlibtool.htm + * contrib/visual-basic.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 total 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. + + 6. Where's the zlib documentation (man pages, etc.)? + + It's in zlib.h for the moment, and Francis S. Lin has converted it to a + web page zlib.html. Volunteers to transform this to Unix-style man pages, + please contact Jean-loup Gailly (jloup@gzip.org). Examples of zlib usage + are in the files example.c and minigzip.c. + + 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? + + 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? + + 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. + +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. 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. + +17. 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. + +18. 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. + + Note that you cannot specify special gzip header contents (e.g. a file + name or modification date), nor will inflate tell you what was in the + gzip header. If you need to customize the header or see what's in it, + you can use the raw deflate and inflate operations and the crc32() + function and roll your own gzip encoding and decoding. Read the gzip + RFC 1952 for details of the header and trailer format. + +19. 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. + +20. Can I use zlib in my commercial application? + + Yes. Please read the license in zlib.h. + +21. Is zlib under the GNU license? + + No. Please read the license in zlib.h. + +22. 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. + +23. Will zlib work on a big-endian or little-endian architecture, and can I + exchange compressed data between them? + + Yes and yes. + +24. Will zlib work on a 64-bit machine? + + It should. 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 + +25. 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. + +26. 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. + +27. Does zlib work on MVS, OS/390, CICS, etc.? + + We don't know for sure. We have heard occasional reports of success on + these systems. If you do use it on one of these, please provide us with + a report, instructions, and patches that we can reference when we get + these questions. Thanks. + +28. 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. + +29. 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 + +30. 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. + +31. 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 a 4K string space, other than the caller of + gzprintf() assuring that the output will not exceed 4K. 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. + +32. 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://www.zlib.org/ + +33. I get this or that compiler or source-code scanner warning when I crank it + up to maximally-pendantic. 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. So now, we simply make sure that the code always + works. + +34. 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. + +35. 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 gpg ( http://www.gnupg.org/ ) which already includes zlib compression. + For PKZIP compatible "encryption", look at http://www.info-zip.org/ + +36. 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. + +37. 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. + +38. 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. diff --git a/SlnkDWFImpl/CxImage/zlib/README b/SlnkDWFImpl/CxImage/zlib/README new file mode 100644 index 0000000..718aab2 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/README @@ -0,0 +1,126 @@ +ZLIB DATA COMPRESSION LIBRARY + +zlib 1.2.1 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). These documents are also available in other +formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html + +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 short "make test; make install" should work for most +machines. For Unix: "./configure; make test; make install" For MSDOS, use one +of the special makefiles such as Makefile.msc. For VMS, use Make_vms.com or +descrip.mms. + +Questions about zlib should be sent to , or to Gilles Vollant + for the Windows DLL version. The zlib home page is +http://www.zlib.org or http://www.gzip.org/zlib/ 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://www.gzip.org/zlib/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 in +http://dogma.net/markn/articles/zlibtool/zlibtool.htm + +The changes made in version 1.2.1 are documented in the file ChangeLog. + +Unsupported third party contributions are provided in directory "contrib". + +A Java implementation of zlib is available in the Java Development Kit +http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/package-summary.html +See the zlib home page http://www.zlib.org for details. + +A Perl interface to zlib written by Paul Marquess is in the +CPAN (Comprehensive Perl Archive Network) sites +http://www.cpan.org/modules/by-module/Compress/ + +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 + +A zlib binding for TCL written by Andreas Kupries is +availlable at http://www.oche.de/~akupries/soft/trf/trf_zip.html + +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, BEOS and by some Mac compilers. + +- For PalmOs, see http://palmzlib.sourceforge.net/ + +- When building a shared, i.e. dynamic library on Mac OS X, the library must be + installed before testing (do "make install" before "make test"), since the + library location is specified in the library. + + +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-2003 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. diff --git a/SlnkDWFImpl/CxImage/zlib/ZLIB.DEF b/SlnkDWFImpl/CxImage/zlib/ZLIB.DEF new file mode 100644 index 0000000..3fb7a40 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/ZLIB.DEF @@ -0,0 +1,46 @@ +LIBRARY "zlib" + +DESCRIPTION '"""zlib data compression library"""' + +EXETYPE NT + +SUBSYSTEM WINDOWS + +STUB 'WINSTUB.EXE' + +VERSION 1.14 + +CODE EXECUTE READ + +DATA READ WRITE + +HEAPSIZE 1048576,4096 + +EXPORTS + zlibVersion + deflate + deflateEnd + inflate + inflateEnd + deflateSetDictionary + deflateCopy + deflateReset + deflateParams + inflateSetDictionary + inflateSync + inflateReset + compress + uncompress + gzopen + gzdopen + gzread + gzwrite + gzflush + gzclose + gzerror + adler32 + crc32 + deflateInit_ + inflateInit_ + deflateInit2_ + inflateInit2_ diff --git a/SlnkDWFImpl/CxImage/zlib/ZLIB.RC b/SlnkDWFImpl/CxImage/zlib/ZLIB.RC new file mode 100644 index 0000000..69f2155 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/ZLIB.RC @@ -0,0 +1,32 @@ +#include + +#define IDR_VERSION1 1 +IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE + FILEVERSION 1,1,4,0 + PRODUCTVERSION 1,1,4,0 + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS 0 + FILEOS VOS_DOS_WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0 // not used +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904E4" + //language ID = U.S. English, char set = Windows, Multilingual + + BEGIN + VALUE "FileDescription", "zlib data compression library\0" + VALUE "FileVersion", "1.1.4\0" + VALUE "InternalName", "zlib\0" + VALUE "OriginalFilename", "zlib.lib\0" + VALUE "ProductName", "ZLib.DLL\0" + VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" + VALUE "LegalCopyright", "(C) 1995-2002 Jean-loup Gailly & Mark Adler\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 1252 + END +END diff --git a/SlnkDWFImpl/CxImage/zlib/adler32.c b/SlnkDWFImpl/CxImage/zlib/adler32.c new file mode 100644 index 0000000..dd6d60f --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/adler32.c @@ -0,0 +1,74 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +#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) {s1 += buf[i]; s2 += s1;} +#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); + +#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) +#else +# define MOD(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long s1 = adler & 0xffff; + unsigned long s2 = (adler >> 16) & 0xffff; + int k; + + if (buf == Z_NULL) return 1L; + + while (len > 0) { + k = len < NMAX ? (int)len : NMAX; + len -= k; + while (k >= 16) { + DO16(buf); + buf += 16; + k -= 16; + } + if (k != 0) do { + s1 += *buf++; + s2 += s1; + } while (--k); + MOD(s1); + MOD(s2); + } + return (s2 << 16) | s1; +} diff --git a/SlnkDWFImpl/CxImage/zlib/algorithm.txt b/SlnkDWFImpl/CxImage/zlib/algorithm.txt new file mode 100644 index 0000000..9f6b068 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/algorithm.txt @@ -0,0 +1,209 @@ +1. Compression algorithm (deflate) + +The deflation algorithm used by gzip (also zip and zlib) is a variation of +LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in +the input data. The second occurrence of a string is replaced by a +pointer to the previous string, in the form of a pair (distance, +length). Distances are limited to 32K bytes, and lengths are limited +to 258 bytes. When a string does not occur anywhere in the previous +32K bytes, it is emitted as a sequence of literal bytes. (In this +description, `string' must be taken as an arbitrary sequence of bytes, +and is not restricted to printable characters.) + +Literals or match lengths are compressed with one Huffman tree, and +match distances are compressed with another tree. The trees are stored +in a compact form at the start of each block. The blocks can have any +size (except that the compressed data for one block must fit in +available memory). A block is terminated when deflate() determines that +it would be useful to start another block with fresh trees. (This is +somewhat similar to the behavior of LZW-based _compress_.) + +Duplicated strings are found using a hash table. All input strings of +length 3 are inserted in the hash table. A hash index is computed for +the next 3 bytes. If the hash chain for this index is not empty, all +strings in the chain are compared with the current input string, and +the longest match is selected. + +The hash chains are searched starting with the most recent strings, to +favor small distances and thus take advantage of the Huffman encoding. +The hash chains are singly linked. There are no deletions from the +hash chains, the algorithm simply discards matches that are too old. + +To avoid a worst-case situation, very long hash chains are arbitrarily +truncated at a certain length, determined by a runtime option (level +parameter of deflateInit). So deflate() does not always find the longest +possible match but generally finds a match which is long enough. + +deflate() also defers the selection of matches with a lazy evaluation +mechanism. After a match of length N has been found, deflate() searches for +a longer match at the next input byte. If a longer match is found, the +previous match is truncated to a length of one (thus producing a single +literal byte) and the process of lazy evaluation begins again. Otherwise, +the original match is kept, and the next match search is attempted only N +steps later. + +The lazy match evaluation is also subject to a runtime parameter. If +the current match is long enough, deflate() reduces the search for a longer +match, thus speeding up the whole process. If compression ratio is more +important than speed, deflate() attempts a complete second search even if +the first match is already long enough. + +The lazy match evaluation is not performed for the fastest compression +modes (level parameter 1 to 3). For these fast modes, new strings +are inserted in the hash table only when no match was found, or +when the match is not too long. This degrades the compression ratio +but saves time since there are both fewer insertions and fewer searches. + + +2. Decompression algorithm (inflate) + +2.1 Introduction + +The key question is how to represent a Huffman code (or any prefix code) so +that you can decode fast. The most important characteristic is that shorter +codes are much more common than longer codes, so pay attention to decoding the +short codes fast, and let the long codes take longer to decode. + +inflate() sets up a first level table that covers some number of bits of +input less than the length of longest code. It gets that many bits from the +stream, and looks it up in the table. The table will tell if the next +code is that many bits or less and how many, and if it is, it will tell +the value, else it will point to the next level table for which inflate() +grabs more bits and tries to decode a longer code. + +How many bits to make the first lookup is a tradeoff between the time it +takes to decode and the time it takes to build the table. If building the +table took no time (and if you had infinite memory), then there would only +be a first level table to cover all the way to the longest code. However, +building the table ends up taking a lot longer for more bits since short +codes are replicated many times in such a table. What inflate() does is +simply to make the number of bits in the first table a variable, and then +to set that variable for the maximum speed. + +For inflate, which has 286 possible codes for the literal/length tree, the size +of the first table is nine bits. Also the distance trees have 30 possible +values, and the size of the first table is six bits. Note that for each of +those cases, the table ended up one bit longer than the ``average'' code +length, i.e. the code length of an approximately flat code which would be a +little more than eight bits for 286 symbols and a little less than five bits +for 30 symbols. + + +2.2 More details on the inflate table lookup + +Ok, you want to know what this cleverly obfuscated inflate tree actually +looks like. You are correct that it's not a Huffman tree. It is simply a +lookup table for the first, let's say, nine bits of a Huffman symbol. The +symbol could be as short as one bit or as long as 15 bits. If a particular +symbol is shorter than nine bits, then that symbol's translation is duplicated +in all those entries that start with that symbol's bits. For example, if the +symbol is four bits, then it's duplicated 32 times in a nine-bit table. If a +symbol is nine bits long, it appears in the table once. + +If the symbol is longer than nine bits, then that entry in the table points +to another similar table for the remaining bits. Again, there are duplicated +entries as needed. The idea is that most of the time the symbol will be short +and there will only be one table look up. (That's whole idea behind data +compression in the first place.) For the less frequent long symbols, there +will be two lookups. If you had a compression method with really long +symbols, you could have as many levels of lookups as is efficient. For +inflate, two is enough. + +So a table entry either points to another table (in which case nine bits in +the above example are gobbled), or it contains the translation for the symbol +and the number of bits to gobble. Then you start again with the next +ungobbled bit. + +You may wonder: why not just have one lookup table for how ever many bits the +longest symbol is? The reason is that if you do that, you end up spending +more time filling in duplicate symbol entries than you do actually decoding. +At least for deflate's output that generates new trees every several 10's of +kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code +would take too long if you're only decoding several thousand symbols. At the +other extreme, you could make a new table for every bit in the code. In fact, +that's essentially a Huffman tree. But then you spend two much time +traversing the tree while decoding, even for short symbols. + +So the number of bits for the first lookup table is a trade of the time to +fill out the table vs. the time spent looking at the second level and above of +the table. + +Here is an example, scaled down: + +The code being decoded, with 10 symbols, from 1 to 6 bits long: + +A: 0 +B: 10 +C: 1100 +D: 11010 +E: 11011 +F: 11100 +G: 11101 +H: 11110 +I: 111110 +J: 111111 + +Let's make the first table three bits long (eight entries): + +000: A,1 +001: A,1 +010: A,1 +011: A,1 +100: B,2 +101: B,2 +110: -> table X (gobble 3 bits) +111: -> table Y (gobble 3 bits) + +Each entry is what the bits decode as and how many bits that is, i.e. how +many bits to gobble. Or the entry points to another table, with the number of +bits to gobble implicit in the size of the table. + +Table X is two bits long since the longest code starting with 110 is five bits +long: + +00: C,1 +01: C,1 +10: D,2 +11: E,2 + +Table Y is three bits long since the longest code starting with 111 is six +bits long: + +000: F,2 +001: F,2 +010: G,2 +011: G,2 +100: H,2 +101: H,2 +110: I,3 +111: J,3 + +So what we have here are three tables with a total of 20 entries that had to +be constructed. That's compared to 64 entries for a single table. Or +compared to 16 entries for a Huffman tree (six two entry tables and one four +entry table). Assuming that the code ideally represents the probability of +the symbols, it takes on the average 1.25 lookups per symbol. That's compared +to one lookup for the single table, or 1.66 lookups per symbol for the +Huffman tree. + +There, I think that gives you a picture of what's going on. For inflate, the +meaning of a particular symbol is often more than just a letter. It can be a +byte (a "literal"), or it can be either a length or a distance which +indicates a base value and a number of bits to fetch after the code that is +added to the base value. Or it might be the special end-of-block code. The +data structures created in inftrees.c try to encode all that information +compactly in the tables. + + +Jean-loup Gailly Mark Adler +jloup@gzip.org madler@alumni.caltech.edu + + +References: + +[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data +Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3, +pp. 337-343. + +``DEFLATE Compressed Data Format Specification'' available in +http://www.ietf.org/rfc/rfc1951.txt diff --git a/SlnkDWFImpl/CxImage/zlib/compress.c b/SlnkDWFImpl/CxImage/zlib/compress.c new file mode 100644 index 0000000..5a7eeee --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/compress.c @@ -0,0 +1,79 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2002 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) + 11; +} diff --git a/SlnkDWFImpl/CxImage/zlib/crc32.c b/SlnkDWFImpl/CxImage/zlib/crc32.c new file mode 100644 index 0000000..235fa9e --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/crc32.c @@ -0,0 +1,311 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2003 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 about a factor + * of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +#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)+(((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 */ + +#ifdef DYNAMIC_CRC_TABLE + +local 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 const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* 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; + +#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; + unsigned 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 *)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 *)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 */ diff --git a/SlnkDWFImpl/CxImage/zlib/crc32.h b/SlnkDWFImpl/CxImage/zlib/crc32.h new file mode 100644 index 0000000..5de49bc --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/crc32.h @@ -0,0 +1,441 @@ +/* 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 + } +}; diff --git a/SlnkDWFImpl/CxImage/zlib/deflate.c b/SlnkDWFImpl/CxImage/zlib/deflate.c new file mode 100644 index 0000000..022d6b8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/deflate.c @@ -0,0 +1,1502 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2003 Jean-loup Gailly. + * 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.1 Copyright 1995-2003 Jean-loup Gailly "; +/* + 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 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)); +#ifndef FASTEST +#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 +#endif +local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); + +#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 */ + +#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. + */ + +/* 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_RLE) { + 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->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->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 > MAX_DIST(s)) { + length = MAX_DIST(s); +#ifndef USE_DICT_HEAD + dictionary += dictLength - length; /* use the tail of the dictionary */ +#endif + } + 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 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_RLE) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if (func != configuration_table[level].func && strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_PARTIAL_FLUSH); + } + 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; +} + +/* ========================================================================= + * 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, as well as wrap. + * 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 destLen; + + /* conservative upper bound */ + destLen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; + + /* if can't get parameters, return conservative bound */ + if (strm == Z_NULL || strm->state == Z_NULL) + return destLen; + + /* if not default parameters, return conservative bound */ + s = strm->state; + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return destLen; + + /* default settings: return tight bound for that case */ + return compressBound(sourceLen); +} + +/* ========================================================================= + * 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_FINISH || 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) { + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + 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, 255); + s->status = BUSY_STATE; + strm->adler = crc32(0L, Z_NULL, 0); + } + 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); + } + } + + /* 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 = (*(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 { /* 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 */ + } + } + 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 != 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; + + *dest = *source; + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + *ds = *ss; + 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; +#ifdef ASMV + match_init(); /* initialize the asm code */ +#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: + */ +#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 */ +#endif /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for level == 1 or strategy == Z_RLE only + */ +local uInt longest_match_fast(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; +} + +#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); +} + +/* =========================================================================== + * 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, eof) { \ + _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), \ + (eof)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, eof) { \ + FLUSH_BLOCK_ONLY(s, eof); \ + if (s->strm->avail_out == 0) return (eof) ? 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 = NIL; /* 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: + */ + 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). + */ +#ifdef FASTEST + if ((s->strategy < Z_HUFFMAN_ONLY) || + (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { + s->match_length = longest_match_fast (s, hash_head); + } +#else + if (s->strategy < Z_HUFFMAN_ONLY) { + s->match_length = longest_match (s, hash_head); + } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { + s->match_length = longest_match_fast (s, hash_head); + } +#endif + /* longest_match() or longest_match_fast() 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 = NIL; /* 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: + */ + 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). + */ + if (s->strategy < Z_HUFFMAN_ONLY) { + s->match_length = longest_match (s, hash_head); + } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { + s->match_length = longest_match_fast (s, hash_head); + } + /* longest_match() or longest_match_fast() 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 */ diff --git a/SlnkDWFImpl/CxImage/zlib/deflate.h b/SlnkDWFImpl/CxImage/zlib/deflate.h new file mode 100644 index 0000000..ee00773 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/deflate.h @@ -0,0 +1,326 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2002 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 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 */ + int pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + Byte data_type; /* UNKNOWN, BINARY or ASCII */ + 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. + */ + +} 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. + */ + + /* in trees.c */ +void _tr_init OF((deflate_state *s)); +int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); +void _tr_align OF((deflate_state *s)); +void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); + +#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 _length_code[]; + extern uch _dist_code[]; +#else + extern const uch _length_code[]; + extern const uch _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 */ diff --git a/SlnkDWFImpl/CxImage/zlib/gzio.c b/SlnkDWFImpl/CxImage/zlib/gzio.c new file mode 100644 index 0000000..26f2da1 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/gzio.c @@ -0,0 +1,1005 @@ +/* gzio.c -- IO on .gz files + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Compile this file with -DNO_GZCOMPRESS to avoid the compression code. + */ + +/* @(#) $Id$ */ + +#include + +#include "zutil.h" + +#ifdef NO_DEFLATE /* for compatiblity with old definition */ +# define NO_GZCOMPRESS +#endif + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +#ifndef Z_BUFSIZE +# ifdef MAXSEG_64K +# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ +# else +# define Z_BUFSIZE 16384 +# endif +#endif +#ifndef Z_PRINTF_BUFSIZE +# define Z_PRINTF_BUFSIZE 4096 +#endif + +#ifdef __MVS__ +# pragma map (fdopen , "\174\174FDOPEN") + FILE *fdopen(int, const char *); +#endif + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern void free OF((voidpf ptr)); +#endif + +#define ALLOC(size) malloc(size) +#define TRYFREE(p) {if (p) free(p);} + +static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ + +/* gzip flag byte */ +#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ +#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ +#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ +#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ +#define COMMENT 0x10 /* bit 4 set: file comment present */ +#define RESERVED 0xE0 /* bits 5..7: reserved */ + +typedef struct gz_stream { + z_stream stream; + int z_err; /* error code for last stream operation */ + int z_eof; /* set if end of input file */ + FILE *file; /* .gz file */ + Byte *inbuf; /* input buffer */ + Byte *outbuf; /* output buffer */ + uLong crc; /* crc32 of uncompressed data */ + char *msg; /* error message */ + char *path; /* path name for debugging only */ + int transparent; /* 1 if input file is not a .gz file */ + char mode; /* 'w' or 'r' */ + z_off_t start; /* start of compressed data in file (header skipped) */ + z_off_t in; /* bytes into deflate or inflate */ + z_off_t out; /* bytes out of deflate or inflate */ + int back; /* one character push-back */ + int last; /* true if push-back is last character */ +} gz_stream; + + +local gzFile gz_open OF((const char *path, const char *mode, int fd)); +local int do_flush OF((gzFile file, int flush)); +local int get_byte OF((gz_stream *s)); +local void check_header OF((gz_stream *s)); +local int destroy OF((gz_stream *s)); +local void putLong OF((FILE *file, uLong x)); +local uLong getLong OF((gz_stream *s)); + +/* =========================================================================== + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb"). The file is given either by file descriptor + or path name (if fd == -1). + gz_open returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). +*/ +local gzFile gz_open (path, mode, fd) + const char *path; + const char *mode; + int fd; +{ + int err; + int level = Z_DEFAULT_COMPRESSION; /* compression level */ + int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ + char *p = (char*)mode; + gz_stream *s; + char fmode[80]; /* copy of mode, without the compression level */ + char *m = fmode; + + if (!path || !mode) return Z_NULL; + + s = (gz_stream *)ALLOC(sizeof(gz_stream)); + if (!s) return Z_NULL; + + s->stream.zalloc = (alloc_func)0; + s->stream.zfree = (free_func)0; + s->stream.opaque = (voidpf)0; + s->stream.next_in = s->inbuf = Z_NULL; + s->stream.next_out = s->outbuf = Z_NULL; + s->stream.avail_in = s->stream.avail_out = 0; + s->file = NULL; + s->z_err = Z_OK; + s->z_eof = 0; + s->in = 0; + s->out = 0; + s->back = EOF; + s->crc = crc32(0L, Z_NULL, 0); + s->msg = NULL; + s->transparent = 0; + + s->path = (char*)ALLOC(strlen(path)+1); + if (s->path == NULL) { + return destroy(s), (gzFile)Z_NULL; + } + strcpy(s->path, path); /* do this early for debugging */ + + s->mode = '\0'; + do { + if (*p == 'r') s->mode = 'r'; + if (*p == 'w' || *p == 'a') s->mode = 'w'; + if (*p >= '0' && *p <= '9') { + level = *p - '0'; + } else if (*p == 'f') { + strategy = Z_FILTERED; + } else if (*p == 'h') { + strategy = Z_HUFFMAN_ONLY; + } else if (*p == 'R') { + strategy = Z_RLE; + } else { + *m++ = *p; /* copy the mode */ + } + } while (*p++ && m != fmode + sizeof(fmode)); + if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + err = Z_STREAM_ERROR; +#else + err = deflateInit2(&(s->stream), level, + Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); + /* windowBits is passed < 0 to suppress zlib header */ + + s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); +#endif + if (err != Z_OK || s->outbuf == Z_NULL) { + return destroy(s), (gzFile)Z_NULL; + } + } else { + s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); + + err = inflateInit2(&(s->stream), -MAX_WBITS); + /* windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are + * present after the compressed stream. + */ + if (err != Z_OK || s->inbuf == Z_NULL) { + return destroy(s), (gzFile)Z_NULL; + } + } + s->stream.avail_out = Z_BUFSIZE; + + errno = 0; + s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); + + if (s->file == NULL) { + return destroy(s), (gzFile)Z_NULL; + } + if (s->mode == 'w') { + /* Write a very simple .gz header: + */ + fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], + Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); + s->start = 10L; + /* We use 10L instead of ftell(s->file) to because ftell causes an + * fflush on some systems. This version of the library doesn't use + * start anyway in write mode, so this initialization is not + * necessary. + */ + } else { + check_header(s); /* skip the .gz header */ + s->start = ftell(s->file) - s->stream.avail_in; + } + + return (gzFile)s; +} + +/* =========================================================================== + Opens a gzip (.gz) file for reading or writing. +*/ +gzFile ZEXPORT gzopen (path, mode) + const char *path; + const char *mode; +{ + return gz_open (path, mode, -1); +} + +/* =========================================================================== + Associate a gzFile with the file descriptor fd. fd is not dup'ed here + to mimic the behavio(u)r of fdopen. +*/ +gzFile ZEXPORT gzdopen (fd, mode) + int fd; + const char *mode; +{ + char name[20]; + + if (fd < 0) return (gzFile)Z_NULL; + sprintf(name, "", fd); /* for debugging */ + + return gz_open (name, mode, fd); +} + +/* =========================================================================== + * Update the compression level and strategy + */ +int ZEXPORT gzsetparams (file, level, strategy) + gzFile file; + int level; + int strategy; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + /* Make room to allow flushing */ + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + } + s->stream.avail_out = Z_BUFSIZE; + } + + return deflateParams (&(s->stream), level, strategy); +} + +/* =========================================================================== + Read a byte from a gz_stream; update next_in and avail_in. Return EOF + for end of file. + IN assertion: the stream s has been sucessfully opened for reading. +*/ +local int get_byte(s) + gz_stream *s; +{ + if (s->z_eof) return EOF; + if (s->stream.avail_in == 0) { + errno = 0; + s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) s->z_err = Z_ERRNO; + return EOF; + } + s->stream.next_in = s->inbuf; + } + s->stream.avail_in--; + return *(s->stream.next_in)++; +} + +/* =========================================================================== + Check the gzip header of a gz_stream opened for reading. Set the stream + mode to transparent if the gzip magic header is not present; set s->err + to Z_DATA_ERROR if the magic header is present but the rest of the header + is incorrect. + IN assertion: the stream s has already been created sucessfully; + s->stream.avail_in is zero for the first time, but may be non-zero + for concatenated .gz files. +*/ +local void check_header(s) + gz_stream *s; +{ + int method; /* method byte */ + int flags; /* flags byte */ + uInt len; + int c; + + /* Assure two bytes in the buffer so we can peek ahead -- handle case + where first byte of header is at the end of the buffer after the last + gzip segment */ + len = s->stream.avail_in; + if (len < 2) { + if (len) s->inbuf[0] = s->stream.next_in[0]; + errno = 0; + len = fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); + if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; + s->stream.avail_in += len; + s->stream.next_in = s->inbuf; + if (s->stream.avail_in < 2) { + s->transparent = s->stream.avail_in; + return; + } + } + + /* Peek ahead to check the gzip magic header */ + if (s->stream.next_in[0] != gz_magic[0] || + s->stream.next_in[1] != gz_magic[1]) { + s->transparent = 1; + return; + } + s->stream.avail_in -= 2; + s->stream.next_in += 2; + + /* Check the rest of the gzip header */ + method = get_byte(s); + flags = get_byte(s); + if (method != Z_DEFLATED || (flags & RESERVED) != 0) { + s->z_err = Z_DATA_ERROR; + return; + } + + /* Discard time, xflags and OS code: */ + for (len = 0; len < 6; len++) (void)get_byte(s); + + if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ + len = (uInt)get_byte(s); + len += ((uInt)get_byte(s))<<8; + /* len is garbage if EOF but the loop below will quit anyway */ + while (len-- != 0 && get_byte(s) != EOF) ; + } + if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ + while ((c = get_byte(s)) != 0 && c != EOF) ; + } + if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ + while ((c = get_byte(s)) != 0 && c != EOF) ; + } + if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ + for (len = 0; len < 2; len++) (void)get_byte(s); + } + s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; +} + + /* =========================================================================== + * Cleanup then free the given gz_stream. Return a zlib error code. + Try freeing in the reverse order of allocations. + */ +local int destroy (s) + gz_stream *s; +{ + int err = Z_OK; + + if (!s) return Z_STREAM_ERROR; + + TRYFREE(s->msg); + + if (s->stream.state != NULL) { + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + err = Z_STREAM_ERROR; +#else + err = deflateEnd(&(s->stream)); +#endif + } else if (s->mode == 'r') { + err = inflateEnd(&(s->stream)); + } + } + if (s->file != NULL && fclose(s->file)) { +#ifdef ESPIPE + if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ +#endif + err = Z_ERRNO; + } + if (s->z_err < 0) err = s->z_err; + + TRYFREE(s->inbuf); + TRYFREE(s->outbuf); + TRYFREE(s->path); + TRYFREE(s); + return err; +} + +/* =========================================================================== + Reads the given number of uncompressed bytes from the compressed file. + gzread returns the number of bytes actually read (0 for end of file). +*/ +int ZEXPORT gzread (file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + gz_stream *s = (gz_stream*)file; + Bytef *start = (Bytef*)buf; /* starting point for crc computation */ + Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ + + if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR; + + if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; + if (s->z_err == Z_STREAM_END) return 0; /* EOF */ + + next_out = (Byte*)buf; + s->stream.next_out = (Bytef*)buf; + s->stream.avail_out = len; + + if (s->stream.avail_out && s->back != EOF) { + *next_out++ = s->back; + s->stream.next_out++; + s->stream.avail_out--; + s->back = EOF; + s->out++; + if (s->last) { + s->z_err = Z_STREAM_END; + return 1; + } + } + + while (s->stream.avail_out != 0) { + + if (s->transparent) { + /* Copy first the lookahead bytes: */ + uInt n = s->stream.avail_in; + if (n > s->stream.avail_out) n = s->stream.avail_out; + if (n > 0) { + zmemcpy(s->stream.next_out, s->stream.next_in, n); + next_out += n; + s->stream.next_out = next_out; + s->stream.next_in += n; + s->stream.avail_out -= n; + s->stream.avail_in -= n; + } + if (s->stream.avail_out > 0) { + s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out, + s->file); + } + len -= s->stream.avail_out; + s->in += len; + s->out += len; + if (len == 0) s->z_eof = 1; + return (int)len; + } + if (s->stream.avail_in == 0 && !s->z_eof) { + + errno = 0; + s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) { + s->z_err = Z_ERRNO; + break; + } + } + s->stream.next_in = s->inbuf; + } + s->in += s->stream.avail_in; + s->out += s->stream.avail_out; + s->z_err = inflate(&(s->stream), Z_NO_FLUSH); + s->in -= s->stream.avail_in; + s->out -= s->stream.avail_out; + + if (s->z_err == Z_STREAM_END) { + /* Check CRC and original size */ + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + start = s->stream.next_out; + + if (getLong(s) != s->crc) { + s->z_err = Z_DATA_ERROR; + } else { + (void)getLong(s); + /* The uncompressed length returned by above getlong() may be + * different from s->out in case of concatenated .gz files. + * Check for such files: + */ + check_header(s); + if (s->z_err == Z_OK) { + inflateReset(&(s->stream)); + s->crc = crc32(0L, Z_NULL, 0); + } + } + } + if (s->z_err != Z_OK || s->z_eof) break; + } + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + + return (int)(len - s->stream.avail_out); +} + + +/* =========================================================================== + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ +int ZEXPORT gzgetc(file) + gzFile file; +{ + unsigned char c; + + return gzread(file, &c, 1) == 1 ? c : -1; +} + + +/* =========================================================================== + Push one byte back onto the stream. +*/ +int ZEXPORT gzungetc(c, file) + int c; + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF; + s->back = c; + s->out--; + s->last = (s->z_err == Z_STREAM_END); + if (s->last) s->z_err = Z_OK; + s->z_eof = 0; + return c; +} + + +/* =========================================================================== + 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. The string is then terminated + with a null character. + gzgets returns buf, or Z_NULL in case of error. + + The current implementation is not optimized at all. +*/ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + char *b = buf; + if (buf == Z_NULL || len <= 0) return Z_NULL; + + while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ; + *buf = '\0'; + return b == buf && len > 0 ? Z_NULL : b; +} + + +#ifndef NO_GZCOMPRESS +/* =========================================================================== + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of bytes actually written (0 in case of error). +*/ +int ZEXPORT gzwrite (file, buf, len) + gzFile file; + voidpc buf; + unsigned len; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + s->stream.next_in = (Bytef*)buf; + s->stream.avail_in = len; + + while (s->stream.avail_in != 0) { + + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + break; + } + s->stream.avail_out = Z_BUFSIZE; + } + s->in += s->stream.avail_in; + s->out += s->stream.avail_out; + s->z_err = deflate(&(s->stream), Z_NO_FLUSH); + s->in -= s->stream.avail_in; + s->out -= s->stream.avail_out; + if (s->z_err != Z_OK) break; + } + s->crc = crc32(s->crc, (const Bytef *)buf, len); + + return (int)(len - s->stream.avail_in); +} + + +/* =========================================================================== + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). +*/ +#ifdef STDC +#include + +int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...) +{ + char buf[Z_PRINTF_BUFSIZE]; + va_list va; + int len; + + buf[sizeof(buf) - 1] = 0; + va_start(va, format); +#ifdef NO_vsnprintf +# ifdef HAS_vsprintf_void + (void)vsprintf(buf, format, va); + va_end(va); + for (len = 0; len < sizeof(buf); len++) + if (buf[len] == 0) break; +# else + len = vsprintf(buf, format, va); + va_end(va); +# endif +#else +# ifdef HAS_vsnprintf_void + (void)vsnprintf(buf, sizeof(buf), format, va); + va_end(va); + len = strlen(buf); +# else + len = vsnprintf(buf, sizeof(buf), format, va); + va_end(va); +# endif +#endif + if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0) + return 0; + return gzwrite(file, buf, (unsigned)len); +} +#else /* not ANSI C */ + +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; +{ + char buf[Z_PRINTF_BUFSIZE]; + int len; + + buf[sizeof(buf) - 1] = 0; +#ifdef NO_snprintf +# ifdef HAS_sprintf_void + sprintf(buf, 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 < sizeof(buf); len++) + if (buf[len] == 0) break; +# else + len = sprintf(buf, 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(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen(buf); +# else + len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#endif + if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0) + return 0; + return gzwrite(file, buf, len); +} +#endif + +/* =========================================================================== + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned char cc = (unsigned char) c; /* required for big endian systems */ + + return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1; +} + + +/* =========================================================================== + 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. +*/ +int ZEXPORT gzputs(file, s) + gzFile file; + const char *s; +{ + return gzwrite(file, (char*)s, (unsigned)strlen(s)); +} + + +/* =========================================================================== + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. +*/ +local int do_flush (file, flush) + gzFile file; + int flush; +{ + uInt len; + int done = 0; + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + s->stream.avail_in = 0; /* should be zero already anyway */ + + for (;;) { + len = Z_BUFSIZE - s->stream.avail_out; + + if (len != 0) { + if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { + s->z_err = Z_ERRNO; + return Z_ERRNO; + } + s->stream.next_out = s->outbuf; + s->stream.avail_out = Z_BUFSIZE; + } + if (done) break; + s->out += s->stream.avail_out; + s->z_err = deflate(&(s->stream), flush); + s->out -= s->stream.avail_out; + + /* Ignore the second of two consecutive flushes: */ + if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; + + /* deflate has finished flushing only when it hasn't used up + * all the available space in the output buffer: + */ + done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); + + if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; + } + return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; +} + +int ZEXPORT gzflush (file, flush) + gzFile file; + int flush; +{ + gz_stream *s = (gz_stream*)file; + int err = do_flush (file, flush); + + if (err) return err; + fflush(s->file); + return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; +} +#endif /* NO_GZCOMPRESS */ + +/* =========================================================================== + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error. + SEEK_END is not implemented, returns error. + In this version of the library, gzseek can be extremely slow. +*/ +z_off_t ZEXPORT gzseek (file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || whence == SEEK_END || + s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { + return -1L; + } + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + return -1L; +#else + if (whence == SEEK_SET) { + offset -= s->in; + } + if (offset < 0) return -1L; + + /* At this point, offset is the number of zero bytes to write. */ + if (s->inbuf == Z_NULL) { + s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ + if (s->inbuf == Z_NULL) return -1L; + zmemzero(s->inbuf, Z_BUFSIZE); + } + while (offset > 0) { + uInt size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (uInt)offset; + + size = gzwrite(file, s->inbuf, size); + if (size == 0) return -1L; + + offset -= size; + } + return s->in; +#endif + } + /* Rest of function is for reading only */ + + /* compute absolute position */ + if (whence == SEEK_CUR) { + offset += s->out; + } + if (offset < 0) return -1L; + + if (s->transparent) { + /* map to fseek */ + s->back = EOF; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; + + s->in = s->out = offset; + return offset; + } + + /* For a negative seek, rewind and use positive seek */ + if (offset >= s->out) { + offset -= s->out; + } else if (gzrewind(file) < 0) { + return -1L; + } + /* offset is now the number of bytes to skip. */ + + if (offset != 0 && s->outbuf == Z_NULL) { + s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); + if (s->outbuf == Z_NULL) return -1L; + } + if (offset && s->back != EOF) { + s->back = EOF; + s->out++; + offset--; + if (s->last) s->z_err = Z_STREAM_END; + } + while (offset > 0) { + int size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (int)offset; + + size = gzread(file, s->outbuf, (uInt)size); + if (size <= 0) return -1L; + offset -= size; + } + return s->out; +} + +/* =========================================================================== + Rewinds input file. +*/ +int ZEXPORT gzrewind (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r') return -1; + + s->z_err = Z_OK; + s->z_eof = 0; + s->back = EOF; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + s->crc = crc32(0L, Z_NULL, 0); + if (!s->transparent) (void)inflateReset(&s->stream); + s->in = 0; + s->out = 0; + return fseek(s->file, s->start, SEEK_SET); +} + +/* =========================================================================== + 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. +*/ +z_off_t ZEXPORT gztell (file) + gzFile file; +{ + return gzseek(file, 0L, SEEK_CUR); +} + +/* =========================================================================== + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ +int ZEXPORT gzeof (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + /* With concatenated compressed files that can have embedded + * crc trailers, z_eof is no longer the only/best indicator of EOF + * on a gz_stream. Handle end-of-stream error explicitly here. + */ + if (s == NULL || s->mode != 'r') return 0; + if (s->z_eof) return 1; + return s->z_err == Z_STREAM_END; +} + +/* =========================================================================== + Outputs a long in LSB order to the given file +*/ +local void putLong (file, x) + FILE *file; + uLong x; +{ + int n; + for (n = 0; n < 4; n++) { + fputc((int)(x & 0xff), file); + x >>= 8; + } +} + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets z_err in case + of error. +*/ +local uLong getLong (s) + gz_stream *s; +{ + uLong x = (uLong)get_byte(s); + int c; + + x += ((uLong)get_byte(s))<<8; + x += ((uLong)get_byte(s))<<16; + c = get_byte(s); + if (c == EOF) s->z_err = Z_DATA_ERROR; + x += ((uLong)c)<<24; + return x; +} + +/* =========================================================================== + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. +*/ +int ZEXPORT gzclose (file) + gzFile file; +{ + int err; + gz_stream *s = (gz_stream*)file; + + if (s == NULL) return Z_STREAM_ERROR; + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + return Z_STREAM_ERROR; +#else + err = do_flush (file, Z_FINISH); + if (err != Z_OK) return destroy((gz_stream*)file); + + putLong (s->file, s->crc); + putLong (s->file, (uLong)(s->in & 0xffffffff)); +#endif + } + return destroy((gz_stream*)file); +} + +/* =========================================================================== + Returns the error message for the last error which occured on the + given compressed file. errnum is set to zlib error number. If an + error occured 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. +*/ +const char * ZEXPORT gzerror (file, errnum) + gzFile file; + int *errnum; +{ + char *m; + gz_stream *s = (gz_stream*)file; + + if (s == NULL) { + *errnum = Z_STREAM_ERROR; + return (const char*)ERR_MSG(Z_STREAM_ERROR); + } + *errnum = s->z_err; + if (*errnum == Z_OK) return (const char*)""; + + m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); + + if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); + + TRYFREE(s->msg); + s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3); + if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR); + strcpy(s->msg, s->path); + strcat(s->msg, ": "); + strcat(s->msg, m); + return (const char*)s->msg; +} + +/* =========================================================================== + Clear the error and end-of-file flags, and do the same for the real file. +*/ +void ZEXPORT gzclearerr (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL) return; + if (s->z_err != Z_STREAM_END) s->z_err = Z_OK; + s->z_eof = 0; + clearerr(s->file); +} diff --git a/SlnkDWFImpl/CxImage/zlib/infback.c b/SlnkDWFImpl/CxImage/zlib/infback.c new file mode 100644 index 0000000..5cf5d22 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/infback.c @@ -0,0 +1,619 @@ +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2003 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_stream FAR *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 = (voidpf)state; + state->wbits = windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->write = 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_stream FAR *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 this; /* 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 (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.val < 16) { + NEEDBITS(this.bits); + DROPBITS(this.bits); + state->lens[state->have++] = this.val; + } + else { + if (this.val == 16) { + NEEDBITS(this.bits + 2); + DROPBITS(this.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 (this.val == 17) { + NEEDBITS(this.bits + 3); + DROPBITS(this.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(this.bits + 7); + DROPBITS(this.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; + } + } + + /* build code tables */ + 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 (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.op && (this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + state->length = (unsigned)this.val; + + /* process literal */ + if (this.op == 0) { + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (this.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (this.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(this.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 (;;) { + this = state->distcode[BITS(state->distbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if ((this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + if (this.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)this.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(this.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_stream FAR *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; +} diff --git a/SlnkDWFImpl/CxImage/zlib/inffast.c b/SlnkDWFImpl/CxImage/zlib/inffast.c new file mode 100644 index 0000000..63aa440 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/inffast.c @@ -0,0 +1,305 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2003 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) + - 68060 (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 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 */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned write; /* 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 this; /* 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); + wsize = state->wsize; + whave = state->whave; + write = state->write; + 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; + } + this = lcode[hold & lmask]; + dolen: + op = (unsigned)(this.bits); + hold >>= op; + bits -= op; + op = (unsigned)(this.op); + if (op == 0) { /* literal */ + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + PUP(out) = (unsigned char)(this.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(this.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; + } + this = dcode[hold & dmask]; + dodist: + op = (unsigned)(this.bits); + hold >>= op; + bits -= op; + op = (unsigned)(this.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(this.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); + 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) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + from = window - OFF; + if (write == 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 (write < op) { /* wrap around window */ + from += wsize + write - op; + op -= write; + if (op < len) { /* some from end of window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + if (write < len) { /* some from start of window */ + op = write; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += write - 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 */ + this = dcode[this.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 */ + this = lcode[this.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 write == 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 */ diff --git a/SlnkDWFImpl/CxImage/zlib/inffast.h b/SlnkDWFImpl/CxImage/zlib/inffast.h new file mode 100644 index 0000000..614fa78 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003 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 inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/SlnkDWFImpl/CxImage/zlib/inffixed.h b/SlnkDWFImpl/CxImage/zlib/inffixed.h new file mode 100644 index 0000000..423d5c5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/inffixed.h @@ -0,0 +1,94 @@ + /* 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} + }; diff --git a/SlnkDWFImpl/CxImage/zlib/inflate.c b/SlnkDWFImpl/CxImage/zlib/inflate.c new file mode 100644 index 0000000..71fe3cc --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/inflate.c @@ -0,0 +1,1270 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2003 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 write == 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; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->wsize = 0; + state->whave = 0; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +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) 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 = (voidpf)state; + if (windowBits < 0) { + state->wrap = 0; + windowBits = -windowBits; + } + else { + state->wrap = (windowBits >> 4) + 1; +#ifdef GUNZIP + if (windowBits < 48) windowBits &= 15; +#endif + } + if (windowBits < 8 || windowBits > 15) { + ZFREE(strm, state); + strm->state = Z_NULL; + return Z_STREAM_ERROR; + } + state->wbits = (unsigned)windowBits; + state->window = Z_NULL; + return inflateReset(strm); +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +/* + 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->write = 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->write = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->write; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->write, strm->next_out - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, strm->next_out - copy, copy); + state->write = copy; + state->whave = state->wsize; + } + else { + state->write += dist; + if (state->write == state->wsize) state->write = 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 this; /* 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->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); + if (BITS(4) + 8 > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + 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->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->flags & 0x0200) CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + 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->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + } + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (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->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + } while (len && copy < have); + if (state->flags & 0x02000) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + } while (len && copy < have); + if (state->flags & 0x02000) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + 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(); + } + 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) 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 */ + 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; + 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 (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.val < 16) { + NEEDBITS(this.bits); + DROPBITS(this.bits); + state->lens[state->have++] = this.val; + } + else { + if (this.val == 16) { + NEEDBITS(this.bits + 2); + DROPBITS(this.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 (this.val == 17) { + NEEDBITS(this.bits + 3); + DROPBITS(this.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(this.bits + 7); + DROPBITS(this.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; + } + } + + /* build code tables */ + 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: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + break; + } + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.op && (this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + state->length = (unsigned)this.val; + if ((int)(this.op) == 0) { + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + state->mode = LIT; + break; + } + if (this.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + if (this.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(this.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->mode = DIST; + case DIST: + for (;;) { + this = state->distcode[BITS(state->distbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if ((this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + if (this.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)this.val; + state->extra = (unsigned)(this.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->whave + out - left) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + 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->write) { + copy -= state->write; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->write - 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); + 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->mode != DICT) return Z_STREAM_ERROR; + + /* check for correct dictionary id */ + 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; +} + +/* + 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; + + /* 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 */ + *dest = *source; + *copy = *state; + 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) + zmemcpy(window, state->window, 1U << state->wbits); + copy->window = window; + dest->state = (voidpf)copy; + return Z_OK; +} diff --git a/SlnkDWFImpl/CxImage/zlib/inflate.h b/SlnkDWFImpl/CxImage/zlib/inflate.h new file mode 100644 index 0000000..b696512 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/inflate.h @@ -0,0 +1,117 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2003 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 */ +#ifdef GUNZIP + 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) */ +#endif + 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: 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: waiting for length/lit 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 */ +#ifdef GUNZIP + LENGTH, /* i: waiting for 32-bit length (gzip) */ +#endif + 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 the BAD or MEM mode -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME + NAME -> COMMENT -> HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + Read deflate blocks: + TYPE -> STORED or TABLE or LEN or CHECK + STORED -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN + Read deflate codes: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* state maintained between inflate() calls. Approximately 7K 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 long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + /* 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 write; /* 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 */ +}; diff --git a/SlnkDWFImpl/CxImage/zlib/inftrees.c b/SlnkDWFImpl/CxImage/zlib/inftrees.c new file mode 100644 index 0000000..55fd27b --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/inftrees.c @@ -0,0 +1,321 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2003 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.1 Copyright 1995-2003 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 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 this; /* 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, 76, 66}; + 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) return -1; /* no codes! */ + for (min = 1; min <= MAXBITS; 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 || (codes - count[0] != 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 when a LENS table is being made + against the space in *table, ENOUGH, minus the maximum space needed by + the worst case distance code, MAXD. This should never happen, but the + sufficiency of ENOUGH has not been proven exhaustively, hence the check. + This assumes that when type == LENS, bits == 9. + + 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 - MAXD) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + this.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + this.op = (unsigned char)0; + this.val = work[sym]; + } + else if ((int)(work[sym]) > end) { + this.op = (unsigned char)(extra[work[sym]]); + this.val = base[work[sym]]; + } + else { + this.op = (unsigned char)(32 + 64); /* end of block */ + this.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + do { + fill -= incr; + next[(huff >> drop) + fill] = this; + } 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 += 1U << 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 - MAXD) + 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. + */ + this.op = (unsigned char)64; /* invalid code marker */ + this.bits = (unsigned char)(len - drop); + this.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; + curr = root; + this.bits = (unsigned char)len; + } + + /* put invalid code marker in table */ + next[huff >> drop] = this; + + /* 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; +} diff --git a/SlnkDWFImpl/CxImage/zlib/inftrees.h b/SlnkDWFImpl/CxImage/zlib/inftrees.h new file mode 100644 index 0000000..1dbfe53 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/inftrees.h @@ -0,0 +1,55 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2003 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 dynamic tree. The maximum found in a long but non- + exhaustive search was 1004 code structures (850 for length/literals + and 154 for distances, the latter actually the result of an + exhaustive search). The true maximum is not known, but the value + below is more than safe. */ +#define ENOUGH 1440 +#define MAXD 154 + +/* Type of code to build for inftable() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +extern int inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/SlnkDWFImpl/CxImage/zlib/trees.c b/SlnkDWFImpl/CxImage/zlib/trees.c new file mode 100644 index 0000000..1d36eaa --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/trees.c @@ -0,0 +1,1215 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2003 Jean-loup Gailly + * 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 void set_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 |= (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 |= 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 |= (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 |= (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: */ + 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; + + /* 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 _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 _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 _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 (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 _tr_stored_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+eof, 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 _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 _tr_flush_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int eof; /* true 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 ascii or binary */ + if (s->data_type == Z_UNKNOWN) set_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, eof); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+eof, 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)+eof, 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 (eof) { + 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*eof)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int _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; +} + +/* =========================================================================== + * Set the data type to ASCII or BINARY, using a crude approximation: + * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. + * IN assertion: the fields freq of dyn_ltree are set and the total of all + * frequencies does not exceed 64K (to fit in an int on 16 bit machines). + */ +local void set_data_type(s) + deflate_state *s; +{ + int n = 0; + unsigned ascii_freq = 0; + unsigned bin_freq = 0; + while (n < 7) bin_freq += s->dyn_ltree[n++].Freq; + while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq; + while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq; + s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII); +} + +/* =========================================================================== + * 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++); + } +} diff --git a/SlnkDWFImpl/CxImage/zlib/trees.h b/SlnkDWFImpl/CxImage/zlib/trees.h new file mode 100644 index 0000000..1ca868b --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/trees.h @@ -0,0 +1,128 @@ +/* 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 _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 _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 +}; + diff --git a/SlnkDWFImpl/CxImage/zlib/uncompr.c b/SlnkDWFImpl/CxImage/zlib/uncompr.c new file mode 100644 index 0000000..ad6db0a --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/uncompr.c @@ -0,0 +1,61 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003 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. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + 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; +} diff --git a/SlnkDWFImpl/CxImage/zlib/zconf.h b/SlnkDWFImpl/CxImage/zlib/zconf.h new file mode 100644 index 0000000..759d757 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zconf.h @@ -0,0 +1,323 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2003 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. + */ +#ifdef Z_PREFIX +# define deflateInit_ z_deflateInit_ +# define deflate z_deflate +# define deflateEnd z_deflateEnd +# define inflateInit_ z_inflateInit_ +# define inflate z_inflate +# define inflateEnd z_inflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateSetDictionary z_deflateSetDictionary +# define deflateCopy z_deflateCopy +# define deflateReset z_deflateReset +# define deflatePrime z_deflatePrime +# define deflateParams z_deflateParams +# define deflateBound z_deflateBound +# define inflateInit2_ z_inflateInit2_ +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateCopy z_inflateCopy +# define inflateReset z_inflateReset +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define uncompress z_uncompress +# define adler32 z_adler32 +# define crc32 z_crc32 +# define get_crc_table z_get_crc_table + +# define Byte z_Byte +# define uInt z_uInt +# define uLong z_uLong +# define Bytef z_Bytef +# define charf z_charf +# define intf z_intf +# define uIntf z_uIntf +# define uLongf z_uLongf +# define voidpf z_voidpf +# define voidp z_voidp +#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__)) && !defined(WIN32) +# define WIN32 +#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 + +#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ +# include /* for off_t */ +# include /* for SEEK_* and off_t */ +# ifdef VMS +# include /* for off_t */ +# endif +# define z_off_t off_t +#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(__OS400__) +#define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +# ifdef FAR +# undef FAR +# endif +#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 */ diff --git a/SlnkDWFImpl/CxImage/zlib/zconf.in.h b/SlnkDWFImpl/CxImage/zlib/zconf.in.h new file mode 100644 index 0000000..759d757 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zconf.in.h @@ -0,0 +1,323 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2003 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. + */ +#ifdef Z_PREFIX +# define deflateInit_ z_deflateInit_ +# define deflate z_deflate +# define deflateEnd z_deflateEnd +# define inflateInit_ z_inflateInit_ +# define inflate z_inflate +# define inflateEnd z_inflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateSetDictionary z_deflateSetDictionary +# define deflateCopy z_deflateCopy +# define deflateReset z_deflateReset +# define deflatePrime z_deflatePrime +# define deflateParams z_deflateParams +# define deflateBound z_deflateBound +# define inflateInit2_ z_inflateInit2_ +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateCopy z_inflateCopy +# define inflateReset z_inflateReset +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define uncompress z_uncompress +# define adler32 z_adler32 +# define crc32 z_crc32 +# define get_crc_table z_get_crc_table + +# define Byte z_Byte +# define uInt z_uInt +# define uLong z_uLong +# define Bytef z_Bytef +# define charf z_charf +# define intf z_intf +# define uIntf z_uIntf +# define uLongf z_uLongf +# define voidpf z_voidpf +# define voidp z_voidp +#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__)) && !defined(WIN32) +# define WIN32 +#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 + +#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ +# include /* for off_t */ +# include /* for SEEK_* and off_t */ +# ifdef VMS +# include /* for off_t */ +# endif +# define z_off_t off_t +#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(__OS400__) +#define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +# ifdef FAR +# undef FAR +# endif +#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 */ diff --git a/SlnkDWFImpl/CxImage/zlib/zlib.dsp b/SlnkDWFImpl/CxImage/zlib/zlib.dsp new file mode 100644 index 0000000..41512e5 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zlib.dsp @@ -0,0 +1,190 @@ +# Microsoft Developer Studio Project File - Name="zlib" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=zlib - Win32 Release +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "zlib.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "zlib.mak" CFG="zlib - Win32 Release" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "zlib - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "zlib - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "zlib - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir ".\Release" +# PROP BASE Intermediate_Dir ".\Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c +# ADD CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_AFXDLL" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x809 +# ADD RSC /l 0x809 /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "zlib - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir ".\Debug" +# PROP BASE Intermediate_Dir ".\Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c +# ADD CPP /nologo /MDd /W3 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_AFXDLL" /FD /c +# SUBTRACT CPP /YX +# ADD BASE RSC /l 0x809 +# ADD RSC /l 0x809 /d "_AFXDLL" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "zlib - Win32 Release" +# Name "zlib - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90" +# Begin Source File + +SOURCE=.\adler32.c +# End Source File +# Begin Source File + +SOURCE=.\compress.c +# End Source File +# Begin Source File + +SOURCE=.\crc32.c +# End Source File +# Begin Source File + +SOURCE=.\deflate.c +# End Source File +# Begin Source File + +SOURCE=.\gzio.c +# End Source File +# Begin Source File + +SOURCE=.\infback.c +# End Source File +# Begin Source File + +SOURCE=.\inffast.c +# End Source File +# Begin Source File + +SOURCE=.\inflate.c +# End Source File +# Begin Source File + +SOURCE=.\inftrees.c +# End Source File +# Begin Source File + +SOURCE=.\trees.c +# End Source File +# Begin Source File + +SOURCE=.\uncompr.c +# End Source File +# Begin Source File + +SOURCE=.\zutil.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" +# Begin Source File + +SOURCE=.\crc32.h +# End Source File +# Begin Source File + +SOURCE=.\deflate.h +# End Source File +# Begin Source File + +SOURCE=.\inffast.h +# End Source File +# Begin Source File + +SOURCE=.\inffixed.h +# End Source File +# Begin Source File + +SOURCE=.\inflate.h +# End Source File +# Begin Source File + +SOURCE=.\inftrees.h +# End Source File +# Begin Source File + +SOURCE=.\trees.h +# End Source File +# Begin Source File + +SOURCE=.\zconf.h +# End Source File +# Begin Source File + +SOURCE=.\zconf.in.h +# End Source File +# Begin Source File + +SOURCE=.\zlib.h +# End Source File +# Begin Source File + +SOURCE=.\zutil.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/SlnkDWFImpl/CxImage/zlib/zlib.dsw b/SlnkDWFImpl/CxImage/zlib/zlib.dsw new file mode 100644 index 0000000..3d84d79 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zlib.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "zlib"=.\zlib.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/SlnkDWFImpl/CxImage/zlib/zlib.h b/SlnkDWFImpl/CxImage/zlib/zlib.h new file mode 100644 index 0000000..d54ac94 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zlib.h @@ -0,0 +1,1200 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.1, November 17th, 2003 + + Copyright (C) 1995-2003 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.1" +#define ZLIB_VERNUM 0x1210 + +/* + 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 (for example if an input file is mmap'ed), 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 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. + + 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. + + This library does not provide any functions to write gzip files in memory. + However such functions could be easily written using zlib's deflate function, + the documentation in the gzip RFC, and the examples in gzio.c. + + 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: ascii or binary */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + 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 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +/* 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_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_ASCII 1 +#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, + 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. + + 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. + + 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 + the 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 data_type if it can make a good guess about + the input data type (Z_ASCII or Z_BINARY). 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 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. msg is set to null if there is no error + message. inflateInit does not perform any decompression apart from reading + the zlib header if present: this will be done by inflate(). (So next_in and + avail_in may be modified, but next_out and avail_out are unchanged.) +*/ + + +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, or Z_BLOCK. 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 get 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. + + 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 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() will decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically. 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 + if next_in or next_out was 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). + + 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 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. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + method). 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 in + deflate or deflate2. Thus the strings most likely to be useful should be + put at the end of the dictionary, not at the front. + + 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 (such as NULL dictionary) 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 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 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 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(). 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 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 -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). + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative + memLevel). msg is set to null if there is no error message. inflateInit2 + does not perform any decompression apart from reading the zlib header if + present: this will be done by inflate(). (So next_in and avail_in may be + modified, but next_out and avail_out are unchanged.) +*/ + +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 this call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by this call of + inflate. The compressor and decompressor must use exactly the same + dictionary (see deflateSetDictionary). + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) 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 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 NULL). +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_stream FAR *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_stream FAR *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 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_stream FAR *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 easily 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. + This function can be used to compress a whole file at once if the + input file is mmap'ed. + 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 compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + 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. +*/ + + +typedef voidp gzFile; + +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", or 'R' for run-length encoding + as in "wb1R". (See the description of deflateInit2 for more information + about the strategy parameter.) + + 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 or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). */ + +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 (in 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 gzdopen(dup(fd), mode). + gzdopen returns NULL if there was insufficient memory to allocate + the (de)compression state. +*/ + +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. + gzread returns the number of uncompressed bytes actually read (0 for + end of file, -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 actually written + (0 in case of error). +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). The number of + uncompressed bytes written is limited to 4095. The caller should assure that + this limit is not exceeded. If it is exceeded, then gzprintf() will return + 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. +*/ + +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. The string is then terminated with a null + character. + gzgets returns buf, or Z_NULL in case of error. +*/ + +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 again later. + Only one character of push-back is allowed. gzungetc() returns the + character pushed, or -1 on failure. gzungetc() will fail if a + character has been pushed but not read yet, or if c is -1. 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 returns Z_OK if + the flush parameter is Z_FINISH and all output could be flushed. + gzflush should be called only when strictly necessary because it can + degrade compression. +*/ + +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. + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. The return value is the zlib + error number (see function gzerror below). +*/ + +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. +*/ + +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 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 crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running crc with the bytes buf[0..len-1] and return the updated + crc. If buf is NULL, this function returns the required initial value + 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(); +*/ + + + /* 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_stream FAR *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)) + + +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; /* hack for buggy compilers */ +#endif + +ZEXTERN const char * ZEXPORT zError OF((int err)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/SlnkDWFImpl/CxImage/zlib/zlib.mak b/SlnkDWFImpl/CxImage/zlib/zlib.mak new file mode 100644 index 0000000..8913f65 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zlib.mak @@ -0,0 +1,432 @@ +# Microsoft Developer Studio Generated NMAKE File, Format Version 4.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +!IF "$(CFG)" == "" +CFG=zlib - Win32 Debug +!MESSAGE No configuration specified. Defaulting to zlib - Win32 Debug. +!ENDIF + +!IF "$(CFG)" != "zlib - Win32 Release" && "$(CFG)" != "zlib - Win32 Debug" +!MESSAGE Invalid configuration "$(CFG)" specified. +!MESSAGE You can specify a configuration when running NMAKE on this makefile +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "zlib.mak" CFG="zlib - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "zlib - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "zlib - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE +!ERROR An invalid configuration is specified. +!ENDIF + +!IF "$(OS)" == "Windows_NT" +NULL= +!ELSE +NULL=nul +!ENDIF +################################################################################ +# Begin Project +# PROP Target_Last_Scanned "zlib - Win32 Debug" +CPP=cl.exe + +!IF "$(CFG)" == "zlib - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +OUTDIR=.\Release +INTDIR=.\Release + +ALL : "$(OUTDIR)\zlib.lib" + +CLEAN : + -@erase ".\Release\zlib.lib" + -@erase ".\Release\Deflate.obj" + -@erase ".\Release\Infblock.obj" + -@erase ".\Release\Uncompr.obj" + -@erase ".\Release\Inflate.obj" + -@erase ".\Release\Infutil.obj" + -@erase ".\Release\Infcodes.obj" + -@erase ".\Release\Inftrees.obj" + -@erase ".\Release\Adler32.obj" + -@erase ".\Release\Trees.obj" + -@erase ".\Release\Compress.obj" + -@erase ".\Release\Inffast.obj" + -@erase ".\Release\Zutil.obj" + -@erase ".\Release\Gzio.obj" + -@erase ".\Release\Crc32.obj" + +"$(OUTDIR)" : + if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" + +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c +# ADD CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /c +# SUBTRACT CPP /YX +CPP_PROJ=/nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D\ + "_AFXDLL" /D "_MBCS" /Fo"$(INTDIR)/" /c +CPP_OBJS=.\Release/ +CPP_SBRS= +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +BSC32_FLAGS=/nologo /o"$(OUTDIR)/zlib.bsc" +BSC32_SBRS= +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo +LIB32_FLAGS=/nologo /out:"$(OUTDIR)/zlib.lib" +LIB32_OBJS= \ + ".\Release\Deflate.obj" \ + ".\Release\Infblock.obj" \ + ".\Release\Uncompr.obj" \ + ".\Release\Inflate.obj" \ + ".\Release\Infutil.obj" \ + ".\Release\Infcodes.obj" \ + ".\Release\Inftrees.obj" \ + ".\Release\Adler32.obj" \ + ".\Release\Trees.obj" \ + ".\Release\Compress.obj" \ + ".\Release\Inffast.obj" \ + ".\Release\Zutil.obj" \ + ".\Release\Gzio.obj" \ + ".\Release\Crc32.obj" + +"$(OUTDIR)\zlib.lib" : "$(OUTDIR)" $(DEF_FILE) $(LIB32_OBJS) + $(LIB32) @<< + $(LIB32_FLAGS) $(DEF_FLAGS) $(LIB32_OBJS) +<< + +!ELSEIF "$(CFG)" == "zlib - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 2 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +OUTDIR=.\Debug +INTDIR=.\Debug + +ALL : "$(OUTDIR)\zlib.lib" + +CLEAN : + -@erase ".\Debug\zlib.lib" + -@erase ".\Debug\Inffast.obj" + -@erase ".\Debug\Infblock.obj" + -@erase ".\Debug\Inftrees.obj" + -@erase ".\Debug\Deflate.obj" + -@erase ".\Debug\Uncompr.obj" + -@erase ".\Debug\Adler32.obj" + -@erase ".\Debug\Inflate.obj" + -@erase ".\Debug\Infcodes.obj" + -@erase ".\Debug\Crc32.obj" + -@erase ".\Debug\Infutil.obj" + -@erase ".\Debug\Gzio.obj" + -@erase ".\Debug\Trees.obj" + -@erase ".\Debug\Compress.obj" + -@erase ".\Debug\Zutil.obj" + +"$(OUTDIR)" : + if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" + +# ADD BASE CPP /nologo /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c +# ADD CPP /nologo /MDd /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /c +# SUBTRACT CPP /YX +CPP_PROJ=/nologo /MDd /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D\ + "_AFXDLL" /D "_MBCS" /Fo"$(INTDIR)/" /c +CPP_OBJS=.\Debug/ +CPP_SBRS= +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +BSC32_FLAGS=/nologo /o"$(OUTDIR)/zlib.bsc" +BSC32_SBRS= +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo +LIB32_FLAGS=/nologo /out:"$(OUTDIR)/zlib.lib" +LIB32_OBJS= \ + ".\Debug\Inffast.obj" \ + ".\Debug\Infblock.obj" \ + ".\Debug\Inftrees.obj" \ + ".\Debug\Deflate.obj" \ + ".\Debug\Uncompr.obj" \ + ".\Debug\Adler32.obj" \ + ".\Debug\Inflate.obj" \ + ".\Debug\Infcodes.obj" \ + ".\Debug\Crc32.obj" \ + ".\Debug\Infutil.obj" \ + ".\Debug\Gzio.obj" \ + ".\Debug\Trees.obj" \ + ".\Debug\Compress.obj" \ + ".\Debug\Zutil.obj" + +"$(OUTDIR)\zlib.lib" : "$(OUTDIR)" $(DEF_FILE) $(LIB32_OBJS) + $(LIB32) @<< + $(LIB32_FLAGS) $(DEF_FLAGS) $(LIB32_OBJS) +<< + +!ENDIF + +.c{$(CPP_OBJS)}.obj: + $(CPP) $(CPP_PROJ) $< + +.cpp{$(CPP_OBJS)}.obj: + $(CPP) $(CPP_PROJ) $< + +.cxx{$(CPP_OBJS)}.obj: + $(CPP) $(CPP_PROJ) $< + +.c{$(CPP_SBRS)}.sbr: + $(CPP) $(CPP_PROJ) $< + +.cpp{$(CPP_SBRS)}.sbr: + $(CPP) $(CPP_PROJ) $< + +.cxx{$(CPP_SBRS)}.sbr: + $(CPP) $(CPP_PROJ) $< + +################################################################################ +# Begin Target + +# Name "zlib - Win32 Release" +# Name "zlib - Win32 Debug" + +!IF "$(CFG)" == "zlib - Win32 Release" + +!ELSEIF "$(CFG)" == "zlib - Win32 Debug" + +!ENDIF + +################################################################################ +# Begin Source File + +SOURCE=.\Zutil.c +DEP_CPP_ZUTIL=\ + ".\zutil.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Zutil.obj" : $(SOURCE) $(DEP_CPP_ZUTIL) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Compress.c +DEP_CPP_COMPR=\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Compress.obj" : $(SOURCE) $(DEP_CPP_COMPR) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Crc32.c +DEP_CPP_CRC32=\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Crc32.obj" : $(SOURCE) $(DEP_CPP_CRC32) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Deflate.c +DEP_CPP_DEFLA=\ + ".\deflate.h"\ + ".\zutil.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Deflate.obj" : $(SOURCE) $(DEP_CPP_DEFLA) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Gzio.c +DEP_CPP_GZIO_=\ + ".\zutil.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Gzio.obj" : $(SOURCE) $(DEP_CPP_GZIO_) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Infblock.c +DEP_CPP_INFBL=\ + ".\zutil.h"\ + ".\infblock.h"\ + ".\inftrees.h"\ + ".\infcodes.h"\ + ".\infutil.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Infblock.obj" : $(SOURCE) $(DEP_CPP_INFBL) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Infcodes.c +DEP_CPP_INFCO=\ + ".\zutil.h"\ + ".\inftrees.h"\ + ".\infblock.h"\ + ".\infcodes.h"\ + ".\infutil.h"\ + ".\inffast.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Infcodes.obj" : $(SOURCE) $(DEP_CPP_INFCO) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Inffast.c +DEP_CPP_INFFA=\ + ".\zutil.h"\ + ".\inftrees.h"\ + ".\infblock.h"\ + ".\infcodes.h"\ + ".\infutil.h"\ + ".\inffast.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Inffast.obj" : $(SOURCE) $(DEP_CPP_INFFA) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Inflate.c +DEP_CPP_INFLA=\ + ".\zutil.h"\ + ".\infblock.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Inflate.obj" : $(SOURCE) $(DEP_CPP_INFLA) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Inftrees.c +DEP_CPP_INFTR=\ + ".\zutil.h"\ + ".\inftrees.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Inftrees.obj" : $(SOURCE) $(DEP_CPP_INFTR) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Infutil.c +DEP_CPP_INFUT=\ + ".\zutil.h"\ + ".\infblock.h"\ + ".\inftrees.h"\ + ".\infcodes.h"\ + ".\infutil.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Infutil.obj" : $(SOURCE) $(DEP_CPP_INFUT) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Trees.c +DEP_CPP_TREES=\ + ".\deflate.h"\ + ".\zutil.h"\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Trees.obj" : $(SOURCE) $(DEP_CPP_TREES) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Uncompr.c +DEP_CPP_UNCOM=\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Uncompr.obj" : $(SOURCE) $(DEP_CPP_UNCOM) "$(INTDIR)" + + +# End Source File +################################################################################ +# Begin Source File + +SOURCE=.\Adler32.c +DEP_CPP_ADLER=\ + ".\zlib.h"\ + ".\zconf.h"\ + + +"$(INTDIR)\Adler32.obj" : $(SOURCE) $(DEP_CPP_ADLER) "$(INTDIR)" + + +# End Source File +# End Target +# End Project +################################################################################ diff --git a/SlnkDWFImpl/CxImage/zlib/zlib.sln b/SlnkDWFImpl/CxImage/zlib/zlib.sln new file mode 100644 index 0000000..35d54ab --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zlib.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 7.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlib", "zlib.vcproj", "{CD81085B-5A78-40F0-BC51-5109F09678DF}" +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + ConfigName.0 = Debug + ConfigName.1 = Release + EndGlobalSection + GlobalSection(ProjectDependencies) = postSolution + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {CD81085B-5A78-40F0-BC51-5109F09678DF}.Debug.ActiveCfg = Debug|Win32 + {CD81085B-5A78-40F0-BC51-5109F09678DF}.Debug.Build.0 = Debug|Win32 + {CD81085B-5A78-40F0-BC51-5109F09678DF}.Release.ActiveCfg = Release|Win32 + {CD81085B-5A78-40F0-BC51-5109F09678DF}.Release.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/SlnkDWFImpl/CxImage/zlib/zlib.vcproj b/SlnkDWFImpl/CxImage/zlib/zlib.vcproj new file mode 100644 index 0000000..c337c70 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zlib.vcproj @@ -0,0 +1,467 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/zlib/zlib.vcproj.7.00.old b/SlnkDWFImpl/CxImage/zlib/zlib.vcproj.7.00.old new file mode 100644 index 0000000..442968f --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zlib.vcproj.7.00.old @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/zlib/zlib.vcproj.DIJKORAAD.jgl.user b/SlnkDWFImpl/CxImage/zlib/zlib.vcproj.DIJKORAAD.jgl.user new file mode 100644 index 0000000..f57b253 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zlib.vcproj.DIJKORAAD.jgl.user @@ -0,0 +1,65 @@ + + + + + + + + + + + diff --git a/SlnkDWFImpl/CxImage/zlib/zutil.c b/SlnkDWFImpl/CxImage/zlib/zutil.c new file mode 100644 index 0000000..a94cdb8 --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zutil.c @@ -0,0 +1,319 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2003 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 + +#ifndef STDC +extern void exit OF((int)); +#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 (sizeof(uInt)) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch (sizeof(uLong)) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch (sizeof(voidpf)) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch (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 += 1 << 16; +#endif +#ifdef NO_GZIP + flags += 1 << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1 << 20; +#endif +#ifdef FASTEST + flags += 1 << 21; +#endif +#ifdef STDC +# ifdef NO_vsnprintf + flags += 1 << 25; +# ifdef HAS_vsprintf_void + flags += 1 << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1 << 26; +# endif +# endif +#else + flags += 1 << 24; +# ifdef NO_snprintf + flags += 1 << 25; +# ifdef HAS_sprintf_void + flags += 1 << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1 << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int z_verbose = verbose; + +void 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) + /* does not exist on WCE */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void 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 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 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 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 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 zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void 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 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 zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ diff --git a/SlnkDWFImpl/CxImage/zlib/zutil.h b/SlnkDWFImpl/CxImage/zlib/zutil.h new file mode 100644 index 0000000..06cb62e --- /dev/null +++ b/SlnkDWFImpl/CxImage/zlib/zutil.h @@ -0,0 +1,258 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2003 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 + +#define ZLIB_INTERNAL +#include "zlib.h" + +#ifdef STDC +# include +# include +# include +#endif +#ifdef NO_ERRNO_H + extern int errno; +#else +# 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 +#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)) +# 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 + + /* 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) +# define vsnprintf _vsnprintf +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +#endif + +#ifdef HAVE_STRERROR + extern char *strerror OF((int)); +# define zstrerror(errnum) strerror(errnum) +#else +# define zstrerror(errnum) "" +#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 + extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + extern void zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include + extern int z_verbose; + extern void 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 zcalloc OF((voidpf opaque, unsigned items, unsigned size)); +void 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 */ diff --git a/SlnkDWFImpl/DWFFileImpl.cpp b/SlnkDWFImpl/DWFFileImpl.cpp new file mode 100644 index 0000000..95f4bfc --- /dev/null +++ b/SlnkDWFImpl/DWFFileImpl.cpp @@ -0,0 +1,117 @@ +// DWFFile.cpp : Implementation of CDWFFile + +#include "stdafx.h" +#include "assert.h" +#include "DWFFileImpl.h" + +#include "myEPlotSectionImpl.h" + +// CDWFFile + +//CDWFFileImpl::~CDWFFile() +//{ +// // It seems we never get here? Use FinalRelease +//}; + +CDWFFileImpl::~CDWFFileImpl() +{ + if (m_oReader!=NULL) + delete m_oReader; + + if (m_DWF!=NULL) + delete m_DWF; +} + +bool CDWFFileImpl::Open(const CString &DWFPath) +{ + if (m_isOpen) + { + throw CString("\nCDWFFileImpl::Open already open"); + } + try + { + myDoTRACE("\nCDWFFileImpl::Open('%s')", DWFPath); + m_DWF = new DWFFile( DWFPath ); + m_oReader = new DWFPackageReader( *m_DWF ); + + m_oReader->getPackageInfo( m_tInfo ); + + wchar_t zBuffer[256] = {0}; + + myTRACE("\nCDWFFileImpl::Opened('%s')", DWFPath); + if (m_tInfo.eType == DWFPackageReader::eW2DStream || + m_tInfo.eType == DWFPackageReader::eDWFStream) + { // Dit is wel heel gemakkelijk + m_W2DFileName = DWFString(DWFPath); + assert(m_W2DFileName.chars() != 0); + m_isOpen = TRUE; + return true; + } + + if (m_tInfo.eType != DWFPackageReader::eDWFPackage) + { + _DWFCORE_SWPRINTF( zBuffer, 256, L"File is not a DWF package [%s]", + (m_tInfo.eType == DWFPackageReader::eW2DStream) ? L"W2D Stream" : + (m_tInfo.eType == DWFPackageReader::eDWFStream) ? L"DWF Stream (<6.0)" : + (m_tInfo.eType == DWFPackageReader::eZIPFile) ? L"ZIP Archive" : L"Unknown" ); + + myTRACE("%ls", zBuffer); + throw myCString("ERROR: Unable to open file: %s\n%ls", DWFPath, zBuffer); + } + + // + // read and parse the manifest + // + DWFManifest& rManifest = m_oReader->getManifest(); + + if (!m_EPlotSections.ProcessManifest(rManifest, CString(DWFPath))) + { + CString err("Unable to retrieve EPlotSections. Perhaps it is a 3D DWF?"); + throw myCString ("\nCDWFFileImpl::Open('%s')\n%s", DWFPath, err); + } + + m_isOpen = TRUE; + return true; + } + catch (DWFException& ex) + { + CString err; + err.Format("%ls\n%ls\n%s\n%ls(%d)",ex.type(),ex.message(),ex.function(),ex.file(),ex.line()); + throw myCString ("\nCDWFFileImpl::Open('%s')\n%s", DWFPath, err); + } +} + +#if DESIRED_CODE(WHIP_OUTPUT) +bool CDWFFileImpl::get_PropertiesXML(CString & pVal) +{ + if (!m_isOpen) + throw myCString ("\nDWF File is not opened"); + + if (m_DWF!=NULL) + { + DWFCore::DWFBufferOutputStream m_XMLProps(1024); + DWFUUID _oUUID; + DWFXMLSerializer XML(_oUUID); + XML.attach(m_XMLProps); + + DWFManifest& rManifest = m_oReader->getManifest(); + rManifest.serializeXML(XML, DWFPackageWriter::eManifest); + XML.detach(); + + pVal = CString((LPCSTR)m_XMLProps.buffer(), (int)m_XMLProps.bytes()); + return true; + } + else + return false; + + return true; +} +#endif + +CEPlotSectionsImpl *CDWFFileImpl::get_EPlotSections() +{ + if (!m_isOpen) + throw myCString("\nDWF File is not opened"); + + return &m_EPlotSections; +} diff --git a/SlnkDWFImpl/EplotSectionsImpl.cpp b/SlnkDWFImpl/EplotSectionsImpl.cpp new file mode 100644 index 0000000..71df91e --- /dev/null +++ b/SlnkDWFImpl/EplotSectionsImpl.cpp @@ -0,0 +1,72 @@ +// EPlotSections.cpp : Implementation of CEPlotSections + +#include "stdafx.h" +#include "EPlotSectionsImpl.h" + + +// CEPlotSections +CEPlotSectionsImpl::~CEPlotSectionsImpl() +{ + for (size_t i=0; ivalid() == false)) + { + if (piSections) + { + DWFCORE_FREE_OBJECT( piSections ); + } + + myTRACE("%ls", L"Malformed or unexpected 3D DWF, cannot continue without an EPlot section"); + return FALSE; + } + + // + // get the EPlot Section + // + int page=0; + while (piSections->valid()) + { + DWFEPlotSection* pSection = + dynamic_cast(piSections->get()); + + CEPlotSectionImpl *mySection = new CEPlotSectionImpl; + CString s;s.Format("%s (page %d)", sourceDescription, page++); + mySection->Init(pSection, s); + m_EPlotSections.Add(mySection); + piSections->next(); + } + + // + // done with the iterator + // + DWFCORE_FREE_OBJECT( piSections ); + + return TRUE; +} + +long CEPlotSectionsImpl::get_Count() +{ + return (LONG)m_EPlotSections.GetCount(); +} + +CEPlotSectionImpl *CEPlotSectionsImpl::get_Item(LONG i) +{ + if (i<0 || i>=(LONG)m_EPlotSections.GetCount()) + return NULL; + + return (m_EPlotSections.GetAt(i)); +} diff --git a/SlnkDWFImpl/JglUtil.cpp b/SlnkDWFImpl/JglUtil.cpp new file mode 100644 index 0000000..2721e93 --- /dev/null +++ b/SlnkDWFImpl/JglUtil.cpp @@ -0,0 +1,93 @@ +#include "stdafx.h" +#include + +//#include "JglUtil.h" +int CmyTimer::level=0; + +HRESULT myAtlReportError(const CLSID & clsid, LPCTSTR lpszFormat, ...) +{ + va_list args; + va_start(args, lpszFormat); + + int nBuf; + char szBuffer[1024]; // Maximum voor wvsprintf!! + + nBuf = _vsnprintf(szBuffer, sizeof(szBuffer), lpszFormat, args); + if (errno) + nBuf = _snprintf(szBuffer, sizeof(szBuffer), + "%s\n(errno %d)", szBuffer, errno); + if (GetLastError()) + nBuf = _snprintf(szBuffer, sizeof(szBuffer), + "%s\n(lasterror may not apply) %d: %s", szBuffer, GetLastError(), myGetLastErrorMsg()); + // ASSERT(nBuf < _countof(szBuffer)); + + va_end(args); + + return AtlReportError(clsid, szBuffer); +} + +const CString myCString(LPCTSTR lpszFormat, ...) +{ + va_list args; + va_start(args, lpszFormat); + + int nBuf; + char szBuffer[1024]; // Maximum voor wvsprintf!! + + nBuf = _vsnprintf(szBuffer, sizeof(szBuffer), lpszFormat, args); + + va_end(args); + + return CString(szBuffer); +} + +void myDoTRACE(LPCTSTR lpszFormat, ...) +{ + va_list args; + va_start(args, lpszFormat); + + int nBuf; + char szBuffer[512]; + + nBuf = _vsnprintf(szBuffer, sizeof(szBuffer), lpszFormat, args); + // ASSERT(nBuf < _countof(szBuffer)); + + OutputDebugString(szBuffer); + + va_end(args); +} + +const char* myGetLastErrorMsg() +{ + static char MsgBuf [_MAX_PATH]; + + ::FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPTSTR) &MsgBuf, + sizeof(MsgBuf), + NULL + ); + + return MsgBuf; +} + +long myRound(double const &x) { + ATLASSERT(x >= LONG_MIN-0.5); + ATLASSERT(x <= LONG_MAX+0.5); + if (x >= 0) + return (long) (x+0.5); + return (long) (x-0.5); + } + +BOOL isDarkRGB(COLORREF const &clr) +{ + return pow(255.0 - GetRValue(clr),2) + + pow(255.0 - GetGValue(clr),2) + + pow(255.0 - GetBValue(clr),2) > + pow(GetRValue(clr), 2.0) + + pow(GetGValue(clr), 2.0) + + pow(GetBValue(clr), 2.0); +} diff --git a/SlnkDWFImpl/Jglutil.h b/SlnkDWFImpl/Jglutil.h new file mode 100644 index 0000000..53fbcd9 --- /dev/null +++ b/SlnkDWFImpl/Jglutil.h @@ -0,0 +1,102 @@ +void myDoTRACE(LPCTSTR lpszFormat, ...); + +#ifdef _DEBUG +#define myTRACE myDoTRACE +#else +#define myTRACE 1 ? (void)0 : myDoTRACE +#endif + +long myRound(double const &x); + +const char* myGetLastErrorMsg(); +HRESULT myAtlReportError(const CLSID & clsid, LPCTSTR lpszFormat, ...); +const CString myCString(LPCTSTR lpszFormat, ...); + +class myTempPEN +{ +public: + myTempPEN(HDC hDC, int w, COLORREF clr) + { + m_hDC = hDC; + HPEN hpenNew; + hpenNew = CreatePen(PS_SOLID, w, clr); + m_hpenOld = (HPEN)SelectObject(m_hDC, hpenNew); + } + ~myTempPEN() + { + HPEN hpenNew = (HPEN)SelectObject(m_hDC, m_hpenOld); + DeleteObject(hpenNew); + } +private: + HPEN m_hpenOld; + HDC m_hDC; +}; + +#ifdef _DEBUG +// Niet in release mode want dan werkt NT4 niet meer +class CneutralGDI +{ +public: + CneutralGDI(char *msg) + { + strncpy(m_msg, msg, sizeof(m_msg)); + nGDI = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); + nUSER = GetGuiResources(GetCurrentProcess(), GR_USEROBJECTS); + }; + + ~CneutralGDI() + { + int nGDIend = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); + int nUSERend = GetGuiResources(GetCurrentProcess(), GR_USEROBJECTS); + if (nGDI != nGDIend || nUSER != nUSERend) + { + myTRACE("\n================================================================"); + myTRACE("\n= Leaking detected in %s.", m_msg); + myTRACE("\n= Lost %d GDI and %d USER objects",nGDIend - nGDI, nUSERend - nUSER); + myTRACE("\n================================================================"); + } + }; + BOOL hasLeak() + { + int nGDIend = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); + int nUSERend = GetGuiResources(GetCurrentProcess(), GR_USEROBJECTS); + return (nGDI != nGDIend || nUSER != nUSERend); + } +private: + int nGDI, nUSER; + char m_msg[2048]; +}; +#endif + +class CmyTimer +{ +public: + CmyTimer() + { + strcpy(m_msg, "Time"); + QueryPerformanceCounter(&startTime); + CmyTimer::level++; + }; + CmyTimer(const char*msg) + { + strncpy(m_msg, msg, sizeof(m_msg)); + QueryPerformanceCounter(&startTime); + CmyTimer::level++; + } + ~CmyTimer() + { + level--; + LARGE_INTEGER endTime; + LARGE_INTEGER frequency; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&endTime); + myDoTRACE("\n%*s%s: %.0fms", CmyTimer::level*4, "", m_msg, ((double)(endTime.QuadPart -startTime.QuadPart))/frequency.QuadPart*1000); + } +private: + LARGE_INTEGER startTime; + char m_msg[2048]; +protected: + static int level; +}; + +BOOL isDarkRGB(COLORREF const& clr); diff --git a/SlnkDWFImpl/MemLeakDetect.cpp b/SlnkDWFImpl/MemLeakDetect.cpp new file mode 100644 index 0000000..8f4de93 --- /dev/null +++ b/SlnkDWFImpl/MemLeakDetect.cpp @@ -0,0 +1,521 @@ +/************************************************************* + Author : David A. Jones + File Name : MemLeakDetect.h + Date : July 30, 2004 + Synopsis + A trace memory feature for source code to trace and + find memory related bugs. + + +****************************************************************/ +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +// +#pragma warning(disable:4312) +#pragma warning(disable:4313) +#pragma warning(disable:4267) +#pragma warning(disable:4100) + +#include "stdafx.h" +#include "MemLeakDetect.h" + +static CMemLeakDetect* g_pMemTrace = NULL; +static _CRT_ALLOC_HOOK pfnOldCrtAllocHook = NULL; +//extern _crtDgbFlag; + +int MyTrace(LPCTSTR lpszFormat, ...) +{ + TCHAR buffer[1024]; + va_list args; + va_start( args, lpszFormat); + vsprintf( buffer, lpszFormat, args ); + + return _CrtDbgReport(_CRT_WARN,NULL,NULL,NULL,buffer); + +} + +int catchMemoryAllocHook(int allocType, + void *userData, + size_t size, + int blockType, + long requestNumber, + const unsigned char *filename, + int lineNumber) +{ + _CrtMemBlockHeader *pCrtHead; + long prevRequestNumber; + + // internal C library internal allocations + if ( blockType == _CRT_BLOCK ) + { + return( TRUE ); + } + // check if someone has turned off mem tracing + if ((( _CRTDBG_ALLOC_MEM_DF & _crtDbgFlag) == 0) && + (( allocType == _HOOK_ALLOC) || + ( allocType == _HOOK_REALLOC))) + { + if (pfnOldCrtAllocHook) + { + pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber); + } + return TRUE; + } + + // protect if mem trace is not initialized + if (g_pMemTrace == NULL) + { + if (pfnOldCrtAllocHook) + { + pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber); + } + return TRUE; + } + + // protect internal mem trace allocs + if (g_pMemTrace->isLocked) + { + if (pfnOldCrtAllocHook) + { + pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber); + } + return( TRUE); + } + // lock the function + g_pMemTrace->isLocked = true; + // + if (allocType == _HOOK_ALLOC) + { + g_pMemTrace->addMemoryTrace((void *) requestNumber, size, (char*)filename, lineNumber); + } + else + if (allocType == _HOOK_REALLOC) + { + if (_CrtIsValidHeapPointer(userData)) + { + pCrtHead = pHdr(userData); + prevRequestNumber = pCrtHead->lRequest; + // + if (pCrtHead->nBlockUse == _IGNORE_BLOCK) + { + if (pfnOldCrtAllocHook) + { + pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber); + } + goto END; + } + g_pMemTrace->redoMemoryTrace((void *) requestNumber, (void *) prevRequestNumber, size, (char*)filename, lineNumber); + } + } + else + if (allocType == _HOOK_FREE) + { + if (_CrtIsValidHeapPointer(userData)) + { + pCrtHead = pHdr(userData); + requestNumber = pCrtHead->lRequest; + // + if (pCrtHead->nBlockUse == _IGNORE_BLOCK) + { + if (pfnOldCrtAllocHook) + { + pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber); + } + goto END; + } + g_pMemTrace->removeMemoryTrace((void *) requestNumber, userData); + } + } +END: + // unlock the function + g_pMemTrace->isLocked = false; + return TRUE; +} + +void CMemLeakDetect::addMemoryTrace(void* addr, DWORD asize, TCHAR *fname, DWORD lnum) +{ + AllocBlockInfo ainfo; + // + if (m_AllocatedMemoryList.Lookup(addr, ainfo)) + { + // already allocated + AfxTrace("ERROR!CMemLeakDetect::addMemoryTrace() Address(0x%08X) already allocated\n", addr); + return; + } + // + ainfo.address = addr; + ainfo.lineNumber = lnum; + ainfo.size = asize; + ainfo.occurance = memoccurance++; + MLD_STACKWALKER(&ainfo.traceinfo[0]); + // + if (fname) + _tcsncpy(&ainfo.fileName[0], fname, MLD_MAX_NAME_LENGTH); + else + ainfo.fileName[0] = 0; + // + m_AllocatedMemoryList.SetAt(addr, ainfo); +}; +void CMemLeakDetect::redoMemoryTrace(void* addr, void* oldaddr, DWORD asize, char *fname, DWORD lnum) +{ + AllocBlockInfo ainfo; + + if (m_AllocatedMemoryList.Lookup(oldaddr,(AllocBlockInfo &) ainfo)) + { + m_AllocatedMemoryList.RemoveKey(oldaddr); + } + else + { + AfxTrace(_T("ERROR!CMemLeakDetect::redoMemoryTrace() didnt find Address(0x%08X) to free\n"), oldaddr); + } + // + ainfo.address = addr; + ainfo.lineNumber = lnum; + ainfo.size = asize; + ainfo.occurance = memoccurance++; + MLD_STACKWALKER(&ainfo.traceinfo[0]); + // + if (fname) + _tcsncpy(&ainfo.fileName[0], fname, MLD_MAX_NAME_LENGTH); + else + ainfo.fileName[0] = 0; + + m_AllocatedMemoryList.SetAt(addr, ainfo); +}; +void CMemLeakDetect::removeMemoryTrace(void* addr, void* realdataptr) +{ + AllocBlockInfo ainfo; + // + if (m_AllocatedMemoryList.Lookup(addr,(AllocBlockInfo &) ainfo)) + { + m_AllocatedMemoryList.RemoveKey(addr); + } + else + { + //freeing unallocated memory + AfxTrace(_T("ERROR!CMemLeakDetect::removeMemoryTrace() didnt find Address(0x%08X) to free\n"), addr); + } +}; +void CMemLeakDetect::cleanupMemoryTrace() +{ + m_AllocatedMemoryList.RemoveAll(); +}; + +void CMemLeakDetect::dumpMemoryTrace() +{ + POSITION pos; + LPVOID addr; + AllocBlockInfo ainfo; + TCHAR buf[MLD_MAX_NAME_LENGTH]; + TCHAR symInfo[MLD_MAX_NAME_LENGTH]; + TCHAR srcInfo[MLD_MAX_NAME_LENGTH]; + int totalSize = 0; + int numLeaks = 0; + STACKFRAMEENTRY* p = 0; + + // + _tcscpy(symInfo, MLD_TRACEINFO_NOSYMBOL); + _tcscpy(srcInfo, MLD_TRACEINFO_NOSYMBOL); + // + pos = m_AllocatedMemoryList.GetStartPosition(); + // + while(pos != m_AllocatedMemoryList.end()) + { + numLeaks++; + sprintf(buf, "Memory Leak(%d)------------------->\n", numLeaks); + AfxTrace(buf); + // + m_AllocatedMemoryList.GetNextAssoc(pos, (LPVOID &) addr, (AllocBlockInfo&) ainfo); + + if (ainfo.fileName[0] != NULL) + { + sprintf(buf, "Memory Leak <0x%X> bytes(%d) occurance(%d) %s(%d)\n", + ainfo.address, ainfo.size, ainfo.occurance, ainfo.fileName, ainfo.lineNumber); + } + else + { + sprintf(buf, "Memory Leak <0x%X> bytes(%d) occurance(%d)\n", + ainfo.address, ainfo.size, ainfo.occurance); + } + // + AfxTrace(buf); + // + p = &ainfo.traceinfo[0]; + while(p[0].addrPC.Offset) + { + symFunctionInfoFromAddresses( p[0].addrPC.Offset, p[0].addrFrame.Offset, symInfo ); + symSourceInfoFromAddress( p[0].addrPC.Offset, srcInfo ); + AfxTrace("%s->%s()\n", srcInfo, symInfo); + p++; + } + totalSize += ainfo.size; + } + _stprintf(buf, _T("\n-----------------------------------------------------------\n")); + AfxTrace(buf); + if(!totalSize) + { + _stprintf(buf,_T("No Memory Leaks Detected for %d Allocations\n\n"), memoccurance); + AfxTrace(buf); + } + else + { + _stprintf(buf, _T("Total %d Memory Leaks: %d bytes Total Alocations %d\n\n"), numLeaks, totalSize, memoccurance); + AfxTrace(buf); + } +} + +void CMemLeakDetect::Init() +{ + m_dwsymBufSize = (MLD_MAX_NAME_LENGTH + sizeof(PIMAGEHLP_SYMBOL)); + m_hProcess = GetCurrentProcess(); + m_pSymbol = (PIMAGEHLP_SYMBOL)GlobalAlloc( GMEM_FIXED, m_dwsymBufSize); + + m_AllocatedMemoryList.InitHashTable(10211, TRUE); + initSymInfo( NULL ); + isLocked = false; + g_pMemTrace = this; + pfnOldCrtAllocHook = _CrtSetAllocHook( catchMemoryAllocHook ); +} +void CMemLeakDetect::End() +{ + isLocked = true; + _CrtSetAllocHook(pfnOldCrtAllocHook); + dumpMemoryTrace(); + cleanupMemoryTrace(); + cleanupSymInfo(); + GlobalFree(m_pSymbol); + g_pMemTrace = NULL; +} +CMemLeakDetect::CMemLeakDetect() +{ + Init(); +} + +CMemLeakDetect::~CMemLeakDetect() +{ + End(); +} + +// PRIVATE STUFF +void CMemLeakDetect::symbolPaths( TCHAR* lpszSymbolPath) +{ + TCHAR lpszPath[MLD_MAX_NAME_LENGTH]; + + // Creating the default path where the dgbhelp.dll is located + // ".;%_NT_SYMBOL_PATH%;%_NT_ALTERNATE_SYMBOL_PATH%;%SYSTEMROOT%;%SYSTEMROOT%\System32;" + _tcscpy( lpszSymbolPath, _T(".;..\\;..\\..\\")); + + // environment variable _NT_SYMBOL_PATH + if ( GetEnvironmentVariable(_T("_NT_SYMBOL_PATH"), lpszPath, MLD_MAX_NAME_LENGTH )) + { + strcat( lpszSymbolPath, _T(";")); + strcat( lpszSymbolPath, lpszPath ); + } + + // environment variable _NT_ALTERNATE_SYMBOL_PATH + if ( GetEnvironmentVariable( _T("_NT_ALTERNATE_SYMBOL_PATH"), lpszPath, MLD_MAX_NAME_LENGTH )) + { + _tcscat( lpszSymbolPath, _T(";")); + _tcscat( lpszSymbolPath, lpszPath ); + } + + // environment variable SYSTEMROOT + if ( GetEnvironmentVariableA( "SYSTEMROOT", lpszPath, MLD_MAX_NAME_LENGTH ) ) + { + _tcscat( lpszSymbolPath, _T(";")); + _tcscat( lpszSymbolPath, lpszPath); + _tcscat( lpszSymbolPath, _T(";")); + + // SYSTEMROOT\System32 + _tcscat( lpszSymbolPath, lpszPath ); + _tcscat( lpszSymbolPath, _T("\\System32")); + } +} + +BOOL CMemLeakDetect::cleanupSymInfo() +{ + return SymCleanup( GetCurrentProcess() ); +} + +// Initializes the symbol files +BOOL CMemLeakDetect::initSymInfo( TCHAR* lpszUserSymbolPath ) +{ + CHAR lpszSymbolPath[MLD_MAX_NAME_LENGTH]; + DWORD symOptions = SymGetOptions(); + + symOptions |= SYMOPT_LOAD_LINES; + symOptions &= ~SYMOPT_UNDNAME; + SymSetOptions( symOptions ); + + // Get the search path for the symbol files + symbolPaths( lpszSymbolPath); + // + if (lpszUserSymbolPath) + { + _tcscat(lpszSymbolPath, _T(";")); + _tcscat(lpszSymbolPath, lpszUserSymbolPath); + } + return SymInitialize( GetCurrentProcess(), lpszSymbolPath, TRUE); +} + +void CMemLeakDetect::symStackTrace(STACKFRAMEENTRY* pStacktrace ) +{ + STACKFRAME callStack; + BOOL bResult; + CONTEXT context; + HANDLE hThread = GetCurrentThread(); + + // get the context + memset( &context, NULL, sizeof(context) ); + context.ContextFlags = CONTEXT_FULL; + if ( !GetThreadContext( hThread, &context ) ) + { + AfxTrace("Call stack info(thread=0x%X) failed.\n", hThread ); + return; + } + //initialize the call stack + memset( &callStack, NULL, sizeof(callStack) ); + callStack.AddrPC.Offset = context.Eip; + callStack.AddrStack.Offset = context.Esp; + callStack.AddrFrame.Offset = context.Ebp; + callStack.AddrPC.Mode = AddrModeFlat; + callStack.AddrStack.Mode = AddrModeFlat; + callStack.AddrFrame.Mode = AddrModeFlat; + // + for( DWORD index = 0; index < MLD_MAX_TRACEINFO; index++ ) + { + bResult = StackWalk(IMAGE_FILE_MACHINE_I386, + m_hProcess, + hThread, + &callStack, + NULL, + NULL, + SymFunctionTableAccess, + SymGetModuleBase, + NULL); + + //if ( index == 0 ) + // continue; + + if( !bResult || callStack.AddrFrame.Offset == 0 ) + break; + // + pStacktrace[0].addrPC = callStack.AddrPC; + pStacktrace[0].addrFrame = callStack.AddrFrame; + pStacktrace++; + } + //clear the last entry + memset(pStacktrace, NULL, sizeof(STACKFRAMEENTRY)); +} + +// +// This code is still under investigation +// I have to test this code and make sure it is compatible +// with the other stack walker! +// +void CMemLeakDetect::symStackTrace2(STACKFRAMEENTRY* pStacktrace ) +{ + ADDR FramePtr = NULL; + ADDR InstructionPtr = NULL; + ADDR OriFramePtr = NULL; + ADDR PrevFramePtr = NULL; + long StackIndex = NULL; + + // Get frame pointer + _asm mov DWORD PTR [OriFramePtr], ebp + + FramePtr = OriFramePtr; + + // + while (FramePtr) + { + InstructionPtr = ((ADDR *)FramePtr)[1]; + + pStacktrace[StackIndex].addrPC.Offset = InstructionPtr; + pStacktrace[StackIndex].addrPC.Segment = NULL; + pStacktrace[StackIndex].addrPC.Mode = AddrModeFlat; + // + StackIndex++; + PrevFramePtr = FramePtr; + FramePtr = ((ADDR *)FramePtr)[0]; + } +} +BOOL CMemLeakDetect::symFunctionInfoFromAddresses( ULONG fnAddress, ULONG stackAddress, LPTSTR lpszSymbol ) +{ + DWORD dwDisp = 0; + + ::ZeroMemory(m_pSymbol, m_dwsymBufSize ); + m_pSymbol->SizeOfStruct = m_dwsymBufSize; + m_pSymbol->MaxNameLength = m_dwsymBufSize - sizeof(IMAGEHLP_SYMBOL); + + // Set the default to unknown + _tcscpy( lpszSymbol, MLD_TRACEINFO_NOSYMBOL); + + // Get symbol info for IP + if ( SymGetSymFromAddr( m_hProcess, (ULONG)fnAddress, &dwDisp, m_pSymbol ) ) + { + _tcscpy(lpszSymbol, m_pSymbol->Name); + return TRUE; + } + //create the symbol using the address because we have no symbol + _stprintf(lpszSymbol, "0x%08X", fnAddress); + return FALSE; +} + +BOOL CMemLeakDetect::symSourceInfoFromAddress(UINT address, TCHAR* lpszSourceInfo) +{ + BOOL ret = FALSE; + IMAGEHLP_LINE lineInfo; + DWORD dwDisp; + TCHAR lpModuleInfo[MLD_MAX_NAME_LENGTH] = MLD_TRACEINFO_EMPTY; + + _tcscpy( lpszSourceInfo, MLD_TRACEINFO_NOSYMBOL); + + memset( &lineInfo, NULL, sizeof( IMAGEHLP_LINE ) ); + lineInfo.SizeOfStruct = sizeof( IMAGEHLP_LINE ); + + if ( SymGetLineFromAddr( m_hProcess, address, &dwDisp, &lineInfo ) ) + { + // Using the "sourcefile(linenumber)" format + _stprintf( lpszSourceInfo, _T("%s(%d): 0x%08X"), lineInfo.FileName, lineInfo.LineNumber, address ); + ret = TRUE; + } + else + { + // Using the "modulename!address" format + symModuleNameFromAddress( address, lpModuleInfo ); + + if ( lpModuleInfo[0] == _T('?') || lpModuleInfo[0] == _T('\0')) + { + // Using the "address" format + _stprintf(lpszSourceInfo, _T("0x%08X"), lpModuleInfo, address ); + } + else + { + _stprintf(lpszSourceInfo, _T("%sdll! 0x%08X"), lpModuleInfo, address ); + } + ret = FALSE; + } + // + return ret; +} + +BOOL CMemLeakDetect::symModuleNameFromAddress( UINT address, TCHAR* lpszModule ) +{ + BOOL ret = FALSE; + IMAGEHLP_MODULE moduleInfo; + + ::ZeroMemory( &moduleInfo, sizeof(IMAGEHLP_MODULE) ); + moduleInfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE); + + if ( SymGetModuleInfo( m_hProcess, (DWORD)address, &moduleInfo ) ) + { + _tcscpy(moduleInfo.ModuleName, lpszModule); + ret = TRUE; + } + else + { + _tcscpy( lpszModule, MLD_TRACEINFO_NOSYMBOL); + } + + return ret; +} \ No newline at end of file diff --git a/SlnkDWFImpl/MemLeakDetect.h b/SlnkDWFImpl/MemLeakDetect.h new file mode 100644 index 0000000..4b8559e --- /dev/null +++ b/SlnkDWFImpl/MemLeakDetect.h @@ -0,0 +1,170 @@ +/************************************************************* + Author : David A. Jones + File Name : MemLeakDetect.h + Date : July 30, 2004 + Synopsis : + A trace memory feature for source code to trace and + find memory related bugs. + + Future : + 1) Memory corruption + 2) Freeing memory without allocating + 3) Freeing memory twice + 4) Not Freeing memory at all + 5) over running memory boundardies + + +****************************************************************/ +#if !defined(MEMLEAKDETECT_H) +#define MEMLEAKDETECT_H + +#define _CRTDBG_MAP_ALLOC + +#include +#define _CRTBLD +#include +#include "dbgint.h" +#include +#include + + +#pragma comment( lib, "imagehlp.lib" ) + +using namespace std; + +// if you want to use the custom stackwalker otherwise +// comment this line out +#define MLD_CUSTOMSTACKWALK 1 +// +#define MLD_MAX_NAME_LENGTH 256 +#define MLD_MAX_TRACEINFO 256 +#define MLD_TRACEINFO_EMPTY _T("") +#define MLD_TRACEINFO_NOSYMBOL _T("?(?)") + +#ifdef MLD_CUSTOMSTACKWALK +#define MLD_STACKWALKER symStackTrace2 +#else +#define MLD_STACKWALKER symStackTrace +#endif + +#define AfxTrace MyTrace + +typedef DWORD ADDR; + +class CMemLeakDetect +{ + public: + + typedef struct { + ADDRESS addrPC; + ADDRESS addrFrame; + + } STACKFRAMEENTRY; + + typedef struct { + void* address; + DWORD size; + TCHAR fileName[MLD_MAX_NAME_LENGTH]; + DWORD lineNumber; + DWORD occurance; + STACKFRAMEENTRY traceinfo[MLD_MAX_TRACEINFO]; + + } AllocBlockInfo; + + //typedef int POSITION; + typedef map KEYMAP; + typedef map::iterator POSITION; + typedef pair KEYVALUE; + + class CMapMem + { + public: + + KEYMAP m_Map; + POSITION m_Pos; + + inline BOOL Lookup(LPVOID pAddr, AllocBlockInfo& aInfo) { + + m_Pos = m_Map.find(pAddr); + // + if (m_Pos == m_Map.end()) + { + return FALSE; + } + // + pAddr = m_Pos->first; + aInfo = m_Pos->second; + + return TRUE; + }; + + inline POSITION end() { + + return m_Map.end(); + }; + + inline void RemoveKey(LPVOID pAddr) { + + m_Map.erase(pAddr); + }; + + inline void RemoveAll() { + m_Map.clear(); + }; + + void SetAt(LPVOID pAddr, AllocBlockInfo& aInfo) { + + m_Map[pAddr] = aInfo; + }; + + inline POSITION GetStartPosition() { + POSITION pos = m_Map.begin(); + return pos; + }; + + inline void GetNextAssoc(POSITION& pos, LPVOID& rAddr, AllocBlockInfo& aInfo) { + + rAddr = pos->first; + aInfo = pos->second; + pos++; + }; + + void InitHashTable(int preAllocEntries, BOOL flag) { + preAllocEntries = NULL; + flag = NULL; + }; + + }; + + CMemLeakDetect(); + ~CMemLeakDetect(); + void Init(); + void End(); + void addMemoryTrace(void* addr, DWORD asize, TCHAR *fname, DWORD lnum); + void redoMemoryTrace(void* addr, void* oldaddr, DWORD asize, TCHAR *fname, DWORD lnum); + void removeMemoryTrace(void* addr, void* realdataptr); + void cleanupMemoryTrace(); + void dumpMemoryTrace(); + // + + //CMap m_AllocatedMemoryList; + CMapMem m_AllocatedMemoryList; + DWORD memoccurance; + bool isLocked; + // + private: + + BOOL initSymInfo(TCHAR* lpUserPath); + BOOL cleanupSymInfo(); + void symbolPaths( TCHAR* lpszSymbolPaths); + void symStackTrace(STACKFRAMEENTRY* pStacktrace); + void symStackTrace2(STACKFRAMEENTRY* pStacktrace); + BOOL symFunctionInfoFromAddresses(ULONG fnAddress, ULONG stackAddress, char* lpszSymbol); + BOOL symSourceInfoFromAddress(UINT address, TCHAR* lpszSourceInfo); + BOOL symModuleNameFromAddress(UINT address, TCHAR* lpszModule); + + HANDLE m_hProcess; + PIMAGEHLP_SYMBOL m_pSymbol; + DWORD m_dwsymBufSize; +}; +#endif \ No newline at end of file diff --git a/SlnkDWFImpl/SLNKContourImpl.cpp b/SlnkDWFImpl/SLNKContourImpl.cpp new file mode 100644 index 0000000..eb2b1c6 --- /dev/null +++ b/SlnkDWFImpl/SLNKContourImpl.cpp @@ -0,0 +1,505 @@ +#include "StdAfx.h" +#include "slnkcontourImpl.h" +#include + +#define PALETTE_RED 1 // Color in the default colormap is red. + +/*static*/ WT_Integer32 CSLNKContourImpl::m_next_node_num = 0; // Eigenlijk initialiseren op laatste van planfile + +CSLNKContourImpl::CSLNKContourImpl(void) + : m_DWGArea(-1), m_outlineAlpha(255) +{ + m_Color = WT_RGBA32(0,0,0,0); // alpha==0, 100% transparant +} + +CSLNKContourImpl::~CSLNKContourImpl(void) +{ +} + +// Algoritm: search google for Randolph Franklin polygon +BOOL CSLNKContourImpl::PointInPolygon(const WT_Logical_Point pt, const WT_Point_Set &ps) +{ + double ptx = pt.m_x; + double pty = pt.m_y; + int i, j, c = 0; + for (i = 0, j = ps.count()-1; i < ps.count(); j = i++) { + WT_Logical_Point pti = ps.points()[i]; + + if (pti.m_x==ptx&&pti.m_y==pty) // Op een hoekpunt is altijd goed! + { + return TRUE; + } + + WT_Logical_Point ptj = ps.points()[j]; + if ((((pti.m_y <= pty) && (pty < ptj.m_y)) || + ((ptj.m_y <= pty) && (pty < pti.m_y))) && + (ptx < (ptj.m_x - pti.m_x) * (pty - pti.m_y) / (ptj.m_y - pti.m_y) + pti.m_x)) + c = !c; + } + return c; +} + +BOOL CSLNKContourImpl::PointInPolygon(const CPoint pt, const CPoint *ps, int size) +{ + double ptx = pt.x; + double pty = pt.y; + int i, j, c = 0; + for (i = 0, j = size-1; i < size; j = i++) { + CPoint pti = ps[i]; + + if (pti.x==ptx&&pti.y==pty) // Op een hoekpunt is altijd goed! + { + return TRUE; + } + + CPoint ptj = ps[j]; + if ((((pti.y <= pty) && (pty < ptj.y)) || + ((ptj.y <= pty) && (pty < pti.y))) && + (ptx < (ptj.x - pti.x) * (pty - pti.y) / (ptj.y - pti.y) + pti.x)) + c = !c; + } + return c; +} + +// Signed Area needed for centroid! +// Negative is clockwise, Positve counterclockwise +/*static*/double CSLNKContourImpl::DWFArea(const WT_Polygon &pg) +{ + int i; + double area = 0; + for (i=0;i points()[i].m_x - pt.m_x) + pt = points()[i]; + } + return pt; + } + case LABEL_OUTSIDERIGHT: + { + WT_Logical_Box bx = bounds(); + return WT_Logical_Point(bx.maxpt().m_x, bx.minpt().m_y/2+bx.maxpt().m_y/2); // Pas op voor overflow + } + case LABEL_OUTSIDEBOTTOM: + { + WT_Logical_Box bx = bounds(); + return WT_Logical_Point(bx.minpt().m_x/2+bx.maxpt().m_x/2, bx.minpt().m_y); // Pas op voor overflow + } + default: + return WT_Logical_Point(m_ptLabel.m_x, m_ptLabel.m_y); + + } +} + +/*static*/WT_Logical_Point CSLNKContourImpl::Centroid(const WT_Polygon &pg) +{ + double ptx = 0; + double pty = 0; + int i, j; + for (i = 0; i < pg.count(); i++) { + j = (i + 1) % pg.count(); + double Xi=pg.points()[i].m_x, // Alles naar double anders krijgen wel overflows + Yi=pg.points()[i].m_y, + Xj=pg.points()[j].m_x, + Yj=pg.points()[j].m_y; + double dArea = Xi*Yj - Xj*Yi; + ptx += (Xi+Xj) * dArea; + pty += (Yi+Yj) * dArea; + } + double dDWFArea6 = 6*DWFArea(pg); + return WT_Logical_Point((WT_Integer32)(ptx / dDWFArea6), (WT_Integer32)(pty / dDWFArea6)); +} + +void CSLNKContourImpl::SerializeLabel(WT_File &my_file, LABELPOS pos, int fontheight, HDC myDC) +{ + if (m_Color.rgba().m_rgb.a==255) + { // Volle achtergrond kleur + COLORREF DCclr = RGB(m_Color.rgba().m_rgb.r, + m_Color.rgba().m_rgb.g, + m_Color.rgba().m_rgb.b); + // Net niet 100% kleuren om te zorgen dat bij achtergrond + // zwart/wit toggle deze kleuren niet mee togglen + if (isDarkRGB(DCclr)) + my_file.desired_rendition().color() = WT_Color(254,254,254,0); + else + my_file.desired_rendition().color() = WT_Color(1,1,1,0); + } + else + my_file.desired_rendition().color() = WT_Color(255,255,255,0); //Teksten wit + + CString tok(m_ExtraLabel); // strtok seems to modify + tok.Replace("~", "\n"); // We ondersteunen ook ~ als newline + tok.Replace("[br]", "\n"); // We ondersteunen ook [br] als newline + tok.Replace("[BR]", "\n"); // We ondersteunen ook [BR] als newline + + WT_Logical_Point ptTxt = LabelPosition(pos); + // De wiskundige label-positie is bepaald. Nu iets corrigeren om + // (afhankelijk van het font) mooier te zijn + // Ook eventueel hori/vert centreren + int width = -1; // Voor UBB code [c] van centreren + switch (pos) + { + case CSLNKContourImpl::LABEL_DEFAULT: + break; + case CSLNKContourImpl::LABEL_TOPLEFT: // Iets naar rechtstonder moven + ptTxt.m_x += fontheight/4; + ptTxt.m_y -= fontheight; + break; + case CSLNKContourImpl::LABEL_OUTSIDERIGHT: // Iets naar rechts en verticaal centreren + { + // Eerst een keer simuleren om grootte te bepalen + ATLASSERT(myDC!=NULL); + WT_Logical_Point ptBR = DrawOneLabel(my_file, pos, ptTxt, tok, fontheight, myDC); + width = (ptBR.m_x - ptTxt.m_x); + ptTxt.m_y -= (ptBR.m_y - ptTxt.m_y)/2 + fontheight*9/10; + ptTxt.m_x += fontheight/4; + break; + } + case CSLNKContourImpl::LABEL_OUTSIDEBOTTOM: // Iets naar beneden en horizontaal centreren + { + // Eerst een keer simuleren om grootte te bepalen + ATLASSERT(myDC!=NULL); + WT_Logical_Point ptBR = DrawOneLabel(my_file, pos, ptTxt, tok, fontheight, myDC); + width = (ptBR.m_x - ptTxt.m_x); + ptTxt.m_y -= fontheight; + ptTxt.m_x -= (ptBR.m_x - ptTxt.m_x)/2; + break; + } + case CSLNKContourImpl::LABEL_CENTROID: + { ATLASSERT(myDC!=NULL); + // Als niet binnen contour dan terugvallen op DEFAULT + if (!CSLNKContourImpl::PointInPolygon(ptTxt, *this)) + ptTxt = LabelPosition(CSLNKContourImpl::LABEL_DEFAULT); + // Eerst een keer simuleren om grootte te bepalen + WT_Logical_Point ptBR = DrawOneLabel(my_file, pos, ptTxt, tok, fontheight, myDC); + width = (ptBR.m_x - ptTxt.m_x); + ptTxt.m_x -= (ptBR.m_x - ptTxt.m_x)/2; + ptTxt.m_y -= (ptBR.m_y - ptTxt.m_y)/2 + fontheight*9/10; + // Nooit verder naar links/boven dan TOPLEFT zou doen + // JGL: jul 2007: Waarom niet? Bij heel kleine ruimtes mag bij centreren de boel er best wel iets buiten + // WT_Logical_Point ptTL = LabelPosition(CSLNKContourImpl::LABEL_TOPLEFT); + //ptTxt.m_x = max(ptTxt.m_x, ptTL.m_x+fontheight/4); + //ptTxt.m_y = min(ptTxt.m_y, ptTL.m_y-fontheight); +#ifdef _DEBUG +WT_Polymarker pm(1, &ptTxt, true); +pm.serialize(my_file); +#endif + } + } + + // Nu echt tekenen met width<>-2 + DrawOneLabel(my_file, pos, ptTxt, tok, fontheight, myDC, width); +} + +// Draw one (possibly multline) label +// When width==-2 the drawing is simulated and the result +// is the calculated bottomright of the full text +// Als width==-1 is centreren niet mogelijk/nodig +// Als width>0 is centreren mogelijk via [c] +WT_Logical_Point CSLNKContourImpl::DrawOneLabel(WT_File &my_file, + LABELPOS pos, + WT_Logical_Point ptTxt, + CString tok, + int fontheight, + HDC myDC, + int width/*=-2*/)// Voor centreren. Moet aanroeper al een keer bepaald hebben +{ + long max_width=0; // Bepaal hiermee 'rechtsonder' van de tekst als myDC + +//TODO: UBB sluitcodes ondersteunen + int curpos = 0; + CString token = tok.Tokenize("\n", curpos); + int line = 0; + bool centering=false; + while( token != "" ) + { +//CString f(token); + int skipextra = 0; // Extra skip bij underline + long size=100; + + // Supported UBB-like codes: + // [[This is literal text in square brackets] + // [i]This text is italic + // [b]This text is bold + // [u]This text is underline + // [cFF00FF]This text is colored + // [s50]This text is 50% sized + // Bovenstaand alleen voor de huidige regel + // [c] Centreer alle regels binnen bounding box (anders links gealigned) + while (token[0] == '[') + { + token.Delete(0); + if (token[0]=='[') break; // [[ALF-TB] to escape parsing + + switch (tolower(token[0])) + { + case 'i': // Italic + if (width != -2) + my_file.desired_rendition().font().style().set_italic(true); + token.Delete(0); + break; + case 'b': // Bold + if (width != -2) + my_file.desired_rendition().font().style().set_bold(true); + token.Delete(0); + break; + case 'u': // Underline + if (width != -2) + my_file.desired_rendition().font().style().set_underlined(true); + token.Delete(0); + skipextra = fontheight / 5; + break; + case 'c': // Color or Center + { + int end = token.Find(']'); + if (end==1) + { + token.Delete(0); + if (width>0) centering = true; + break; + } + if (end >= 0) + { + long clr; + if (sscanf(token, "c%lx]", &clr)) + { + WT_Color x(clr>>16,(clr&0xff00)>>8,clr&0xff); + if (width != -2) + my_file.desired_rendition().color() = x; + } + token.Delete(0, end); + } + break; + } + case 's': // Size + { + int end = token.Find(']'); + if (end >= 0) + { + if (sscanf(token, "s%d]", &size)) + { + int fh = myRound(double(size)*fontheight/100); + ptTxt.m_y += (fontheight - fh); + if (width != -2) + my_file.desired_rendition().font().height() = fh; + } + token.Delete(0, end); + } + break; + } + } + if (token[0]==']') token.Delete(0); // Skip closing ] + } + + if (width != -2) // Echt tekenen (lees: wegschrijven naar DWF) + { + int horoffset=0; + if (centering) + { + RECT rc = { 0, 0, 0, 0}; + DrawText(myDC, token, token.GetLength(), &rc, DT_CALCRECT); // Grootte bepalen + // Tekst horizontaal centreren + horoffset = width/2 - MulDiv(rc.right*size/100,fontheight,FONT_SIZER)/2; + } + WT_String txt; + if (WT_String::is_ascii(token.GetLength(), token)) +// txt.set(f.GetLength(), f); + txt.set(token.GetLength(), token); + else + { // Use UNICODE for example for Michaël + CStringW s(token); + txt.set(s.GetLength(), s); + } + WT_Text my_text(WT_Logical_Point(ptTxt.m_x+horoffset, ptTxt.m_y), txt); + my_text.serialize(my_file); + + // Altijd terug voor volgende regel + my_file.desired_rendition().font().style().set_italic(false); + my_file.desired_rendition().font().style().set_bold(false); + my_file.desired_rendition().font().style().set_underlined(false); + my_file.desired_rendition().color() = WT_Color(255,255,255,0); //Teksten wit TODO: (contrasteren met background) + my_file.desired_rendition().font().height() = fontheight; + } + else + { + // We willen de breedte en hoogte weten van de volledige tekst + RECT rc = { 0, 0, 0, 0}; + // Volgens de documentatie werkt DT_CALCRECT niet voor de breedte bij + // multiline teksten maar in de praktijk wel? + // ==>JGL: Onze token is toch maar één regel + DrawText(myDC, token, token.GetLength(), &rc, DT_CALCRECT); // Grootte bepalen + + // Tekst horizontaal en verticaal centreren + // ptRes.m_y += rc.bottom; halen we wel uit ptY + max_width = max(max_width, MulDiv(rc.right,size,100)); + } + + line ++; + /* Get next token: */ + token = tok.Tokenize("\n", curpos); + + ptTxt.m_y -= fontheight + skipextra; + } + return WT_Logical_Point(ptTxt.m_x+MulDiv(max_width,fontheight,FONT_SIZER), ptTxt.m_y); +} + +/**************************************************************************** + Serialize een contour. + Varianten: + - (!fromSymbol)Gesloten polyline op contourlaag + Hiermee komen we twee keer langs, met en zonder solidOnly + - waar uiteindelijk geen label in gevonden (m_contLabel is leeg) + - waar uiteindelijk wel label in gevonden (m_Key zal waarschijnlijk contourlabel zijn maar kan zijn veranderd) + - Geen kleur gezet + - Met solid kleur gezet + - Met transparante kleur gezet + - (m_fromSymbol) Symbool (al dan niet met m_Key gedefinieerd) + - Ingebouwd (star) + - Gedefinieerd (bounding octagon) + + Als solidOnly dan alleen als alpha==255 en een label (wel herkend) + ****************************************************************************/ +WT_Result CSLNKContourImpl::serialize(WT_File & file, BOOL solidOnly) +{ + if (!m_fromSymbol && m_contLabel == "" && !solidOnly) // Alleen bij tweede slag + { // May very well be a textobject itself, just emit it + file.desired_rendition().color() = + WT_Color(PALETTE_RED, file.desired_rendition().color_map()); + file.desired_rendition().line_weight() = 0; + WT_Polyline my_line( count(), points(), WD_False); + my_line.serialize(file); + } + else + { // We have got a proper label/contour + if (m_fromSymbol || + (m_Color.rgba().m_rgb.a==255 && solidOnly) || + (m_Color.rgba().m_rgb.a<255 && !solidOnly)) + { + // Start a node for 'everything'. Dit is wat we concreet teruggeven bij klikken in de tekening + WT_Object_Node my_node(file,m_next_node_num++,m_Key); + file.desired_rendition().object_node() = my_node; + + //char s[256]; + //sprintf(s, "Ruimte %s (%.2fm2)", m_Label.ascii(), m_DWGArea/1e6); + + // Van de URL gebruiken we met name de friendlyName voor de poly2Map + if (m_Url.index() !=0 ) + { + file.desired_rendition().url().add_url_optimized(m_Url, file); + } + + // + // Add the filled polygon for the room + // + // Ook als geheel doorzichtig + // - poly2Map heeft namelijk een poly nodig + // - voor als we ruimte willen aanwijzen want de point-in werkt later op polygons + + file.desired_rendition().color() = m_Color; // Set the color for the polygon + WT_Polygon my_poly( count(), points(), WD_False); + my_poly.serialize(file); +#if 0 + WT_RGBA32 rgba[3]; + WT_RGBA32 clr(this.m_Color.rgba()); + rgba[0] = clr; + rgba[1] = WT_RGBA32 (clr.m_rgb.r+64>255?255:clr.m_rgb.r+64, + clr.m_rgb.g+64>255?255:clr.m_rgb.g+64, + clr.m_rgb.b+64>255?255:clr.m_rgb.b+64, clr.m_rgb.a); + rgba[1] = WT_RGBA32 (clr.m_rgb.r-64<0?0:clr.m_rgb.r-64, + clr.m_rgb.g-64<0?0:clr.m_rgb.g-64, + clr.m_rgb.b-64<0?0:clr.m_rgb.b-64, clr.m_rgb.a); + rgba[2] = rgba[1]; + + WT_Logical_Point vP[3]; + vP[0] = this.LabelPosition(CSLNKContourImpl::LABEL_CENTROID); + if (!CSLNKContourImpl::PointInPolygon(vP[0], *contour)) + vP[0] = this.LabelPosition(CSLNKContourImpl::LABEL_DEFAULT); + for (int i = 0; i < count()-1; i++) + { + vP[1] = points()[i]; + vP[2] = points()[i+1]; + + WT_Gouraud_Polytriangle gpt (3, vP, rgba, WD_True); + gpt.serialize (my_file); + } +#endif + if (m_Pattern.pattern_id() != WT_Fill_Pattern::Solid) + { // Nog een keer gearceerd + WT_Fill_Pattern pOld = file.desired_rendition().fill_pattern(); + file.desired_rendition().fill_pattern() = m_Pattern; + WT_RGBA32 clr(m_Color.rgba()); + //WT_Color xor((128+clr.m_rgb.r)%256, (128+clr.m_rgb.g)%256,(128+clr.m_rgb.b)%256); + WT_Color xor(255, (128+clr.m_rgb.g)%256,(128+clr.m_rgb.b)%256); + file.desired_rendition().color() = xor; // Inverse + WT_Polygon my_poly2( count(), points(), WD_False); + my_poly2.serialize(file); + file.desired_rendition().fill_pattern() = pOld; + } + // + // Nu nogmaals om de rand van de ruimte te tekenen + // Dikte is door de aanroeper al gezet + // + // TODO: Altijd contrasteren met achtergrond + if (m_outlineAlpha>0) // Voor symbolen niet nodig + { + file.desired_rendition().color() = WT_Color(128,128,128, m_outlineAlpha); // Set the color for the polyline + //my_file.desired_rendition().color() = WT_Color(0,0,0); // Zwart + WT_Polyline my_line( count(), points(), WD_False); + my_line.serialize(file); + } + + file.desired_rendition().url().clear(); + } + } + return WT_Result::Success; +}; + + +#ifndef DWFTK_READ_ONLY +void CSLNKContourImpl::serializeXML( DWFToolkit::DWFXMLSerializer& rSerializer, unsigned int nFlags ) + throw( DWFException ) +{ + rSerializer.startElement( L"Contour ", L"SLNKDWF" ); + + rSerializer.addAttribute( L"Label", DWFString(m_contLabel) ); + wchar_t zTempBuffer[32]; + _DWFCORE_SWPRINTF( zTempBuffer, 32, L"%.2f", m_DWGArea ); + rSerializer.addAttribute( "Area", zTempBuffer ); + //rSerializer.addAttribute( DWFXML::kzAttribute_Category, _zCategory ); + //rSerializer.addAttribute( DWFXML::kzAttribute_Type, _zType ); + //rSerializer.addAttribute( DWFXML::kzAttribute_Units, _zUnits ); + + rSerializer.endElement(); + +} +#endif \ No newline at end of file diff --git a/SlnkDWFImpl/SLNKContourImpl.h b/SlnkDWFImpl/SLNKContourImpl.h new file mode 100644 index 0000000..b644e4a --- /dev/null +++ b/SlnkDWFImpl/SLNKContourImpl.h @@ -0,0 +1,69 @@ +#pragma once +#include "Whiptk/whip_toolkit.h" + +#define FONT_SIZER 1000 + +class CWhipFileState; // Forward declaration + +class CSLNKContourImpl : + public WT_Polygon +{ +public: + typedef enum { + LABEL_DEFAULT, + LABEL_CENTROID, // Not guaranteed inside + LABEL_TOPLEFT, + LABEL_OUTSIDERIGHT, + LABEL_OUTSIDEBOTTOM + } LABELPOS; + + CSLNKContourImpl(void); + + CSLNKContourImpl( + int count, /**< The number of points in the array. */ + WT_Logical_Point const * points, /**< Pointer to the array of points. */ + WT_Boolean copy, /**< Whether the points should be copied or if their addresses should be used directly from the array. */ + CWhipFileState *parent + ) + : WT_Polygon(count, points, copy), m_outlineAlpha(255), m_fromSymbol(false) + { + m_Color = WT_RGBA32(0,0,0,0); // alpha==0, 100% transparant + m_parentWhipFileState = parent; + } + + ~CSLNKContourImpl(void); +public: + WT_String m_contLabel; // As scanned from DWF-file + CString m_Key; // standaard m_contLabel voor contouren maar kan (en voor symbolen moet) een andere waarde krijgen + WT_Color m_Color; + int m_outlineAlpha; // Default 255, zet op 0 voor transparant + BOOL m_fromSymbol; // Dan zijn onze bounds maar matig betrouwbaar zo lang ze niet getransformeerd zijn. + CWhipFileState *m_parentWhipFileState; + WT_Fill_Pattern m_Pattern; + WT_Logical_Point m_ptLabel; // Coordinates of the label + CString m_ExtraLabel; // Can be defined + WT_URL_Item m_Url; // Can be defined + double m_DWGArea; // As determined, original source drawing units + + WT_Result serialize(WT_File & file, BOOL solidOnly); + static BOOL PointInPolygon(const WT_Logical_Point pt, const WT_Point_Set &ps); + static BOOL PointInPolygon(const CPoint pt, const CPoint *ps, int size); + static double DWFArea(const WT_Polygon &pg); + static WT_Logical_Point Centroid(const WT_Polygon &pg); + WT_Logical_Point LabelPosition(LABELPOS pos = LABEL_DEFAULT); + void SerializeLabel(WT_File &my_file, LABELPOS pos, + int fontheight, + HDC myDC); + WT_Logical_Point DrawOneLabel(WT_File &my_file, + LABELPOS pos, + WT_Logical_Point ptTxt, + CString tok, + int fontheight, + HDC myDC, int width=-2); + + static WT_Integer32 m_next_node_num; +#ifndef DWFTK_READ_ONLY + void serializeXML( DWFToolkit::DWFXMLSerializer& rSerializer, unsigned int nFlags ) + throw( DWFException ); +#endif +}; diff --git a/SlnkDWFImpl/SLNKDWFStatic.h b/SlnkDWFImpl/SLNKDWFStatic.h new file mode 100644 index 0000000..d5143ee --- /dev/null +++ b/SlnkDWFImpl/SLNKDWFStatic.h @@ -0,0 +1,21 @@ +#define WHIP_STATIC_LIB +#define DWFTK_STATIC +#define CONVERTER_STATIC_LIB +#define DWFTK_BUILD_EXPAT +#define DWFCORE_BUILD_ZLIB +#define DWFCORE_STATIC + +#pragma warning( disable : 4290 ) + +#include "dwfcore/File.h" +#include "dwfcore/String.h" +#include "dwf/package/Constants.h" +#include "dwf/package/Manifest.h" +#include "dwf/package/EPlotSection.h" +#include "dwf/package/reader/PackageReader.h" +#include "dwf/package/xml.h" +#include "dwf/package/reader/DuplicateAttributeFilter.h" + +#include +#include "atlrx.h" +#include "DWFFileImpl.h" diff --git a/SlnkDWFImpl/SLNKDWFStaticRO.h b/SlnkDWFImpl/SLNKDWFStaticRO.h new file mode 100644 index 0000000..230c69b --- /dev/null +++ b/SlnkDWFImpl/SLNKDWFStaticRO.h @@ -0,0 +1,3 @@ +#define DWFTK_READ_ONLY + +#include "SLNKDWFStatic.h" diff --git a/SlnkDWFImpl/SLNKDWFStaticRO.vcproj b/SlnkDWFImpl/SLNKDWFStaticRO.vcproj new file mode 100644 index 0000000..83574e6 --- /dev/null +++ b/SlnkDWFImpl/SLNKDWFStaticRO.vcproj @@ -0,0 +1,382 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/SLNKDWFStaticRW.h b/SlnkDWFImpl/SLNKDWFStaticRW.h new file mode 100644 index 0000000..9b71e32 --- /dev/null +++ b/SlnkDWFImpl/SLNKDWFStaticRW.h @@ -0,0 +1,5 @@ +#ifdef DWFTK_READ_ONLY +#error "Don't define DWFTK_READ_ONLY" +#endif + +#include "SLNKDWFStatic.h" diff --git a/SlnkDWFImpl/SLNKDWFStaticRW.vcproj b/SlnkDWFImpl/SLNKDWFStaticRW.vcproj new file mode 100644 index 0000000..0d4916d --- /dev/null +++ b/SlnkDWFImpl/SLNKDWFStaticRW.vcproj @@ -0,0 +1,382 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SlnkDWFImpl/TextFormatter.cpp b/SlnkDWFImpl/TextFormatter.cpp new file mode 100644 index 0000000..160ca55 --- /dev/null +++ b/SlnkDWFImpl/TextFormatter.cpp @@ -0,0 +1,156 @@ +#include "StdAfx.h" + +#include "TextFormatter.h" +// pixelsize: in logical space +BOOL KTextFormator::SetupPixel(HDC hDC, HFONT hFont, double pixelsize) +{ + OUTLINETEXTMETRIC otm[3]; // big enough for the strings + + if ( GetOutlineTextMetrics(hDC, sizeof(otm), otm)==0 ) + return FALSE; + + LOGFONT lf; + ::GetObject(hFont, sizeof(lf), & lf); + int emsquare= otm[0].otmEMSquare; // get EM square size + double scale = 1.0; + if (lf.lfWidth != 0 && lf.lfHeight != 0) + scale = ((double)lf.lfWidth)/abs(lf.lfHeight)*emsquare/1024; + lf.lfHeight = - emsquare; // font size for 1:1 mapping + lf.lfWidth = 0; // original proportion rekenen + + HFONT hRefFont = CreateFontIndirect(&lf); + HDC hRefDC = CreateCompatibleDC(hDC); + HGDIOBJ hOld = SelectObject(hRefDC, hRefFont); + + int nCharWidth[MaxCharNo]; + GetCharWidth32(hRefDC, 0, MaxCharNo-1, nCharWidth); + + if ( GetOutlineTextMetrics(hRefDC, sizeof(otm), otm)==0 ) + return FALSE; + + SelectObject(hRefDC, hOld); + + DeleteObject(hRefDC); + DeleteObject(hRefFont); + + m_fHeight = otm[0].otmTextMetrics.tmHeight * pixelsize / emsquare; + m_fLinespace = ( otm[0].otmTextMetrics.tmHeight + otm + [0].otmTextMetrics.tmExternalLeading) * pixelsize / emsquare; + + for (int i=0; i 0) + { + // allocate memory for the point data and for the vertex types + LPPOINT p_points = new POINT[num_points]; + LPBYTE p_types = new BYTE[num_points]; + + // get the path's description + GetPath(hDC, p_points, p_types, num_points); + //myTRACE(", points: %d", num_points); + + // + // Let wel: aanroeper heeft al gecorrigeerd voor rotatie op dxWidth en dxHeight + for (int i = 0; i < num_points; i++) + { + p_points[i].x = x + myRound((p_points[i].x - x) * dxWidth); + p_points[i].y = y + myRound((p_points[i].y - y) * dxHeight); + } + // + // Make pen width 0, just in case + //HPEN hpenNew, hpenOld; + LOGPEN lp; + GetObject((HPEN)GetCurrentObject(hDC, OBJ_PEN), sizeof(LOGPEN), &lp); + lp.lopnWidth = CPoint(5,5); + + myTempPEN tempPen(hDC, 0, GetTextColor(hDC)); + + // Via nieuw path zodat we kunnen vullen met FillPath + BeginPath(hDC); + PolyDraw(hDC, p_points, p_types, num_points); + EndPath(hDC); + // Make brush solid just in case + HBRUSH hbrushNew, hbrushOld; + LOGBRUSH lb; + lb.lbColor = GetTextColor(hDC); + //b.lbHatch = hatchCode; + lb.lbStyle = BS_SOLID; + hbrushNew = CreateBrushIndirect(&lb); + hbrushOld = (HBRUSH)SelectObject(hDC, hbrushNew); + StrokeAndFillPath(hDC); + + // Opruimen + SelectObject(hDC, hbrushOld); + DeleteObject(hbrushNew); + + delete [] p_points; + delete [] p_types; + } +#endif + return true; +} diff --git a/SlnkDWFImpl/Whip2DCImpl.cpp b/SlnkDWFImpl/Whip2DCImpl.cpp new file mode 100644 index 0000000..1484595 --- /dev/null +++ b/SlnkDWFImpl/Whip2DCImpl.cpp @@ -0,0 +1,1702 @@ +// Whip2DCImpl.cpp : Implementation of CWhip2DCImpl + +#include "stdafx.h" + +#undef USE_CIMAGE + +#include "Whip2DCImpl.h" + +#ifndef USE_CIMAGE +#include "CxImage\CxImage\ximage.h" +#else +#include "atlimage.h" +#endif + +#include "SLNKContourImpl.h" + +// CWhip2DC + +STDMETHODIMP CWhip2DCImpl::Load(HDC hDC, CEPlotSectionImpl *EPlotStream, + const CString &WhipPath, + const CString & RegExp, long sizeX, long sizeY, + VARIANT_BOOL centerImage, VARIANT_BOOL maximize,/*=FALSE*/ + double dwgScale/*=0.0*/) +{ + m_State.Reset(); + + m_WhipPath = WhipPath; + m_State.myDC = hDC; + m_State.m_Layernames.RemoveAll(); + m_State.m_centerImage = centerImage; + m_State.m_Maximize = maximize; + + m_iEPlotSection = EPlotStream; + + REParseError status = m_State.reLayers.Parse( CString(RegExp), false ); + if (REPARSE_ERROR_OK != status) + { + myTRACE("\nSorry, kan reguliere expressie layersOn niet parsen"); + // return E_FAIL; + } + + m_State.m_Size = CSize(sizeX, sizeY); + + // Om iets zinvols te kunnen doen moeten we altijd wel schaalinformatie hebben + // In het eenvoudigste geval komen we al heel rap een view of viewport tegen + // Die 'geloven' en gebruiken we. Daarmee kunnen we o.a. m_mul bepalen, de verhouding + // tussen DWF units en device units + // maximize: Voor (draggable) symbolen moeten we de exacte extents/bounds weten + // van de drawable entiteiten en doorzoeken we gegarandeerd de hele tekening + myWT_File my_input_file; // input file. + if (m_iEPlotSection) + { + my_input_file.set_eplotsection(m_iEPlotSection); + m_State.m_ClipWidth = m_iEPlotSection->get_PaperClipWidth(); + m_State.m_ClipHeight = m_iEPlotSection->get_PaperClipHeight(); + } + else + my_input_file.set_filename(m_WhipPath.ascii()); + m_State.m_mul=0; + my_input_file.set_file_mode(WT_File::File_Read); + WT_Result result; + if (my_input_file.open() != WT_Result::Success) + throw myCString("\nCWhip2DCImpl::Load: unable to open file '%s'", m_WhipPath.ascii()); + + BOOL ViewportDone = FALSE; + double dScale = 0.0; + // Doorloop de DWF totdat alles gelezen is + // Stop als we een view/viewport hebben (dan wordt m_mul gezet) tenzij maximize, dan lezen we alles + while ((result = my_input_file.process_next_object()) == WT_Result::Success + && (m_State.m_mul == 0 || maximize)) + { + switch(my_input_file.current_object()->object_type()) + { + case WT_Object::Attribute: + { + const WT_Attribute *obj = (WT_Attribute *)my_input_file.current_object(); + if (obj->object_id() == WT_Object::View_ID) + { + WT_View *view = (WT_View *)my_input_file.current_object(); + if (!maximize) + m_State.SetExtents(view->view()); // m_mul wordt gezet en de loop eindigt + break; + } + if (obj->object_id() == WT_Object::Viewport_ID) + { + if (m_State.m_mul == 0) + { + WT_Viewport *viewport = (WT_Viewport *)my_input_file.current_object(); + dScale = viewport->viewport_units().application_to_dwf_transform()(0,0); // Symbol's dScale + if (!maximize) + { + WT_Logical_Point dwfPtmin = viewport->contour()->points()[0]; + WT_Logical_Point dwfPtmax = viewport->contour()->points()[2]; + m_State.SetExtents(WT_Logical_Box(dwfPtmin, dwfPtmax)); // m_mul wordt gezet en de loop eindigt + } + } + break; + } + break; + } + case WT_Object::Drawable: + { + WT_Drawable *obj = (WT_Drawable *)my_input_file.current_object(); + if (obj->object_id() != WT_Object::Origin_ID)// Belachelijk dat die Drawable is? + { + WT_Logical_Box bx = obj->bounds(&my_input_file); + m_State.m_MinMax.minpt().m_x = min(m_State.m_MinMax.minpt().m_x, bx.minpt().m_x); + m_State.m_MinMax.minpt().m_y = min(m_State.m_MinMax.minpt().m_y, bx.minpt().m_y); + m_State.m_MinMax.maxpt().m_x = max(m_State.m_MinMax.maxpt().m_x, bx.minpt().m_x); + m_State.m_MinMax.maxpt().m_y = max(m_State.m_MinMax.maxpt().m_y, bx.minpt().m_y); + m_State.m_MinMax.minpt().m_x = min(m_State.m_MinMax.minpt().m_x, bx.maxpt().m_x); + m_State.m_MinMax.minpt().m_y = min(m_State.m_MinMax.minpt().m_y, bx.maxpt().m_y); + m_State.m_MinMax.maxpt().m_x = max(m_State.m_MinMax.maxpt().m_x, bx.maxpt().m_x); + m_State.m_MinMax.maxpt().m_y = max(m_State.m_MinMax.maxpt().m_y, bx.maxpt().m_y); + } + break; + } + default: + //myTRACE("Skipping '%s'\n", wtFile->file_stats()->descriptions()); + break; + } + } + result = my_input_file.close(); // closing Input file. + if (m_State.m_mul==0 && result == WT_Result::Success) + { // Blijkbaar geen view en/of viewport gevonden + m_State.SetExtents(m_State.m_MinMax); // Die hebben we dan in de vorige slag wel bepaald + } + result = my_input_file.close(); // closing Input file. + + if (dwgScale > 0.0) // dwgSchaal geforceerd! + { // Vooralsnog alleen getest met m_Maximize aan + double old_mul = m_State.m_mul; + CSize old_size = m_State.m_Size; + m_State.m_mul = 1.0/dwgScale/dScale; + + if (m_State.m_Maximize) // Eventueel centreren ongedaan maken + m_State.m_MinMax = m_State.m_orgMinMax; + + WT_Integer32 dwfDx = m_State.m_MinMax.maxpt().m_x - m_State.m_MinMax.minpt().m_x; + WT_Integer32 dwfDy = m_State.m_MinMax.maxpt().m_y - m_State.m_MinMax.minpt().m_y; + m_State.m_Size = CPoint(myRound(m_State.m_mul*dwfDx)+1, myRound(m_State.m_mul*dwfDy+1)+1); + m_State.m_Size.cx = max(m_State.m_Size.cx, 1); + m_State.m_Size.cy = max(m_State.m_Size.cy, 1); + + myDoTRACE("\nm_mul forced from %.8f to %.8f and size from (%d, %d) to (%d, %d)", + old_mul, m_State.m_mul, old_size.cx,old_size.cy,m_State.m_Size.cx,m_State.m_Size.cy); + } + + ATLASSERT(m_State.m_mul!=0); + return S_OK; +} + +// Om onze definitieve bitmap grootte te kunnen bepalen +CSize &CWhip2DCImpl::get_Size() +{ + return m_State.m_Size; +} + +STDMETHODIMP CWhip2DCImpl::Paint(VARIANT_BOOL forceBW) +{ +#ifdef _DEBUG + /// CneutralGDI neutralGDI("CWhip2DCImpl::Paint"); +#endif + CmyTimer Timer("CWhip2DCImpl::Paint"); + + m_State.m_forceBW = forceBW; + m_State.findIt = FALSE; + + SetBkMode(m_State.myDC, TRANSPARENT); + + m_State.geekFontSize = 4; // 4pt en lager is toch niet leesbaar + // Overigens tikt dit vooral hard aan omdat we de + // rotatie van die kleine teksten niet meer zetten + + myWT_File my_input_file; // input file. + + if (m_iEPlotSection) + { + my_input_file.set_eplotsection(m_iEPlotSection); + if (!m_State.m_forcePaper) + { + m_State.m_paperColor = m_iEPlotSection->get_PaperColor(); + } + } + else + { + if (!m_State.m_forcePaper) + { + m_State.m_paperColor = RGB(255,255,255); // Gok maar op wit. Echte kleur komt misschien wel + } + my_input_file.set_filename(m_WhipPath.ascii()); + } + + // Setup our default font + WT_Font myFont; + myFont.font_name().set("Arial"); + myFont.height() = 100; + + my_input_file.rendition().font() = myFont; + + // Alle callback functies zijn static. Die kunnen de variabele + // m_State niet benaderen. Daarom maar via set_user_data + my_input_file.heuristics().set_user_data((void *)&m_State); + + my_input_file.set_file_mode(WT_File::File_Read); + + if (my_input_file.open() == WT_Result::Success) + { + SetTextAlign(m_State.myDC,TA_LEFT|TA_BASELINE); + // Setup our default pen and brush + if (isDarkRGB(m_State.m_paperColor)) + SetTextColor(m_State.myDC, RGB(255,255,255)); + else + SetTextColor(m_State.myDC, RGB(0, 0, 0)); + + // Standaard zit onze m_pen in de DC + // Alleen als echt nodig (w>1) stoppen we tijdelijk m_penExt erin. + // Die is wel trager namelijk + m_State.m_pen = CreatePen(PS_INSIDEFRAME, 0, GetTextColor(m_State.myDC)); + m_State.m_brush = CreateSolidBrush(GetTextColor(m_State.myDC)); + LOGBRUSH b; + b.lbColor = GetTextColor(m_State.myDC); + //b.lbHatch = hatchCode; + b.lbStyle = BS_SOLID; + m_State.m_penExt = ExtCreatePen(PS_GEOMETRIC, 0, &b, 0, NULL); + + HBRUSH oldbrush=(HBRUSH) SelectObject(m_State.myDC, m_State.m_pen); + HPEN oldpen=(HPEN)SelectObject(m_State.myDC, m_State.m_brush); + + // Wis myDC met wit. Wordt mogelijk overruled in WT_Background + m_State.erasePaper(my_input_file); + WT_Result result = read_dwf_for_extracting_Objects(my_input_file, FALSE); + my_input_file.close(); // closing Input file. + + // Alles opruimen + if (m_State.m_hrgn) + DeleteObject(m_State.m_hrgn); + if (m_State.m_font) + DeleteObject(m_State.m_font); + + SelectObject(m_State.myDC, oldbrush); + SelectObject(m_State.myDC, oldpen); + DeleteObject(m_State.m_brush); + DeleteObject(m_State.m_pen); + DeleteObject(m_State.m_penExt); + + if (result != WT_Result::Success) + throw myCString("\nCWhip2DCImpl::Paint: unable to read file '%s'", m_WhipPath.ascii()); + } + else // TODO: Fatsoenlijke error terug + { + throw myCString("\nCWhip2DCImpl::Paint: unable to open file '%s'", m_WhipPath.ascii()); + } + // For when user wants to use DPtoDWF + m_State.m_Units = my_input_file.rendition().viewport().viewport_units(); + +#if 0 + { + // Raster er overheen + CRect clip; + GetClipBox(m_State.myDC,&clip); // Zichtbaar deel op scherm + SetBkMode(m_State.myDC, TRANSPARENT); + HBRUSH tempBrush = ::CreateHatchBrush(HS_DIAGCROSS, RGB(32,0,0)); + HBRUSH tempBrush2 = ::CreateHatchBrush(HS_CROSS, RGB(0,64,0)); + HBRUSH oldbrush = (HBRUSH) SelectObject(m_State.myDC,tempBrush); + CRect rc; + GetClipBox(m_State.myDC,&rc); + SetBrushOrgEx(m_State.myDC, 0, 0, NULL); + //Rectangle(m_State.myDC, clip.left,clip.top,clip.right,clip.bottom); + HBRUSH oldbrush2 = (HBRUSH) SelectObject(m_State.myDC,tempBrush2); + Rectangle(m_State.myDC, clip.left,clip.top,clip.right,clip.bottom); + SetBrushOrgEx(m_State.myDC, 2, 2, NULL); + Rectangle(m_State.myDC, clip.left,clip.top,clip.right,clip.bottom); + SetBrushOrgEx(m_State.myDC, 4, 4, NULL); + Rectangle(m_State.myDC, clip.left,clip.top,clip.right,clip.bottom); + SetBrushOrgEx(m_State.myDC, 6, 6, NULL); + Rectangle(m_State.myDC, clip.left,clip.top,clip.right,clip.bottom); + SelectObject(m_State.myDC,oldbrush2); + + SelectObject(m_State.myDC,oldbrush); + DeleteObject(tempBrush); + DeleteObject(tempBrush2); + } +#endif + +#ifdef _DEBUG + // Toon bij sterk inzoomen een raster van DWF-punten ter referentie + LOGFONT lf; + memset(&lf, 0, sizeof(LOGFONT)); // clear out structure. + strncpy(lf.lfFaceName, "Tahoma", LF_FACESIZE); + lf.lfHeight = -10; + HFONT fnt = CreateFontIndirect(&lf); + HGDIOBJ oldfont = SelectObject(m_State.myDC, fnt); + + if (m_State.m_mul > 10.0) + { + CRect clip; + GetClipBox(m_State.myDC,&clip); // Zichtbaar deel op scherm + + WT_Logical_Point topleft(m_State.LPToDWF(clip.TopLeft())); + WT_Logical_Point botright(m_State.LPToDWF(clip.BottomRight())); + for (int x = topleft.m_x; x <= botright.m_x; x++) + for (int y = topleft.m_y; y >= botright.m_y; y--) + { + CPoint pt = m_State.DWFToLP(WT_Logical_Point(x, y)); + SetPixel(m_State.myDC, pt.x, pt.y, RGB(128,128,128)); + // Bij nog sterker inzoomen tonen we DWF-coordinaten + if (m_State.m_mul > 80.0) + { + CString txt; + txt.Format("%d", x); + TextOut(m_State.myDC, pt.x+5, pt.y, txt, txt.GetLength()); + txt.Format("%d", y); + TextOut(m_State.myDC, pt.x+5, pt.y+10, txt, txt.GetLength()); + } + } + } + SelectObject(m_State.myDC, oldfont); + DeleteObject(fnt); + + // Pas op: geeft ASSERT's op te grote myRound binnen DWFToLP bij ver inzoomen +#if 0 + //CPoint pt0 = m_State.DWFToLP(WT_Logical_Point(INT_MAX, 100000000)); + //CPoint pt1 = m_State.DWFToLP(WT_Logical_Point(INT_MAX, -100000000)); + HPEN m_pen = CreatePen(PS_SOLID, 3, RGB(255,255,0)); + HPEN oldpen = (HPEN) SelectObject(m_State.myDC, m_pen); + MoveToEx(m_State.myDC, pt0.x, pt0.y, NULL); + + LineTo(m_State.myDC, pt1.x, pt1.y); +#endif +#endif + + return S_OK; +} + +STDMETHODIMP CWhip2DCImpl::FindTexts(const CString &findText) +{ + CmyTimer Timer("CWhip2DCImpl::FindText"); + + m_State.bLayerVisible = TRUE; // When no layers at all + m_State.findIt = TRUE; + m_State.m_FoundTexts.RemoveAll(); + + m_State.foundTextLabel = ""; + + myWT_File my_input_file; // input file. + + if (m_iEPlotSection) + my_input_file.set_eplotsection(m_iEPlotSection); + else + my_input_file.set_filename(m_WhipPath.ascii()); + + my_input_file.heuristics().set_user_data((void *)&m_State); + + my_input_file.set_file_mode(WT_File::File_Read); + if (my_input_file.open() == WT_Result::Success) + { + WT_Result result; + my_input_file.set_polygon_action(my_process_polygon_find); // Requires polyline and fill too! + my_input_file.set_text_action(my_process_text_scan); + my_input_file.set_layer_action(my_process_layer); + + // Do the actual reading. + do { + result = my_input_file.process_next_object(); + } while (result == WT_Result::Success); + + if (result == WT_Result::End_Of_DWF_Opcode_Found || result == WT_Result::User_Requested_Abort) + return WT_Result::Success; + else + return result; + } + else + myTRACE("\nSorry, kan file niet openen: %s", m_WhipPath); + + // For when user wants to use DPtoDWF + m_State.m_Units = my_input_file.rendition().viewport().viewport_units(); + + my_input_file.close(); // closing Input file. + + return S_OK; +} + +/*****************************************************************************\ + * Name CWhip2DCImpl::Find() + * Input HDC dc + * LONG sizeX, + * LONG sizeY, + * LONG offsetX, + * LONG offsetY, + * DOUBLE dScale + * .... + * Action Zoek een in de tekening aangeklikt punt op + * of bepaal de clientside imagemap (voor tooltips) + * Deze laatste heeft als neveneffect dat SLNKEvent clientside + * gezet wordt waar we een heleboel info uit halen + * Return S_OK + * + * Called + * TODO: AsMap wordt voor steeds meer doeleinden gebruikt. Oppassen dat + * bijvoorbeeld extents wel correct worden bepaald + *****************************************************************************/ +STDMETHODIMP CWhip2DCImpl::Find(LONG findX, LONG findY, + BYTE AsMap, + CString & pContourLabel,CString & pContourLayer, + CString & pTextLabel, CString & pTextLayer) +{ + CmyTimer Timer("CWhip2DCImpl::Find (includes AsMap)"); + + m_State.bLayerVisible = TRUE; // When no layers at all + m_State.findIt = TRUE; + + m_State.foundTextLabel = ""; + + // Note: At the first View we find we will fill + // DWFfindXY with the actual WT_logical coordinates + + m_State.LPfindXY = CPoint(findX, findY); + DPtoLP(m_State.myDC, &m_State.LPfindXY, 1); + // Extents zijn in Load al bepaald, we kunnen ons zoekpunt in DWF-coordinaten bepalen + m_State.DWFfindXY = m_State.LPToDWF(m_State.LPfindXY); + myTRACE("\nZoeken naar : (%d, %d)-->(%d, %d)", m_State.LPfindXY.x, m_State.LPfindXY.y, m_State.DWFfindXY.m_x, m_State.DWFfindXY.m_y); +#ifdef _DEBUG + CPoint ptback = m_State.DWFToLP(m_State.DWFfindXY); + myTRACE("\nTerugvertaling: (%d, %d)\n", ptback.x, ptback.y); +#endif + + myWT_File my_input_file; // input file. + + // For TextExtent32 + SetTextAlign(m_State.myDC,TA_LEFT|TA_BASELINE); + WT_Font myFont; + myFont.font_name().set("Arial"); // Real font will follow later + myFont.height() = 100; + my_input_file.rendition().font() = myFont; + + // Papierkleur zetten voor Find lijkt onzinnig maar we willen + // de kleur na afloop kunnen opvragen als oMap.paperColor + if (m_iEPlotSection) + { + my_input_file.set_eplotsection(m_iEPlotSection); + if (!m_State.m_forcePaper) + { + m_State.m_paperColor = m_iEPlotSection->get_PaperColor(); + } + } + else + { + my_input_file.set_filename(m_WhipPath.ascii()); + if (!m_State.m_forcePaper) + { + m_State.m_paperColor = RGB(255,255,255); // Gok maar op wit. Echte kleur komt misschien wel + } + } + + // Alle callback functies zijn static. Die kunnen de variabele + // m_State niet benaderen. Daarom maar via set_user_data + my_input_file.heuristics().set_user_data((void *)&m_State); + + my_input_file.set_file_mode(WT_File::File_Read); + if (my_input_file.open() == WT_Result::Success) + { + WT_Result result = read_dwf_for_extracting_Objects(my_input_file, TRUE); + } + else + myTRACE("\nSorry, kan file niet openen: %s", m_WhipPath); + + // For when user wants to use DPtoDWF + m_State.m_Units = my_input_file.rendition().viewport().viewport_units(); + + my_input_file.close(); // closing Input file. + + if (AsMap) + pContourLabel = m_State.MapBuilder; + else + { + if (m_State.foundTextLabel != "") + { + pTextLabel = m_State.foundTextLabel; + pTextLayer = m_State.foundTextLayer; + } + + if (m_State.foundNode.object_node_name()) + { + pContourLabel = CString(m_State.foundNode.object_node_name().ascii()); + pContourLayer = m_State.foundNodeLayer; + } + } + + // Alles opruimen + if (m_State.m_hrgn) + DeleteObject(m_State.m_hrgn); + if (m_State.m_font) + DeleteObject(m_State.m_font); + + return S_OK; +} + +// Call Find() or Paint() first!! +STDMETHODIMP CWhip2DCImpl::DPtoDWG(LONG findX, LONG findY, + DOUBLE* resX, DOUBLE* resY) +{ + m_State.LPfindXY = CPoint(findX, findY); + DPtoLP(m_State.myDC, &m_State.LPfindXY, 1); + + if ((resX != NULL) && (resY != NULL)) + { + if (m_State.m_mul==0) // Geen extents, vast ook geen transform + { + (*resX) = 0; // Zoek het maar lekker zelf uit + (*resY) = 0; + } + else + { + // Zoek de DWG coordinaten op + m_State.LPToDWG(m_State.LPfindXY, *resX, *resY); + } + } + return S_OK; +} + +// Call Find() or Paint() first!! +STDMETHODIMP CWhip2DCImpl::DWGExtents(DOUBLE* resminX, DOUBLE* resminY, + DOUBLE* resmaxX, DOUBLE* resmaxY) +{ + if (resminX && resminY && resmaxX && resmaxY) + { + if (m_State.m_mul==0) // Geen extents, vast ook geen transform + { + (*resminX) = (*resminY) = 0; // Zoek het maar lekker zelf uit + (*resmaxX) = (*resmaxY) = 0; + } + else + { + // Zoek de DWG coordinaten op + m_State.DWGExtents(*resminX, *resminY, *resmaxX, *resmaxY); + } + } + return S_OK; +} + +WT_Result CWhip2DCImpl::read_dwf_for_extracting_Objects(myWT_File &my_input_file, BOOL findIt) +{ + WT_Result result; + // Defined actions. + + if (!findIt) // When finding we don't need most handlers in the first place + { + my_input_file.set_color_action(my_process_color); + my_input_file.set_fill_pattern_action(my_process_fillPattern); + my_input_file.set_line_weight_action(my_process_lineWeight); + my_input_file.set_line_style_action(my_process_lineStyle); + my_input_file.set_line_pattern_action(my_process_linePattern); + my_input_file.set_filled_ellipse_action(my_process_filledEllipse); + my_input_file.set_outline_ellipse_action(my_process_outlineEllipse); + my_input_file.set_polytriangle_action(my_process_polytriangle); + my_input_file.set_polymarker_action(my_process_polymarker); + my_input_file.set_contour_set_action(my_process_contourSet); + my_input_file.set_png_group4_image_action(my_process_pngGroup4Image); + my_input_file.set_image_action(my_process_image); + my_input_file.set_gouraud_polyline_action(my_process_gouraudPolyline); + my_input_file.set_gouraud_polytriangle_action(my_process_gouraudPolytriangle); + my_input_file.set_polygon_action(my_process_polygon); // Requires polyline and fill too! + my_input_file.set_text_action(my_process_text); + my_input_file.set_polyline_action(my_process_polyline); + } + else // Use find-version + { + my_input_file.set_polygon_action(my_process_polygon_find); // Requires polyline and fill too! + my_input_file.set_text_action(my_process_text_find); + } + + // The following are also necessary when finding + my_input_file.set_background_action(my_process_background); // setting m_paperColor + my_input_file.set_font_extension_action(my_process_font_extension); + my_input_file.set_font_action(my_process_font); + my_input_file.set_layer_action(my_process_layer); + my_input_file.set_viewport_action(my_process_viewport); + my_input_file.set_view_action(my_process_view); + + // Do the actual reading. + do { + //CneutralGDI neutralGDI("read_dwf_for_extracting_Objects"); +#ifdef _DEBUG + CString s(my_input_file.file_stats()->descriptions()); + //myTRACE("Attribute '%s'\n", s); +#endif + if (m_progress_action) + { + int pos = my_input_file.file_pos(); + size_t sz = my_input_file.size(); + if (!m_progress_action(m_progress_param, sz==0?0:double(pos)/sz)) + return WT_Result::User_Requested_Abort; + } + + result = my_input_file.process_next_object(); + } while (result == WT_Result::Success); + + if (result == WT_Result::End_Of_DWF_Opcode_Found || result == WT_Result::User_Requested_Abort) + return WT_Result::Success; + else + return result; +} + +// We gebruiken deze view als initial display +// Sinds we het scannen al in de load doen is deze obsolete +WT_Result CWhip2DCImpl::my_process_view (WT_View & view, WT_File & file) +{ + return WT_Result::Success; +} + +// (Alleen) als we nog geen View hebben gehad gebruiken we de 1e Viewport +// als alternatief. Je moet toch wat. DWFPrinter doet dat +WT_Result CWhip2DCImpl::my_process_viewport (WT_Viewport & viewport, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + BOOL firstTime = (!file.rendition().viewport().contour()); + file.rendition().viewport() = viewport; + + // Voor de zekerheid opnieuw. ADT3_MTextFormattingCodesinScheduleTags.dwf had + // (waarschijnlijk door de DWFPrinter) de eerste (Font) voor de eerste (Viewport) + // en dan was de hoogte niet goed gezet + m_State->my_process_font(file.rendition().font()); + + double dScale = viewport.viewport_units().application_to_dwf_transform()(0,0); + myDoTRACE("\nThis viewport: 1 pixel = %.8f drawing units.", 1.0/(dScale*m_State->m_mul)); + + if (m_State->findIt) // When finding no need (or actually: support) for clipping + return WT_Result::Success; + + if (!viewport.contour()) // dwftest_bc.dwf + { + SelectClipRgn(m_State->myDC, NULL); + return WT_Result::Success; + } + + // Viewports-ANSI A.dwf heeft diverse viewports + myTRACE("\nViewport met %d punten", viewport.contour()->total_points()); + + // TODO: Door afronding kan het gebeuren dat de clipregion ene pixel + // te ver naar binnen valt waardoor meest rechtse lijntjes wegvallen + // Daarom viewport ter grootte van minmax niet aanzetten + // NOOT: Ook riskant als later symbolen net buiten de extents geplaatst zijn? + if (firstTime) + { + myTRACE("\nSkipping 'region-all'"); + SelectClipRgn(m_State->myDC, NULL); // Eventueel uitzetten + return WT_Result::Success; + } + + CPoint *vertexList = + m_State->new_DWFToLP(WT_Point_Set(viewport.contour()->total_points(), + viewport.contour()->points(), false)); + + // LET OP: CreatePolyPolygonRgn verwacht Device Units! + LPtoDP(m_State->myDC, vertexList, viewport.contour()->total_points()); + if (m_State->m_hrgn) + DeleteObject(m_State->m_hrgn); + m_State->m_hrgn = CreatePolyPolygonRgn(vertexList, (int *)viewport.contour()->counts(), + viewport.contour()->contours(), + ALTERNATE); + ATLASSERT(m_State->m_hrgn); + + int res = SelectClipRgn(m_State->myDC, m_State->m_hrgn); + ATLASSERT(res != ERROR); +#ifdef _DEBUG + { + CString s; + switch(res) { + case NULLREGION : s = "NULLREGION Region is empty."; break; + case SIMPLEREGION: s = "SIMPLEREGION Region is a single rectangle."; break; + case COMPLEXREGION: s = "COMPLEXREGION Region is more than one rectangle."; break; + case ERROR: s.Format("SelectClipRgn failed (%d): %s", GetLastError(), myGetLastErrorMsg()); break; + } + myTRACE("\nRegion aangemaakt: %s", s); + } +#endif + + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_color (WT_Color & color, WT_File & file) +{ + WT_Color::default_process(color, file); + + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + + m_State->ColorPenAndBrush(file); + + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_lineWeight (WT_Line_Weight & lineWeight, WT_File & file) +{ + WT_Line_Weight::default_process(lineWeight, file); + my_process_color(file.rendition().color(),file); + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_lineStyle (WT_Line_Style & lineStyle, WT_File & file) +{ + WT_Line_Style::default_process(lineStyle, file); + my_process_color(file.rendition().color(),file); + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_linePattern (WT_Line_Pattern & linePattern, WT_File & file) +{ + WT_Line_Pattern::default_process(linePattern, file); + my_process_color(file.rendition().color(),file); + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_layer (WT_Layer & layer, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + + file.rendition().layer() = layer; + if (layer.layer_name().length()>0) // Anders zittie alleen maar in de weg + { // Dat doet de default_process 'fout' + file.layer_list().add_layer(layer); + m_State->m_Layernames.Add(layer.layer_name().ascii()); + } + + WT_Integer32 layer_num = layer.layer_num(); + WT_Layer *ll = file.layer_list().find_layer_from_index(layer_num); + + if (ll&&ll->layer_name().ascii()) + { + //myTRACE("\n my_output_file.desired_rendition().layer() = layer %s;", layer.layer_name().ascii()); + CAtlREMatchContext<> mcUrl; + if ( m_State->reLayers.Match(ll->layer_name().ascii(), &mcUrl)) + { + //myTRACE(".. does match!"); + m_State->bLayerVisible = TRUE; + } + else + { + m_State->bLayerVisible = FALSE; +// myTRACE("\nLayer %s .. does not match", ll->layer_name().ascii()); + } + +// myTRACE("\nLayer %s .. does not match", ll->layer_name().ascii()); + m_State->bIsSymbolLayer = (ll->layer_name() == "SLNK Symbols"); + //myDoTRACE("\nLayer %s %d", ll->layer_name().ascii(), m_State->bIsSymbolLayer); + } + else + { + myTRACE("\nNo layer name for contour. Assuming match"); + m_State->bLayerVisible = TRUE; + m_State->bIsSymbolLayer = FALSE; + } + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_font_extension (WT_Font_Extension & font_extension, WT_File & file) +{ +// myTRACE("\n !! Don't know how to handle font_extension yet!! (%s/%s)", +// font_extension.logfont_name().ascii(), font_extension.cannonical_name().ascii()); + + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_font (WT_Font & font, WT_File & file) +{ + WT_Font::default_process ( font, file); + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + + m_State->my_process_font(file.rendition().font()); + + return WT_Result::Success; +} + +// Merk op: gewone cirkels komen ook hier binnen met Ellipse.start()+65536==Ellipse.end() +WT_Result CWhip2DCImpl::my_process_Ellipse (WT_Ellipse & Ellipse, WT_File & file, WT_Boolean fill) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + //TODO: De tilt correct meenemen als hij niet orthogonaal is + // Overigens nog nooit gezien + WT_Integer32 minor=Ellipse.minor(); + WT_Integer32 major=Ellipse.major(); + WT_Logical_Point pos = Ellipse.position(); + + if (minor<0||major<0) + { // Gebeurde bij "Inventor_Engine _2D.dwf". + return WT_Result::Success; // Negeren + } + + switch (Ellipse.tilt()) + { + case 0: break; + case 32768: break; + case 16384: + case 49152: + { + int tmp=major;major=minor;minor=tmp; + break; + } + default: + if (major != minor) + myTRACE("\nNiet-ortho tilt (%d) nog niet ondersteund (%d,%d)", Ellipse.tilt(), pos.m_x, pos.m_y); + } + + double start = Ellipse.start_radian(); + double end = Ellipse.end_radian(); + double tilt = Ellipse.tilt_radian(); + +#define SC 5 + // Bij GDI hoeven de referentiepunten niet op de ellipse te liggen + // En door SC hebben we betere resolutie + WT_Logical_Point ls(pos.m_x+myRound(cos(start+tilt)*SC*major), + pos.m_y+myRound(sin(start+tilt)*SC*minor)); + WT_Logical_Point le(pos.m_x+myRound(cos(end +tilt)*SC*major), + pos.m_y+myRound(sin(end +tilt)*SC*minor)); + + CPoint s = m_State->DWFToLP(ls); + CPoint e = m_State->DWFToLP(le); + +#ifdef _DEBUG + // Toon aanhaallijnen + if (m_State->m_mul>10) + { + HPEN p2 = CreatePen (PS_DOT, 0, RGB(128,128,128)); + HPEN oldpen = (HPEN) SelectObject(m_State->myDC, p2); + + CPoint acPt = m_State->DWFToLP(pos); + m_State->Marker(acPt); + MoveToEx(m_State->myDC, s.x, s.y, (LPPOINT) NULL); + LineTo (m_State->myDC, acPt.x, acPt.y); + LineTo (m_State->myDC, e.x, e.y); + + SelectObject(m_State->myDC, oldpen); + DeleteObject(p2); + } +#endif + if ( Ellipse.start()+65536!=Ellipse.end() + && _hypot(e.x-s.x, e.y-s.y)<2.0) + { // Voorkom onbedoelde volledige cirkels als s==e door afronding + // Wel de niet-uitvergrootte versies + WT_Logical_Point ls(pos.m_x+myRound(cos(start+tilt)*major), + pos.m_y+myRound(sin(start+tilt)*minor)); + WT_Logical_Point le(pos.m_x+myRound(cos(end +tilt)*major), + pos.m_y+myRound(sin(end +tilt)*minor)); + CPoint s = m_State->DWFToLP(ls); + CPoint e = m_State->DWFToLP(le); + MoveToEx(m_State->myDC, s.x, s.y, NULL); + LineTo(m_State->myDC, e.x, e.y); + return WT_Result::Success; + } + + CPoint topleft = m_State->DWFToLP(WT_Logical_Point(pos.m_x-major, pos.m_y-minor)); + CPoint bottomright = m_State->DWFToLP(WT_Logical_Point(pos.m_x+major, pos.m_y+minor)); + if (fill) + { + SetPolyFillMode(m_State->myDC, ALTERNATE); + ::Ellipse(m_State->myDC, topleft.x, topleft.y, + bottomright.x, bottomright.y); + } + else + { + if (Ellipse.start() + 65536 == Ellipse.end()) + { + // Voorkom afrondfouten. ::Ellipse zou gaan vullen + e=s; + } + SetArcDirection(m_State->myDC, AD_COUNTERCLOCKWISE); + Arc(m_State->myDC, topleft.x, topleft.y, + bottomright.x, bottomright.y, + s.x, s.y, e.x, e.y); + } + + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_filledEllipse (WT_Filled_Ellipse & filledEllipse, WT_File & file) +{ + return my_process_Ellipse(filledEllipse, file, TRUE); +} + +WT_Result CWhip2DCImpl::my_process_outlineEllipse (WT_Outline_Ellipse & outlineEllipse, WT_File & file) +{ + return my_process_Ellipse(outlineEllipse, file, FALSE); +} + +CString CWhip2DCImpl::PolyToMap(WT_Polygon & polygon, + WT_Object_Node node, WT_URL URL, + CWhip2DCState *m_State) +{ + CString objKey = node.object_node_name().ascii(); // Zo doen wij dat namelijk + + CString ptList; + double opp = CSLNKContourImpl::DWFArea(polygon)*m_State->m_mul*m_State->m_mul; + if (abs(opp) < 10) // Clientside minder dan 10 pixels + { + myTRACE("\nSkipping oppervlakte %.6f", opp); + return ""; + } + + for (int i = 0; i < polygon.count(); i++) + { + CPoint pt = m_State->DWFToLP(polygon.points()[i]); + LPtoDP(m_State->myDC, &pt, 1); + CString s; + s.Format("%s,%d,%d", ptList, pt.x, pt.y); + ptList = s; + } + ptList = ptList.Mid(1); // Eerste komma er af + + CString Coords, Title, Href; + Coords.Format("COORDS=\"%s\"", ptList); + + WT_URL_List lUrl = URL.url(); + + CString ttl; + if (lUrl.count()>0) + { + WT_URL_Item *firstURL = (WT_URL_Item *)lUrl.get_head(); + if (firstURL->address().length() == 0) + Href = ""; + else + Href.Format("HREF=\"%s\"", CString(firstURL->address().ascii())); + if (firstURL->friendly_name().is_ascii()) + ttl = firstURL->friendly_name().ascii(); + else + ttl = CStringW(firstURL->friendly_name().unicode()); + } + else + ttl = objKey; // Is dit wel zo logisch/wenselijk? + + ttl.Replace("\\n", "\n"); + Title.Format("TITLE=\"%s\"", ttl); + + CString smbl = ""; + if (m_State->bIsSymbolLayer && objKey != "") + smbl.Format("SLNKSymbolKey=\"%s\"", objKey); + + CString Builder; + Builder.Format("\n", + Coords, Title, Href, smbl); + return Builder; +}; + +WT_Result CWhip2DCImpl::my_process_polygon (WT_Polygon & polygon, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + if (m_State->m_alpha>0) // Niet geheel doorzichtig + { + // Zo weinig mogelijk onze penExt gebruiken want die is trager. + // Voor de arcering is hij mogelijk wel nodig + HPEN pOld = (HPEN)SelectObject(m_State->myDC, m_State->m_penExt); + CPoint *vertexList = m_State->new_DWFToLP(polygon); + if (m_State->m_forceBW) // Dan nooit vullen + Polyline(m_State->myDC, vertexList, polygon.count()); + else if (m_State->m_alpha==255) // Normal polygon + Polygon(m_State->myDC, vertexList, polygon.count()); + else + m_State->AlphaPolygon(vertexList, polygon.count()); + SelectObject(m_State->myDC, pOld); + } + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_polygon_find (WT_Polygon & polygon, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + // Kijk if we het punt gevonden hebben + if (CSLNKContourImpl::PointInPolygon(m_State->DWFfindXY, polygon)) + { + m_State->foundNode = file.rendition().object_node(); + WT_Integer32 layer_num = file.rendition().layer().layer_num(); + WT_Layer *ll = file.layer_list().find_layer_from_index(layer_num); + if (ll&&ll->layer_name().ascii()) + { + myTRACE("op laag '%s'", ll->layer_name().ascii()); + m_State->foundNodeLayer = ll->layer_name().ascii(); + } + } + +#if 0 + Werkt niet goed: het (b)lijkt dat bij clipbox altijd leeg is (omdat we geen bitmap in de DC hebben?) + // Imagemap opbouwen. Alleen voor die entiteiten die (deels) in beeld zijn + WT_Logical_Box bx = polygon.bounds(&file); + CRect rc(m_State->DWFToLP(bx.minpt()), m_State->DWFToLP(bx.maxpt())); + CRect clip; + GetClipBox(m_State->myDC,&clip); + CRect res; + if (!res.IntersectRect(clip, rc)) // Niet geheel erbuiten + return WT_Result::Success; // Toch niet zichtbaar +#endif + // Achterwaarts opbouwen. Laatste getekende staat dan vooraan de Map + // en wordt als eerste gevonden + m_State->MapBuilder = PolyToMap(polygon, + file.rendition().object_node(), + file.rendition().url(), + m_State ) + m_State->MapBuilder; + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_polymarker (WT_Polymarker & polymarker, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + // TODO: Dit moet nog beter. Kleur en zo en de goede markers + //if (file.rendition().m_marker_symbol() + for (int i = 0; i < polymarker.count(); i++) + { + CPoint acPt = m_State->DWFToLP(polymarker.points()[i]); + SetPixel(m_State->myDC, acPt.x, acPt.y, RGB(128,128,128)); +#ifdef _DEBUG + m_State->Marker(acPt); +#endif + } + + return WT_Result::Success; +} + +// Wordt bijvoorbeeld gegenereerd voor ScalaSans truetype teksten die gerenderd worden +WT_Result CWhip2DCImpl::my_process_contourSet (WT_Contour_Set & contourSet, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + CPoint *vertexList = m_State->new_DWFToLP(WT_Point_Set(contourSet.total_points(), contourSet.points(), false)); + + PolyPolygon(m_State->myDC, vertexList, (int *)contourSet.counts(), contourSet.contours()); // No Alpha support + + return WT_Result::Success; +} + +// Gesignaleerd: locatie.dwf kleine roze solid cirkels +// en H_BRNDMLDR.dwf (overshoots na verkleining?) +WT_Result CWhip2DCImpl::my_process_polytriangle (WT_Polytriangle & polytriangle, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + SetPolyFillMode(m_State->myDC, ALTERNATE); + CPoint *vertexList = m_State->new_DWFToLP(WT_Point_Set(polytriangle.count(), polytriangle.points(), false)); + +// Het volgende is wel iets efficienter maar werkt niet goed omdat +// de volgorde van de punten van de triangles niet netjes een polygon vormt +// Eigenlijk moet het echter wel: wij krijgen nu een outline om iedere triangle +// wat niet de boeling is +// Polygon(m_State->myDC, vertexList, polytriangle.count()); +// return WT_Result::Success; + + //HPEN pOld = (HPEN)SelectObject(m_State->myDC, m_State->m_penExt); + for (int i = 0; i < polytriangle.count()-2; i++) + { + Polygon(m_State->myDC, vertexList+i, 3); + } + //SelectObject(m_State->myDC, pOld); + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_pngGroup4Image (WT_PNG_Group4_Image & pngGroup4Image, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + CPoint Pt1 = m_State->DWFToLP(pngGroup4Image.min_corner()); + CPoint Pt2 = m_State->DWFToLP(pngGroup4Image.max_corner()); + int dx = Pt2.x - Pt1.x; + int dy = Pt1.y - Pt2.y; + if (dx==0 || dy==0) + return WT_Result::Success; + + // Is de tekst uberhaubt zichtbaar? Laat anders maar + if (GetDeviceCaps(m_State->myDC, TECHNOLOGY) != DT_METAFILE && + GetObjectType(m_State->myDC) != OBJ_ENHMETADC) + { + CRect textRect(Pt1, Pt2); // Tikkie grof voor diagonale teksten. Better safe than sorry + + if (!RectVisible(m_State->myDC, textRect)) + return WT_Result::Success; + } + + //CString s; + //s.Format("CWhip2DCImpl::my_process_pngGroup4Image sz=%d dx=%d dy=%d", + // pngGroup4Image.data_size(), dx, dy); + //CmyTimer p(s); + +#ifdef USE_CIMAGE + HGLOBAL m_hBuffer = ::GlobalAlloc(GMEM_MOVEABLE, pngGroup4Image.data_size()); + if (m_hBuffer) + { + void* pBuffer = ::GlobalLock(m_hBuffer); + if (pBuffer) + { + CopyMemory(pBuffer, pngGroup4Image.data(), pngGroup4Image.data_size()); + + IStream* pStream = NULL; + if (::CreateStreamOnHGlobal(m_hBuffer, FALSE, &pStream) == S_OK) + { + CImage m_pBitmap; + HRESULT res = m_pBitmap.Load(pStream); + pStream->Release(); + if (SUCCEEDED(res)) + { + ::SetStretchBltMode(m_State->myDC, HALFTONE) ; + m_pBitmap.Draw(m_State->myDC, Pt1.x, Pt2.y, dx, dy); + } + } + ::GlobalUnlock(m_hBuffer); + } + ::GlobalFree(m_hBuffer); + m_hBuffer = NULL; + } + +#else + CxImage img; + + DWORD fmt = CXIMAGE_FORMAT_UNKNOWN; + switch (pngGroup4Image.format()) + { + case WD_IMAGE_GROUP4X_MAPPED_EXT_OPCODE: + { + fmt = CXIMAGE_FORMAT_UNKNOWN; + break; + } + case WD_IMAGE_GROUP4_BITONAL_EXT_OPCODE: + { + fmt = CXIMAGE_FORMAT_TIF; + break; + } + case WD_IMAGE_PNG_EXT_OPCODE: + { + fmt = CXIMAGE_FORMAT_PNG; + break; + } + } + + if (img.Decode((BYTE *) pngGroup4Image.data(), + pngGroup4Image.data_size(), + fmt)) + { + if (m_State->m_ClipWidth > 0) + { + double inchWidth = m_State->m_ClipWidth + *(pngGroup4Image.max_corner().m_x - pngGroup4Image.min_corner().m_x) + /(m_State->m_MinMax.maxpt().m_x-m_State->m_MinMax.minpt().m_x); + double dpi=double(img.GetWidth()) / inchWidth; + myDoTRACE("\nGuessing raster dpi: %d", myRound(dpi)); + } + // Forceert *niet* transparant + // Telecommunications.dwf heeft iets van transparante PNG's wat niet niets toonde + // (GDI+ deed dat wel goed) + //img.SetTransIndex(-1); + //Draw2 (b)lijkt transparantie (op zwarte achtergrond) alleen goed te doen al we achtergrond/voorgrond zetten + COLORREF keepBk = SetBkColor(m_State->myDC, RGB(255, 255, 255)); + COLORREF keepText = SetTextColor(m_State->myDC, RGB(0, 0, 0)); + + img.Draw2(m_State->myDC, Pt1.x, Pt2.y, dx, dy); + + SetBkColor(m_State->myDC, keepBk); + SetTextColor(m_State->myDC, keepText); + } + else + myDoTRACE("\nimg.Decode failed: %s", img.GetLastError()); +#endif + + return WT_Result::Success; +} + +// Wordt gebruikt voor JPG's +WT_Result CWhip2DCImpl::my_process_image (WT_Image & image, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + DWORD fmt = CXIMAGE_FORMAT_UNKNOWN; + switch (image.format()) + { + case WD_IMAGE_JPEG_EXT_OPCODE: + { + fmt = CXIMAGE_FORMAT_JPG; + break; + } + } + if (image.format() != WD_IMAGE_JPEG_EXT_OPCODE) + { + myTRACE("\nWT_Image format %d not supported", image.format()); + return WT_Result::Success; + } + + CPoint Pt1 = m_State->DWFToLP(image.min_corner()); + CPoint Pt2 = m_State->DWFToLP(image.max_corner()); + +#ifdef USE_CIMAGE + HGLOBAL m_hBuffer = ::GlobalAlloc(GMEM_MOVEABLE, image.data_size()); + if (m_hBuffer) + { + void* pBuffer = ::GlobalLock(m_hBuffer); + if (pBuffer) + { + CopyMemory(pBuffer, image.data(), image.data_size()); + + IStream* pStream = NULL; + if (::CreateStreamOnHGlobal(m_hBuffer, FALSE, &pStream) == S_OK) + { + CImage m_pBitmap; + HRESULT res = m_pBitmap.Load(pStream); + pStream->Release(); + if (SUCCEEDED(res)) + { + ::SetStretchBltMode(m_State->myDC, HALFTONE) ; + m_pBitmap.Draw(m_State->myDC, Pt1.x, Pt2.y, Pt2.x - Pt1.x, Pt1.y - Pt2.y); + } + } + //m_pBitmap = NULL; + ::GlobalUnlock(m_hBuffer); + } + ::GlobalFree(m_hBuffer); + m_hBuffer = NULL; + } + +#else + CxImage img; + + if (img.Decode((BYTE *) image.data(), + image.data_size(), + fmt)) + { + if (m_State->m_ClipWidth > 0) + { + double inchWidth = m_State->m_ClipWidth + *(image.max_corner().m_x - image.min_corner().m_x) + /(m_State->m_MinMax.maxpt().m_x-m_State->m_MinMax.minpt().m_x); + double dpi=double(img.GetWidth()) / inchWidth; + myDoTRACE("\nGuessing raster dpi: %d", myRound(dpi)); + } + + img.Draw2(m_State->myDC, Pt1.x, Pt2.y, Pt2.x - Pt1.x, Pt1.y - Pt2.y); + } + else + myTRACE("\nimg.Decode failed: %s", img.GetLastError()); +#endif + + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_polyline (WT_Polyline & polyline, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + CPoint *vertexList = m_State->new_DWFToLP(polyline); + Polyline(m_State->myDC, vertexList, polyline.count()); + + return WT_Result::Success; +} + +// Merk op dat alleen TrueType teksten hier getekend worden. +// De SHX fonts worden als losse lijnstukjes gedaan +WT_Result CWhip2DCImpl::my_process_text (WT_Text & text, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + // Van Pseudo-teksten weten we de hoogte niet. Zoeken kunnen we er ook niet mee + if (!file.rendition().visibility().visible()) + return WT_Result::Success; + + CPoint acPt = m_State->DWFToLP(text.position()); + if (m_State->m_mul==0) + { // Heel grof hoogte bepalen voor extents + WT_Logical_Point pt(text.position()); + CPoint dummy = m_State->DWFToLP(pt); + pt.m_x += file.rendition().font().height(); // Gok op één vierkante letter + pt.m_y += file.rendition().font().height(); + dummy = m_State->DWFToLP(pt); + } + + if (text.string().is_ascii()) + { +// myTRACE("\nTekst: %s", text.string().ascii()); +#ifdef _DEBUG +//if (!strcmp(text.string().ascii(),"Width scale=1024 (1x)")) +if (!strcmp(text.string().ascii(),"TP036")) +{ + int x = 1; +} +#endif + CString txt(text.string().ascii()); + if (txt.Trim().GetLength() == 0) // Komt voor bij outlets van AC_C2_0 + return WT_Result::Success; // voorkom geeking + + if (text.bounds().bounds() != NULL) + { + return m_State->drawBoundText(text, file); + } + + // Vervang heel kleine teksten door een simpel gekleurd vlakje als het kan. + // Is een stuk sneller + // Helaas lijkt schuine true-type tekst (bemating) niet altijd bounds te hebben? + // ==>Maar vertikale wel + if (file.rendition().font().height()*m_State->m_mul < m_State->geekFontSize) + { + m_State->DrawGeekText(text); + return WT_Result::Success; + } + else + m_State->m_kfm.TextOutSpacing(m_State->myDC, acPt.x, acPt.y, + text.string().ascii(), text.string().length(), + (m_State->m_spacing/1024.0)); + //TextOut(m_State->myDC, acPt.x, acPt.y, text.string().ascii(), text.string().length()); + } + else + { + if (file.rendition().font().height()*m_State->m_mul >= 0.5) + TextOutW(m_State->myDC, acPt.x, acPt.y, text.string().unicode(), text.string().length()); + } + +#ifdef _DEBUG + if (m_State->m_mul > 0.1) + m_State->Marker(acPt); +#endif + + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_text_scan (WT_Text & text, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + CString txt(text.string().ascii()); + if (txt.Trim().GetLength() == 0) // Komt voor bij outlets van AC_C2_0 + return WT_Result::Success; + + CFoundText tFound; + tFound.m_FoundText = text; + WT_Integer32 layer_num = file.rendition().layer().layer_num(); + WT_Layer *ll = file.layer_list().find_layer_from_index(layer_num); + if (ll&&ll->layer_name().ascii()) + tFound.m_FoundLayer = ll->layer_name().ascii(); + tFound.m_FoundAt = text.position(); + + m_State->m_FoundTexts.Add(tFound); + + return WT_Result::Success; +} + +#pragma optimize( "p", on ) +WT_Result CWhip2DCImpl::my_process_text_find (WT_Text & text, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + if (!file.rendition().visibility().visible()) + return WT_Result::Success; + + CPoint acPt = m_State->DWFToLP(text.position()); + + if (!text.string().is_ascii()) // Die kunnen we nog niet aan + return WT_Result::Success; + + BOOL found = FALSE; + CPoint LPbounds[4]; // Het echte testen gaan we in LP-coordinaten doen + // (Mooie tussenweg tussen DP en DWF) + + double radian = 0.0; // Graden rotatie + // Echte boundingbox heeft voorkeur + if (text.bounds().bounds() != NULL) + { + CPoint pts[]= + { + m_State->DWFToLP(text.bounds().bounds()[0]), + m_State->DWFToLP(text.bounds().bounds()[1]), + m_State->DWFToLP(text.bounds().bounds()[2]), + m_State->DWFToLP(text.bounds().bounds()[3]) + }; + memcpy(LPbounds, pts, 4*sizeof(CPoint)); + //myTRACE("\nZoeken met behulp van text bounds %s", text.string().ascii()); + } + else + { + CSize LPSize(0,0); + + if (text.string().is_ascii()) + { + double w,h; + m_State->m_kfm.GetTextExtent(m_State->myDC, text.string().ascii(), text.string().length(), w, h); + // TODO: De .6 snap ik nog niet maar anders is de box te groot + LPSize = CPoint((int)w, (int)(h*0.6)); + //GetTextExtentPoint32(m_State->myDC, text.string().ascii(), text.string().length(), &LPSize); + } +// else +// GetTextExtentPoint32W(m_State->myDC, text.string().unicode(), text.string().length(), &Size); + + CPoint pts[]= + { + acPt, + CPoint(acPt.x+LPSize.cx, acPt.y), + CPoint(acPt.x+LPSize.cx, acPt.y-LPSize.cy), + CPoint(acPt.x , acPt.y-LPSize.cy) + }; + radian = m_State->m_logfont.lfOrientation * TWO_PI / 3600; + memcpy(LPbounds, pts, 4*sizeof(CPoint)); + } + + // In plaats van onze box 'goed' draaien gaan we ons testpunt 'fout' draaien. Is simpeler + CPoint dist(m_State->LPfindXY - acPt); + CPoint fnd(acPt); + +// Compiler bug? De volgende regels deden het niet goed in release mode: +// fnd.y werd gewoon niet aangepast +// Opgelost door voor deze functie #pragma optimize( "p", on ) te zetten + fnd.x += int(cos(radian) * dist.x - sin(radian) * dist.y); + fnd.y += int(sin(radian) * dist.x + cos(radian) * dist.y); + + if (CSLNKContourImpl::PointInPolygon(fnd, LPbounds, 4)) + { + m_State->foundTextLabel = text.string().ascii(); +// myTRACE("\nVolgens mij geklikt binnen (%d-%d,%d-%d) op '%s'", acPt.x, acPt.y, acPt.x+Size.cx, acPt.y+Size.cy, text.string().ascii()); + WT_Integer32 layer_num = file.rendition().layer().layer_num(); + WT_Layer *ll = file.layer_list().find_layer_from_index(layer_num); + if (ll&&ll->layer_name().ascii()) + { + myTRACE("op laag '%s'", ll->layer_name().ascii()); + m_State->foundTextLayer = ll->layer_name().ascii(); + } + } + + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_background (WT_Background & background, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (m_State->m_forcePaper) // Wissen is al wel gedaan + return WT_Result::Success; + + WT_RGBA32 clr; + if (background.color().index() == WD_NO_COLOR_INDEX) + clr = background.color().rgba(); + else + clr = file.rendition().color_map().map(background.color().index()); + + COLORREF DCclr = RGB(clr.m_rgb.r, clr.m_rgb.g, clr.m_rgb.b); + + m_State->m_paperColor = DCclr; // Wordt later misschien opgevraagd. + + if (m_State->findIt) // When finding no need for actuel painting + return WT_Result::Success; + + m_State->erasePaper(file); + + return WT_Result::Success; +} + +// poor mans Gouraud shading +#if 0 +COLORREF avgColor (WT_Gouraud_Point_Set & gouraudPointSet) +{ + int r=0,g=0,b=0; + for (int i = 0; i < gouraudPointSet.count(); i++) + { + WT_RGBA32 clr = gouraudPointSet.colors()[i]; + r+=clr.m_rgb.r; + g+=clr.m_rgb.g; + b+=clr.m_rgb.b; + } + COLORREF DCclr; + DCclr = RGB(r/gouraudPointSet.count(), + g/gouraudPointSet.count(), + b/gouraudPointSet.count()); + return DCclr; +} + +void shadedline (int x1, int firstcolor, int x2, int lastcolor, int y) +{ +int length; +int numcolors; +int colorvalue; +int step; +int x; + + length = x2 - x1 + 1; + if (length > 0) + { + numcolors = lastcolor - firstcolor + 1; + + colorvalue = firstcolor << 8; + step = ((long)numcolors << 8) / (long)length; + for (x = x1; x <= x2; x++) + { + drawpixel (x, y, colorvalue >> 8); + colorvalue += step; + } + } +} +#endif + +WT_Result CWhip2DCImpl::my_process_gouraudPolyline (WT_Gouraud_Polyline & gouraudPolyline, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + //myTRACE("\n !! Don't know how to handle gouraudPolyline very well yet!! (%d points)", gouraudPolyline.count()); + +#if 1 + int w=myRound(file.rendition().line_weight().weight_value()*m_State->m_mul); + + WT_RGBA32 prev_clr; + CPoint prev_pt; + for (int i = 0; i < gouraudPolyline.count(); i++) + { + WT_RGBA32 clr = gouraudPolyline.colors()[i]; + CPoint pt = m_State->DWFToLP(gouraudPolyline.points()[i]); + if (i > 0) + { + //int dv = myRound(_hypot(pt.x-prev_pt.x,pt.y-prev_pt.y) / 10); // Om de 10 pixels is goed zat + int dv = 10; // Toch maar altijd 10 stuks + + int j; + for (j = 0; j < dv; j++) + { + COLORREF DCclr = RGB((clr.m_rgb.r*j + prev_clr.m_rgb.r*(dv-j))/dv, + (clr.m_rgb.g*j + prev_clr.m_rgb.g*(dv-j))/dv, + (clr.m_rgb.b*j + prev_clr.m_rgb.b*(dv-j))/dv); + m_State->m_pen = CreatePen (PS_SOLID, w, DCclr); + HPEN oldpen = (HPEN) SelectObject(m_State->myDC, m_State->m_pen); + DeleteObject(oldpen); + LineTo(m_State->myDC, myRound(((double)pt.x*j+prev_pt.x*(dv-j))/dv), + myRound(((double)pt.y*j+prev_pt.y*(dv-j))/dv)); + } + } + else + MoveToEx(m_State->myDC, pt.x, pt.y, NULL); + prev_pt = pt; + prev_clr = clr; + } + + return WT_Result::Success; +#endif + +#if 0 + COLORREF DCclr = RGB(0,0,0); + DCclr = avgColor(gouraudPolyline); + + int w=myRound(file.rendition().line_weight().weight_value()*m_State->m_mul); + m_State->m_pen = CreatePen (PS_SOLID, w, DCclr); + HPEN oldpen = (HPEN) SelectObject(m_State->myDC, m_State->m_pen); + DeleteObject(oldpen); + + CPoint *vertexList = m_State->new_DWFToLP(gouraudPolyline); + Polyline(m_State->myDC, vertexList, gouraudPolyline.count()); + return WT_Result::Success; +#endif + +#if 0 + // TODO: Dit is natuurlijk gewoon een gedegenereerde gouraudPolytriangle! + // maar die lijkt GradientFill niet te tekenen? + // Waarschijnlijk: "Triangle drawing is lower-right exclusive" + TRIVERTEX *vert = new TRIVERTEX[2*gouraudPolyline.count()]; + GRADIENT_TRIANGLE *gTri = new GRADIENT_TRIANGLE[gouraudPolyline.count()]; + for (int i = 0; i < gouraudPolyline.count(); i++) + { + WT_RGBA32 clr = gouraudPolyline.colors()[i]; + vert[2*i].x = m_State->DWFToLP(gouraudPolyline.points()[i]).x; + vert[2*i].y = m_State->DWFToLP(gouraudPolyline.points()[i]).y; + // Pas op: TRIVERTEX verwacht 16 bit RGB! + vert[2*i].Red = clr.m_rgb.r<<8; + vert[2*i].Green = clr.m_rgb.g<<8; + vert[2*i].Blue = clr.m_rgb.b<<8; + vert[2*i+1].x = m_State->DWFToLP(gouraudPolyline.points()[i]).x; + vert[2*i+1].y = m_State->DWFToLP(gouraudPolyline.points()[i]).y+1; + // Pas op: TRIVERTEX verwacht 16 bit RGB! + vert[2*i+1].Red = clr.m_rgb.r<<8; + vert[2*i+1].Green = clr.m_rgb.g<<8; + vert[2*i+1].Blue = clr.m_rgb.b<<8; + vert[i].Alpha = clr.m_rgb.a<<8; + gTri[i].Vertex1 = 2*i; + gTri[i].Vertex2 = 2*(i+1); + gTri[i].Vertex3 = 2*(i+1)+1; + } + GradientFill(m_State->myDC,vert,2*gouraudPolyline.count(), + gTri,gouraudPolyline.count()-2,GRADIENT_FILL_TRIANGLE); + delete [] vert; + delete [] gTri; +#endif + return WT_Result::Success; +} + +WT_Result CWhip2DCImpl::my_process_gouraudPolytriangle (WT_Gouraud_Polytriangle & gouraudPolytriangle, WT_File & file) +{ + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + if (!m_State->bLayerVisible) + return WT_Result::Success; + + TRIVERTEX *vert = new TRIVERTEX[gouraudPolytriangle.count()]; + GRADIENT_TRIANGLE *gTri = new GRADIENT_TRIANGLE[gouraudPolytriangle.count()]; + for (int i = 0; i < gouraudPolytriangle.count(); i++) + { + WT_RGBA32 clr = gouraudPolytriangle.colors()[i]; + vert[i].x = m_State->DWFToLP(gouraudPolytriangle.points()[i]).x; + vert[i].y = m_State->DWFToLP(gouraudPolytriangle.points()[i]).y; + // Pas op: TRIVERTEX verwacht 16 bit RGB! + vert[i].Red = clr.m_rgb.r<<8; + vert[i].Green = clr.m_rgb.g<<8; + vert[i].Blue = clr.m_rgb.b<<8; + vert[i].Alpha = clr.m_rgb.a<<8; + gTri[i].Vertex1 = i; + gTri[i].Vertex2 = i+1; + gTri[i].Vertex3 = i+2; + } + // Zal geloof ik niet werken op Windows 95... + GradientFill(m_State->myDC,vert,gouraudPolytriangle.count(), + gTri,gouraudPolytriangle.count()-2,GRADIENT_FILL_TRIANGLE); + delete [] vert; + delete [] gTri; + return WT_Result::Success; +} + + +WT_Result CWhip2DCImpl::my_process_fillPattern (WT_Fill_Pattern & fillPattern, WT_File & file) +{ + WT_Fill_Pattern::default_process(fillPattern, file); + file.rendition().fill_pattern() = fillPattern; // Dit doet de default niet (goed)!! + + CWhip2DCState *m_State = (CWhip2DCState *)file.heuristics().user_data(); + + m_State->ColorPenAndBrush(file); + + return WT_Result::Success; +} + +STDMETHODIMP CWhip2DCImpl::get_LayerCount(LONG* pVal) +{ + (*pVal) = (LONG)m_State.m_Layernames.GetCount(); + + return S_OK; +} + +STDMETHODIMP CWhip2DCImpl::get_TextCount(LONG* pVal) +{ + (*pVal) = (LONG)m_State.m_FoundTexts.GetCount(); + + return S_OK; +} + + +STDMETHODIMP CWhip2DCImpl::get_TextItem(LONG i, CFoundText &pVal) +{ + if (i<0 || i>=(LONG)m_State.m_FoundTexts.GetCount()) + return E_INVALIDARG; + + pVal = m_State.m_FoundTexts.GetAt(i); + return S_OK; +} + +STDMETHODIMP CWhip2DCImpl::get_LayerItem(LONG i, CString* pVal) +{ + if (i<0 || i>=(LONG)m_State.m_Layernames.GetCount()) + return E_INVALIDARG; + + (*pVal) = m_State.m_Layernames.GetAt(i); + return S_OK; +} + +STDMETHODIMP CWhip2DCImpl::get_paperColor(LONG* pVal) +{ + (*pVal) = m_State.m_paperColor; + + return S_OK; +} + +STDMETHODIMP CWhip2DCImpl::put_paperColor(LONG newVal) +{ + m_State.m_forcePaper = true; + m_State.m_paperColor = newVal; + + return S_OK; +} + +STDMETHODIMP CWhip2DCImpl::ReplaceColor(LONG paperColor, LONG oldColor, LONG newColor) +{ + m_State.m_replaceColors[paperColor] = CFromTo(oldColor, newColor); + + return S_OK; +} diff --git a/SlnkDWFImpl/Whip2DCImpl.h b/SlnkDWFImpl/Whip2DCImpl.h new file mode 100644 index 0000000..de72a59 --- /dev/null +++ b/SlnkDWFImpl/Whip2DCImpl.h @@ -0,0 +1,150 @@ +// Whip2DC.h : Declaration of the CWhip2DC + +#pragma once +#include "resource.h" // main symbols + +#include "mywt_file.h" + +#include "whip2dcState.h" +#include "myEPlotSectionImpl.h" + +#ifdef USE_CIMAGE +#include "atlimage.h" +#endif + +// CWhip2DC + +typedef BOOL (* WHIP2DC_Progress_Action) (void *param, double progress); + +class CWhip2DCImpl +{ +public: + CWhip2DCImpl() + { + m_progress_action = NULL; + m_progress_param = NULL; + } + +public: + +protected: + WT_String m_WhipPath; + CEPlotSectionImpl *m_iEPlotSection; + + CWhip2DCState m_State; +#ifdef USE_CIMAGE + // Dummy globale CImage aanhouden zodat CImage::count > 0 blijft + // en GDIShutdown niet te vaak wordt aan geroepen. Scheelt fors bij + // Telecommunications.dwf met 3000 PNG objectjes + CImage m_pBitmapDummy; +#endif + + WT_Result read_dwf_for_extracting_Objects(myWT_File &my_input_file, BOOL findIt); + + static CString PolyToMap(WT_Polygon & polygon, WT_Object_Node node, WT_URL URL, CWhip2DCState *m_State); + + static WT_Result my_process_author (WT_Author & author, WT_File & file); + static WT_Result my_process_creator (WT_Creator & creator, WT_File & file); + static WT_Result my_process_created (WT_Creation_Time & created, WT_File & file); + static WT_Result my_process_modified (WT_Modification_Time & modified, WT_File & file); + static WT_Result my_process_sourceFilename (WT_Source_Filename & sourceFilename, WT_File & file); + static WT_Result my_process_sourceCreationTime (WT_Source_Creation_Time & sourceCreated, WT_File & file); + static WT_Result my_process_sourceModificationTime (WT_Source_Modification_Time & sourceModified, WT_File & file); + static WT_Result my_process_units (WT_Units & units, WT_File & file); + static WT_Result my_process_embed (WT_Embed & embed, WT_File & file); + static WT_Result my_process_namedView (WT_Named_View & namedView, WT_File & file); + static WT_Result my_process_view (WT_View & view, WT_File & file); + static WT_Result my_process_plotInfo (WT_Plot_Info & plotInfo, WT_File & file); + static WT_Result my_process_background (WT_Background & background, WT_File & file); + static WT_Result my_process_color (WT_Color & color, WT_File & file); + static WT_Result my_process_lineWeight (WT_Line_Weight & lineWeight, WT_File & file); + static WT_Result my_process_lineStyle (WT_Line_Style & lineStyle, WT_File & file); + static WT_Result my_process_linePattern (WT_Line_Pattern & linePattern, WT_File & file); + static WT_Result my_process_layer (WT_Layer & layer, WT_File & file); + static WT_Result my_process_viewport (WT_Viewport & viewport, WT_File & file); + static WT_Result my_process_visibility (WT_Visibility & visibility, WT_File & file); + static WT_Result my_process_codePage (WT_Code_Page & codePage, WT_File & file); + static WT_Result my_process_colorMap (WT_Color_Map & colorMap, WT_File & file); + static WT_Result my_process_comments (WT_Comments & comments, WT_File & file); + static WT_Result my_process_contourSet (WT_Contour_Set & contourSet, WT_File & file); + static WT_Result my_process_copyright (WT_Copyright & copyright, WT_File & file); + static WT_Result my_process_dashPattern (WT_Dash_Pattern & dashPattern, WT_File & file); + static WT_Result my_process_description (WT_Description & description, WT_File & file); + static WT_Result my_process_fill (WT_Fill & fill, WT_File & file); + static WT_Result my_process_font (WT_Font & font, WT_File & file); + static WT_Result my_process_font_extension (WT_Font_Extension & font_extension, WT_File & file); + static WT_Result my_process_gouraudPolyline (WT_Gouraud_Polyline & gouraudPolyline, WT_File & file); + static WT_Result my_process_gouraudPolytriangle (WT_Gouraud_Polytriangle & gouraudPolytriangle, WT_File & file); + static WT_Result my_process_image (WT_Image & image, WT_File & file); + static WT_Result my_process_keywords (WT_Keywords & keywords, WT_File & file); + static WT_Result my_process_markerSize (WT_Marker_Size & markerSize, WT_File & file); + static WT_Result my_process_markerSymbol (WT_Marker_Symbol & markerSymbol, WT_File & file); + static WT_Result my_process_namedViewList (WT_Named_View_List & namedViewList, WT_File & file); + static WT_Result my_process_origin (WT_Origin & origin, WT_File & file); + static WT_Result my_process_Ellipse (WT_Ellipse & Ellipse, WT_File & file, WT_Boolean fill); + static WT_Result my_process_filledEllipse (WT_Filled_Ellipse & filledEllipse, WT_File & file); + static WT_Result my_process_outlineEllipse (WT_Outline_Ellipse & outlineEllipse, WT_File & file); + static WT_Result my_process_polygon (WT_Polygon & polygon, WT_File & file); + static WT_Result my_process_polygon_find (WT_Polygon & polygon, WT_File & file); + static WT_Result my_process_polymarker (WT_Polymarker & polymarker, WT_File & file); + static WT_Result my_process_polytriangle (WT_Polytriangle & polytriangle, WT_File & file); + static WT_Result my_process_projection (WT_Projection & projection, WT_File & file); + static WT_Result my_process_subject (WT_Subject & subject, WT_File & file); + static WT_Result my_process_title (WT_Title & title, WT_File & file); + static WT_Result my_process_unknown (WT_Unknown & unknown, WT_File & file); + static WT_Result my_process_url (WT_URL & url, WT_File & file); + static WT_Result my_process_pngGroup4Image (WT_PNG_Group4_Image & pngGroup4Image, WT_File & file); + static WT_Result my_process_polyline (WT_Polyline & polyline, WT_File & file); + static WT_Result my_process_text (WT_Text & text, WT_File & file); + static WT_Result my_process_text_find (WT_Text & text, WT_File & file); + static WT_Result my_process_text_scan (WT_Text & text, WT_File & file); + static WT_Result my_process_inkedArea (WT_Inked_Area & inkedArea, WT_File & file); + static WT_Result my_process_plotOptimized (WT_Plot_Optimized & plotOptimized, WT_File & file); + static WT_Result my_process_groupBegin (WT_Group_Begin & groupBegin, WT_File & file); + static WT_Result my_process_groupEnd (WT_Group_End & groupEnd, WT_File & file); + + static WT_Result my_process_embeddedFont (WT_Embedded_Font & embeddedFont, WT_File & file); + static WT_Result my_process_trustedFontList (WT_Trusted_Font_List & tustedFontList, WT_File & file); + static WT_Result my_process_blockref (WT_BlockRef & blockref, WT_File & file); + static WT_Result my_process_blockMeaning (WT_Block_Meaning & blockMeaning, WT_File & file); + static WT_Result my_process_encryption (WT_Encryption & encryption, WT_File & file); + static WT_Result my_process_orientation (WT_Orientation & orientation, WT_File & file); + static WT_Result my_process_alignment (WT_Alignment & alignment, WT_File & file); + static WT_Result my_process_password (WT_Password & password, WT_File & file); + static WT_Result my_process_guid (WT_Guid & guid, WT_File & file); + static WT_Result my_process_fileTime (WT_FileTime & fileTime, WT_File & file); + static WT_Result my_process_userData (WT_UserData & userData, WT_File & file); + static WT_Result my_process_penPattern (WT_Pen_Pattern & penPattern, WT_File & file); + static WT_Result my_process_fillPattern (WT_Fill_Pattern & fillPattern, WT_File & file); + static WT_Result my_process_DigitalSign (WT_SignData & digitalSing, WT_File & file); + static WT_Result my_process_dwf_header (WT_DWF_Header & dwf_header, WT_File & file); + + WHIP2DC_Progress_Action m_progress_action; + void * m_progress_param; +public: + STDMETHOD(Load)(HDC hDC, CEPlotSectionImpl *EPlotSection, const CString &WhipPath, + const CString &RegExp, long sizeX, long sizeY, + VARIANT_BOOL centerImage, VARIANT_BOOL maximize=FALSE, + double dwgScale=0.0); + STDMETHOD(Paint)(VARIANT_BOOL forceBW); + STDMETHOD(Find)(LONG findX, LONG findY, BYTE AsMap, + CString &pContourLabel, CString &pContourLayer, + CString &pTextLabel, CString &pTextLayer); + STDMETHOD(FindTexts) (const CString &findText); + STDMETHOD(DPtoDWG)(LONG findX, LONG findY, DOUBLE* resX, DOUBLE* resY); + STDMETHOD(DWGExtents)(DOUBLE* resminX, DOUBLE* resminY, DOUBLE* resmaxX, DOUBLE* resmaxY); + STDMETHOD(get_LayerCount)(LONG* pVal); + STDMETHOD(get_LayerItem)(LONG i, CString* pVal); + STDMETHOD(get_TextCount)(LONG* pVal); + STDMETHOD(get_TextItem)(LONG i, CFoundText &pVal); + STDMETHOD(get_paperColor)(LONG* pVal); + STDMETHOD(put_paperColor)(LONG newVal); + STDMETHOD(ReplaceColor)(LONG paperColor, LONG oldColor, LONG newColor); + CSize &get_Size(); + + void set_progress_action(WHIP2DC_Progress_Action action, void * param) + { + m_progress_action = action; + m_progress_param = param; + }; +}; diff --git a/SlnkDWFImpl/Whip2DCState.cpp b/SlnkDWFImpl/Whip2DCState.cpp new file mode 100644 index 0000000..f08c0f3 --- /dev/null +++ b/SlnkDWFImpl/Whip2DCState.cpp @@ -0,0 +1,774 @@ +#include "StdAfx.h" +#include "Whip2dcState.h" +#include "SLNKContourImpl.h" +#include + +#ifndef PI + #define PI 3.141592653589793f +#endif + +CWhip2DCState::CWhip2DCState() +{ + Reset(); +} + +void CWhip2DCState::Reset() +{ + m_vertexList_size=100; // Aardig begin + m_vertexList = new CPoint[m_vertexList_size]; + bLayerVisible = TRUE; // When no layers at all + bIsSymbolLayer = FALSE; + + findIt = FALSE; + m_ClipWidth = -1; + m_ClipHeight = -1; + m_mul = 0; // Signal invalid + m_MinMax = WT_Logical_Box(INT_MAX, INT_MAX, INT_MIN, INT_MIN); // Signal invalid + memset(&m_logfont, 0, sizeof(LOGFONT)); // clear out structure. + m_spacing = 1024; + m_height = 1024; + m_hrgn = NULL; + m_font = NULL; + m_forcePaper = false; + m_Maximize = false; +} + +CWhip2DCState::~CWhip2DCState() +{ + myTRACE("\nVertextlist eindigde op: %d", m_vertexList_size); + delete [] m_vertexList; +} + +void CWhip2DCState::erasePaper (WT_File & file) +{ + HBRUSH tempBrush = CreateSolidBrush(m_paperColor); + HBRUSH oldbrush = (HBRUSH) SelectObject(myDC,tempBrush); + + CRect rc; + + GetClipBox(myDC,&rc); + FillRect(myDC,rc,tempBrush); + + SelectObject(myDC,oldbrush); + DeleteObject(tempBrush); + + SetBkColor(myDC, m_paperColor); + ColorPenAndBrush(file); // Eventuele toggle wit<-->zwart +} + +CPoint *CWhip2DCState::new_DWFToLP(WT_Point_Set const &pts) +{ + if (m_vertexList_sizeDingbats + } + m_logfont.lfOutPrecision = OUT_DEFAULT_PRECIS; + m_logfont.lfClipPrecision = CLIP_DEFAULT_PRECIS; + m_logfont.lfQuality = NONANTIALIASED_QUALITY; // Nooit cleartype o.i.d. + //m_logfont.lfQuality = DEFAULT_QUALITY; + if (fd & (WT_Font::FONT_PITCH_BIT || WT_Font::FONT_FAMILY_BIT)) + m_logfont.lfPitchAndFamily = pitch_and_family; + m_logfont.lfPitchAndFamily |= TMPF_TRUETYPE; + + if (fd & WT_Font::FONT_NAME_BIT) + { + char* facename = new char[font.font_name().name().length()+1]; + strcpy(facename, font.font_name().name().ascii()); + memset(m_logfont.lfFaceName,0,LF_FACESIZE*sizeof(char)); + strncpy(m_logfont.lfFaceName,facename,LF_FACESIZE); + delete [] facename; + } + +int keep=m_logfont.lfOrientation; +if (findIt || m_height*m_mul < geekFontSize + ) // Dan doen we hier toch niets met de rotatie. Hoogte/breedte moeten we wel hebben +{ + m_logfont.lfOrientation = 0; + m_logfont.lfEscapement = 0; // Moet bijna altijd gelijk zijn +} + HFONT oldfont1 = m_font; + m_font = CreateFontIndirect(&m_logfont); + ATLASSERT(m_font); + HFONT oldfont = (HFONT) SelectObject(myDC, m_font); + ATLASSERT(oldfont); + + DeleteObject(oldfont); + DeleteObject(oldfont1); + + // Alleen TrueType texten reageren op Orientation + // Voor heel kleine fontgroottes wordt wel een 'Ms Sans Serif' of 'Small fonts' gekozen + // door CreateFontIndirect + // Daarom hier vooralsnog TrueType forceren door Arial te benoemen. + // TODO: Alleen als orientation <> 0 + // TODO: TextFormatter ook voor niet TrueType teksten laten werken +#ifdef _DEBUG + OUTLINETEXTMETRIC otm[3]; // big enough for the strings + if ( GetOutlineTextMetrics(myDC, sizeof(otm), otm)==0 ) + { + // ATLASSERT(FALSE); // Waarschijnlijk klein font dat geen TrueType is + } +#endif + if (GetDeviceCaps(myDC, TECHNOLOGY) != DT_METAFILE) // Daar werkt dit niet voor + { + TEXTMETRIC tm; + BOOL x = GetTextMetrics(myDC, &tm); + ATLASSERT(x); + + char szFaceName[LF_FULLFACESIZE]; + GetTextFace (myDC, LF_FULLFACESIZE, szFaceName) ; + + if (!(TMPF_TRUETYPE & tm.tmPitchAndFamily)) + { + HFONT oldfont1 = m_font; + strcpy(m_logfont.lfFaceName, "Arial"); // Probeer het nog eens met een echte TrueType + m_font = CreateFontIndirect(&m_logfont); + ATLASSERT(m_font); + HFONT oldfont = (HFONT) SelectObject(myDC, m_font); + ATLASSERT(oldfont); + + DeleteObject(oldfont); + DeleteObject(oldfont1); + } + } + + m_logfont.lfOrientation = keep; // Wel terugzetten voor findIt want er wordt nog wel mee gerekend + m_logfont.lfEscapement = keep; + + //if (!hfont || hfont == INVALID_HANDLE_VALUE) + if (!m_kfm.Setup(myDC, m_font, m_height*m_mul)) + { // Waarschijnlijk rasterfont? Zo ver mag het hier niet meer komen? + myTRACE("\nGetOutlineTextMetrics faalde: !!!"); + } + return WT_Result::Success; +} + + +// Soms worden de bounds meegegeven. Die gelden heel sterk +// Ze forceren de rotatie en afmetingen +// De hoogte doen we door een goede fontgrootte te kiezen +// De breedte doen we door de spacing te varieren +WT_Result CWhip2DCState::drawBoundText (WT_Text & text, WT_File & file) +{ + // Vervang heel kleine teksten door een simpel gekleurd vlakje als het kan. + // Is een stuk sneller + // Helaas lijkt schuine true-type tekst (bemating) niet altijd bounds te hebben? + // ==>Maar vertikale wel + if (file.rendition().font().height()*m_mul < geekFontSize) + { + CPoint *vertexList = new_DWFToLP(WT_Polygon(4, text.bounds().bounds(), FALSE)); + DrawGeekBox(vertexList, 4); + return WT_Result::Success; + } +#ifdef _DEBUG + if (m_mul > 0.1) + Marker(DWFToLP(text.bounds().bounds()[0])); +#endif + +#ifdef xxxxDEBUG + SetPolyFillMode(myDC, ALTERNATE); + CPoint *vertexList = new_DWFToLP(WT_Polygon(4, text.bounds().bounds(), FALSE)); + Polyline(myDC, vertexList, 4); + //return WT_Result::Success; +#endif + + CPoint p0(DWFToLP(text.bounds().bounds()[0])); + CPoint p1(DWFToLP(text.bounds().bounds()[1])); + CPoint p2(DWFToLP(text.bounds().bounds()[2])); + CPoint p3(DWFToLP(text.bounds().bounds()[3])); + + // Is de tekst uberhaubt zichtbaar? Laat anders maar + if (GetDeviceCaps(myDC, TECHNOLOGY) != DT_METAFILE && + GetObjectType(myDC) != OBJ_ENHMETADC) + { + CRect textRect(p0, p2); // Tikkie grof voor diagonale teksten. Better safe than sorry + + if (!RectVisible(myDC, textRect)) + return WT_Result::Success; + } + + // dx, dy van de onderlijn bepaalt rotatie + int dx=(p1.x-p0.x), dy=(p0.y-p1.y); + double angle; + if (dx==0) + angle = (dy>0?TWO_PI:-TWO_PI)/4.0; + else + angle = atan((double)dy/dx); + + int rotation = myRound(3600*angle/TWO_PI); + int keep_rotation = m_logfont.lfOrientation; + int keep_height = m_logfont.lfHeight; + int keep_width = m_logfont.lfWidth; + + double w = _hypot(dx,dy); // sqrt((double)dx*dx+dy*dy); + dx=(p3.x-p0.x), dy=(p0.y-p3.y); + double h = _hypot(dx,dy); // sqrt((double)dx*dx+dy*dy); + + // Hoe groot wordt hij als ik niets bijzonders doe? + SIZE sz; + GetTextExtentPoint32(myDC,text.string().ascii(), text.string().length(), &sz); + + // grootte correctie + double wScale = w/sz.cx; + double hScale = h/sz.cy; +//myTRACE("\nlfh=%d, hscl=%.3f,wscl=%.3f h=%.1f w=%.1f cy=%d cx=%d %s", m_logfont.lfHeight, hScale, wScale, h, w, sz.cy, sz.cx, text.string().ascii()); + + // Nauwkeuriger fontbepalen + m_logfont.lfHeight = myRound(m_logfont.lfHeight * hScale); + // TODO: Indien mogelijk nauwkeuriger benaderen met lfWidth? + // Is nodig voor SPCA tekst rechtsboven. Widthscale 1.5 en ook bounds + TEXTMETRIC tm; + if (m_logfont.lfWidth == 0) + { + if ( GetTextMetrics(myDC, &tm) !=0 ) + { // Rationale: Hierboven is lfHeight nog vergroot met hScale + // Anderzijds moeten we corrigeren voor wScale/hScale + // tm.tmAveCharWidth * hScale * (wScale/hScale) reduceert tot: + m_logfont.lfWidth = myRound(tm.tmAveCharWidth * wScale); + } + } + else + m_logfont.lfWidth = myRound(m_logfont.lfWidth * wScale); + + // Ook nu corrigeren voor rotatie + m_logfont.lfOrientation = rotation; + m_logfont.lfEscapement = rotation; // Moet bijna altijd gelijk zijn + + HFONT temp_font = CreateFontIndirect(&m_logfont); // Voor de rotatie en nieuwe hoogte + HFONT old_font = (HFONT) SelectObject(myDC, temp_font); + + // Hoe groot wordt hij nu? + GetTextExtentPoint32(myDC,text.string().ascii(), text.string().length(), &sz); + // grootte correctie + wScale = w/sz.cx; + hScale = h/sz.cy; + + SetTextAlign(myDC,TA_LEFT|TA_BOTTOM); + +//myTRACE("\nlfh=%d, hscl=%.3f,wscl=%.3f h=%.1f w=%.1f cy=%d cx=%d %s", m_logfont.lfHeight, hScale, wScale, h, w, sz.cy, sz.cx, text.string().ascii()); +int errH = myRound(h-sz.cy); +int errW = myRound(w-sz.cx); +//myTRACE("\nAfwijking: h=%d w=%d", errH, errW); + if (abs(errW) <= 1) // Goedkoopste variant (errH doen we toch niets meer mee) + { + TextOut(myDC, p0.x, p0.y, + text.string().ascii(), text.string().length()); // Efficienter en fraaier +// myTRACE("->Normal"); + } + else + { // Spacing aanpassen +// if (!strcmp(text.string().ascii(), "02-06-1L18")) +// DebugBreak(); + m_kfm.Setup(myDC, temp_font, abs(m_logfont.lfHeight)); // Voor als height gewijzigd + +// myTRACE("->Spacing"); + double dw, dh; + m_kfm.GetTextExtent(myDC, text.string().ascii(), text.string().length(), dw, dh); + m_kfm.TextOutSpacing(myDC, p0.x, myRound(p0.y-(h-sz.cy)/2.0), + text.string().ascii(), text.string().length(), w / dw); // acceptabel + } + // Font wel weer terugzetten, tijdelijk boundsrotatie goldt puur voor de huidige tekst + (HFONT) SelectObject(myDC, old_font); + m_logfont.lfOrientation = keep_rotation; + m_logfont.lfEscapement = keep_rotation; + m_logfont.lfHeight = keep_height; + m_logfont.lfWidth = keep_width; + DeleteObject(temp_font); + + SetTextAlign(myDC,TA_LEFT|TA_BASELINE); + return WT_Result::Success; +} + +// SetExtents is a very important functions as m_mul is +// calculated here +#define SWAP32(a, b) { WT_Integer32 h=b;b=a;a=h; } +void CWhip2DCState::SetExtents(WT_Logical_Box MinMax) +{ + WT_Logical_Point dwfPtmin = MinMax.m_min; + WT_Logical_Point dwfPtmax = MinMax.m_max; + + // better_markups_large.dwf pagina 'Untitled sheet 2' had een ongenormaliseerde Contour + if (dwfPtmin.m_x > dwfPtmax.m_x) + SWAP32(dwfPtmin.m_x, dwfPtmax.m_x); + + if (dwfPtmin.m_y > dwfPtmax.m_y) + SWAP32(dwfPtmin.m_y, dwfPtmax.m_y); + + WT_Integer32 dwfDx = dwfPtmax.m_x - dwfPtmin.m_x; + WT_Integer32 dwfDy = dwfPtmax.m_y - dwfPtmin.m_y; + + m_MinMax = WT_Logical_Box(dwfPtmin, dwfPtmax); + m_orgMinMax = m_MinMax; + if (m_ClipWidth > 0) + { + double dpi= max(dwfDx / m_ClipWidth, dwfDy / m_ClipHeight); + myDoTRACE("\nGuessing vector dpi: %d", myRound(dpi)); + } + + //CSize ss; + //GetViewportExtEx(myDC,&ss); + + double mulY = (double)m_Size.cy / dwfDy; + double mulX = (double)m_Size.cx / dwfDx; + if (mulY Bij "S-HuntngtnCllg-10YR - MP-Model.dwf" gaat het fout, veel zwart wat wit had moeten blijven + // Daar moeten we dan maar mee leven + // ==> Ook bij intelligent_design_data_large.dwf waar een witte rechthoek + // achter tekst is getekend. Die wordt zwart + if (1) + { + if (!isDarkRGB(m_paperColor) // licht papier + && clr == WT_RGBA32(255,255,255,clr.m_rgb.a)) // Wit naar zwart + m_DCclr = RGB(0, 0, 0); + + if (isDarkRGB(m_paperColor) // donker papier + && clr == WT_RGBA32(0,0,0,clr.m_rgb.a)) // Zwart naar wit + m_DCclr = RGB(255, 255, 255); + } + + CFromTo replace; + if (m_replaceColors.Lookup(m_paperColor, replace)) + { + if (m_DCclr == replace.from) + m_DCclr = replace.to; + } + + m_alpha = clr.m_rgb.a; // Misschien later nodig voor AlphaPolygon + + SetTextColor(myDC, m_DCclr); // Deze in ieder geval zetten + + int w = myRound(file.rendition().line_weight().weight_value()*m_mul); + +#if 0 + m_pen = CreatePen (PS_INSIDEFRAME , w, DCclr); + HPEN oldpenn = (HPEN) SelectObject(myDC, m_pen); + DeleteObject(oldpenn); + return; +#endif + + // + // fillpattern + // + int hatchCode = -1; // invalid becomes solid + switch (fillPattern.pattern_id()) + { + case WT_Fill_Pattern::Illegal: // Not a pattern (the enum default.) + case WT_Fill_Pattern::Solid: // Solid filled. + break; // No hatch + case WT_Fill_Pattern::Checkerboard: //Checkerboard pattern. + hatchCode = HS_CROSS; break; + case WT_Fill_Pattern::Square_Dots: //Pattern with square dots. + case WT_Fill_Pattern::Diamonds: //Diamond pattern. + case WT_Fill_Pattern::Crosshatch: //Crosshatched pattern. + hatchCode = HS_DIAGCROSS; break; + case WT_Fill_Pattern::Horizontal_Bars: //Pattern with horizontal bars. + hatchCode = HS_HORIZONTAL; break; + case WT_Fill_Pattern::Slant_Left: // Pattern with lines slanting left. + hatchCode = HS_FDIAGONAL; break; + case WT_Fill_Pattern::Slant_Right: //Pattern with lines slanting right. + hatchCode = HS_BDIAGONAL; break; + case WT_Fill_Pattern::Vertical_Bars: //Pattern with vertical bars. + hatchCode = HS_VERTICAL; break; + case WT_Fill_Pattern::User_Defined: //RESERVED, currently no way to describe a user defined fill pattern. + case WT_Fill_Pattern::Undefined: //Not a pattern. + break; // No hatch + default: + break; + } + + if (hatchCode == -1) + m_brush = ::CreateSolidBrush(m_DCclr); + else + m_brush = ::CreateHatchBrush(hatchCode, m_DCclr); + HBRUSH oldbrush = (HBRUSH) SelectObject(myDC, m_brush); + DeleteObject(oldbrush); + + if (w==0) + m_pen = CreatePen(PS_SOLID, w, GetTextColor(myDC)); // Die is veel sneller + else + { + // + // pen style + // + DWORD penStyle = PS_GEOMETRIC;//|PS_INSIDEFRAME; + switch (style.line_end_cap()) // We negeren line_start_cap + { + case WT_Line_Style::Square_Cap: + case WT_Line_Style::Diamond_Cap: { penStyle |= PS_ENDCAP_SQUARE; break; }; + case WT_Line_Style::Butt_Cap: { penStyle |= PS_ENDCAP_FLAT; break; }; + case WT_Line_Style::Round_Cap: {penStyle |= PS_ENDCAP_ROUND; break; }; + default: {penStyle |= PS_ENDCAP_SQUARE; break; }; + } + switch (style.line_join()) + { + case WT_Line_Style::Bevel_Join: { penStyle |= PS_JOIN_BEVEL; break; }; + case WT_Line_Style::Miter_Join: { penStyle |= PS_JOIN_MITER; break; }; + case WT_Line_Style::Round_Join: { penStyle |= PS_JOIN_ROUND; break; }; + case WT_Line_Style::Diamond_Join: { penStyle |= PS_JOIN_ROUND; break; }; + default: { penStyle |= PS_JOIN_ROUND; break; }; + } + // TODO: Goed interpreteren. SetMiterLimit(myDC, style.miter_length(), NULL); + LOGBRUSH b; + b.lbColor = m_DCclr; + b.lbHatch = hatchCode; + b.lbStyle = BS_SOLID; + m_pen = ExtCreatePen(penStyle, w, &b, 0, NULL); + } + + if (m_pen == 0) + { + myTRACE("\n(Ext)CreatePen failed (%d): %s", GetLastError(), myGetLastErrorMsg()); + }; + HPEN oldpen = (HPEN) SelectObject(myDC, m_pen); + DeleteObject(oldpen); +} + +// Altijd rond 0,0 +CPoint rotate(double radian, double ptx, double pty) +{ + return CPoint(myRound(ptx * cos(radian) + pty * sin(radian)), + myRound(pty * cos(radian) - ptx * sin(radian))); +} + +void CWhip2DCState::DrawGeekBox(CPoint *pts, int nCount) +{ + // Pendikte tijdelijk op 0 + myTempPEN tempPen(myDC, 0, GetTextColor(myDC)); + //HBRUSH hbrushNew = CreateSolidBrush(GetTextColor(myDC)); + HBRUSH hbrushNew = CreateHatchBrush(HS_DIAGCROSS, GetTextColor(myDC)); // Minder 'eng' + + HBRUSH hbrushOld = (HBRUSH)SelectObject(myDC, hbrushNew); + Polygon(myDC, pts, nCount); + + // Opruimen + SelectObject(myDC, hbrushOld); + DeleteObject(hbrushNew); +} + +void CWhip2DCState::DrawGeekText(WT_Text &text) +{ + CPoint acPt = DWFToLP(text.position()); + + double w,h; + if (text.string().is_ascii()) + { + m_kfm.GetTextExtent(myDC, text.string().ascii(), text.string().length(), w, h); + } + else + { + CSize s; + GetTextExtentPoint32W(myDC, text.string().unicode(), text.string().length(), &s); + w = s.cx; h = s.cy; + } + // TODO: De .5 snap ik nog niet maar anders is de box te groot + h *= 0.5; + if (h < 1.0) h = 1.0; + double radian = m_logfont.lfOrientation * 2 * PI / 3600; + + CPoint pts[]= + { + acPt, + acPt + rotate(radian, w, 0), + acPt + rotate(radian, w, -h), + acPt + rotate(radian, 0, -h), + acPt + }; + + DrawGeekBox(pts, sizeof(pts)/sizeof(pts[0])); +} diff --git a/SlnkDWFImpl/Whip2DCState.h b/SlnkDWFImpl/Whip2DCState.h new file mode 100644 index 0000000..0e18ece --- /dev/null +++ b/SlnkDWFImpl/Whip2DCState.h @@ -0,0 +1,104 @@ +#pragma once + +#include "Whiptk/whip_toolkit.h" +//#include "SLNKDWF.h" + +#include "TextFormatter.h" + +class CFoundText +{ +public: + WT_Text m_FoundText; + CString m_FoundLayer; + WT_Logical_Point m_FoundAt; +}; + +class CFromTo { +public: + CFromTo(COLORREF pFrom, COLORREF pTo): from(pFrom), to(pTo){}; + CFromTo(){}; + COLORREF from; COLORREF to; +}; + +class CWhip2DCState +{ +public: + CWhip2DCState(); + ~CWhip2DCState(); + void Reset(); + + // CW2D2PNG + long myRound(double x) const // Dikke kans dattie zo inline wordt + { + ATLASSERT(x >= LONG_MIN-0.5); + ATLASSERT(x <= LONG_MAX+0.5); + if (x >= 0) + return (long) (x+0.5); + return (long) (x-0.5); + } + + LOGFONT m_logfont; + WT_Integer32 m_spacing; + WT_Integer32 m_height; // Niet afgeronde waarde voor SetupPixel + HPEN m_pen, m_penExt; + HFONT m_font; + HRGN m_hrgn; + + KTextFormator m_kfm; + HBRUSH m_brush; int m_alpha; + COLORREF m_DCclr; + HDC myDC; + + CAtlRegExp<> reLayers; // Welke layers moeten aan + BOOL bLayerVisible; // Current Layer visible? + BOOL bIsSymbolLayer; + + CAtlArray m_Layernames; + CAtlArray m_FoundTexts; + + WT_Logical_Box m_orgMinMax; + WT_Logical_Box m_MinMax; + WT_Units m_Units; // Remember them after processing + + double m_ClipWidth, m_ClipHeight; + COLORREF m_paperColor; + BOOL m_forcePaper; // forceer een bepaalde papierkleur + BOOL m_forceBW; + BOOL m_Maximize; + BOOL m_centerImage; + double m_mul; // schaal onze DWF-coordinaten naar bitmap coordinaten + + CSize m_Size; + BOOL findIt; + CString MapBuilder; + CPoint LPfindXY; + WT_Object_Node foundNode; + CString foundNodeLayer; + CString foundTextLabel; + CString foundTextLayer; + WT_Logical_Point DWFfindXY; + int geekFontSize; + + int m_vertexList_size; + CPoint *m_vertexList; // tempArray to hold translated Points. Used over and over + + CAtlMap m_replaceColors; // paper, from, to + + void AlphaPolygon(LPPOINT lpPoints, int nCount) const; + void erasePaper (WT_File & file); + CPoint *new_DWFToLP(WT_Point_Set const &pts); + CPoint DWFToLP(WT_Logical_Point const &pt); + + WT_Logical_Point LPToDWF(CPoint pt); + void LPToDWG(CPoint pt, double &resX, double &resY); + void DWGExtents(double &resminX, double &resminY, + double &resmaxX, double &resmaxY); + WT_Result my_process_font (WT_Font & font); + WT_Result drawBoundText (WT_Text & text, WT_File & file); + void Marker( CPoint pt); + void SetExtents(WT_Logical_Box MinMax); + void ColorPenAndBrush (WT_File & file); + void DrawGeekBox(CPoint *pts, int nCount); + void DrawGeekText(WT_Text &text); +}; + diff --git a/SlnkDWFImpl/dbgint.h b/SlnkDWFImpl/dbgint.h new file mode 100644 index 0000000..10fbde3 --- /dev/null +++ b/SlnkDWFImpl/dbgint.h @@ -0,0 +1,308 @@ +/*** +*dbgint.h - Supports debugging features of the C runtime library. +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Support CRT debugging features. +* +* [Internal] +* +****/ + +#if _MSC_VER > 1000 +#pragma once +#endif /* _MSC_VER > 1000 */ + +#ifndef _INC_DBGINT +#define _INC_DBGINT + +#ifndef _CRTBLD +/* + * This is an internal C runtime header file. It is used when building + * the C runtimes only. It is not to be used as a public header file. + */ +#error ERROR: Use of C runtime library internal header file. +#endif /* _CRTBLD */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef _DEBUG + + /**************************************************************************** + * + * Debug OFF + * Debug OFF + * Debug OFF + * + ***************************************************************************/ + +#ifdef __cplusplus + +#define _new_crt new + +#endif /* __cplusplus */ + +#define _malloc_crt malloc +#define _calloc_crt calloc +#define _realloc_crt realloc +#define _expand_crt _expand +#define _free_crt free +#define _msize_crt _msize + + +#define _malloc_base malloc +#define _nh_malloc_base _nh_malloc +#define _nh_malloc_dbg(s, n, t, f, l) _nh_malloc(s, n) +#define _heap_alloc_base _heap_alloc +#define _heap_alloc_dbg(s, t, f, l) _heap_alloc(s) +#define _calloc_base calloc +#define _realloc_base realloc +#define _expand_base _expand +#define _free_base free +#define _msize_base _msize +#define _aligned_malloc_base _aligned_malloc +#define _aligned_realloc_base _aligned_realloc +#define _aligned_offset_malloc_base _aligned_offset_malloc +#define _aligned_offset_realloc_base _aligned_offset_realloc +#define _aligned_free_base _aligned_free + +#ifdef _MT + +#define _calloc_dbg_lk(c, s, t, f, l) _calloc_lk(c, s) +#define _realloc_dbg_lk(p, s, t, f, l) _realloc_lk(p, s) +#define _free_base_lk _free_lk +#define _free_dbg_lk(p, t) _free_lk(p) + +#else /* _MT */ + +#define _calloc_dbg_lk(c, s, t, f, l) calloc(c, s) +#define _realloc_dbg_lk(p, s, t, f, l) realloc(p, s) +#define _free_base_lk free +#define _free_dbg_lk(p, t) free(p) + +#endif /* _MT */ + + +#else /* _DEBUG */ + + + /**************************************************************************** + * + * Debug ON + * Debug ON + * Debug ON + * + ***************************************************************************/ + +#define _THISFILE __FILE__ + +#ifdef __cplusplus + +#define _new_crt new(_CRT_BLOCK, _THISFILE, __LINE__) + +#endif /* __cplusplus */ + +#define _malloc_crt(s) _malloc_dbg(s, _CRT_BLOCK, _THISFILE, __LINE__) +#define _calloc_crt(c, s) _calloc_dbg(c, s, _CRT_BLOCK, _THISFILE, __LINE__) +#define _realloc_crt(p, s) _realloc_dbg(p, s, _CRT_BLOCK, _THISFILE, __LINE__) +#define _expand_crt(p, s) _expand_dbg(p, s, _CRT_BLOCK) +#define _free_crt(p) _free_dbg(p, _CRT_BLOCK) +#define _msize_crt(p) _msize_dbg(p, _CRT_BLOCK) + +/* + * Prototypes for malloc, free, realloc, etc are in malloc.h + */ + +void * __cdecl _malloc_base( + size_t + ); + +void * __cdecl _nh_malloc_base ( + size_t, + int + ); + +void * __cdecl _nh_malloc_dbg ( + size_t, + int, + int, + const char *, + int + ); + +void * __cdecl _heap_alloc_base( + size_t + ); + +void * __cdecl _heap_alloc_dbg( + size_t, + int, + const char *, + int + ); + +void * __cdecl _calloc_base( + size_t, + size_t + ); + +void * __cdecl _realloc_base( + void *, + size_t + ); + +void * __cdecl _expand_base( + void *, + size_t + ); + +void __cdecl _free_base( + void * + ); + +size_t __cdecl _msize_base ( + void * + ); + +void __cdecl _aligned_free_base( + void * + ); + +void * __cdecl _aligned_malloc_base( + size_t, + size_t + ); + +void * __cdecl _aligned_offset_malloc_base( + size_t, + size_t, + size_t + ); + +void * __cdecl _aligned_realloc_base( + void *, + size_t, + size_t + ); + +void * __cdecl _aligned_offset_realloc_base( + void *, + size_t, + size_t, + size_t + ); + +#ifdef _MT + +/* + * Prototypes and macros for multi-thread support + */ + + +void * __cdecl _calloc_dbg_lk( + size_t, + size_t, + int, + char *, + int + ); + + +void * __cdecl _realloc_dbg_lk( + void *, + size_t, + int, + const char *, + int + ); + + +void __cdecl _free_base_lk( + void * + ); + +void __cdecl _free_dbg_lk( + void *, + int + ); + +#else /* _MT */ + +#define _calloc_dbg_lk _calloc_dbg +#define _realloc_dbg_lk _realloc_dbg +#define _free_base_lk _free_base +#define _free_dbg_lk _free_dbg + +#endif /* _MT */ + +/* + * For diagnostic purpose, blocks are allocated with extra information and + * stored in a doubly-linked list. This makes all blocks registered with + * how big they are, when they were allocated, and what they are used for. + */ + +#define nNoMansLandSize 4 + +typedef struct _CrtMemBlockHeader +{ + struct _CrtMemBlockHeader * pBlockHeaderNext; + struct _CrtMemBlockHeader * pBlockHeaderPrev; + char * szFileName; + int nLine; +#ifdef _WIN64 + /* These items are reversed on Win64 to eliminate gaps in the struct + * and ensure that sizeof(struct)%16 == 0, so 16-byte alignment is + * maintained in the debug heap. + */ + int nBlockUse; + size_t nDataSize; +#else /* _WIN64 */ + size_t nDataSize; + int nBlockUse; +#endif /* _WIN64 */ + long lRequest; + unsigned char gap[nNoMansLandSize]; + /* followed by: + * unsigned char data[nDataSize]; + * unsigned char anotherGap[nNoMansLandSize]; + */ +} _CrtMemBlockHeader; + +#define pbData(pblock) ((unsigned char *)((_CrtMemBlockHeader *)pblock + 1)) +#define pHdr(pbData) (((_CrtMemBlockHeader *)pbData)-1) + + +_CRTIMP void __cdecl _CrtSetDbgBlockType( + void *, + int + ); + +#define _BLOCK_TYPE_IS_VALID(use) (_BLOCK_TYPE(use) == _CLIENT_BLOCK || \ + (use) == _NORMAL_BLOCK || \ + _BLOCK_TYPE(use) == _CRT_BLOCK || \ + (use) == _IGNORE_BLOCK) + +extern _CRT_ALLOC_HOOK _pfnAllocHook; /* defined in dbghook.c */ + +int __cdecl _CrtDefaultAllocHook( + int, + void *, + size_t, + int, + long, + const unsigned char *, + int + ); + +#endif /* _DEBUG */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* _INC_DBGINT */ diff --git a/SlnkDWFImpl/dwffileimpl.h b/SlnkDWFImpl/dwffileimpl.h new file mode 100644 index 0000000..f5e22f2 --- /dev/null +++ b/SlnkDWFImpl/dwffileimpl.h @@ -0,0 +1,41 @@ +// DWFFile.h : Declaration of the CDWFFile + +#pragma once +#include "resource.h" // main symbols +#include "EPlotSectionsImpl.h" + +//#include "SLNKDWF.h" + +#include "Whiptk/whip_toolkit.h" +#include "Dwf/Toolkit.h" + +// CDWFFile + +class CDWFFileImpl +{ +public: + CDWFFileImpl() + : m_DWF(NULL),m_oReader(NULL), m_isOpen(FALSE) + { + } + ~CDWFFileImpl(); + +public: + bool get_PropertiesXML(CString & pVal); + CEPlotSectionsImpl *get_EPlotSections(); + bool Open(const CString &DWFPath); + +public: + CEPlotSectionsImpl m_EPlotSections; + DWFPackageReader::tPackageInfo m_tInfo; + +private: + DWFCore::DWFFile *m_DWF; + DWFToolkit::DWFPackageReader* m_oReader; + + WT_File m_DWFFile; + BOOL m_isOpen; + + DWFString m_W2DFileName; + +}; diff --git a/SlnkDWFImpl/eplotsectionsimpl.h b/SlnkDWFImpl/eplotsectionsimpl.h new file mode 100644 index 0000000..d22500b --- /dev/null +++ b/SlnkDWFImpl/eplotsectionsimpl.h @@ -0,0 +1,30 @@ +// EPlotSections.h : Declaration of the CEPlotSections + +#pragma once +#include "resource.h" // main symbols + +//#include "SLNKDWF.h" +using namespace DWFToolkit; + +//#include "ComObjectEmbed.h" +#include "myEPlotSectionImpl.h" + +// CEPlotSections + +class CEPlotSectionsImpl +{ +public: + CEPlotSectionsImpl() + { + } + ~CEPlotSectionsImpl(); + +protected: + CAtlArray m_EPlotSections; + +public: + BOOL ProcessManifest(DWFToolkit::DWFManifest& rManifest, CString sourceDescription); + + long get_Count(); + CEPlotSectionImpl *get_Item(LONG i); +}; diff --git a/SlnkDWFImpl/myEPlotSectionImpl.cpp b/SlnkDWFImpl/myEPlotSectionImpl.cpp new file mode 100644 index 0000000..1a19f63 --- /dev/null +++ b/SlnkDWFImpl/myEPlotSectionImpl.cpp @@ -0,0 +1,345 @@ +// EPlotSection.cpp : Implementation of CEPlotSection + +#include "stdafx.h" + +#include "myEPlotSectionImpl.h" + +#include "myWT_File.h" + +#include "dwfcore/mime.h" + +// CEPlotSection + +CEPlotSectionImpl::~CEPlotSectionImpl() +{ +#ifndef DWFTK_READ_ONLY + if (m_pW2DOutStream) + delete m_pW2DOutStream; +#endif + if (m_pW2DInStream) + delete m_pW2DInStream; +} + +void CEPlotSectionImpl::Init(DWFToolkit::DWFEPlotSection* pSection, + const CString SourceDescription, + BOOL pForWrite) +{ + m_pSection = pSection; + ATLASSERT(m_pSection == pSection); + m_ForWrite = pForWrite; + m_SourceDescription = SourceDescription; + + if (!pForWrite) +{ +//#ifdef _DWFTK_SAMPLE_FIX_BAD_EPLOT_DESCRIPTOR_XML + // Nodig voor 222306-1-0601-05_Malacko_-_WD2.dwf + + // + // some sections might not also be descriptor readers which implement this interface... + // + DWFToolkit::DWFXMLCallback* pXMLCallback = dynamic_cast(pSection); + if (pXMLCallback) + { + myTRACE("\nXML fixing requested - inserting duplicate attribute filter."); + // + // hook up the filter - as and added bonus tell the section to delete it too + // + DWFToolkit::DWFDuplicateAttributeFilter* pFilter = DWFCORE_ALLOC_OBJECT( DWFToolkit::DWFDuplicateAttributeFilter ); + pXMLCallback->setStreamFilter( pFilter, true ); + } + +//#endif + m_pSection->readDescriptor(); + + } +} + +const CString CEPlotSectionImpl::get_Name() +{ + return CString(m_pSection->name()); +} + + +const CString CEPlotSectionImpl::get_Title() +{ + return CString(m_pSection->title()); +} + +ULONG CEPlotSectionImpl::get_PaperColor() +{ + DWFPaper *paper = m_pSection->paper(); + return paper->color(); +} + +// Always inches +double CEPlotSectionImpl::get_PaperClipWidth() +{ + DWFPaper *paper = m_pSection->paper(); + if (paper) + { + const double *clip = paper->clip(); + switch (paper->units()) + { + case DWFPaper::eMillimeters: + return (clip[2] - clip[0])/25.4; + break; + case DWFPaper::eInches: + return clip[2] - clip[0]; + break; + } + } + + return -1; // Invalid +} + +double CEPlotSectionImpl::get_PaperClipHeight() +{ + DWFPaper *paper = m_pSection->paper(); + if (paper) + { + const double *clip = paper->clip(); + switch (paper->units()) + { + case DWFPaper::eMillimeters: + return (clip[3] - clip[1])/25.4; + break; + case DWFPaper::eInches: + return clip[3] - clip[1]; + break; + } + } + + return -1; // Invalid +} + +STDMETHODIMP CEPlotSectionImpl::Open(BOOL bForWrite) +{ +#ifdef DWFTK_READ_ONLY + ATLASSERT(!bForWrite); +#endif + try + { + // + // get the graphics stream + // + DWFResourceContainer::ResourceIterator* piResources = + m_pSection->findResourcesByRole( DWFXML::kzRole_Graphics2d ); + + if ((piResources == NULL) || (piResources->valid() == false)) + { + if (piResources) + { + DWFCORE_FREE_OBJECT( piResources ); + } + + myTRACE("%ls", "Illegal EPlot section - no graphics"); + return E_FAIL; + } + + // + // get the w2d resource + // + //Since we know it's a Graphics2D role, we should be able to cast + //into an EPlotGraphicResource, otherwise the authoring tool didn't + //read the spec. + DWFToolkit::DWFGraphicResource* pW2D = dynamic_cast(piResources->get()); + ATLASSERT(pW2D != NULL); + DWFString s = pW2D->creationTime(); + if (s.chars()) + myTRACE("\nCreationTime %s", (const wchar_t *)pW2D->creationTime()); + + + // + // done with the iterator + // + DWFCORE_FREE_OBJECT( piResources ); + + if (pW2D->mime() != DWFCore::DWFMIME::kzMIMEType_W2D) + { + myDoTRACE("\nMime: %ls", (const wchar_t*)pW2D->mime()); + throw myCString("Unsupported graphics resource (%ls)." + "\nMeasurement/Print disabled?", (const wchar_t*)pW2D->mime()); + } + + if (pW2D == NULL) + { + myTRACE("%ls", L"Type mismatch - not a W2D resource"); + return E_FAIL; + } + + // + // get the data stream + // +#ifndef DWFTK_READ_ONLY + if (bForWrite) + { + m_pW2DOutStream = new DWFCore::DWFBufferOutputStream(1024); + } + else +#endif + { + // TODO: Fors geheugenlek? + m_pW2DInStream = pW2D->getInputStream(); + m_nSize = pW2D->size(); +#ifndef DWFTK_READ_ONLY + if (!m_pW2DInStream && m_pW2DOutStream) + m_pW2DInStream = new DWFCore::DWFBufferInputStream(m_pW2DOutStream->buffer(), m_pW2DOutStream->bytes()); +#endif + } + return S_OK; + } + catch (DWFException& ex) + { + CString err; + err.Format("%ls\n%ls\n%s\n%ls(%d)",ex.type(),ex.message(),ex.function(),ex.file(),ex.line()); + throw myCString("\nCEPlotSectionImpl::open(\"%s\")\n%s", m_SourceDescription, err); + } +} + +const DWFProperty* const CEPlotSectionImpl::findProperty( const DWFString& zName, + const DWFString& zCategory ) +{ + return m_pSection->findProperty( zName, zCategory); +} + + +HRESULT CEPlotSectionImpl::Read( void *pv, ULONG cb, ULONG *pcbRead) +{ + ATLASSERT(m_pW2DInStream); // Open first! + + (*pcbRead)=0; + if (m_pW2DInStream->available()>0) + { + (*pcbRead) = (ULONG)m_pW2DInStream->read( pv, cb ); + } + return S_OK; +}; + +HRESULT CEPlotSectionImpl::Seek( ULONG cb, ULONG *pcbRead) +{ + ATLASSERT(m_pW2DInStream); // Open first! + + (*pcbRead)=0; + if (m_pW2DInStream->available()>0) + { + (*pcbRead) = (ULONG)m_pW2DInStream->seek( SEEK_CUR, cb ); + } + return S_OK; +}; + +#ifndef DWFTK_READ_ONLY +HRESULT CEPlotSectionImpl::Write( const void *pv, ULONG cb, ULONG *pcbWritten) +{ + ATLASSERT(m_pW2DOutStream); // Open first! + + (*pcbWritten)=0; + + (*pcbWritten) = (ULONG)m_pW2DOutStream->write( pv, cb ); + return S_OK; +}; +#endif + +STDMETHODIMP CEPlotSectionImpl::Close(void) +{ + // Don't bother ASSERT(m_pW2DInStream); // Open first! +// if (m_pW2DOutStream) +// m_pSection->res m_pW2DOutStream + if (m_pW2DInStream) + delete m_pW2DInStream; + m_pW2DInStream = NULL; + return S_OK; +} + +STDMETHODIMP CEPlotSectionImpl::get_SourceDescription(CString & pVal) +{ + pVal = m_SourceDescription; + return S_OK; +} + +#ifndef DWFTK_READ_ONLY +STDMETHODIMP CEPlotSectionImpl::get_PropertiesXML(CString &pVal) +{ + if (m_pSection!=NULL) + { + DWFCore::DWFBufferOutputStream m_XMLProps(1024); + DWFUUID _oUUID; + DWFXMLSerializer XML(_oUUID); + XML.attach(m_XMLProps); + + //DWFManifest& rManifest = m_pSection; + m_pSection->serializeXML(XML, DWFPackageWriter::eDescriptor); + XML.detach(); + + pVal = CString((LPCSTR)m_XMLProps.buffer(), (int)m_XMLProps.bytes()); + return S_OK; + } + else + return E_FAIL; + + return S_OK; +} + +bool CEPlotSectionImpl::SaveAs(const CString &destpath) +{ + ATLASSERT(!m_pW2DInStream); // Don't open first! + + try + { + Open(false); + DWFFile m_pTempFile(destpath); + DWFStreamFileDescriptor fds (m_pTempFile, L"wb"); + fds.open(); + DWFFileOutputStream rTempStream; + rTempStream.attach(&fds,false); + + // Copy pW2DStream to rTempStream +#define DATA_BUFFER_BYTES 16384 + unsigned char* pDataBuffer = DWFCORE_ALLOC_MEMORY( unsigned char, DATA_BUFFER_BYTES ); + if (pDataBuffer == NULL) + { + _DWFCORE_THROW( DWFMemoryException, L"No memory for data buffer" ); + } + + while (m_pW2DInStream->available()>0) + { + size_t nBytes; + nBytes = m_pW2DInStream->read( pDataBuffer, DATA_BUFFER_BYTES ); + rTempStream.write( pDataBuffer, nBytes ); + } + rTempStream.flush(); + rTempStream.detach(); + fds.close(); + + DWFCORE_FREE_MEMORY( pDataBuffer ) + Close(); + } + catch (DWFException& ex) + { + CString err; + err.Format("%ls\n%ls\n%s\n%ls(%d)",ex.type(),ex.message(),ex.function(),ex.file(),ex.line()); + throw myCString("\nCEPlotSectionImpl::open(\"%s\")\n%s", m_SourceDescription, err); + } + + return true; +}; + +bool CEPlotSectionImpl::SaveAsAscii(const CString &srcpath, const CString &destpath) +{ + myWT_File my_input_file; + my_input_file.set_filename(srcpath); + my_input_file.SaveAsAscii(destpath); + + return true; +} + +bool CEPlotSectionImpl::SaveAsAscii(const CString &destpath) +{ + ATLASSERT(!m_pW2DInStream); // Don't open first! + + myWT_File my_input_file; + my_input_file.set_eplotsection(this); + my_input_file.SaveAsAscii(destpath); + + return true; +}; +#endif \ No newline at end of file diff --git a/SlnkDWFImpl/myWT_File.cpp b/SlnkDWFImpl/myWT_File.cpp new file mode 100644 index 0000000..390e675 --- /dev/null +++ b/SlnkDWFImpl/myWT_File.cpp @@ -0,0 +1,158 @@ +#include "StdAfx.h" +#include "mywt_file.h" + +/************************************************************\ +* Een variant op WT_File die ook EPlotSections uit DWF- +* packages kan lezen of schrijven +* of om precies te zijn: Onze CEPlotSectionImpl +* Gebruik dan set_eplotsection ipv set_filename +\************************************************************/ + +myWT_File::myWT_File(void): m_color(0x00ffffff), + m_EPlotSection(NULL) +{ +} + +myWT_File::~myWT_File(void) +{ +} + +WT_Result myWT_File::set_eplotsection(CEPlotSectionImpl *EPlotSection) +{ + m_EPlotSection = EPlotSection; + return WT_Result::Success; +} + + +WT_Result myWT_File::open() +{ + m_current_file_position = 0; + if (m_EPlotSection) // Deze heeft altijd voorkeur + { + CString src; + m_EPlotSection->get_SourceDescription(src); + myTRACE("\nmyWT_File::open %s in this 0x%x", src, this); + set_stream_user_data(this); + set_stream_open_action(my_WSopen); + set_stream_close_action(my_WSclose); + set_stream_read_action(my_WSread); + set_stream_seek_action(my_WSseek); +#ifndef DWFTK_READ_ONLY + set_stream_write_action (my_WSwrite); +#endif +//void set_stream_end_seek_action (WT_Stream_End_Seek_Action action) +//void set_stream_tell_action (WT_Stream_Tell_Action action) + + } + else // moet/zal het een oldstyle DWF zijn + ATLASSERT(this->filename().length()>0); + return WT_File::open(); +} + + +WT_Result myWT_File::my_WSopen (WT_File & file) +{ + myWT_File *mine = (myWT_File *)file.stream_user_data(); + mine->m_EPlotSection->Open(file.file_mode() == File_Write); + return WT_Result::Success; +} + +WT_Result myWT_File::my_WSclose (WT_File & file) +{ + myWT_File *mine = (myWT_File *)file.stream_user_data(); + HRESULT res = mine->m_EPlotSection->Close(); + return WT_Result::Success; +}; + +WT_Result myWT_File::my_WSread (WT_File & file, int desired_bytes, + int &bytes_read, void * buffer) +{ + myWT_File *mine = (myWT_File *)file.stream_user_data(); + ULONG bread; // IStream + HRESULT res = mine->m_EPlotSection->Read(buffer,desired_bytes, &bread); + bytes_read = bread; + mine->m_current_file_position += bread; + return WT_Result::Success; +}; + +// O.a. gebruikt door WT_Unknown om te skippen +WT_Result myWT_File::my_WSseek (WT_File & file, int distance, int &amount_seeked) +{ + myWT_File *mine = (myWT_File *)file.stream_user_data(); + ULONG bread; // IStream + HRESULT res = mine->m_EPlotSection->Seek(distance, &bread); + amount_seeked = bread; + mine->m_current_file_position += bread; + return WT_Result::Success; +}; + +#ifndef DWFTK_READ_ONLY +WT_Result myWT_File::my_WSwrite (WT_File & file,int size,void const * buffer) +{ + myWT_File *mine = (myWT_File *)file.stream_user_data(); + ULONG bWritten; // IStream + HRESULT res = mine->m_EPlotSection->Write(buffer,size,&bWritten); + return WT_Result::Success; +}; + +bool myWT_File::SaveAsAscii(const CString &destpath) +{ + try + { + set_file_mode(WT_File::File_Read); + open(); + + WT_File my_output_file; + my_output_file.set_filename(destpath); + my_output_file.set_file_mode(WT_File::File_Write); + + + WT_Result result; + // Do the actual reading. + while (result = process_next_object(), result==WT_Result::Success) + { + switch(current_object()->object_id()) + { + case WT_Object::DWF_Header_ID: + { + my_output_file.heuristics().set_target_version(rendition().drawing_info().decimal_revision()); + my_output_file.open(); + my_output_file.heuristics().set_allow_binary_data(WD_False); + break; + } + case WT_Object::Origin_ID: + break; // Mag niet met ASCII + default: + switch(current_object()->object_type()) + { + case WT_Object::Drawable: + current_object()->serialize(my_output_file); + break; + case WT_Object::Attribute: + { const WT_Attribute *obj = (WT_Attribute *)current_object(); + // myTRACE("Attribute '%s'\n", my_plan_file.file_stats()->descriptions()); + // Hoewel een Attibute gaat hij toch niet via desired_rendition + //Omdat we weten dat we net uit uit een DWF komen kunnen we best wel rechtstreeks serializen + //Let wel: desired_rendition is dan niet meer te vertrouwen. Zie @@@ + obj->serialize(my_output_file); + } + break; + default: + myTRACE("Skipping '%s'\n", file_stats()->descriptions()); + break; + } + } + } + + close(); // closing Input file. + my_output_file.close(); // closing Output file. + } + catch (DWFException& ex) + { + CString err; + err.Format("%ls\n%ls\n%s\n%ls(%d)",ex.type(),ex.message(),ex.function(),ex.file(),ex.line()); + throw myCString("\nSaveAsAscii(\"%s\")\n%s", destpath, err); + } + return true; +} +#endif \ No newline at end of file diff --git a/SlnkDWFImpl/myeplotsectionimpl.h b/SlnkDWFImpl/myeplotsectionimpl.h new file mode 100644 index 0000000..a2f76b5 --- /dev/null +++ b/SlnkDWFImpl/myeplotsectionimpl.h @@ -0,0 +1,69 @@ +// EPlotSection.h : Declaration of the CEPlotSection + +#pragma once +#include "resource.h" // main symbols + +// CEPlotSection + +class CEPlotSectionImpl +{ +public: + CEPlotSectionImpl() + : m_pSection(NULL),m_pW2DInStream(NULL) +#ifndef DWFTK_READ_ONLY + ,m_pW2DOutStream(NULL) +#endif + { + } + + ~CEPlotSectionImpl(); + + +private: + DWFCore::DWFInputStream* m_pW2DInStream; + size_t m_nSize; +#ifndef DWFTK_READ_ONLY + DWFCore::DWFBufferOutputStream* m_pW2DOutStream; +#endif + CString m_SourceDescription; // Waar komen we vandaan? + + DWFString m_W2DFileName; + BOOL m_ForWrite; + +private: + DWFToolkit::DWFEPlotSection* m_pSection; + +public: + void Init(DWFToolkit::DWFEPlotSection* pSection, + const CString SourceDescription, + BOOL ForWrite = FALSE); + + + // IWhipSequentialStream Methods +public: + const size_t size() { return m_nSize; }; + + const CString get_Name(); + const CString get_Title(); + STDMETHOD(Open)(BOOL bForWrite); + STDMETHOD(Read) ( void *pv, ULONG cb, ULONG *pcbRead); + STDMETHOD(Seek) ( ULONG cb, ULONG *pcbRead); + const DWFProperty* const findProperty( const DWFString& zName, + const DWFString& zCategory = L"" ); +#ifndef DWFTK_READ_ONLY + bool SaveAs(const CString &destpath); + static bool SaveAsAscii(const CString &srcpath, const CString &destpath); + bool SaveAsAscii(const CString &destpath); + STDMETHOD(Write)( const void *pv, ULONG cb,ULONG *pcbWritten); +#endif + STDMETHOD(Close)(void); + ULONG get_PaperColor(); + STDMETHOD(get_SourceDescription)(CString &pVal); +#ifndef DWFTK_READ_ONLY + STDMETHOD(get_PropertiesXML)(CString & pVal); +#endif + double get_PaperClipWidth(); + double get_PaperClipHeight(); +}; + +//REMOVED OBJECT_ENTRY_AUTO(__uuidof(EPlotSection), CEPlotSection) diff --git a/SlnkDWFImpl/mywt_file.h b/SlnkDWFImpl/mywt_file.h new file mode 100644 index 0000000..7e5a2f5 --- /dev/null +++ b/SlnkDWFImpl/mywt_file.h @@ -0,0 +1,43 @@ +#pragma once + +#include "Whiptk/whip_toolkit.h" + +#include "myEPlotSectionImpl.h" + +class myWT_File : + public WT_File +{ +public: + myWT_File(void); + ~myWT_File(void); + + WT_Result set_eplotsection(CEPlotSectionImpl *EPlotSection); + WT_Result myWT_File::open(); + const int file_pos() { return m_current_file_position; }; + const size_t size() + { + if (m_EPlotSection) + return m_EPlotSection->size(); + else + return 0; // Weet ik zo nog niet + }; + + const unsigned int PaperColor() { return m_color; }; +#ifndef DWFTK_READ_ONLY + bool SaveAsAscii(const CString &destpath); +#endif + +protected: + unsigned int m_color; + CEPlotSectionImpl *m_EPlotSection; + + int m_current_file_position; + static WT_Result my_WSopen (WT_File & file); + static WT_Result my_WSclose (WT_File & file); + static WT_Result my_WSread (WT_File & file, int desired_bytes, int & + bytes_read, void * buffer); + static WT_Result my_WSseek (WT_File & file, int distance, int &amount_seeked); +#ifndef DWFTK_READ_ONLY + static WT_Result my_WSwrite (WT_File & file,int size,void const * buffer); +#endif +}; diff --git a/SlnkDWFImpl/stdafx.cpp b/SlnkDWFImpl/stdafx.cpp new file mode 100644 index 0000000..67ecdda --- /dev/null +++ b/SlnkDWFImpl/stdafx.cpp @@ -0,0 +1,5 @@ +// stdafx.cpp : source file that includes just the standard includes +// SLNKDWF.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" diff --git a/SlnkDWFImpl/stdafx.h b/SlnkDWFImpl/stdafx.h new file mode 100644 index 0000000..cbfab83 --- /dev/null +++ b/SlnkDWFImpl/stdafx.h @@ -0,0 +1,56 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, +// but are changed infrequently + +#pragma once + +#ifndef STRICT +#define STRICT +#endif + +// Modify the following defines if you have to target a platform prior to the ones specified below. +// Refer to MSDN for the latest info on corresponding values for different platforms. +#ifndef WINVER // Allow use of features specific to Windows XP or later. +#define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows. +#endif + +#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. +#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. +#endif + +#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. +#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. +#endif + +#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later. +#define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE. +#endif + +#define _ATL_APARTMENT_THREADED +#define _ATL_NO_AUTOMATIC_NAMESPACE + +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit + +// turns off ATL's hiding of some common and often safely ignored warning messages +#define _ATL_ALL_WARNINGS + +//#include "resource.h" +#include +#include + +using namespace ATL; + +// [JGL] added manually +#include +#include "atlstr.h" +#include "atlrx.h" +#include "../SLNKDwfImpl/jglutil.h" + +#include "SLNKDWFStatic.h" + +using namespace DWFCore; +using namespace DWFToolkit; + +#ifdef _DEBUG +#include "MemLeakDetect.h" +#endif \ No newline at end of file diff --git a/SlnkDWFImpl/textformatter.h b/SlnkDWFImpl/textformatter.h new file mode 100644 index 0000000..b162b29 --- /dev/null +++ b/SlnkDWFImpl/textformatter.h @@ -0,0 +1,22 @@ +class KTextFormator +{ + typedef enum { MaxCharNo = 256 }; + + double m_fCharWidth[MaxCharNo]; + double m_fHeight; + double m_fLinespace; + +public: + + BOOL SetupPixel(HDC hDC, HFONT hFont, double pixelsize); + BOOL Setup(HDC hDC, HFONT hFont, double pointsize); + + double GetLinespace(void) const + { + return m_fLinespace; + } + BOOL GetTextExtent(HDC hdc, LPCTSTR pString, int cbString, double & width, double & height); + BOOL TextOutSpacing(HDC hDC, int x, int y, LPCTSTR pString, int nCount, double dSpacing); + BOOL TextOutSize(HDC hDC, int x, int y, LPCTSTR pString, int nCount, + double dWidth, double dHeight); +}; diff --git a/Standalone/SLNKDWFViewer.aps b/Standalone/SLNKDWFViewer.aps new file mode 100644 index 0000000..81f0dc5 Binary files /dev/null and b/Standalone/SLNKDWFViewer.aps differ diff --git a/Standalone/SLNKDWFViewer.cpp b/Standalone/SLNKDWFViewer.cpp new file mode 100644 index 0000000..a1d1846 --- /dev/null +++ b/Standalone/SLNKDWFViewer.cpp @@ -0,0 +1,76 @@ +// SLNKDwfViewer.cpp : main source file for SLNKDwfViewer.exe +// + +#include "stdafx.h" + +#include "resource.h" + +CAppModule _Module; + +HINSTANCE g_hInstance; + +int Run(LPTSTR lpstrCmdLine, int nCmdShow = SW_SHOWDEFAULT) +{ + CMessageLoop theLoop; + _Module.AddMessageLoop(&theLoop); + + CMainFrame wndMain; + + if(wndMain.CreateEx() == NULL) + { + ATLTRACE(_T("Main window creation failed!\n")); + return 0; + } + + wndMain.ShowWindow(nCmdShow); + + if (*lpstrCmdLine) + { + CString s(lpstrCmdLine); + if (s[0] == '\"') + s = s.Mid(1, s.GetLength()-2); + wndMain.SetDWF(s); + } + else + { + CFileDialog dlg(TRUE, _T("dwf"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("DWF Files (*.dwf)\0*.dwf\0All Files (*.*)\0*.*\0")); + if(dlg.DoModal() == IDOK) + { + wndMain.SetDWF(CString(dlg.m_szFileName)); + } + else + return 0; + } + + int nRet = theLoop.Run(); + + _Module.RemoveMessageLoop(); + return nRet; +} + +int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow) +{ + g_hInstance = hInstance; + + // this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used + ::DefWindowProc(NULL, 0, 0, 0L); + +// AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES); // add flags to support other controls + + HRESULT hRes = _Module.Init(NULL, hInstance); + ATLASSERT(SUCCEEDED(hRes)); + + int nRet; + try + { + nRet = Run(lpstrCmdLine, nCmdShow); + } + catch (...) + { + int y=1; + } + + _Module.Term(); + + return nRet; +} diff --git a/Standalone/SLNKDWFViewer.h b/Standalone/SLNKDWFViewer.h new file mode 100644 index 0000000..2081e98 --- /dev/null +++ b/Standalone/SLNKDWFViewer.h @@ -0,0 +1 @@ +// SLNKDWFViewer.h diff --git a/Standalone/SLNKDWFViewer.rc b/Standalone/SLNKDWFViewer.rc new file mode 100644 index 0000000..7cc1235 --- /dev/null +++ b/Standalone/SLNKDWFViewer.rc @@ -0,0 +1,390 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "atlres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""atlres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Toolbar +// + +IDR_MAINFRAME TOOLBAR 16, 15 +BEGIN + BUTTON ID_ZOOM_IN + BUTTON ID_ZOOM_OUT + SEPARATOR + BUTTON ID_ZOOM_EXTENTS + BUTTON ID_FILE_PRINT + SEPARATOR + BUTTON ID_APP_ABOUT +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDR_MAINFRAME BITMAP "res\\Toolbar.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDR_MAINFRAME MENU +BEGIN + POPUP "&File" + BEGIN + MENUITEM "&New\tCtrl+N", ID_FILE_NEW + MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN + MENUITEM "&Save\tCtrl+S", ID_FILE_SAVE + MENUITEM "Save &As...", ID_FILE_SAVE_AS + MENUITEM SEPARATOR + MENUITEM "&Print...\tCtrl+P", ID_FILE_PRINT + MENUITEM "Print Pre&view", ID_FILE_PRINT_PREVIEW + MENUITEM "P&rint Setup...", ID_FILE_PRINT_SETUP + MENUITEM SEPARATOR + MENUITEM "E&xit", ID_APP_EXIT + END + POPUP "&Edit" + BEGIN + MENUITEM "&Undo\tCtrl+Z", ID_EDIT_UNDO + MENUITEM SEPARATOR + MENUITEM "Cu&t\tCtrl+X", ID_EDIT_CUT + MENUITEM "&Copy\tCtrl+C", ID_EDIT_COPY + MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE + END + POPUP "&View" + BEGIN + MENUITEM "&Toolbar", ID_VIEW_TOOLBAR + MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR + MENUITEM "Layers", ID_VIEW_LAYERS + END + POPUP "&Help" + BEGIN + MENUITEM "&About SLNKDWFViewer...", ID_APP_ABOUT + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON "res\\SLNKDWFViewer.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOGEX 0, 0, 247, 161 +STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "About" +FONT 8, "MS Sans Serif", 0, 0, 0x0 +BEGIN + DEFPUSHBUTTON "OK",IDOK,190,140,50,14 + CTEXT "SLNKDWFViewer Application v1.0\n\n(c) Copyright 2006",IDC_STATIC,7,55,136,27 + ICON IDR_MAINFRAME,IDC_STATIC,55,26,20,20 + LTEXT "Static",IDC_DLLPATH,55,84,185,8 + LTEXT "Dll",IDC_STATIC,8,98,9,8 + LTEXT "Static",IDC_DLLVERSION,56,98,119,8 + LTEXT "Version",IDC_STATIC,23,97,24,8 + LTEXT "Built",IDC_STATIC,23,111,20,8 + LTEXT "Static",IDC_DLLBUILDTIME,56,112,131,8 + LTEXT "Path",IDC_STATIC,23,84,16,8 + LTEXT "Static",IDC_WHIPVERSION,56,139,131,8 + LTEXT "Static",IDC_DWFVERSION,55,126,131,8 + LTEXT "DWF",IDC_STATIC,24,126,20,8 + LTEXT "Whip",IDC_STATIC,24,139,20,8 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 240 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Accelerator +// + +IDR_MAINFRAME ACCELERATORS +BEGIN + "N", ID_FILE_NEW, VIRTKEY, CONTROL + "O", ID_FILE_OPEN, VIRTKEY, CONTROL + "S", ID_FILE_SAVE, VIRTKEY, CONTROL + "P", ID_FILE_PRINT, VIRTKEY, CONTROL + "Z", ID_EDIT_UNDO, VIRTKEY, CONTROL + "X", ID_EDIT_CUT, VIRTKEY, CONTROL + "C", ID_EDIT_COPY, VIRTKEY, CONTROL + "V", ID_EDIT_PASTE, VIRTKEY, CONTROL + VK_BACK, ID_EDIT_UNDO, VIRTKEY, ALT + VK_DELETE, ID_EDIT_CUT, VIRTKEY, SHIFT + VK_INSERT, ID_EDIT_COPY, VIRTKEY, CONTROL + VK_INSERT, ID_EDIT_PASTE, VIRTKEY, SHIFT + VK_F6, ID_NEXT_PANE, VIRTKEY + VK_F6, ID_PREV_PANE, VIRTKEY, SHIFT +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "FileDescription", "SLNKDWFViewer Module" + VALUE "FileVersion", "1, 0, 0, 1" + VALUE "InternalName", "SLNKDWFViewer" + VALUE "LegalCopyright", "Copyright 2006" + VALUE "OriginalFilename", "SLNKDWFViewer.exe" + VALUE "ProductName", "SLNKDWFViewer Module" + VALUE "ProductVersion", "1, 0, 0, 1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDR_MAINFRAME "SLNKDWFViewer" +END + +STRINGTABLE +BEGIN + ID_FILE_NEW "Create a new document\nNew" + ID_FILE_OPEN "Open an existing document\nOpen" + ID_FILE_CLOSE "Close the active document\nClose" + ID_FILE_SAVE "Save the active document\nSave" + ID_FILE_SAVE_AS "Save the active document with a new name\nSave As" + ID_FILE_PAGE_SETUP "Change the printing options\nPage Setup" + ID_FILE_PRINT_SETUP "Change the printer and printing options\nPrint Setup" + ID_FILE_PRINT "Print the active document\nPrint" + ID_FILE_PRINT_PREVIEW "Display full pages\nPrint Preview" +END + +STRINGTABLE +BEGIN + ID_APP_ABOUT "Display program information, version number and copyright\nAbout" + ID_APP_EXIT "Quit the application; prompts to save documents\nExit" +END + +STRINGTABLE +BEGIN + ID_NEXT_PANE "Switch to the next window pane\nNext Pane" + ID_PREV_PANE "Switch back to the previous window pane\nPrevious Pane" +END + +STRINGTABLE +BEGIN + ID_WINDOW_NEW "Open another window for the active document\nNew Window" + ID_WINDOW_ARRANGE "Arrange icons at the bottom of the window\nArrange Icons" + ID_WINDOW_CASCADE "Arrange windows so they overlap\nCascade Windows" + ID_WINDOW_TILE_HORZ "Arrange windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_TILE_VERT "Arrange windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_SPLIT "Split the active window into panes\nSplit" +END + +STRINGTABLE +BEGIN + ID_EDIT_CLEAR "Erase the selection\nErase" + ID_EDIT_CLEAR_ALL "Erase everything\nErase All" + ID_EDIT_COPY "Copy the selection and put it on the Clipboard\nCopy" + ID_EDIT_CUT "Cut the selection and put it on the Clipboard\nCut" + ID_EDIT_FIND "Find the specified text\nFind" + ID_EDIT_PASTE "Insert Clipboard contents\nPaste" + ID_EDIT_REPEAT "Repeat the last action\nRepeat" + ID_EDIT_REPLACE "Replace specific text with different text\nReplace" + ID_EDIT_SELECT_ALL "Select the entire document\nSelect All" + ID_EDIT_UNDO "Undo the last action\nUndo" + ID_EDIT_REDO "Redo the previously undone action\nRedo" +END + +STRINGTABLE +BEGIN + ID_VIEW_TOOLBAR "Show or hide the toolbar\nToggle ToolBar" + ID_VIEW_STATUS_BAR "Show or hide the status bar\nToggle StatusBar" +END + +STRINGTABLE +BEGIN + ATL_IDS_SCSIZE "Change the window size" + ATL_IDS_SCMOVE "Change the window position" + ATL_IDS_SCMINIMIZE "Reduce the window to an icon" + ATL_IDS_SCMAXIMIZE "Enlarge the window to full size" + ATL_IDS_SCNEXTWINDOW "Switch to the next document window" + ATL_IDS_SCPREVWINDOW "Switch to the previous document window" + ATL_IDS_SCCLOSE "Close the active window and prompts to save the documents" +END + +STRINGTABLE +BEGIN + ATL_IDS_SCRESTORE "Restore the window to normal size" + ATL_IDS_SCTASKLIST "Activate Task List" + ATL_IDS_MDICHILD "Activate this window" +END + +STRINGTABLE +BEGIN + ATL_IDS_IDLEMESSAGE "Ready" +END + +STRINGTABLE +BEGIN + ATL_IDS_MRU_FILE "Open this document" +END + +STRINGTABLE +BEGIN + ID_ZOOM_EXTENTS "Zoom Extents\nZoom Extents" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Neutral (Sys. Default) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEUSD) +#ifdef _WIN32 +LANGUAGE LANG_NEUTRAL, SUBLANG_SYS_DEFAULT +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_LAYERS DIALOGEX 0, 0, 230, 302 +STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME +CAPTION "Layers" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,173,7,50,14 + PUSHBUTTON "Cancel",IDCANCEL,173,24,50,14 + LISTBOX IDC_LAYERLIST,7,7,161,288,LBS_SORT | LBS_NOINTEGRALHEIGHT | LBS_EXTENDEDSEL | WS_VSCROLL | WS_TABSTOP +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_LAYERS, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 223 + TOPMARGIN, 7 + BOTTOMMARGIN, 295 + END +END +#endif // APSTUDIO_INVOKED + +#endif // Neutral (Sys. Default) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/Standalone/SLNKDWFViewer.vcproj b/Standalone/SLNKDWFViewer.vcproj new file mode 100644 index 0000000..5a2fb72 --- /dev/null +++ b/Standalone/SLNKDWFViewer.vcproj @@ -0,0 +1,288 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Standalone/res/.gitignore b/Standalone/res/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/Standalone/res/SLNKDWFViewer.ico b/Standalone/res/SLNKDWFViewer.ico new file mode 100644 index 0000000..3b11c7a Binary files /dev/null and b/Standalone/res/SLNKDWFViewer.ico differ diff --git a/Standalone/res/SLNKDwfViewer.exe.manifest b/Standalone/res/SLNKDwfViewer.exe.manifest new file mode 100644 index 0000000..0057be9 --- /dev/null +++ b/Standalone/res/SLNKDwfViewer.exe.manifest @@ -0,0 +1,24 @@ + + + + + SLNKDwfViewer Application + + + + + + + diff --git a/Standalone/res/toolbar.bmp b/Standalone/res/toolbar.bmp new file mode 100644 index 0000000..a5cb458 Binary files /dev/null and b/Standalone/res/toolbar.bmp differ diff --git a/Standalone/resource.h b/Standalone/resource.h new file mode 100644 index 0000000..dd3e6e4 --- /dev/null +++ b/Standalone/resource.h @@ -0,0 +1,32 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by SLNKDWFViewer.rc +// +#define IDD_ABOUTBOX 100 +#define IDR_MAINFRAME 128 +#define IDD_LAYERS 201 +#define IDC_LAYERLIST 1000 +#define IDC_DLLVERSION 1001 +#define IDC_DLLPATH 1002 +#define IDC_DLLBUILD 1003 +#define IDC_DLLBUILDTIME 1003 +#define IDC_WHIPVERSION 1004 +#define IDC_DWFVERSION 1005 +#define IDC_DWF2VERSION 1005 +#define ID_VIEW_LAYERS 32772 +#define ID_ZOOM_IN 32774 +#define ID_ZOOM_EXTENTS 32777 +#define ID_ZOOM_OUT 32782 +#define IDP_PLACEHOLDER 32783 +#define IDC_COMBO 32784 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 202 +#define _APS_NEXT_COMMAND_VALUE 32785 +#define _APS_NEXT_CONTROL_VALUE 1004 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/Standalone/stdafx.cpp b/Standalone/stdafx.cpp new file mode 100644 index 0000000..9888bd2 --- /dev/null +++ b/Standalone/stdafx.cpp @@ -0,0 +1,9 @@ +// stdafx.cpp : source file that includes just the standard includes +// SLNKDWFViewer.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +#if (_ATL_VER < 0x0700) +#include +#endif //(_ATL_VER < 0x0700) diff --git a/Standalone/stdafx.h b/Standalone/stdafx.h new file mode 100644 index 0000000..0e8d45e --- /dev/null +++ b/Standalone/stdafx.h @@ -0,0 +1,37 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +// Change these values to use different versions +#define WINVER 0x0400 +//#define _WIN32_WINNT 0x0400 +#define _WIN32_IE 0x0400 +#define _RICHEDIT_VER 0x0100 + +#include +#include + +extern CAppModule _Module; + +#include + +#include +#include +#include +#include + +#if defined _M_IX86 + #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") +#elif defined _M_IA64 + #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"") +#elif defined _M_X64 + #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") +#else + #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") +#endif + +//JGL added +#include "../Viewer/ViewerLib.h" diff --git a/TO.Doc b/TO.Doc new file mode 100644 index 0000000..be0c9b4 Binary files /dev/null and b/TO.Doc differ diff --git a/Testing.txt b/Testing.txt new file mode 100644 index 0000000..4bee47f --- /dev/null +++ b/Testing.txt @@ -0,0 +1,21 @@ +Interessante files om te testen/ aandachtspunten: + +- f_66.dwf heeft rechtsboven (alleen) op regel K een Unicode tekst staan die + dus niet 100% correct verschaalt. (Unicode door doorsnede symbool denk ik) +- ac_c3_0.dwf heeft linksonder 3 keer schuine(!) bound teksten (de LSV) + KTextFormator::TextOutSpacing doet dat niet 100% goed +- ac_c3_0.dwf heeft diverse verticale texten zonder bounds. Die moeten wel + goed gegeeked worden. +- better_markups_large.dwf en andere zijn gemaakt met de DWFPrinter. + Die hebben geen extents +- budweiser3 heeft leuke Gouraud shading + TODO: De Gouraud lijnen tussendoor +- Muurtekening1.dwf gebruikt ScalaSans. Die moet wel op de server staan +- ttf_test-Model.dwf is goed om teksthoogte te controleren +- AC_C2_0 bevat lege teksten. Zoek op: ' ') + Zorg dat dit ook goed gaat bij geeken +- "1 - IRD Addition.dwf" geeft problemen met charset: SansSerif-->Dingbats soms +- 1030_A_00 heeft hele rare (hidden) labelteksten: {\Fiso.shx;8} +- Locatie.dwf (Brinkgreven buitensituatie) heeft heel veel TrueType texten en dan ook nog + vaak met verschillende rotatie. Optimalizaties met geekFontSize tikken hier goed aan +- SPCA heeft rechtsboven TrueType tekst die met kleine fontsize toch groot is. Goede geektest \ No newline at end of file diff --git a/Todo.txt b/Todo.txt new file mode 100644 index 0000000..e6dd51a --- /dev/null +++ b/Todo.txt @@ -0,0 +1,24 @@ +Bugs: + +- Symbool Star is bij ZwartWit niet geheel gesloten +- Bij Sommige tekeningen (ac_bad.dwf) valt bij bepaalde zoomfactoren de meest rechtse lijn weg +- Als Zoom Window actief dan werkt het contextmenu niet altijd +- Copy -commando laat zich niet altijd goed pasten in MS-Word. Paste-special werkt beter +- Hans Gersen: wil bij Esc op het print commando in de print preview blijven + +- Overigens zijn dat bij SPCA embedded fonts die 'vervallen' naar Arial +- Inventor_fire_nozzle_2D.dwf heeft meerdere Viewports. Achtergrondkleur gaat niet goed +- Bij resizen van IE raakt het plaatje vertekend +- Een dynamisch schaalbalkje is grappig +- Finder kan nu ook wel zonder temporary files +- Finder moet ook pagina's ondersteunen +- S_FALSE is geen geldige returncode. Je moet E_ codes gebruiken + +Uitbreidingen: +- XML met Alle ruimtes kunnen opvragen met hun oppervlakte +- [Techniek] Voor de array met contouren een van de template-MAPS gebruiken +- Ook meer XML info kunnen exporteren (ook van versie 0.55 tekeningen) +- Geen temporary files meer gebruiken + +Solved + diff --git a/Viewer/AboutDlg.cpp b/Viewer/AboutDlg.cpp new file mode 100644 index 0000000..b97ec5d --- /dev/null +++ b/Viewer/AboutDlg.cpp @@ -0,0 +1,48 @@ +// aboutdlg.cpp : implementation of the CAboutDlg class +// +///////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "resource.h" + +#include "aboutdlg.h" + +extern HINSTANCE g_hInstance; + +LRESULT CAboutDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +{ + CenterWindow(GetParent()); +#if 0 + if (FAILED (m_iAbout.CoCreateInstance (L"SLNKDWF.About"))) + { + ::MessageBox(NULL, "Unable to create object SLNKDWF.About", "SLNKDWF Viewer error", MB_ICONEXCLAMATION | MB_OK); + return FALSE; + } + + CComBSTR bDLLPath, bBuildTime, bUserContext, bVersionString; + m_iAbout->get_DLLPath(&bDLLPath); + m_iAbout->get_Buildtime(&bBuildTime); + m_iAbout->get_UserContext(&bUserContext); + m_iAbout->get_VersionString(&bVersionString); + SetDlgItemText(IDC_DLLPATH, CString(bDLLPath)); + SetDlgItemText(IDC_DLLBUILDTIME, CString(bBuildTime)); + SetDlgItemText(IDC_DLLVERSION, CString(bVersionString)); + +#endif + char module[_MAX_PATH]; // HMODULE + GetModuleFileName(g_hInstance, module, sizeof(module)); + + SetDlgItemText(IDC_DLLPATH, module); + + SetDlgItemText(IDC_DWFVERSION, _DWFTK_VERSION_STRING); + SetDlgItemText(IDC_WHIPVERSION, _WHIPTK_VERSION_STRING); + + + return TRUE; +} + +LRESULT CAboutDlg::OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + EndDialog(wID); + return 0; +} diff --git a/Viewer/AboutDlg.h b/Viewer/AboutDlg.h new file mode 100644 index 0000000..e745025 --- /dev/null +++ b/Viewer/AboutDlg.h @@ -0,0 +1,25 @@ +// aboutdlg.h : interface of the CAboutDlg class +// +///////////////////////////////////////////////////////////////////////////// + +#pragma once + +class CAboutDlg : public CDialogImpl +{ +public: + enum { IDD = IDD_ABOUTBOX }; + + BEGIN_MSG_MAP(CAboutDlg) + MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) + COMMAND_ID_HANDLER(IDOK, OnCloseCmd) + COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) + END_MSG_MAP() + +// Handler prototypes (uncomment arguments if needed): +// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) + + LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); + LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/); +}; diff --git a/Viewer/FindDlg.cpp b/Viewer/FindDlg.cpp new file mode 100644 index 0000000..c1a0641 --- /dev/null +++ b/Viewer/FindDlg.cpp @@ -0,0 +1,49 @@ +// aboutdlg.cpp : implementation of the CFindDlg class +// +///////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "resource.h" + +#include "FindDlg.h" + +LRESULT CFindDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +{ + CenterWindow(GetParent()); + DlgResize_Init(); + m_ListBox.Attach(GetDlgItem(IDC_LAYERLIST)); + LONG lCount; + + CWhip2DCImpl m_iWhip2DC; + CDWFFileImpl m_iDWFFile; + CEPlotSectionsImpl *piEPlotSections; + m_iDWFFile.Open(m_dwfPath); + + piEPlotSections = m_iDWFFile.get_EPlotSections(); + lCount = piEPlotSections->get_Count(); + if (lCount > 0) + { + m_iWhip2DC.Load(NULL, piEPlotSections->get_Item(m_nPage), L"", L".*", + 0, 0, VARIANT_TRUE /*center*/, VARIANT_FALSE /* Maximize */); + } + else + { + m_iWhip2DC.Load(NULL, NULL, m_dwfPath, L".*", 0, 0, VARIANT_TRUE /*center*/, VARIANT_FALSE /* Maximize */); + } + m_iWhip2DC.FindTexts(""); + m_iWhip2DC.get_TextCount(&lCount); + for (int i=0;i < lCount;i++) + { + CFoundText tFound; + m_iWhip2DC.get_TextItem(i, tFound); + if (tFound.m_FoundText.string().is_ascii()) + m_ListBox.AddString(CString(tFound.m_FoundText.string().ascii())); + } + return TRUE; +} + +LRESULT CFindDlg::OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + EndDialog(wID); + return 0; +} diff --git a/Viewer/FindDlg.h b/Viewer/FindDlg.h new file mode 100644 index 0000000..ea33953 --- /dev/null +++ b/Viewer/FindDlg.h @@ -0,0 +1,44 @@ +// aboutdlg.h : interface of the CFindDlg class +// +///////////////////////////////////////////////////////////////////////////// + +#pragma once + +class CFindDlg : public CDialogImpl, + public CDialogResize +{ +public: + enum { IDD = IDD_LAYERS }; + + CFindDlg::CFindDlg(const CString &dwfPath, int nPage) + { + m_dwfPath = dwfPath; + m_nPage = nPage; + }; + + BEGIN_MSG_MAP(CFindDlg) + MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) + COMMAND_ID_HANDLER(IDOK, OnCloseCmd) + COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) + CHAIN_MSG_MAP(CDialogResize) + END_MSG_MAP() + + BEGIN_DLGRESIZE_MAP(CFindDlg) + DLGRESIZE_CONTROL(IDOK, DLSZ_MOVE_X) + DLGRESIZE_CONTROL(IDCANCEL, DLSZ_MOVE_X) + DLGRESIZE_CONTROL(IDC_LAYERLIST, DLSZ_SIZE_X|DLSZ_SIZE_Y) + END_DLGRESIZE_MAP() + +// Handler prototypes (uncomment arguments if needed): +// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) + + LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); + LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + +private: + CListBox m_ListBox; + CString m_dwfPath; + int m_nPage; +}; diff --git a/Viewer/LayerDlg.cpp b/Viewer/LayerDlg.cpp new file mode 100644 index 0000000..85a958d --- /dev/null +++ b/Viewer/LayerDlg.cpp @@ -0,0 +1,30 @@ +// aboutdlg.cpp : implementation of the CLayerDlg class +// +///////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "resource.h" + +#include "layerdlg.h" + +LRESULT CLayerDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +{ + CenterWindow(GetParent()); + DlgResize_Init(); + m_ListBox.Attach(GetDlgItem(IDC_LAYERLIST)); + LONG lCount; + m_iWhip2DC->get_LayerCount(&lCount); + for (int i=0;i < lCount;i++) + { + CComBSTR lName; + m_iWhip2DC->get_LayerItem(i, &lName); + m_ListBox.AddString(CString(lName)); + } + return TRUE; +} + +LRESULT CLayerDlg::OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + EndDialog(wID); + return 0; +} diff --git a/Viewer/MainFrm.cpp b/Viewer/MainFrm.cpp new file mode 100644 index 0000000..f43b591 --- /dev/null +++ b/Viewer/MainFrm.cpp @@ -0,0 +1,205 @@ +// MainFrm.cpp : implmentation of the CMainFrame class +// +///////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "resource.h" + +#include "aboutdlg.h" +#include "FindDlg.h" +#include "SLNKDwfViewerView.h" +#include "MainFrm.h" + +BOOL CMainFrame::PreTranslateMessage(MSG* pMsg) +{ + if(CFrameWindowImpl::PreTranslateMessage(pMsg)) + return TRUE; + + return m_view.PreTranslateMessage(pMsg); +} + +BOOL CMainFrame::OnIdle() +{ + UIUpdateToolBar(); + return FALSE; +} + +LRESULT CMainFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +{ + CreateSimpleToolBar(); + +// CreateSimpleStatusBar(); + ATLTRACE("\nEarly with m_Combo %x", m_Combo.m_hWnd); + + m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE); + + UIAddToolBar(m_hWndToolBar); +// UISetCheck(ID_VIEW_TOOLBAR, 1); + + // register object for message filtering and idle updates +// TODO: Het volgende crashed en lijkt niet echt nodig? +// CMessageLoop* pLoop = _Module.GetMessageLoop(); +// ATLASSERT(pLoop != NULL); +/// pLoop->AddMessageFilter(this); +/// pLoop->AddIdleHandler(this); + + // Create ComboBox in ToolBar + RECT rcCombo = { 190, 1, 440, 200 }; // Hardcode position for now... + DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_VSCROLL | CBS_SIMPLE | CBS_DROPDOWNLIST; + ATLTRACE("\nAbout to Create with m_Combo %x", m_Combo.m_hWnd); + m_Combo.Create(m_hWnd, rcCombo, NULL, dwStyle, 0, IDC_COMBO); + m_Combo.SetFont(AtlGetDefaultGuiFont()); + m_Combo.SetParent(m_hWndToolBar); + + return 0; +} + +void CMainFrame::SetDWF(const CString &dwfPath) +{ + SetWindowText(dwfPath); + + m_view.SetDWF(dwfPath); + // Maak de pagina's aan + m_Combo.ResetContent(); + try + { + CDWFFileImpl m_iDWFFile; + CEPlotSectionsImpl *piEPlotSections; + + m_iDWFFile.Open(dwfPath); + + piEPlotSections = m_iDWFFile.get_EPlotSections(); + LONG lCount; + lCount = piEPlotSections->get_Count(); + + for (LONG i=0; iget_Item(i); + m_Combo.AddString(piEPlotSection->get_Title()); + } + ATLTRACE("\nDone filling ComboBox"); + } + catch (CString &ee) + { + ATLTRACE(ee); + //DoMessage(dc, ee); // komt later vanzelf wel + } + + m_Combo.SetCurSel(0); +} + +LRESULT CMainFrame::OnFileOpen(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + CFileDialog dlg(TRUE, _T("dwf"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("DWF Files (*.dwf)\0*.dwf\0All Files (*.*)\0*.*\0"), m_hWnd); + if(dlg.DoModal() == IDOK) + { + m_view.SetDWF(CString(dlg.m_szFileName)); + } + + return 0; +} + +LRESULT CMainFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + PostMessage(WM_CLOSE); + return 0; +} + +LRESULT CMainFrame::onSelChange(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + int nTab = m_Combo.GetCurSel(); + m_view.SetPage(nTab); + return 0; +} + +LRESULT CMainFrame::OnZoomExtents(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + m_view.Zoom(1.0); + return 0; +} + +LRESULT CMainFrame::OnZoomIn(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + m_view.Zoom(m_view.GetZoomScale() * (1 + m_view.GetZoomDelta())); + m_view.NotifyParentZoomChanged(); + return 0; +} + +LRESULT CMainFrame::OnZoomOut(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + m_view.Zoom(m_view.GetZoomScale() / (1 + m_view.GetZoomDelta())); + m_view.NotifyParentZoomChanged(); + return 0; +} + +LRESULT CMainFrame::OnFilePrint(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + CPrintDialog dlg(FALSE); + dlg.m_pd.hDevMode = m_devmode.CopyToHDEVMODE(); + dlg.m_pd.hDevNames = m_printer.CopyToHDEVNAMES(); + dlg.m_pd.nMinPage = 1; + dlg.m_pd.nMaxPage = m_Combo.GetCount(); + + if(dlg.DoModal() == IDOK) + { + m_devmode.CopyFromHDEVMODE(dlg.m_pd.hDevMode); + m_printer.ClosePrinter(); + m_printer.OpenPrinter(dlg.m_pd.hDevNames, m_devmode.m_pDevMode); + + CPrintJob job; + job.StartPrintJob(false, m_printer, m_devmode.m_pDevMode, this, m_view.m_dwfPath, 0, 0, (dlg.PrintToFile() != FALSE)); + } + + ::GlobalFree(dlg.m_pd.hDevMode); + ::GlobalFree(dlg.m_pd.hDevNames); + + return 0; +} + +LRESULT CMainFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + CAboutDlg dlg; + dlg.DoModal(); + + int nTab = m_Combo.GetCurSel(); + CFindDlg dlg2(m_view.m_dwfPath, nTab); + dlg2.DoModal(); + + return 0; +} + +LRESULT CMainFrame::OnViewLayers(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ +// CLayerDlg dlg(m_view.GetWhip2DC()); +// dlg.DoModal(); + + return 0; +} + +//print job info callbacks + bool CMainFrame::IsValidPage(UINT nPage) +{ + return (nPage == 0); // we have only one page +} + + bool CMainFrame::PrintPage(UINT nPage, HDC hDC) +{ + if (nPage >= 1) // we have only one page + return false; + + CRect rcPage + ( 0, 0, + ::GetDeviceCaps(hDC, PHYSICALWIDTH) - 2 * ::GetDeviceCaps(hDC, PHYSICALOFFSETX), + ::GetDeviceCaps(hDC, PHYSICALHEIGHT) - 2 * ::GetDeviceCaps(hDC, PHYSICALOFFSETY) ); + + CDCHandle dc = hDC; + CClientDC dcScreen(m_hWnd); + CDC dcMem; + dcMem.CreateCompatibleDC(dcScreen); + + CWhip2DCImpl iWhip2DC; + PaintToDC(hDC, m_view.m_dwfPath, 0, iWhip2DC, rcPage.Size(), TRUE); + + return true; +} diff --git a/Viewer/SLNKDWFViewer.aps b/Viewer/SLNKDWFViewer.aps new file mode 100644 index 0000000..85cbc31 Binary files /dev/null and b/Viewer/SLNKDWFViewer.aps differ diff --git a/Viewer/SLNKDWFViewer.rc b/Viewer/SLNKDWFViewer.rc new file mode 100644 index 0000000..7cc1235 --- /dev/null +++ b/Viewer/SLNKDWFViewer.rc @@ -0,0 +1,390 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "atlres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""atlres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Toolbar +// + +IDR_MAINFRAME TOOLBAR 16, 15 +BEGIN + BUTTON ID_ZOOM_IN + BUTTON ID_ZOOM_OUT + SEPARATOR + BUTTON ID_ZOOM_EXTENTS + BUTTON ID_FILE_PRINT + SEPARATOR + BUTTON ID_APP_ABOUT +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDR_MAINFRAME BITMAP "res\\Toolbar.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDR_MAINFRAME MENU +BEGIN + POPUP "&File" + BEGIN + MENUITEM "&New\tCtrl+N", ID_FILE_NEW + MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN + MENUITEM "&Save\tCtrl+S", ID_FILE_SAVE + MENUITEM "Save &As...", ID_FILE_SAVE_AS + MENUITEM SEPARATOR + MENUITEM "&Print...\tCtrl+P", ID_FILE_PRINT + MENUITEM "Print Pre&view", ID_FILE_PRINT_PREVIEW + MENUITEM "P&rint Setup...", ID_FILE_PRINT_SETUP + MENUITEM SEPARATOR + MENUITEM "E&xit", ID_APP_EXIT + END + POPUP "&Edit" + BEGIN + MENUITEM "&Undo\tCtrl+Z", ID_EDIT_UNDO + MENUITEM SEPARATOR + MENUITEM "Cu&t\tCtrl+X", ID_EDIT_CUT + MENUITEM "&Copy\tCtrl+C", ID_EDIT_COPY + MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE + END + POPUP "&View" + BEGIN + MENUITEM "&Toolbar", ID_VIEW_TOOLBAR + MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR + MENUITEM "Layers", ID_VIEW_LAYERS + END + POPUP "&Help" + BEGIN + MENUITEM "&About SLNKDWFViewer...", ID_APP_ABOUT + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON "res\\SLNKDWFViewer.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOGEX 0, 0, 247, 161 +STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "About" +FONT 8, "MS Sans Serif", 0, 0, 0x0 +BEGIN + DEFPUSHBUTTON "OK",IDOK,190,140,50,14 + CTEXT "SLNKDWFViewer Application v1.0\n\n(c) Copyright 2006",IDC_STATIC,7,55,136,27 + ICON IDR_MAINFRAME,IDC_STATIC,55,26,20,20 + LTEXT "Static",IDC_DLLPATH,55,84,185,8 + LTEXT "Dll",IDC_STATIC,8,98,9,8 + LTEXT "Static",IDC_DLLVERSION,56,98,119,8 + LTEXT "Version",IDC_STATIC,23,97,24,8 + LTEXT "Built",IDC_STATIC,23,111,20,8 + LTEXT "Static",IDC_DLLBUILDTIME,56,112,131,8 + LTEXT "Path",IDC_STATIC,23,84,16,8 + LTEXT "Static",IDC_WHIPVERSION,56,139,131,8 + LTEXT "Static",IDC_DWFVERSION,55,126,131,8 + LTEXT "DWF",IDC_STATIC,24,126,20,8 + LTEXT "Whip",IDC_STATIC,24,139,20,8 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 240 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Accelerator +// + +IDR_MAINFRAME ACCELERATORS +BEGIN + "N", ID_FILE_NEW, VIRTKEY, CONTROL + "O", ID_FILE_OPEN, VIRTKEY, CONTROL + "S", ID_FILE_SAVE, VIRTKEY, CONTROL + "P", ID_FILE_PRINT, VIRTKEY, CONTROL + "Z", ID_EDIT_UNDO, VIRTKEY, CONTROL + "X", ID_EDIT_CUT, VIRTKEY, CONTROL + "C", ID_EDIT_COPY, VIRTKEY, CONTROL + "V", ID_EDIT_PASTE, VIRTKEY, CONTROL + VK_BACK, ID_EDIT_UNDO, VIRTKEY, ALT + VK_DELETE, ID_EDIT_CUT, VIRTKEY, SHIFT + VK_INSERT, ID_EDIT_COPY, VIRTKEY, CONTROL + VK_INSERT, ID_EDIT_PASTE, VIRTKEY, SHIFT + VK_F6, ID_NEXT_PANE, VIRTKEY + VK_F6, ID_PREV_PANE, VIRTKEY, SHIFT +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "FileDescription", "SLNKDWFViewer Module" + VALUE "FileVersion", "1, 0, 0, 1" + VALUE "InternalName", "SLNKDWFViewer" + VALUE "LegalCopyright", "Copyright 2006" + VALUE "OriginalFilename", "SLNKDWFViewer.exe" + VALUE "ProductName", "SLNKDWFViewer Module" + VALUE "ProductVersion", "1, 0, 0, 1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDR_MAINFRAME "SLNKDWFViewer" +END + +STRINGTABLE +BEGIN + ID_FILE_NEW "Create a new document\nNew" + ID_FILE_OPEN "Open an existing document\nOpen" + ID_FILE_CLOSE "Close the active document\nClose" + ID_FILE_SAVE "Save the active document\nSave" + ID_FILE_SAVE_AS "Save the active document with a new name\nSave As" + ID_FILE_PAGE_SETUP "Change the printing options\nPage Setup" + ID_FILE_PRINT_SETUP "Change the printer and printing options\nPrint Setup" + ID_FILE_PRINT "Print the active document\nPrint" + ID_FILE_PRINT_PREVIEW "Display full pages\nPrint Preview" +END + +STRINGTABLE +BEGIN + ID_APP_ABOUT "Display program information, version number and copyright\nAbout" + ID_APP_EXIT "Quit the application; prompts to save documents\nExit" +END + +STRINGTABLE +BEGIN + ID_NEXT_PANE "Switch to the next window pane\nNext Pane" + ID_PREV_PANE "Switch back to the previous window pane\nPrevious Pane" +END + +STRINGTABLE +BEGIN + ID_WINDOW_NEW "Open another window for the active document\nNew Window" + ID_WINDOW_ARRANGE "Arrange icons at the bottom of the window\nArrange Icons" + ID_WINDOW_CASCADE "Arrange windows so they overlap\nCascade Windows" + ID_WINDOW_TILE_HORZ "Arrange windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_TILE_VERT "Arrange windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_SPLIT "Split the active window into panes\nSplit" +END + +STRINGTABLE +BEGIN + ID_EDIT_CLEAR "Erase the selection\nErase" + ID_EDIT_CLEAR_ALL "Erase everything\nErase All" + ID_EDIT_COPY "Copy the selection and put it on the Clipboard\nCopy" + ID_EDIT_CUT "Cut the selection and put it on the Clipboard\nCut" + ID_EDIT_FIND "Find the specified text\nFind" + ID_EDIT_PASTE "Insert Clipboard contents\nPaste" + ID_EDIT_REPEAT "Repeat the last action\nRepeat" + ID_EDIT_REPLACE "Replace specific text with different text\nReplace" + ID_EDIT_SELECT_ALL "Select the entire document\nSelect All" + ID_EDIT_UNDO "Undo the last action\nUndo" + ID_EDIT_REDO "Redo the previously undone action\nRedo" +END + +STRINGTABLE +BEGIN + ID_VIEW_TOOLBAR "Show or hide the toolbar\nToggle ToolBar" + ID_VIEW_STATUS_BAR "Show or hide the status bar\nToggle StatusBar" +END + +STRINGTABLE +BEGIN + ATL_IDS_SCSIZE "Change the window size" + ATL_IDS_SCMOVE "Change the window position" + ATL_IDS_SCMINIMIZE "Reduce the window to an icon" + ATL_IDS_SCMAXIMIZE "Enlarge the window to full size" + ATL_IDS_SCNEXTWINDOW "Switch to the next document window" + ATL_IDS_SCPREVWINDOW "Switch to the previous document window" + ATL_IDS_SCCLOSE "Close the active window and prompts to save the documents" +END + +STRINGTABLE +BEGIN + ATL_IDS_SCRESTORE "Restore the window to normal size" + ATL_IDS_SCTASKLIST "Activate Task List" + ATL_IDS_MDICHILD "Activate this window" +END + +STRINGTABLE +BEGIN + ATL_IDS_IDLEMESSAGE "Ready" +END + +STRINGTABLE +BEGIN + ATL_IDS_MRU_FILE "Open this document" +END + +STRINGTABLE +BEGIN + ID_ZOOM_EXTENTS "Zoom Extents\nZoom Extents" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Neutral (Sys. Default) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEUSD) +#ifdef _WIN32 +LANGUAGE LANG_NEUTRAL, SUBLANG_SYS_DEFAULT +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_LAYERS DIALOGEX 0, 0, 230, 302 +STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME +CAPTION "Layers" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,173,7,50,14 + PUSHBUTTON "Cancel",IDCANCEL,173,24,50,14 + LISTBOX IDC_LAYERLIST,7,7,161,288,LBS_SORT | LBS_NOINTEGRALHEIGHT | LBS_EXTENDEDSEL | WS_VSCROLL | WS_TABSTOP +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_LAYERS, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 223 + TOPMARGIN, 7 + BOTTOMMARGIN, 295 + END +END +#endif // APSTUDIO_INVOKED + +#endif // Neutral (Sys. Default) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/Viewer/SLNKDWFViewerView.cpp b/Viewer/SLNKDWFViewerView.cpp new file mode 100644 index 0000000..9594893 --- /dev/null +++ b/Viewer/SLNKDWFViewerView.cpp @@ -0,0 +1,362 @@ +// SLNKDwfViewerView.cpp : implementation of the CSLNKDwfViewerView class +// +///////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" + +#include "atlgdix.h" + +#include "SLNKDwfViewerView.h" + +#define SCL 1 + +CSLNKDwfViewerView::CSLNKDwfViewerView() +{ + m_nPage = 0; + m_busyPanning = FALSE; + m_Bitmap = NULL; +} + +CSLNKDwfViewerView::~CSLNKDwfViewerView() +{ + if (m_Bitmap != NULL) delete m_Bitmap; +} + + + +BOOL CSLNKDwfViewerView::PreTranslateMessage(MSG* pMsg) +{ + pMsg; + return FALSE; +} + +void CSLNKDwfViewerView::SetDWF(const CString &dwfPath) +{ + m_dwfPath = dwfPath; + if (m_Bitmap != NULL) + { + delete m_Bitmap; // It is dirty + m_Bitmap = NULL; + } + + SetZoomMode(ZOOMMODE_IN); + + SetPage(0); +} + +void DoMessage(CDCHandle dc, const CString msg) +{ + CRect clrc; + dc.GetClipBox(clrc); + + FillRect(dc,clrc,GetSysColorBrush( COLOR_WINDOW )); + SetTextColor(dc, GetSysColor( COLOR_WINDOWTEXT )); + + CString tok(msg); + tok.Replace("~", "\n"); // We ondersteunen ook ~ als newline + RECT rc = { 0, 0, clrc.Width(), 0}; + GetClientRect(dc.WindowFromDC(), clrc); + int height = DrawText(dc, tok, tok.GetLength(), &rc, DT_CALCRECT); // Grootte bepalen + rc.top = clrc.Height()/2 - rc.bottom/2; // Vertikaal centreren + rc.bottom = clrc.Height()/2 + rc.bottom/2; + height = DrawText(dc, tok, tok.GetLength(), &rc, DT_TOP); + ATLASSERT(height); +} + +void PaintToDC(HDC dc, CString dwfPath, int nPage, + CWhip2DCImpl &iWhip2DC, CSize wSize, + BOOL forPrint /*=FALSE*/) +{ + try { + CDWFFileImpl m_iDWFFile; + CEPlotSectionsImpl *piEPlotSections; + m_iDWFFile.Open(dwfPath); + + piEPlotSections = m_iDWFFile.get_EPlotSections(); + LONG lCount = piEPlotSections->get_Count(); + if (lCount > 0) + { + iWhip2DC.Load(dc, piEPlotSections->get_Item(nPage), L"", L".*", + wSize.cx, wSize.cy, VARIANT_TRUE /*center*/, VARIANT_FALSE /* Maximize */); + } + else + { + iWhip2DC.Load(dc, NULL, dwfPath, L".*", + wSize.cx, wSize.cy, VARIANT_TRUE /*center*/, VARIANT_FALSE /* Maximize */); + } + + int mm = GetMapMode(dc); + SetMapMode(dc, MM_TEXT); + + if (forPrint) + iWhip2DC.put_paperColor(0xFFFFFF); // Altijd wit papier + + iWhip2DC.Paint(VARIANT_FALSE); + SetMapMode(dc, mm); + } + catch (CString &ee) + { + DoMessage(dc, ee); + } + catch (...) + { + DoMessage(dc, "Unhandled Exception"); + } +} + +BOOL DoEvents() +{ + MSG msg; + + while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) + { + if(msg.message==WM_QUIT) + return FALSE; + TranslateMessage(&msg); + DispatchMessage(&msg); + } + return TRUE; +} + +BOOL CSLNKDwfViewerView::my_progress_action(void *param, double progress) +{ + CSLNKDwfViewerView *vw = (CSLNKDwfViewerView *)param; +// Erg instabiel (door recursieve WM_PAINT?) +// if (!DoEvents()) +// return FALSE; + if (GetSystemMetrics(SM_REMOTESESSION)) + { // App is running on a remote session. + return TRUE; // Geen preview bij terminal services + } + + if (GetTickCount() - vw->m_Timer > 100) + { // Preview time + // Tijdens het blitten willen we geen vertalingen + CRect rc; + vw->GetClientRect(rc); + SIZE orgSize; + + ::SetViewportExtEx(vw->m_hDCOriginal, rc.Size().cx, rc.Size().cy, &orgSize); + CPoint pt; + ::GetViewportOrgEx(vw->m_hDCOriginal, &pt); + CPoint pt2; + vw->m_MemDC.SetViewportOrg(0,0, &pt2); + + ::BitBlt(vw->m_hDCOriginal, + -pt.x, -pt.y, rc.Width(), rc.Height(), + vw->m_MemDC, 0, 0, SRCCOPY); + vw->m_MemDC.SetViewportOrg(pt2); + + if (0) + { // Progress lijntje + // We kunnen rustig rechtstreeks op m_hDCOriginal tekenen want + // er komt toch nog een definitieve bitmap overheen + CPen p; + p.CreatePen(PS_SOLID ,0, RGB(128,128,128)); + HPEN pOld = (HPEN)SelectObject(vw->m_hDCOriginal, p); + CPoint org; + MoveToEx(vw->m_hDCOriginal, 1, 0, &org); + LineTo(vw->m_hDCOriginal, 1, (int)(progress*rc.Height())); + MoveToEx(vw->m_hDCOriginal, org.x, org.y, NULL); + SelectObject(vw->m_hDCOriginal, pOld); + } + ::SetViewportExtEx(vw->m_hDCOriginal, orgSize.cx, orgSize.cy, NULL); + vw->m_Timer = GetTickCount(); + } + return TRUE; // Continue +}; + +void CSLNKDwfViewerView::DoPaint(CDCHandle dc) +{ + if (m_dwfPath == "") + { + DoMessage(dc, "Open DWF first"); + return; + } + + // Altijd 10% van ons beeld zoomen met scrollbars + CRect rc; + GetClientRect(rc); + SetScrollLine(max(rc.Size().cx / GetZoomScale() / 10 + 0.5, 1), + max(rc.Size().cy / GetZoomScale() / 10 + 0.5, 1)); + + // Default 0.5% inzoomen + CSize wSize; + dc.GetViewportExt(&wSize); +#if 0 + CPoint pOrg; + dc.GetViewportOrg(&pOrg); + + pOrg.x += MulDiv(wSize.cx, 1, 200); // Half verschuiven + pOrg.y += MulDiv(wSize.cy, 1, 200); + dc.SetViewportOrg(pOrg); + + wSize.cx = MulDiv(wSize.cx, 198, 200); + wSize.cy = MulDiv(wSize.cy, 198, 200); +#endif + + CWaitCursor Wait; + + if (0&&GetZoomScale() != 1.0) + ::PaintToDC(dc, m_dwfPath, m_nPage, m_iWhip2DC, wSize); + else + { + CPoint pt; + dc.GetViewportOrg(&pt); + + if (m_Bitmap == NULL || + m_BitmapViewportOrigin != pt || + m_BitmapViewportExt != wSize || + m_BitmapClientRect != rc) + { // Bitmap opnieuw maken + if (m_Bitmap != NULL) delete m_Bitmap; + CBitmapHandle pOldBitmap; + + m_MemDC.CreateCompatibleDC(dc); + // Create a bitmap big enough to hold the window's image + + m_Bitmap = new CBitmap; + m_Bitmap->CreateCompatibleBitmap(dc, rc.Width(), rc.Height()); + + m_MemDC.SetViewportOrg(pt.x, pt.y); + pOldBitmap = m_MemDC.SelectBitmap(*m_Bitmap); + + m_Timer = GetTickCount(); + m_hDCOriginal = dc; // Hier gaan we wel progress op tekenen + m_iWhip2DC.set_progress_action(my_progress_action, (void *) this); + + ::PaintToDC(m_MemDC, m_dwfPath, m_nPage, m_iWhip2DC, wSize); + + // Select the original bitmap back in + m_MemDC.SelectBitmap(pOldBitmap); + m_MemDC.DeleteDC(); + + m_BitmapViewportOrigin = pt; + m_BitmapViewportExt = wSize; + m_BitmapClientRect = rc; + + } + // Nu het echt tonen + { + CBitmapHandle pOldBitmap; + CDC MemDC; + + // And a memory DC, set Map Mode + MemDC.CreateCompatibleDC(dc); + pOldBitmap = MemDC.SelectBitmap(*m_Bitmap); + + dc.SetViewportExt(rc.Size()); + dc.BitBlt( -pt.x, -pt.y, rc.Width(), rc.Height(), MemDC, 0, 0, SRCCOPY ); + MemDC.SelectBitmap(pOldBitmap); + MemDC.DeleteDC(); + } + } + return; +} + +void CSLNKDwfViewerView::SetPage(int nPage) +{ + m_nPage = nPage; + if (m_Bitmap != NULL) + { + delete m_Bitmap; // It is dirty + m_Bitmap = NULL; + } + CRect rc; + GetClientRect(&rc); + SetScrollSize(rc.Width()*SCL, rc.Height()*SCL); + SetScrollLine(0, 0); + SetZoomScaleMin(.5 / SCL); + Zoom(1 / SCL); + SetScrollLine(rc.Width() / SCL, rc.Height() / SCL); +}; + +LRESULT CSLNKDwfViewerView::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) +{ + CZoomScrollWindowImpl::OnSize(uMsg, wParam, lParam, bHandled); + int cx = GET_X_LPARAM(lParam); + int cy = GET_Y_LPARAM(lParam); + CRect rc; + GetClientRect(&rc); + if (rc.Width()>0 && rc.Height()>0) + SetScrollSize(rc.Width()*SCL, rc.Height()*SCL); + + return 1; +} + +LRESULT CSLNKDwfViewerView::OnMouseWheel(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/) +{ + int zDelta = (int)(short)HIWORD(wParam); + int fwKeys = (int)(short)LOWORD(wParam); + + CPoint pt(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + + ScreenToClient(&pt); + + double delta = (fwKeys&MK_SHIFT)?0.1:(fwKeys&MK_CONTROL)?0.01:1.0; + double zoom = zDelta / WHEEL_DELTA; + if(zDelta > 0) + zoom = zoom * (1+ GetZoomDelta()*delta); + else + zoom = abs(zoom) / (1+ GetZoomDelta()*delta); + + CRect rc; + GetClientRect(&rc); + + CPoint newcenter(pt.x + (rc.right / 2.0 - pt.x) / zoom, + pt.y + (rc.bottom / 2.0 - pt.y) / zoom); + + Zoom(newcenter, GetZoomScale() * zoom); + + NotifyParentZoomChanged(); + + return 0; +} + +LRESULT CSLNKDwfViewerView::OnRButtonDown(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled) +{ + POINT point = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; + m_PanTotal = CPoint(0, 0); + + m_PanStartPoint = point; + GetScrollOffset(m_PanStartScroll); + SetCapture(); // Zo kunnen we ook "buiten" het venster doorpannen + m_busyPanning = TRUE; +// tPanStart = GetTickCount(); + + bHandled = FALSE; + return 0; +} + +LRESULT CSLNKDwfViewerView::OnRButtonUp(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled) +{ + if (m_busyPanning) + { + ReleaseCapture(); + + m_busyPanning = FALSE; + + // Invalidate(); // Als meer dan 1/10 seconde is nog niet alles getekend + } + bHandled = FALSE; + return 0; +} +LRESULT CSLNKDwfViewerView::OnMouseMove(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled) +{ + if (m_busyPanning && (wParam & MK_RBUTTON)) // Pannen + { + POINT point = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; + + CPoint traveled = m_PanStartPoint - point; + + m_PanTotal += traveled; + +// SetCursor(::LoadCursor(AfxGetResourceHandle(), MAKEINTRESOURCE(IDC_HANDJE))); + + SetScrollOffset(m_PanStartScroll + traveled); + m_PanStartPoint = point; + GetScrollOffset(m_PanStartScroll); + } + bHandled = FALSE; + return 0; +} diff --git a/Viewer/SLNKDwfViewerView.h b/Viewer/SLNKDwfViewerView.h new file mode 100644 index 0000000..a75db04 --- /dev/null +++ b/Viewer/SLNKDwfViewerView.h @@ -0,0 +1,93 @@ +// SLNKDwfViewerView.h : interface of the CSLNKDwfViewerView class +// +///////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "resource.h" +#include "atlgdix.h" + +void PaintToDC(HDC dc, CString dwfPath, int nPage, + CWhip2DCImpl &iWhip2DC, CSize wSize, + BOOL forPrint = FALSE); + +class CSLNKDwfViewerView : public CZoomScrollWindowImpl +// , public CDoubleBufferImpl +// , public COffscreenDraw +// , public CPrintPreviewWindowImpl +{ +public: + DECLARE_WND_CLASS(NULL) + + CSLNKDwfViewerView(); + ~CSLNKDwfViewerView(); + + BOOL PreTranslateMessage(MSG* pMsg); + + BEGIN_MSG_MAP(CSLNKDwfViewerView) + MESSAGE_HANDLER(WM_CREATE, OnCreate) + MESSAGE_HANDLER(WM_SIZE, OnSize) + MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground) + MESSAGE_HANDLER(WM_MOUSEWHEEL, OnMouseWheel) + MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) + MESSAGE_HANDLER(WM_RBUTTONDOWN, OnRButtonDown) + MESSAGE_HANDLER(WM_RBUTTONUP, OnRButtonUp) + MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove) + +// CHAIN_MSG_MAP(CPrintPreviewWindowImpl) +// CHAIN_MSG_MAP(CDoubleBufferImpl) +// CHAIN_MSG_MAP(COffscreenDraw) + CHAIN_MSG_MAP(CZoomScrollWindowImpl) + END_MSG_MAP() + + LRESULT OnMouseWheel(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); + LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) + { + return 1; // no background painting needed. Scheelt geflikker + } + + int OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) + { + CZoomScrollWindowImpl::OnCreate(uMsg, wParam, lParam, bHandled); +// HWND hWndToolBar = CreateSimpleToolBarCtrl(m_hWnd, IDR_MAINFRAME, FALSE, ATL_SIMPLE_TOOLBAR_PANE_STYLE); + return 1; + } + + LRESULT OnRButtonDown(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled); + LRESULT OnRButtonUp(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled); + LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled); + + LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled) + { + SetFocus(); + bHandled = FALSE; + return 0; + } + + LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); + + void DoPaint(CDCHandle dc); + + void SetDWF(const CString &dwfPath); + void SetPage(int nPage); + CWhip2DCImpl *GetWhip2DC() + { + return &m_iWhip2DC; + } + + CString m_dwfPath; +private: + CDC m_MemDC; + CBitmap *m_Bitmap; + CPoint m_BitmapViewportOrigin; // zodat je weet wanneer opnieuw genereren + CSize m_BitmapViewportExt; + CRect m_BitmapClientRect; + + int m_nPage; + CWhip2DCImpl m_iWhip2DC; + BOOL m_busyPanning; + CPoint m_PanStartPoint, m_PanTotal, m_PanStartScroll; + CDCHandle m_hDCOriginal; + static BOOL my_progress_action(void *param, double progress); + time_t m_Timer; +}; diff --git a/Viewer/Viewer.vcproj b/Viewer/Viewer.vcproj new file mode 100644 index 0000000..12bff3c --- /dev/null +++ b/Viewer/Viewer.vcproj @@ -0,0 +1,245 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Viewer/ViewerLib.h b/Viewer/ViewerLib.h new file mode 100644 index 0000000..36ef19a --- /dev/null +++ b/Viewer/ViewerLib.h @@ -0,0 +1,22 @@ +#include + +#include +#include +#include +#include + +//JGL added +#include +#include +#include +#include +#include + +#include "atlrx.h" + +#include "../SLNKDWFImpl/SLNKDWFStaticRO.h" + +#include "../SlnkdwfImpl/Whip2DCImpl.h" + +#include "SlnkDWFViewerView.h" +#include "Mainfrm.h" diff --git a/Viewer/_layerdlg.h b/Viewer/_layerdlg.h new file mode 100644 index 0000000..092605d --- /dev/null +++ b/Viewer/_layerdlg.h @@ -0,0 +1,42 @@ +// aboutdlg.h : interface of the CLayerDlg class +// +///////////////////////////////////////////////////////////////////////////// + +#pragma once + +class CLayerDlg : public CDialogImpl, + public CDialogResize +{ +public: + enum { IDD = IDD_LAYERS }; + + CLayerDlg::CLayerDlg(CComPtr p_iWhip2DC) + { + m_iWhip2DC = p_iWhip2DC; + }; + + BEGIN_MSG_MAP(CLayerDlg) + MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) + COMMAND_ID_HANDLER(IDOK, OnCloseCmd) + COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) + CHAIN_MSG_MAP(CDialogResize) + END_MSG_MAP() + + BEGIN_DLGRESIZE_MAP(CLayerDlg) + DLGRESIZE_CONTROL(IDOK, DLSZ_MOVE_X) + DLGRESIZE_CONTROL(IDCANCEL, DLSZ_MOVE_X) + DLGRESIZE_CONTROL(IDC_LAYERLIST, DLSZ_SIZE_X|DLSZ_SIZE_Y) + END_DLGRESIZE_MAP() + +// Handler prototypes (uncomment arguments if needed): +// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) + + LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); + LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + +private: + CListBox m_ListBox; + CComQIPtr m_iWhip2DC; +}; diff --git a/Viewer/atlgdix.h b/Viewer/atlgdix.h new file mode 100644 index 0000000..de70466 --- /dev/null +++ b/Viewer/atlgdix.h @@ -0,0 +1,911 @@ +#ifndef __ATLGDIX_H__ +#define __ATLGDIX_H__ + +///////////////////////////////////////////////////////////////////////////// +// Additional GDI/USER wrappers +// +// Written by Bjarke Viksoe (bjarke@viksoe.dk) +// Copyright (c) 2001-2002 Bjarke Viksoe. +// Thanks to Daniel Bowen for COffscreenDrawRect. +// +// This code may be used in compiled form in any way you desire. This +// file may be redistributed by any means PROVIDING it is +// not sold for profit without the authors written consent, and +// providing that this notice and the authors name is included. +// +// This file is provided "as is" with no expressed or implied warranty. +// The author accepts no liability if it causes any damage to you or your +// computer whatsoever. It's free, so don't hassle me about it. +// +// Beware of bugs. +// + +#pragma once + +#ifndef __cplusplus + #error ATL requires C++ compilation (use a .cpp suffix) +#endif + +#ifndef __ATLGDI_H__ + #error atlgdix.h requires atlgdi.h to be included first +#endif + +namespace WTL +{ + +///////////////////////////////////////////////////////////////////////////// +// Macros + +// The GetXValue macros below are badly designed and emit +// compiler warnings e.g. when using RGB(255,255,255)... +#pragma warning(disable : 4310) + +#ifndef BlendRGB + #define BlendRGB(c1, c2, factor) \ + RGB( GetRValue(c1) + ((GetRValue(c2) - GetRValue(c1)) * factor / 100L), \ + GetGValue(c1) + ((GetGValue(c2) - GetGValue(c1)) * factor / 100L), \ + GetBValue(c1) + ((GetBValue(c2) - GetBValue(c1)) * factor / 100L) ) +#endif + +#ifndef COLOR_INVALID + #define COLOR_INVALID (COLORREF) CLR_INVALID +#endif + + +#if _WTL_VER < 0x0750 + +///////////////////////////////////////////////////////////////////////////// +// CIcon + +template< bool t_bManaged > +class CIconT +{ +public: + HICON m_hIcon; + + // Constructor/destructor/operators + + CIconT(HICON hIcon = NULL) : m_hIcon(hIcon) + { + } + + ~CIconT() + { + if( t_bManaged && m_hIcon != NULL ) ::DestroyIcon(m_hIcon); + } + + CIconT& operator=(HICON hIcon) + { + m_hIcon = hIcon; + return *this; + } + + void Attach(HICON hIcon) + { + if( t_bManaged && m_hIcon != NULL ) ::DestroyIcon(m_hIcon); + m_hIcon = hIcon; + } + HICON Detach() + { + HICON hIcon = m_hIcon; + m_hIcon = NULL; + return hIcon; + } + + operator HICON() const { return m_hIcon; } + + bool IsNull() const { return m_hIcon == NULL; } + + // Create methods + + HICON LoadIcon(_U_STRINGorID icon) + { + ATLASSERT(m_hIcon==NULL); +#if (_ATL_VER >= 0x0700) + m_hIcon = ::LoadIcon(ATL::_AtlBaseModule.GetResourceInstance(), icon.m_lpstr); +#else + m_hIcon = ::LoadIcon(_Module.GetResourceInstance(), icon.m_lpstr); +#endif + return m_hIcon; + } + HICON LoadIcon(_U_STRINGorID icon, int cxDesired, int cyDesired, UINT fuLoad = 0) + { + ATLASSERT(m_hIcon==NULL); +#if (_ATL_VER >= 0x0700) + m_hIcon = (HICON) ::LoadImage(ATL::_AtlBaseModule.GetResourceInstance(), icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad); +#else + m_hIcon = (HICON) ::LoadImage(_Module.GetResourceInstance(), icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad); +#endif + return m_hIcon; + } + HICON LoadOEMIcon(UINT nIDIcon) // for IDI_ types + { + ATLASSERT(m_hIcon==NULL); + m_hIcon = ::LoadIcon(NULL, MAKEINTRESOURCE(nIDIcon)); + return m_hIcon; + } + HICON CreateIcon(int nWidth, int nHeight, BYTE cPlanes, BYTE cBitsPixel, CONST BYTE* lpbANDButs, CONST BYTE *lpbXORbits) + { + ATLASSERT(m_hIcon==NULL); + ATLASSERT(lpbANDbits); + ATLASSERT(lpbXORbits); +#if (_ATL_VER >= 0x0700) + m_hIcon = ::CreateIcon(ATL::_AtlBaseModule.GetResourceInstance(), nWidth, nHeight, cPlanes, cBitsPixel, lpbANDbits, lpbXORbits); +#else + m_hIcon = ::CreateIcon(_Module.GetResourceInstance(), nWidth, nHeight, cPlanes, cBitsPixel, lpbANDbits, lpbXORbits); +#endif + return m_hIcon; + } + HICON CreateIconFromResource(PBYTE pBits, DWORD dwResSize, DWORD dwVersion = 0x00030000) + { + ATLASSERT(m_hIcon==NULL); + ATLASSERT(pBits); + m_hIcon = ::CreateIconFromResource(pBits, dwResSize, TRUE, dwVersion); + return m_hIcon; + } + HICON CreateIconFromResourceEx(PBYTE pbBits, DWORD cbBits, DWORD dwVersion = 0x00030000, int cxDesired = 0, int cyDesired = 0, UINT uFlags = LR_DEFAULTCOLOR) + { + ATLASSERT(m_hIcon==NULL); + ATLASSERT(pbBits); + ATLASSERT(cbBits>0); + m_hIcon = ::CreateIconFromResourceEx(pbBits, cbBits, TRUE, dwVersion, cxDesired, cyDesired, uFlags); + return m_hIcon; + } + HICON CreateIconIndirect(PICONINFO pIconInfo) + { + ATLASSERT(m_hIcon==NULL); + ATLASSERT(pIconInfo); + m_hIcon = ::CreateIconIndirect(pIconInfo); + return m_hIcon; + } + HICON ExtractIcon(LPCTSTR lpszExeFileName, UINT nIconIndex) + { + ATLASSERT(m_hIcon==NULL); + ATLASSERT(!::IsBadStringPtr(lpszExeFileName,-1)); +#if (_ATL_VER >= 0x0700) + m_hIcon = ::ExtractIcon(ATL::_AtlBaseModule.GetModuleInstance(), lpszExeFileName, nIconIndex); +#else + m_hIcon = ::ExtractIcon(_Module.GetModuleInstance(), lpszExeFileName, nIconIndex); +#endif + return m_hIcon; + } + HICON ExtractAssociatedIcon(HINSTANCE hInst, LPCTSTR lpIconPath, LPWORD lpiIcon) + { + ATLASSERT(m_hIcon==NULL); + ATLASSERT(!::IsBadStringPtr(lpIconPath,-1)); + ATLASSERT(lpiIcon); + m_hIcon = ::ExtractAssociatedIcon(hInst, lpIconPath, lpiIcon); + return m_hIcon; + } + + // Operations + + BOOL DestroyIcon() + { + ATLASSERT(m_hIcon!=NULL); + BOOL bRet = ::DestroyIcon(m_hIcon); + if( bRet ) m_hIcon = NULL; + return bRet; + } + HICON CopyIcon() + { + ATLASSERT(m_hIcon!=NULL); + return ::CopyIcon(m_hIcon); + } + HICON DuplicateIcon() + { + ATLASSERT(m_hIcon!=NULL); + return ::DuplicateIcon(NULL, m_hIcon); + } + + BOOL DrawIcon(HDC hDC, int x, int y) + { + ATLASSERT(m_hIcon!=NULL); + return ::DrawIcon(hDC, x, y, m_hIcon); + } + BOOL DrawIcon(HDC hDC, POINT pt) + { + ATLASSERT(m_hIcon!=NULL); + return ::DrawIcon(hDC, pt.x, pt.y, m_hIcon); + } + BOOL DrawIconEx(HDC hDC, int x, int y, int cxWidth, int cyWidth, UINT uStepIfAniCur = 0, HBRUSH hbrFlickerFreeDraw = NULL, UINT uFlags = DI_NORMAL) + { + ATLASSERT(m_hIcon!=NULL); + return ::DrawIconEx(hDC, x, y, m_hIcon, cxWidth, cyWidth, uStepIfAniCur, hbrFlickerFreeDraw, uFlags); + } + BOOL DrawIconEx(HDC hDC, POINT pt, SIZE size, UINT uStepIfAniCur = 0, HBRUSH hbrFlickerFreeDraw = NULL, UINT uFlags = DI_NORMAL) + { + ATLASSERT(m_hIcon!=NULL); + return ::DrawIconEx(hDC, pt.x, pt.y, m_hIcon, size.cx, size.cy, uStepIfAniCur, hbrFlickerFreeDraw, uFlags); + } + + BOOL GetIconInfo(PICONINFO pIconInfo) + { + ATLASSERT(m_hIcon!=NULL); + ATLASSERT(pIconInfo); + return ::GetIconInfo(m_hIcon, pIconInfo); + } +}; + +typedef CIconT CIcon; +typedef CIconT CIconHandle; + + +///////////////////////////////////////////////////////////////////////////// +// CCursor + +// Protect template against silly macro +#ifdef CopyCursor + #undef CopyCursor +#endif + +template< bool t_bManaged > +class CCursorT +{ +public: + HCURSOR m_hCursor; + + // Constructor/destructor/operators + + CCursorT(HCURSOR hCursor = NULL) : m_hCursor(hCursor) + { + } + + ~CCursorT() + { + if( t_bManaged && m_hCursor != NULL ) ::DestroyCursor(m_hCursor); + } + + CCursorT& operator=(HCURSOR hCursor) + { + m_hCursor = hCursor; + return *this; + } + + void Attach(HCURSOR hCursor) + { + if( t_bManaged && m_hCursor != NULL ) ::DestroyCursor(m_hCursor); + m_hCursor = hCursor; + } + HCURSOR Detach() + { + HCURSOR hCursor = m_hCursor; + m_hCursor = NULL; + return hCursor; + } + + operator HCURSOR() const { return m_hCursor; } + + bool IsNull() const { return m_hCursor == NULL; } + + // Create methods + + HCURSOR LoadCursor(_U_STRINGorID cursor) + { + ATLASSERT(m_hCursor==NULL); +#if (_ATL_VER >= 0x0700) + m_hCursor = ::LoadCursor(ATL::_AtlBaseModule.GetResourceInstance(), cursor.m_lpstr); +#else + m_hCursor = ::LoadCursor(_Module.GetResourceInstance(), cursor.m_lpstr); +#endif + return m_hCursor; + } + HCURSOR LoadOEMCursor(UINT nIDCursor) // for IDC_ types + { + ATLASSERT(m_hCursor==NULL); + m_hCursor = ::LoadCursor(NULL, MAKEINTRESOURCE(nIDCursor)); + return m_hCursor; + } + HICON LoadCursor(_U_STRINGorID cursor, int cxDesired, int cyDesired, UINT fuLoad = 0) + { + ATLASSERT(m_hCursor==NULL); +#if (_ATL_VER >= 0x0700) + m_hCursor = (HCURSOR) ::LoadImage(ATL::_AtlBaseModule.GetResourceInstance(), cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad); +#else + m_hCursor = (HCURSOR) ::LoadImage(_Module.GetResourceInstance(), cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad); +#endif + return m_hCursor; + } + HCURSOR LoadCursorFromFile(LPCTSTR pstrFilename) + { + ATLASSERT(m_hCursor==NULL); + ATLASSERT(!::IsBadStringPtr(pstrFilename,-1)); + m_hCursor = ::LoadCursorFromFile(pstrFilename); + return m_hCursor; + } + HCURSOR CreateCursor(int xHotSpot, int yHotSpot, int nWidth, int nHeight, CONST VOID *pvANDPlane, CONST VOID *pvXORPlane) + { + ATLASSERT(m_hCursor==NULL); +#if (_ATL_VER >= 0x0700) + m_hCursor = ::CreateCursor(ATL::_AtlBaseModule.GetResourceInstance(), xHotSpot, yHotSpot, nWidth, nHeight, pvANDPlane, pvXORPlane); +#else + m_hCursor = ::CreateCursor(_Module.GetResourceInstance(), xHotSpot, yHotSpot, nWidth, nHeight, pvANDPlane, pvXORPlane); +#endif + return m_hCursor; + } + HICON CreateCursorFromResource(PBYTE pBits, DWORD dwResSize, DWORD dwVersion = 0x00030000) + { + ATLASSERT(m_hIcon==NULL); + ATLASSERT(pBits); + m_hIcon = ::CreateIconFromResource(pBits, dwResSize, FALSE, dwVersion); + return m_hIcon; + } + HICON CreateCursorFromResourceEx(PBYTE pbBits, DWORD cbBits, DWORD dwVersion = 0x00030000, int cxDesired = 0, int cyDesired = 0, UINT uFlags = LR_DEFAULTCOLOR) + { + ATLASSERT(m_hIcon==NULL); + ATLASSERT(pbBits); + ATLASSERT(cbBits>0); + m_hIcon = ::CreateIconFromResourceEx(pbBits, cbBits, FALSE, dwVersion, cxDesired, cyDesired, uFlags); + return m_hIcon; + } + + // Operations + + BOOL DestroyCursor() + { + ATLASSERT(m_hCursor!=NULL); + BOOL bRet = ::DestroyCursor(m_hCursor); + if( bRet ) m_hCursor = NULL; + return bRet; + } + + HCURSOR CopyCursor() + { + ATLASSERT(m_hCursor!=NULL); + return (HCURSOR) ::CopyIcon( (HICON) m_hCursor ); + } + +#if(WINVER >= 0x0500) + BOOL GetCursorInfo(LPCURSORINFO pCursorInfo) + { + ATLASSERT(m_hCursor!=NULL); + ATLASSERT(pCursorInfo); + return ::GetCursorInfo(pCursorInfo); + } +#endif +}; + +typedef CCursorT CCursor; +typedef CCursorT CCursorHandle; + + +///////////////////////////////////////////////////////////////////////////// +// CAccelerator + +template< bool t_bManaged > +class CAcceleratorT +{ +public: + HACCEL m_hAccel; + + // Constructor/destructor/operators + + CAcceleratorT(HACCEL hAccel = NULL) : m_hAccel(hAccel) + { + } + + ~CAcceleratorT() + { + if( t_bManaged && m_hAccel != NULL ) ::DestroyAcceleratorTable(m_hAccel); + } + + CAcceleratorT& operator=(HACCEL hAccel) + { + m_hAccel = hAccel; + return *this; + } + + void DestroyObject() + { + if( m_hAccel != NULL ) { + ::DestroyAcceleratorTable(m_hAccel); + m_hAccel = NULL; + } + } + + void Attach(HACCEL hAccel) + { + if( t_bManaged && m_hAccel != NULL ) ::DestroyAcceleratorTable(m_hAccel); + m_hAccel = hAccel; + } + HCURSOR Detach() + { + HACCEL hAccel = m_hAccel; + m_hAccel = NULL; + return hAccel; + } + + operator HACCEL() const { return m_hAccel; } + + bool IsNull() const { return m_hAccel == NULL; } + + // Create methods + + HACCEL LoadAccelerators(_U_STRINGorID accel) + { + ATLASSERT(m_hAccel==NULL); +#if (_ATL_VER >= 0x0700) + m_hAccel = ::LoadAccelerators(ATL::_AtlBaseModule.GetResourceInstance(), accel.m_lpstr); +#else + m_hAccel = ::LoadAccelerators(_Module.GetResourceInstance(), accel.m_lpstr); +#endif + return m_hAccel; + } + HACCEL CreateAcceleratorTable(LPACCEL pAccel, int cEntries) + { + ATLASSERT(m_hAccel==NULL); + ATLASSERT(!::IsBadReadPtr(lpAccelDst, sizeof(ACCEL)*cEntries)); + m_hAccel = ::CreateAcceleratorTable(pAccel, cEntries); + return m_hAccel; + } + + // Operations + + int CopyAcceleratorTable(LPACCEL lpAccelDst, int cEntries) + { + ATLASSERT(m_hAccel!=NULL); + ATLASSERT(!::IsBadWritePtr(lpAccelDst, sizeof(ACCEL)*cEntries)); + return ::CopyAcceleratorTable(m_hAccel, lpAccelDst, cEntries); + } + + BOOL TranslateAccelerator(HWND hWnd, LPMSG pMsg) + { + ATLASSERT(m_hAccel!=NULL); + ATLASSERT(::IsWindow(hWnd)); + ATLASSERT(pMsg); + return ::TranslateAccelerator(hWnd, m_hAccel, pMsg); + } +}; + +typedef CAcceleratorT CAccelerator; +typedef CAcceleratorT CAcceleratorHandle; + + +///////////////////////////////////////////////////////////////////////////// +// CLogFont + +class CLogFont : public LOGFONT +{ +public: + CLogFont() + { + ::ZeroMemory( (LOGFONT*) this, sizeof(LOGFONT) ); + } + CLogFont(const LOGFONT& lf) + { + Copy(&lf); + } + CLogFont(HFONT hFont) + { + ATLASSERT(::GetObjectType(hFont)==OBJ_FONT); + ::GetObject(hFont, sizeof(LOGFONT), (LOGFONT*) this); + } + HFONT CreateFontIndirect() + { + return ::CreateFontIndirect(this); + } + void SetBold() + { + lfWeight = FW_BOLD; + } + BOOL IsBold() const + { + return lfWeight >= FW_BOLD; + } + void MakeBolder(int iScale = 1) + { + lfWeight += FW_BOLD * iScale; + } + void MakeLarger(int iScale) + { + if( lfHeight > 0 ) lfHeight += iScale; else lfHeight -= iScale; + } + void SetHeight(long PointSize, HDC hDC = NULL) + { + // For MM_TEXT mapping mode... + // NOTE: MulDiv() gives correct rounding. + lfHeight = -MulDiv(PointSize, ::GetDeviceCaps(hDC, LOGPIXELSY), 72); + } + long GetHeight(HDC hDC = NULL) const + { + // For MM_TEXT mapping mode... + // NOTE: MulDiv() gives correct rounding. + return MulDiv(-lfHeight, 72, ::GetDeviceCaps(hDC, LOGPIXELSY)); + } + long GetDeciPointHeight(HDC hDC = NULL) + { + POINT ptOrg = { 0, 0 }; + ::DPtoLP(hDC, &ptOrg, 1); + POINT pt = { 0, 0 }; + pt.y = abs(lfHeight) + ptOrg.y; + ::LPtoDP(hDC,&pt,1); + return MulDiv(pt.y, 720, ::GetDeviceCaps(hDC,LOGPIXELSY)); // 72 points/inch, 10 decipoints/point + } + void SetHeightFromDeciPoint(long DeciPtHeight, HDC hDC = NULL) + { + POINT pt; + pt.y = MulDiv(::GetDeviceCaps(hDC, LOGPIXELSY), DeciPtHeight, 720); // 72 points/inch, 10 decipoints/point + ::DPtoLP(hDC, &pt, 1); + POINT ptOrg = { 0, 0 }; + ::DPtoLP(hDC, &ptOrg, 1); + lfHeight = -abs(pt.y - ptOrg.y); + } + void SetCaptionFont() + { + NONCLIENTMETRICS ncm = { 0 }; + ncm.cbSize = sizeof(ncm); + ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0); + Copy(&ncm.lfCaptionFont); + } + void SetMenuFont() + { + NONCLIENTMETRICS ncm = { 0 }; + ncm.cbSize = sizeof(ncm); + ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0); + Copy(&ncm.lfMenuFont); + } + void SetStatusFont() + { + NONCLIENTMETRICS ncm = { 0 }; + ncm.cbSize = sizeof(ncm); + ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0); + Copy(&ncm.lfStatusFont); + } + void SetMessageBoxFont() + { + NONCLIENTMETRICS ncm = { 0 }; + ncm.cbSize = sizeof(ncm); + ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0); + Copy(&ncm.lfMessageFont); + } + void Copy(const LOGFONT* lf) + { + ATLASSERT(lf); + ::CopyMemory( (LOGFONT*) this, lf, sizeof(LOGFONT) ); + } + CLogFont& operator=(const CLogFont& src) + { + Copy(&src); + return *this; + } + CLogFont& operator=(const LOGFONT& src) + { + Copy(&src); + return *this; + } + CLogFont& operator=(HFONT hFont) + { + ATLASSERT(::GetObjectType(hFont)==OBJ_FONT); + ::GetObject(hFont, sizeof(LOGFONT), (LOGFONT*) this); + return *this; + } + bool operator==(const LOGFONT& logfont) const + { + return( logfont.lfHeight == lfHeight && + logfont.lfWidth == lfWidth && + logfont.lfEscapement == lfEscapement && + logfont.lfOrientation == lfOrientation && + logfont.lfWeight == lfWeight && + logfont.lfItalic == lfItalic && + logfont.lfUnderline == lfUnderline && + logfont.lfStrikeOut == lfStrikeOut && + logfont.lfCharSet == lfCharSet && + logfont.lfOutPrecision == lfOutPrecision && + logfont.lfClipPrecision == lfClipPrecision && + logfont.lfQuality == lfQuality && + logfont.lfPitchAndFamily == lfPitchAndFamily && + ::lstrcmp(logfont.lfFaceName, lfFaceName) == 0 ); + } +}; + +#endif // _WTL_VER + + +///////////////////////////////////////////////////////////////////////////// +// CMemDC + +class CMemDC : public CDC +{ +public: + CDCHandle m_dc; // Owner DC + CBitmap m_bitmap; // Offscreen bitmap + CBitmapHandle m_hOldBitmap; // Originally selected bitmap + RECT m_rc; // Rectangle of drawing area + + CMemDC(HDC hDC, LPRECT pRect = NULL) + { + ATLASSERT(hDC!=NULL); + m_dc = hDC; + if( pRect != NULL ) m_rc = *pRect; else m_dc.GetClipBox(&m_rc); + + CreateCompatibleDC(m_dc); + ::LPtoDP(m_dc, (LPPOINT) &m_rc, sizeof(RECT) / sizeof(POINT)); + m_bitmap.CreateCompatibleBitmap(m_dc, m_rc.right - m_rc.left, m_rc.bottom - m_rc.top); + m_hOldBitmap = SelectBitmap(m_bitmap); + ::DPtoLP(m_dc, (LPPOINT) &m_rc, sizeof(RECT) / sizeof(POINT)); + SetWindowOrg(m_rc.left, m_rc.top); + } + ~CMemDC() + { + // Copy the offscreen bitmap onto the screen. + m_dc.BitBlt(m_rc.left, m_rc.top, m_rc.right - m_rc.left, m_rc.bottom - m_rc.top, + m_hDC, m_rc.left, m_rc.top, SRCCOPY); + // Swap back the original bitmap. + SelectBitmap(m_hOldBitmap); + } +}; + + +///////////////////////////////////////////////////////////////////////////// +// COffscreenDraw + +// To use it, derive from it and chain it in the message map. +template< class T > +class COffscreenDraw +{ +public: + BEGIN_MSG_MAP(COffscreenDraw) + MESSAGE_HANDLER(WM_PAINT, OnPaint) + MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint) + MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground) + END_MSG_MAP() + + LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) + { + T* pT = static_cast(this); + if( wParam != NULL ) + { + CMemDC memdc( (HDC) wParam, NULL ); + pT->DoPaint(memdc.m_hDC); + } + else + { + RECT rc; + pT->GetClientRect(&rc); + CPaintDC dc(pT->m_hWnd); + CMemDC memdc(dc.m_hDC, &rc); + pT->DoPaint(memdc.m_hDC); + } + return 0; + } + LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) + { + return 1; // handled; no need to erase background; do it in DoPaint(); + } + void DoPaint(CDCHandle dc) + { + ATLASSERT(false); // must override this + } +}; + +// To use it, derive from it and chain it in the message map. +template< class T > +class COffscreenDrawRect +{ +public: + BEGIN_MSG_MAP(COffscreenDrawRect) + MESSAGE_HANDLER(WM_PAINT, OnPaint) + MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint) + MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground) + END_MSG_MAP() + + LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) + { + T* pT = static_cast(this); + if( wParam != NULL ) + { + CMemDC memdc( (HDC) wParam, NULL ); + pT->DoPaint(memdc.m_hDC, memdc.m_rc); + } + else + { + CPaintDC dc(pT->m_hWnd); + CMemDC memdc(dc.m_hDC, &dc.m_ps.rcPaint); + pT->DoPaint(memdc.m_hDC, dc.m_ps.rcPaint); + } + return 0; + } + LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) + { + return 1; // handled; no need to erase background; do it in DoPaint(); + } + void DoPaint(CDCHandle dc, RECT& rcClip) + { + ATLASSERT(false); // must override this + } +}; + + +///////////////////////////////////////////////////////////////////////////// +// CSaveDC + +class CSaveDC +{ +public: + HDC m_hDC; + int m_iState; + + CSaveDC(HDC hDC) : m_hDC(hDC) + { + ATLASSERT(::GetObjectType(m_hDC)==OBJ_DC || ::GetObjectType(m_hDC)==OBJ_MEMDC); + m_iState = ::SaveDC(hDC); + ATLASSERT(m_iState!=0); + } + ~CSaveDC() + { + Restore(); + } + void Restore() + { + if( m_iState == 0 ) return; + ATLASSERT(::GetObjectType(m_hDC)==OBJ_DC || ::GetObjectType(m_hDC)==OBJ_MEMDC); + ::RestoreDC(m_hDC, m_iState); + m_iState = 0; + } +}; + + +///////////////////////////////////////////////////////////////////////////// +// CHandle + +#if (_ATL_VER < 0x0700) + +class CHandle +{ +public: + HANDLE m_h; + + CHandle(HANDLE hSrc = INVALID_HANDLE_VALUE) : m_h(hSrc) + { } + + ~CHandle() + { + Close(); + } + + operator HANDLE() const { return m_h; }; + + LPHANDLE operator&() + { + ATLASSERT(!IsValid()); + return &m_h; + } + + CHandle& operator=(HANDLE h) + { + ATLASSERT(!IsValid()); + m_h = h; + return *this; + } + + bool IsValid() const { return m_h != INVALID_HANDLE_VALUE; }; + + void Attach(HANDLE h) + { + if( IsValid() ) ::CloseHandle(m_h); + m_h = h; + } + HANDLE Detach() + { + HANDLE h = m_h; + m_h = INVALID_HANDLE_VALUE; + return h; + } + + BOOL Close() + { + BOOL bRes = FALSE; + if( m_h != INVALID_HANDLE_VALUE ) { + bRes = ::CloseHandle(m_h); + m_h = INVALID_HANDLE_VALUE; + } + return bRes; + } + + BOOL Duplicate(HANDLE hSource, bool bInherit = false) + { + ATLASSERT(!IsValid()); + HANDLE hOurProcess = ::GetCurrentProcess(); + BOOL b = ::DuplicateHandle(hOurProcess, + hSource, + hOurProcess, + &m_h, + DUPLICATE_SAME_ACCESS, + bInherit, + DUPLICATE_SAME_ACCESS); + ATLASSERT(b); + return b; + } +}; + +#endif // _ATL_VER + + +///////////////////////////////////////////////////////////////////////////// +// Mouse Hover helper + +#ifndef NOTRACKMOUSEEVENT + +#ifndef WM_MOUSEENTER + #define WM_MOUSEENTER WM_USER + 253 +#endif // WM_MOUSEENTER + +// To use it, derive from it and chain it in the message map. +// Make sure to set bHandled to FALSE when handling WM_MOUSEMOVE or +// the WM_MOUSELEAVE message! +template< class T > +class CMouseHover +{ +public: + bool m_fMouseOver; // Internal mouse-over state + bool m_fMouseForceUpdate; // Update window immediately on event + + CMouseHover() : + m_fMouseOver(false), + m_fMouseForceUpdate(true) + { + } + + void SetForceMouseOverUpdate(bool bForce = false) + { + m_fMouseForceUpdate = bForce; + } + + BEGIN_MSG_MAP(CMouseHover) + MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove) + MESSAGE_HANDLER(WM_MOUSELEAVE, OnMouseLeave) + END_MSG_MAP() + + LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled) + { + T* pT = static_cast(this); + if( !m_fMouseOver ) { + m_fMouseOver = true; + pT->SendMessage(WM_MOUSEENTER, wParam, lParam); + if( m_fMouseForceUpdate ) { + pT->Invalidate(); + pT->UpdateWindow(); + } + _StartTrackMouseLeave(pT->m_hWnd); + } + bHandled = FALSE; + return 0; + } + LRESULT OnMouseLeave(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) + { + T* pT = static_cast(this); + if( m_fMouseOver ) { + m_fMouseOver = false; + if( m_fMouseForceUpdate ) { + pT->Invalidate(); + pT->UpdateWindow(); + } + } + bHandled = FALSE; + return 0; + } + BOOL _StartTrackMouseLeave(HWND hWnd) const + { + ATLASSERT(::IsWindow(hWnd)); + TRACKMOUSEEVENT tme = { 0 }; + tme.cbSize = sizeof(tme); + tme.dwFlags = TME_LEAVE; + tme.hwndTrack = hWnd; + return _TrackMouseEvent(&tme); + } + BOOL _CancelTrackMouseLeave(HWND hWnd) const + { + TRACKMOUSEEVENT tme = { 0 }; + tme.cbSize = sizeof(tme); + tme.dwFlags = TME_LEAVE | TME_CANCEL; + tme.hwndTrack = hWnd; + return _TrackMouseEvent(&tme); + } +}; + +#endif // NOTRACKMOUSEEVENT + + +}; // namespace WTL + +#endif // __ATLGDIX_H__ diff --git a/Viewer/mainfrm.h b/Viewer/mainfrm.h new file mode 100644 index 0000000..3b029b0 --- /dev/null +++ b/Viewer/mainfrm.h @@ -0,0 +1,72 @@ +// MainFrm.h : interface of the CMainFrame class +// +///////////////////////////////////////////////////////////////////////////// + +#pragma once + +class CMainFrame : public CFrameWindowImpl, public CUpdateUI, + public CMessageFilter, public CIdleHandler, public CPrintJobInfo +{ +public: + DECLARE_FRAME_WND_CLASS(NULL, IDR_MAINFRAME) + + CMainFrame() + { + m_printer.OpenDefaultPrinter(); + m_devmode.CopyFromPrinter(m_printer); + ATLTRACE("\nIn constructor with m_Combo %x", m_Combo.m_hWnd); + + }; + + CSLNKDwfViewerView m_view; + + CComboBox m_Combo; + + virtual BOOL PreTranslateMessage(MSG* pMsg); + virtual BOOL OnIdle(); + + BEGIN_UPDATE_UI_MAP(CMainFrame) + UPDATE_ELEMENT(ID_VIEW_TOOLBAR, UPDUI_MENUPOPUP) + END_UPDATE_UI_MAP() + + BEGIN_MSG_MAP(CMainFrame) + MESSAGE_HANDLER(WM_CREATE, OnCreate) + COMMAND_ID_HANDLER(ID_APP_EXIT, OnFileExit) + COMMAND_ID_HANDLER(ID_ZOOM_EXTENTS, OnZoomExtents) + COMMAND_ID_HANDLER(ID_ZOOM_IN, OnZoomIn) + COMMAND_ID_HANDLER(ID_ZOOM_OUT, OnZoomOut) + COMMAND_ID_HANDLER(ID_FILE_PRINT, OnFilePrint) + COMMAND_ID_HANDLER(ID_FILE_OPEN, OnFileOpen) + COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout) + COMMAND_ID_HANDLER(ID_VIEW_LAYERS, OnViewLayers) + COMMAND_HANDLER(IDC_COMBO, CBN_SELCHANGE, onSelChange) + CHAIN_MSG_MAP(CUpdateUI) + CHAIN_MSG_MAP(CFrameWindowImpl) + END_MSG_MAP() + +// Handler prototypes (uncomment arguments if needed): +// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) + + void SetDWF(const CString &dwfPath); + LRESULT onSelChange(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); + LRESULT OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + LRESULT OnFileOpen(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + LRESULT OnZoomExtents(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + LRESULT OnZoomIn(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + LRESULT OnZoomOut(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + LRESULT OnFilePrint(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + LRESULT OnViewToolBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); +public: + LRESULT OnViewLayers(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); + + CPrinter m_printer; + CDevMode m_devmode; + CPrintPreviewWindow m_wndPreview; + + virtual bool IsValidPage(UINT nPage); + virtual bool PrintPage(UINT nPage, HDC hDC); +}; diff --git a/Viewer/res/.gitignore b/Viewer/res/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/Viewer/res/SLNKDWFViewer.ico b/Viewer/res/SLNKDWFViewer.ico new file mode 100644 index 0000000..3b11c7a Binary files /dev/null and b/Viewer/res/SLNKDWFViewer.ico differ diff --git a/Viewer/res/Toolbar.bmp b/Viewer/res/Toolbar.bmp new file mode 100644 index 0000000..a5cb458 Binary files /dev/null and b/Viewer/res/Toolbar.bmp differ diff --git a/Viewer/res/_toolbar.bmp b/Viewer/res/_toolbar.bmp new file mode 100644 index 0000000..60f7a16 Binary files /dev/null and b/Viewer/res/_toolbar.bmp differ diff --git a/Viewer/resource.h b/Viewer/resource.h new file mode 100644 index 0000000..a4ddb78 --- /dev/null +++ b/Viewer/resource.h @@ -0,0 +1,33 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by SLNKDWFViewer.rc +// +#define IDD_ABOUTBOX 100 +#define IDR_MAINFRAME 128 +#define IDD_LAYERS 201 +#define IDC_LAYERLIST 1000 +#define IDC_DLLVERSION 1001 +#define IDC_DLLPATH 1002 +#define IDC_DLLBUILD 1003 +#define IDC_DLLBUILDTIME 1003 +#define IDC_WHIPVERSION 1004 +#define IDC_DWFVERSION 1005 +#define IDC_DWF2VERSION 1005 +#define ID_VIEW_LAYERS 32772 +#define ID_ZOOM_IN 32774 +#define ID_ZOOM_EXTENTS 32777 +#define ID_ZOOM_OUT 32782 +#define IDP_PLACEHOLDER 32783 +#define IDC_COMBO 32784 +#define IDC_PROGRESS 32785 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 202 +#define _APS_NEXT_COMMAND_VALUE 32786 +#define _APS_NEXT_CONTROL_VALUE 1004 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/Viewer/stdafx.cpp b/Viewer/stdafx.cpp new file mode 100644 index 0000000..9888bd2 --- /dev/null +++ b/Viewer/stdafx.cpp @@ -0,0 +1,9 @@ +// stdafx.cpp : source file that includes just the standard includes +// SLNKDWFViewer.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +#if (_ATL_VER < 0x0700) +#include +#endif //(_ATL_VER < 0x0700) diff --git a/Viewer/stdafx.h b/Viewer/stdafx.h new file mode 100644 index 0000000..cc9065e --- /dev/null +++ b/Viewer/stdafx.h @@ -0,0 +1,21 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +// Change these values to use different versions +//#define _WIN32_WINNT 0x0400 +#define _WIN32_IE 0x0400 +#define _RICHEDIT_VER 0x0100 + +#define _ATL_DEBUG_INTERFACES + +#include +#include + +//extern CAppModule _Module; gaf vage instabiliteit +extern CAtlWinModule _Module; + +#include "ViewerLib.h" diff --git a/WincmdContent/.gitignore b/WincmdContent/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/WincmdContent/ReadMe.txt b/WincmdContent/ReadMe.txt new file mode 100644 index 0000000..a722d7c --- /dev/null +++ b/WincmdContent/ReadMe.txt @@ -0,0 +1,7 @@ +Filesys sample plugin: + +It does the same as the (int) built-in content plugin + +Author: Christian Ghisler +Licence: This plugin is in the public domain, you may use +this sample code for your own plugins \ No newline at end of file diff --git a/WincmdContent/StdAfx.cpp b/WincmdContent/StdAfx.cpp new file mode 100644 index 0000000..0a5d6d8 --- /dev/null +++ b/WincmdContent/StdAfx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// filesys.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/WincmdContent/StdAfx.h b/WincmdContent/StdAfx.h new file mode 100644 index 0000000..92920ff --- /dev/null +++ b/WincmdContent/StdAfx.h @@ -0,0 +1,30 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__CEC06545_BCBF_4E7E_8FDC_FE3B0749B374__INCLUDED_) +#define AFX_STDAFX_H__CEC06545_BCBF_4E7E_8FDC_FE3B0749B374__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + + +// Insert your headers here +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + +#include + +// TODO: reference additional headers your program requires here + +#include + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__CEC06545_BCBF_4E7E_8FDC_FE3B0749B374__INCLUDED_) + + +#include "../SLNKDWFImpl/SLNKDWFStaticRO.h" + diff --git a/WincmdContent/WincmdContent.cpp b/WincmdContent/WincmdContent.cpp new file mode 100644 index 0000000..b9c400e --- /dev/null +++ b/WincmdContent/WincmdContent.cpp @@ -0,0 +1,111 @@ +// filesys.cpp : Defines the entry point for the DLL application. +// + +#include "stdafx.h" +#include "contentplug.h" + +#define _detectstring "EXT=\"DWF\"|EXT=\"W2D\"" + +#define fieldcount 2 +char* fieldnames[fieldcount]={ + "version", "sections"}; + +int fieldtypes[fieldcount]={ + ft_string, ft_numeric_32}; + +char* fieldunits_and_multiplechoicestrings[fieldcount]={ + "", ""}; + +BOOL GetValueAborted=false; + + +BOOL APIENTRY DllMain( HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + return TRUE; +} + +char* strlcpy(char* p,const char* p2,int maxlen) +{ + if ((int)strlen(p2)>=maxlen) { + strncpy(p,p2,maxlen); + p[maxlen]=0; + } else + strcpy(p,p2); + return p; +} + +int __stdcall ContentGetDetectString(char* DetectString,int maxlen) +{ + strlcpy(DetectString,_detectstring,maxlen); + return 0; +} + +int __stdcall ContentGetSupportedField(int FieldIndex,char* FieldName,char* Units,int maxlen) +{ + if (FieldIndex<0 || FieldIndex>=fieldcount) + return ft_nomorefields; + strlcpy(FieldName,fieldnames[FieldIndex],maxlen-1); + strlcpy(Units,fieldunits_and_multiplechoicestrings[FieldIndex],maxlen-1); + return fieldtypes[FieldIndex]; +} + +int __stdcall ContentGetValue(char* FileName,int FieldIndex,int UnitIndex,void* FieldValue,int maxlen,int flags) +{ + GetValueAborted=false; + + if (flags & CONTENT_DELAYIFSLOW) { + if (FieldIndex==16) + return ft_delayed; + if (FieldIndex==17) + return ft_ondemand; + } + + try + { + CDWFFileImpl m_iDWFFile; + m_iDWFFile.Open(FileName); + + switch (FieldIndex) + { + case 0: // "Version" + { + CString s; + s.Format("%02d.%02d", m_iDWFFile.m_tInfo.nVersion / 100, m_iDWFFile.m_tInfo.nVersion % 100); + strlcpy((char*)FieldValue,s,maxlen-1); + break; + } + case 1: // "Sections" + { + CEPlotSectionsImpl *piEPlotSections; + piEPlotSections = m_iDWFFile.get_EPlotSections(); + LONG lCount = piEPlotSections->get_Count(); + + *(int*)FieldValue=lCount; + break; + } + default: + return ft_nosuchfield; + } + } + catch (CString &ee) + { + strlcpy((char*)FieldValue,"Kweenie",maxlen-1); + return ft_string; + } +// } else +// return ft_fileerror; + return fieldtypes[FieldIndex]; // very important! +} + +void __stdcall ContentSetDefaultParams(ContentDefaultParamStruct* dps) +{ + +} + +void __stdcall ContentStopGetValue (char* FileName) +{ + GetValueAborted=true; +} diff --git a/WincmdContent/WincmdContent.def b/WincmdContent/WincmdContent.def new file mode 100644 index 0000000..58848c8 --- /dev/null +++ b/WincmdContent/WincmdContent.def @@ -0,0 +1,6 @@ +EXPORTS + ContentGetDetectString + ContentGetSupportedField + ContentGetValue + ContentSetDefaultParams + ContentStopGetValue diff --git a/WincmdContent/contentplug.h b/WincmdContent/contentplug.h new file mode 100644 index 0000000..38b3748 --- /dev/null +++ b/WincmdContent/contentplug.h @@ -0,0 +1,44 @@ +#define ft_nomorefields 0 +#define ft_numeric_32 1 +#define ft_numeric_64 2 +#define ft_numeric_floating 3 +#define ft_date 4 +#define ft_time 5 +#define ft_boolean 6 +#define ft_multiplechoice 7 +#define ft_string 8 +#define ft_fulltext 9 + +// for ContentGetValue +#define ft_delayed 0 +#define ft_nosuchfield -1 +#define ft_fileerror -2 +#define ft_fieldempty -3 +#define ft_ondemand -4 + +#define CONTENT_DELAYIFSLOW 1 + +typedef struct { + int size; + DWORD PluginInterfaceVersionLow; + DWORD PluginInterfaceVersionHi; + char DefaultIniName[MAX_PATH]; +} ContentDefaultParamStruct; + +typedef struct { + WORD wYear; + WORD wMonth; + WORD wDay; +} *pdateformat; + +typedef struct { + WORD wHour; + WORD wMinute; + WORD wSecond; +} *ptimeformat; + +int __stdcall ContentGetDetectString(char* DetectString,int maxlen); +int __stdcall ContentGetSupportedField(int FieldIndex,char* FieldName,char* Units,char* MultipleChoiceStrings,int maxlen); +int __stdcall ContentGetValue(char* FileName,int FieldIndex,int UnitIndex,void* FieldValue,int maxlen,int flags); +void __stdcall ContentSetDefaultParams(ContentDefaultParamStruct* dps); +void __stdcall ContentStopGetValue(char* FileName); diff --git a/WincmdContent/filesys.sln b/WincmdContent/filesys.sln new file mode 100644 index 0000000..b1b038e --- /dev/null +++ b/WincmdContent/filesys.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "filesys", "filesys.vcproj", "{2F492A95-A23D-45C9-BBD9-E5B9325B22C1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Debug|Win32.ActiveCfg = Debug|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Debug|Win32.Build.0 = Debug|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Release|Win32.ActiveCfg = Release|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/WincmdContent/filesys.vcproj b/WincmdContent/filesys.vcproj new file mode 100644 index 0000000..61a6dab --- /dev/null +++ b/WincmdContent/filesys.vcproj @@ -0,0 +1,294 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WincmdPacker/.gitignore b/WincmdPacker/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/WincmdPacker/ReadMe.txt b/WincmdPacker/ReadMe.txt new file mode 100644 index 0000000..a722d7c --- /dev/null +++ b/WincmdPacker/ReadMe.txt @@ -0,0 +1,7 @@ +Filesys sample plugin: + +It does the same as the (int) built-in content plugin + +Author: Christian Ghisler +Licence: This plugin is in the public domain, you may use +this sample code for your own plugins \ No newline at end of file diff --git a/WincmdPacker/StdAfx.cpp b/WincmdPacker/StdAfx.cpp new file mode 100644 index 0000000..0a5d6d8 --- /dev/null +++ b/WincmdPacker/StdAfx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// filesys.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/WincmdPacker/StdAfx.h b/WincmdPacker/StdAfx.h new file mode 100644 index 0000000..1b1be0d --- /dev/null +++ b/WincmdPacker/StdAfx.h @@ -0,0 +1,9 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +// Write nodig voor ascii W2D aanmaken +#include "../SLNKDWFImpl/SLNKDWFStaticRW.h" diff --git a/WincmdPacker/WCX Writer's Reference.hlp b/WincmdPacker/WCX Writer's Reference.hlp new file mode 100644 index 0000000..0d19814 Binary files /dev/null and b/WincmdPacker/WCX Writer's Reference.hlp differ diff --git a/WincmdPacker/WincmdPacker.cpp b/WincmdPacker/WincmdPacker.cpp new file mode 100644 index 0000000..e52cdbc --- /dev/null +++ b/WincmdPacker/WincmdPacker.cpp @@ -0,0 +1,186 @@ +// filesys.cpp : Defines the entry point for the DLL application. +// + +#include "stdafx.h" +#include "packerplug.h" +#define _detectstring "EXT=\"DWF\"|EXT=\"W2D\"" + +const char *strX = "/\\|:?*<>\""; + +tProcessDataProc ProcessDataProc = NULL; + +BOOL APIENTRY DllMain( HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + return TRUE; +} + +HANDLE __stdcall OpenArchive (tOpenArchiveData *ArchiveData) +{ + try + { + COpenArchive *arch = new COpenArchive(); + arch->m_FullName = ArchiveData->ArcName; + arch->m_iDWFFile.Open(arch->m_FullName); + arch->m_AtPage = -1; + arch->AtAscii = TRUE; // Eerstvolgende is binary + + return (HANDLE)arch; // We hebben maar een globale en dus geen HANDLE nodig + } + catch (CString &ee) + { + ::MessageBox(NULL, ee, "SLNKDWF", MB_ICONEXCLAMATION | MB_OK); + ArchiveData->OpenResult = E_UNKNOWN_FORMAT; + return (HANDLE)0; + } +} +int __stdcall ReadHeader (HANDLE hArcData, tHeaderData *HeaderData) +{ + COpenArchive *arch = (COpenArchive*)hArcData; + ATLASSERT(arch); + try + { + CEPlotSectionsImpl *piEPlotSections; + piEPlotSections = arch->m_iDWFFile.get_EPlotSections(); + + HeaderData->PackSize = 0; + HeaderData->UnpSize = 0; + + if (piEPlotSections->get_Count() == 0 && arch->m_AtPage==-1) + { + char drive[_MAX_DRIVE], dir[_MAX_DIR]; + char fname[_MAX_FNAME], ext[_MAX_EXT]; + _splitpath( arch->m_FullName, drive, dir, fname, ext ); + + CString s = CString(fname) + ".ascii" + ext; + // Wel een geldige filenaam van maken + for (size_t i = 0; i < strlen(strX); i++) + s.Replace(strX[i], '_'); + + CString sVer; + sVer.Format("DWF v%02d_%02d", arch->m_iDWFFile.m_tInfo.nVersion / 100, + arch->m_iDWFFile.m_tInfo.nVersion % 100); + + strncpy(HeaderData->FileName, sVer + "\\"+s, sizeof(HeaderData->FileName)-1); + arch->m_AtPage ++; // We blijven AtAscii + return 0; + } + if (arch->AtAscii) + { + arch->m_AtPage ++; + arch->AtAscii = FALSE; + } + else + arch->AtAscii = TRUE; + + if (arch->m_AtPage >= piEPlotSections->get_Count()) + return E_END_ARCHIVE; + + HeaderData->FileAttr = 0;//x10; + + CEPlotSectionImpl *piEPlotSection; + + piEPlotSection = piEPlotSections->get_Item(arch->m_AtPage); + CString s = piEPlotSection->get_Title(); + // Wel een geldige filenaam van maken + for (size_t i = 0; i < strlen(strX); i++) + s.Replace(strX[i], '_'); + s = s + "\\" + s + (arch->AtAscii?".ascii":"") + ".W2D"; + strncpy(HeaderData->FileName, s, sizeof(HeaderData->FileName)-1); + + piEPlotSection->Open(false); + const DWFProperty *dp; // = piEPlotSection->findProperty(DWFXML::kzAttribute_ModificationTime); + dp = piEPlotSection->findProperty(L"Creation Time", L""); // ac_b7_0.dwf + if (dp==NULL) + dp = piEPlotSection->findProperty(L"creationTime", L""); // "1 - IRD Addition.dwf" + if (dp) + { + CString modTime = (const wchar_t*)dp->value();// "2006-05-04T19:31:38.000+01:00" + int year,month,day; + int hour,minute,second; + sscanf(modTime,"%4d-%2d-%2dT%2d:%2d:%2d.", &year,&month,&day,&hour,&minute,&second); + HeaderData->FileTime = (year - 1980) << 25 | month << 21 | day << 16 | hour << 11 | minute << 5 | second/2; + // Merk op dat de ASCII afmeting niet van tevoren bekend is + HeaderData->UnpSize = HeaderData->PackSize = piEPlotSection->size(); + } + piEPlotSection->Close(); + } + catch (CString &ee) + { + ::MessageBox(NULL, ee, "SLNKDWF", MB_ICONEXCLAMATION | MB_OK); + return E_BAD_DATA; + } + return 0; +} + +int __stdcall ProcessFile (HANDLE hArcData, int Operation, char *DestPath, char *DestName) +{ + COpenArchive *arch = (COpenArchive*)hArcData; + switch (Operation) + { + case PK_SKIP: + break; /* Skip this file */ + case PK_TEST: + break; /* Test file integrity */ + case PK_EXTRACT: /* Extract to disk */ + { + if (ProcessDataProc) + ProcessDataProc(NULL, 0); + try + { + CEPlotSectionsImpl *piEPlotSections; + piEPlotSections = arch->m_iDWFFile.get_EPlotSections(); + if (piEPlotSections->get_Count()==0) // Moet wel oldstyle zijn? + { + CEPlotSectionImpl::SaveAsAscii(arch->m_FullName, DestName); + } + else + { + CEPlotSectionImpl *piEPlotSection; + piEPlotSection = piEPlotSections->get_Item(arch->m_AtPage); + + ATLASSERT(arch->m_AtPage < piEPlotSections->get_Count()); + + if (arch->AtAscii) + piEPlotSection->SaveAsAscii(DestName); + else + { + piEPlotSection->SaveAs(DestName); + } + } + } + catch (CString &ee) + { + ::MessageBox(NULL, ee, "SLNKDWF", MB_ICONEXCLAMATION | MB_OK); + return E_BAD_DATA; + } + } + } + + return 0; +} +int __stdcall CloseArchive (HANDLE hArcData) +{ + COpenArchive *arch = (COpenArchive*)hArcData; + ATLASSERT(arch); + delete arch; + return 0; +} + +void __stdcall SetChangeVolProc (HANDLE hArcData, tChangeVolProc pChangeVolProc1) +{ +} + +void __stdcall SetProcessDataProc (HANDLE hArcData, tProcessDataProc pProcessDataProc) +{ + ProcessDataProc = pProcessDataProc; +}; + +int __stdcall GetPackerCaps() +{ + return PK_CAPS_MULTIPLE | /* Archive can contain multiple files */ +// PK_CAPS_SEARCHTEXT | /* Allow searching for text in archives */ + PK_CAPS_HIDE; /* open with Ctrl+PgDn, not Enter */ +}; \ No newline at end of file diff --git a/WincmdPacker/WincmdPacker.def b/WincmdPacker/WincmdPacker.def new file mode 100644 index 0000000..efa89fa --- /dev/null +++ b/WincmdPacker/WincmdPacker.def @@ -0,0 +1,9 @@ +EXPORTS + OpenArchive + ReadHeader + ProcessFile + CloseArchive + SetChangeVolProc + SetProcessDataProc + GetPackerCaps + \ No newline at end of file diff --git a/WincmdPacker/WincmdPacker.sln b/WincmdPacker/WincmdPacker.sln new file mode 100644 index 0000000..fc478a2 --- /dev/null +++ b/WincmdPacker/WincmdPacker.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WincmdPacker", "WincmdPacker.vcproj", "{2F492A95-A23D-45C9-BBD9-E5B9325B22C1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Debug|Win32.ActiveCfg = Debug|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Debug|Win32.Build.0 = Debug|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Release|Win32.ActiveCfg = Release|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/WincmdPacker/WincmdPacker.vcproj b/WincmdPacker/WincmdPacker.vcproj new file mode 100644 index 0000000..02b939a --- /dev/null +++ b/WincmdPacker/WincmdPacker.vcproj @@ -0,0 +1,305 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WincmdPacker/filesys.opt b/WincmdPacker/filesys.opt new file mode 100644 index 0000000..7148e50 Binary files /dev/null and b/WincmdPacker/filesys.opt differ diff --git a/WincmdPacker/filesys.plg b/WincmdPacker/filesys.plg new file mode 100644 index 0000000..97fb527 --- /dev/null +++ b/WincmdPacker/filesys.plg @@ -0,0 +1,25 @@ + + +

+

Build Log

+

+--------------------Configuration: filesys - Win32 Debug-------------------- +

+

Command Lines

+Creating temporary file "c:\temp\RSP10F9.tmp" with contents +[ +kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib version.lib /nologo /dll /incremental:yes /pdb:"Debug/filesys.pdb" /debug /machine:I386 /def:".\filesys.def" /out:"Debug/filesys.wdx" /implib:"Debug/filesys.lib" /pdbtype:sept +.\Debug\filesys.obj +.\Debug\StdAfx.obj +] +Creating command line "link.exe @c:\temp\RSP10F9.tmp" +

Output Window

+Linking... + + + +

Results

+filesys.wdx - 0 error(s), 0 warning(s) +
+ + diff --git a/WincmdPacker/filesys.sln b/WincmdPacker/filesys.sln new file mode 100644 index 0000000..b1b038e --- /dev/null +++ b/WincmdPacker/filesys.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "filesys", "filesys.vcproj", "{2F492A95-A23D-45C9-BBD9-E5B9325B22C1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Debug|Win32.ActiveCfg = Debug|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Debug|Win32.Build.0 = Debug|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Release|Win32.ActiveCfg = Release|Win32 + {2F492A95-A23D-45C9-BBD9-E5B9325B22C1}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/WincmdPacker/packerplug.h b/WincmdPacker/packerplug.h new file mode 100644 index 0000000..0e0f5a7 --- /dev/null +++ b/WincmdPacker/packerplug.h @@ -0,0 +1,117 @@ +/* Contents of file wcxhead.h */ +/* It contains definitions of error codes, flags and callbacks */ + +/* Error codes returned to calling application */ +#define E_END_ARCHIVE 10 /* No more files in archive */ +#define E_NO_MEMORY 11 /* Not enough memory */ +#define E_BAD_DATA 12 /* Data is bad */ +#define E_BAD_ARCHIVE 13 /* CRC error in archive data */ +#define E_UNKNOWN_FORMAT 14 /* Archive format unknown */ +#define E_EOPEN 15 /* Cannot open existing file */ +#define E_ECREATE 16 /* Cannot create file */ +#define E_ECLOSE 17 /* Error closing file */ +#define E_EREAD 18 /* Error reading from file */ +#define E_EWRITE 19 /* Error writing to file */ +#define E_SMALL_BUF 20 /* Buffer too small */ +#define E_EABORTED 21 /* Function aborted by user */ +#define E_NO_FILES 22 /* No files found */ +#define E_TOO_MANY_FILES 23 /* Too many files to pack */ +#define E_NOT_SUPPORTED 24 /* Function not supported */ + +/* flags for unpacking */ +#define PK_OM_LIST 0 +#define PK_OM_EXTRACT 1 + +/* flags for ProcessFile */ +#define PK_SKIP 0 /* Skip this file */ +#define PK_TEST 1 /* Test file integrity */ +#define PK_EXTRACT 2 /* Extract to disk */ + +/* Flags passed through ChangeVolProc */ +#define PK_VOL_ASK 0 /* Ask user for location of next volume */ +#define PK_VOL_NOTIFY 1 /* Notify app that next volume will be unpacked */ + +/* Flags for packing */ + +/* For PackFiles */ +#define PK_PACK_MOVE_FILES 1 /* Delete original after packing */ +#define PK_PACK_SAVE_PATHS 2 /* Save path names of files */ + +/* Returned by GetPackCaps */ +#define PK_CAPS_NEW 1 /* Can create new archives */ +#define PK_CAPS_MODIFY 2 /* Can modify exisiting archives */ +#define PK_CAPS_MULTIPLE 4 /* Archive can contain multiple files */ +#define PK_CAPS_DELETE 8 /* Can delete files */ +#define PK_CAPS_OPTIONS 16 /* Has options dialog */ +#define PK_CAPS_MEMPACK 32 /* Supports packing in memory */ +#define PK_CAPS_BY_CONTENT 64 /* Detect archive type by content */ +#define PK_CAPS_SEARCHTEXT 128 /* Allow searching for text in archives */ + /* created with this plugin} */ +#define PK_CAPS_HIDE 256 /* Show as normal files (hide packer */ + /* icon), open with Ctrl+PgDn, not Enter*/ + +/* Flags for packing in memory */ +#define MEM_OPTIONS_WANTHEADERS 1 /* Return archive headers with packed data */ + +/* Errors returned by PackToMem */ +#define MEMPACK_OK 0 /* Function call finished OK, but there is more data */ +#define MEMPACK_DONE 1 /* Function call finished OK, there is no more data */ + + +typedef struct { + char ArcName[260]; + char FileName[260]; + int Flags; + int PackSize; + int UnpSize; + int HostOS; + int FileCRC; + int FileTime; + int UnpVer; + int Method; + int FileAttr; + char* CmtBuf; + int CmtBufSize; + int CmtSize; + int CmtState; + } tHeaderData; + +typedef struct { + char* ArcName; + int OpenMode; + int OpenResult; + char* CmtBuf; + int CmtBufSize; + int CmtSize; + int CmtState; + } tOpenArchiveData; + +typedef struct { + int size; + DWORD PluginInterfaceVersionLow; + DWORD PluginInterfaceVersionHi; + char DefaultIniName[MAX_PATH]; +} PackDefaultParamStruct; + +/* Definition of callback functions called by the DLL +Ask to swap disk for multi-volume archive */ +typedef int (__stdcall *tChangeVolProc)(char *ArcName,int Mode); +/* Notify that data is processed - used for progress dialog */ +typedef int (__stdcall *tProcessDataProc)(char *FileName,int Size); + +HANDLE __stdcall OpenArchive (tOpenArchiveData *ArchiveData); +int __stdcall ReadHeader (HANDLE hArcData, tHeaderData *HeaderData); +int __stdcall ProcessFile (HANDLE hArcData, int Operation, char *DestPath, char *DestName); +int __stdcall CloseArchive (HANDLE hArcData); +void __stdcall SetChangeVolProc (HANDLE hArcData, tChangeVolProc pChangeVolProc1); +void __stdcall SetProcessDataProc (HANDLE hArcData, tProcessDataProc pProcessDataProc); +int __stdcall GetPackerCaps(); + +class COpenArchive +{ +public: + CDWFFileImpl m_iDWFFile; + int m_AtPage; + BOOL AtAscii; + CString m_FullName; +}; \ No newline at end of file diff --git a/WincmdPacker/wcxhead.pas b/WincmdPacker/wcxhead.pas new file mode 100644 index 0000000..6684ced --- /dev/null +++ b/WincmdPacker/wcxhead.pas @@ -0,0 +1,114 @@ +{ Contents of file wcxhead.pas } +{ It contains definitions of error codes, flags and callbacks } + +unit wcxhead; + +interface + +const {Error codes returned to calling application} + E_END_ARCHIVE= 10; {No more files in archive} + E_NO_MEMORY= 11; {Not enough memory} + E_BAD_DATA= 12; {Data is bad} + E_BAD_ARCHIVE= 13; {CRC error in archive data} + E_UNKNOWN_FORMAT= 14; {Archive format unknown} + E_EOPEN= 15; {Cannot open existing file} + E_ECREATE= 16; {Cannot create file} + E_ECLOSE= 17; {Error closing file} + E_EREAD= 18; {Error reading from file} + E_EWRITE= 19; {Error writing to file} + E_SMALL_BUF= 20; {Buffer too small} + E_EABORTED= 21; {Function aborted by user} + E_NO_FILES= 22; {No files found} + E_TOO_MANY_FILES= 23; {Too many files to pack} + E_NOT_SUPPORTED= 24; {Function not supported} + + {Unpacking flags} + PK_OM_LIST= 0; + PK_OM_EXTRACT= 1; + + {Flags for ProcessFile} + PK_SKIP= 0; {Skip file (no unpacking)} + PK_TEST= 1; {Test file integrity} + PK_EXTRACT= 2; {Extract file to disk} + + {Flags passed through ChangeVolProc} + PK_VOL_ASK= 0; {Ask user for location of next volume} + PK_VOL_NOTIFY= 1; {Notify app that next volume will be unpacked} + + {Packing flags} + + {For PackFiles} + PK_PACK_MOVE_FILES= 1; {Delete original after packing} + PK_PACK_SAVE_PATHS= 2; {Save path names of files} + + {Returned by GetPackCaps} + PK_CAPS_NEW= 1; {Can create new archives} + PK_CAPS_MODIFY= 2; {Can modify exisiting archives} + PK_CAPS_MULTIPLE= 4; {Archive can contain multiple files} + PK_CAPS_DELETE= 8; {Can delete files} + PK_CAPS_OPTIONS= 16; {Supports the options dialogbox} + PK_CAPS_MEMPACK= 32; {Supports packing in memory} + PK_CAPS_BY_CONTENT= 64; {Detect archive type by content} + PK_CAPS_SEARCHTEXT= 128; {Allow searching for text in archives + { created with this plugin} + PK_CAPS_HIDE= 256; { Show as normal files (hide packer icon) } + { open with Ctrl+PgDn, not Enter } + + {Flags for packing in memory} + MEM_OPTIONS_WANTHEADERS=1; {Return archive headers with packed data} + + {Errors returned by PackToMem} + MEMPACK_OK= 0; {Function call finished OK, but there is more data} + MEMPACK_DONE= 1; {Function call finished OK, there is no more data} + +type + {Definition of callback functions called by the DLL} + {Ask to swap disk for multi-volume archive} + PChangeVolProc=^TChangeVolProc; + TChangeVolProc=function(ArcName:pchar;Mode:longint):longint; stdcall; + {Notify that data is processed - used for progress dialog} + PProcessDataProc=^TProcessDataProc; + TProcessDataProc=function(FileName:pchar;Size:longint):longint; stdcall; + +type + THeaderData=packed record + ArcName:array [0..259] of char; + FileName:array [0..259] of char; + Flags, + PackSize, + UnpSize, + HostOS, + FileCRC, + FileTime, + UnpVer, + Method, + FileAttr:longint; + CmtBuf:pchar; + CmtBufSize, + CmtSize, + CmtState:longint; + end; + + tOpenArchiveData=packed record + ArcName:pchar; + OpenMode, + OpenResult:longint; + CmtBuf:pchar; + CmtBufSize, + CmtSize, + CmtState:longint; + end; + + tPackDefaultParamStruct=record + size, + PluginInterfaceVersionLow, + PluginInterfaceVersionHi:longint; + DefaultIniName:array[0..MAX_PATH-1] of char; + end; + pPackDefaultParamStruct=^tPackDefaultParamStruct; + +implementation + +end. + + diff --git a/WincmdViewer/ListDWF.h b/WincmdViewer/ListDWF.h new file mode 100644 index 0000000..007417c --- /dev/null +++ b/WincmdViewer/ListDWF.h @@ -0,0 +1,9 @@ +#pragma once + +class CListDWF +{ +public: + CListDWF(void); +public: + ~CListDWF(void); +}; diff --git a/WincmdViewer/SLNKDWFViewer.rc b/WincmdViewer/SLNKDWFViewer.rc new file mode 100644 index 0000000..7cc1235 --- /dev/null +++ b/WincmdViewer/SLNKDWFViewer.rc @@ -0,0 +1,390 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "atlres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""atlres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Toolbar +// + +IDR_MAINFRAME TOOLBAR 16, 15 +BEGIN + BUTTON ID_ZOOM_IN + BUTTON ID_ZOOM_OUT + SEPARATOR + BUTTON ID_ZOOM_EXTENTS + BUTTON ID_FILE_PRINT + SEPARATOR + BUTTON ID_APP_ABOUT +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDR_MAINFRAME BITMAP "res\\Toolbar.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDR_MAINFRAME MENU +BEGIN + POPUP "&File" + BEGIN + MENUITEM "&New\tCtrl+N", ID_FILE_NEW + MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN + MENUITEM "&Save\tCtrl+S", ID_FILE_SAVE + MENUITEM "Save &As...", ID_FILE_SAVE_AS + MENUITEM SEPARATOR + MENUITEM "&Print...\tCtrl+P", ID_FILE_PRINT + MENUITEM "Print Pre&view", ID_FILE_PRINT_PREVIEW + MENUITEM "P&rint Setup...", ID_FILE_PRINT_SETUP + MENUITEM SEPARATOR + MENUITEM "E&xit", ID_APP_EXIT + END + POPUP "&Edit" + BEGIN + MENUITEM "&Undo\tCtrl+Z", ID_EDIT_UNDO + MENUITEM SEPARATOR + MENUITEM "Cu&t\tCtrl+X", ID_EDIT_CUT + MENUITEM "&Copy\tCtrl+C", ID_EDIT_COPY + MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE + END + POPUP "&View" + BEGIN + MENUITEM "&Toolbar", ID_VIEW_TOOLBAR + MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR + MENUITEM "Layers", ID_VIEW_LAYERS + END + POPUP "&Help" + BEGIN + MENUITEM "&About SLNKDWFViewer...", ID_APP_ABOUT + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON "res\\SLNKDWFViewer.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOGEX 0, 0, 247, 161 +STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "About" +FONT 8, "MS Sans Serif", 0, 0, 0x0 +BEGIN + DEFPUSHBUTTON "OK",IDOK,190,140,50,14 + CTEXT "SLNKDWFViewer Application v1.0\n\n(c) Copyright 2006",IDC_STATIC,7,55,136,27 + ICON IDR_MAINFRAME,IDC_STATIC,55,26,20,20 + LTEXT "Static",IDC_DLLPATH,55,84,185,8 + LTEXT "Dll",IDC_STATIC,8,98,9,8 + LTEXT "Static",IDC_DLLVERSION,56,98,119,8 + LTEXT "Version",IDC_STATIC,23,97,24,8 + LTEXT "Built",IDC_STATIC,23,111,20,8 + LTEXT "Static",IDC_DLLBUILDTIME,56,112,131,8 + LTEXT "Path",IDC_STATIC,23,84,16,8 + LTEXT "Static",IDC_WHIPVERSION,56,139,131,8 + LTEXT "Static",IDC_DWFVERSION,55,126,131,8 + LTEXT "DWF",IDC_STATIC,24,126,20,8 + LTEXT "Whip",IDC_STATIC,24,139,20,8 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 240 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Accelerator +// + +IDR_MAINFRAME ACCELERATORS +BEGIN + "N", ID_FILE_NEW, VIRTKEY, CONTROL + "O", ID_FILE_OPEN, VIRTKEY, CONTROL + "S", ID_FILE_SAVE, VIRTKEY, CONTROL + "P", ID_FILE_PRINT, VIRTKEY, CONTROL + "Z", ID_EDIT_UNDO, VIRTKEY, CONTROL + "X", ID_EDIT_CUT, VIRTKEY, CONTROL + "C", ID_EDIT_COPY, VIRTKEY, CONTROL + "V", ID_EDIT_PASTE, VIRTKEY, CONTROL + VK_BACK, ID_EDIT_UNDO, VIRTKEY, ALT + VK_DELETE, ID_EDIT_CUT, VIRTKEY, SHIFT + VK_INSERT, ID_EDIT_COPY, VIRTKEY, CONTROL + VK_INSERT, ID_EDIT_PASTE, VIRTKEY, SHIFT + VK_F6, ID_NEXT_PANE, VIRTKEY + VK_F6, ID_PREV_PANE, VIRTKEY, SHIFT +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "FileDescription", "SLNKDWFViewer Module" + VALUE "FileVersion", "1, 0, 0, 1" + VALUE "InternalName", "SLNKDWFViewer" + VALUE "LegalCopyright", "Copyright 2006" + VALUE "OriginalFilename", "SLNKDWFViewer.exe" + VALUE "ProductName", "SLNKDWFViewer Module" + VALUE "ProductVersion", "1, 0, 0, 1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDR_MAINFRAME "SLNKDWFViewer" +END + +STRINGTABLE +BEGIN + ID_FILE_NEW "Create a new document\nNew" + ID_FILE_OPEN "Open an existing document\nOpen" + ID_FILE_CLOSE "Close the active document\nClose" + ID_FILE_SAVE "Save the active document\nSave" + ID_FILE_SAVE_AS "Save the active document with a new name\nSave As" + ID_FILE_PAGE_SETUP "Change the printing options\nPage Setup" + ID_FILE_PRINT_SETUP "Change the printer and printing options\nPrint Setup" + ID_FILE_PRINT "Print the active document\nPrint" + ID_FILE_PRINT_PREVIEW "Display full pages\nPrint Preview" +END + +STRINGTABLE +BEGIN + ID_APP_ABOUT "Display program information, version number and copyright\nAbout" + ID_APP_EXIT "Quit the application; prompts to save documents\nExit" +END + +STRINGTABLE +BEGIN + ID_NEXT_PANE "Switch to the next window pane\nNext Pane" + ID_PREV_PANE "Switch back to the previous window pane\nPrevious Pane" +END + +STRINGTABLE +BEGIN + ID_WINDOW_NEW "Open another window for the active document\nNew Window" + ID_WINDOW_ARRANGE "Arrange icons at the bottom of the window\nArrange Icons" + ID_WINDOW_CASCADE "Arrange windows so they overlap\nCascade Windows" + ID_WINDOW_TILE_HORZ "Arrange windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_TILE_VERT "Arrange windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_SPLIT "Split the active window into panes\nSplit" +END + +STRINGTABLE +BEGIN + ID_EDIT_CLEAR "Erase the selection\nErase" + ID_EDIT_CLEAR_ALL "Erase everything\nErase All" + ID_EDIT_COPY "Copy the selection and put it on the Clipboard\nCopy" + ID_EDIT_CUT "Cut the selection and put it on the Clipboard\nCut" + ID_EDIT_FIND "Find the specified text\nFind" + ID_EDIT_PASTE "Insert Clipboard contents\nPaste" + ID_EDIT_REPEAT "Repeat the last action\nRepeat" + ID_EDIT_REPLACE "Replace specific text with different text\nReplace" + ID_EDIT_SELECT_ALL "Select the entire document\nSelect All" + ID_EDIT_UNDO "Undo the last action\nUndo" + ID_EDIT_REDO "Redo the previously undone action\nRedo" +END + +STRINGTABLE +BEGIN + ID_VIEW_TOOLBAR "Show or hide the toolbar\nToggle ToolBar" + ID_VIEW_STATUS_BAR "Show or hide the status bar\nToggle StatusBar" +END + +STRINGTABLE +BEGIN + ATL_IDS_SCSIZE "Change the window size" + ATL_IDS_SCMOVE "Change the window position" + ATL_IDS_SCMINIMIZE "Reduce the window to an icon" + ATL_IDS_SCMAXIMIZE "Enlarge the window to full size" + ATL_IDS_SCNEXTWINDOW "Switch to the next document window" + ATL_IDS_SCPREVWINDOW "Switch to the previous document window" + ATL_IDS_SCCLOSE "Close the active window and prompts to save the documents" +END + +STRINGTABLE +BEGIN + ATL_IDS_SCRESTORE "Restore the window to normal size" + ATL_IDS_SCTASKLIST "Activate Task List" + ATL_IDS_MDICHILD "Activate this window" +END + +STRINGTABLE +BEGIN + ATL_IDS_IDLEMESSAGE "Ready" +END + +STRINGTABLE +BEGIN + ATL_IDS_MRU_FILE "Open this document" +END + +STRINGTABLE +BEGIN + ID_ZOOM_EXTENTS "Zoom Extents\nZoom Extents" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Neutral (Sys. Default) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEUSD) +#ifdef _WIN32 +LANGUAGE LANG_NEUTRAL, SUBLANG_SYS_DEFAULT +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_LAYERS DIALOGEX 0, 0, 230, 302 +STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME +CAPTION "Layers" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,173,7,50,14 + PUSHBUTTON "Cancel",IDCANCEL,173,24,50,14 + LISTBOX IDC_LAYERLIST,7,7,161,288,LBS_SORT | LBS_NOINTEGRALHEIGHT | LBS_EXTENDEDSEL | WS_VSCROLL | WS_TABSTOP +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_LAYERS, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 223 + TOPMARGIN, 7 + BOTTOMMARGIN, 295 + END +END +#endif // APSTUDIO_INVOKED + +#endif // Neutral (Sys. Default) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/WincmdViewer/WINCDMDWF.vcproj b/WincmdViewer/WINCDMDWF.vcproj new file mode 100644 index 0000000..194ac47 --- /dev/null +++ b/WincmdViewer/WINCDMDWF.vcproj @@ -0,0 +1,249 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WincmdViewer/WincmdViewer.cpp b/WincmdViewer/WincmdViewer.cpp new file mode 100644 index 0000000..55c5152 --- /dev/null +++ b/WincmdViewer/WincmdViewer.cpp @@ -0,0 +1,114 @@ +#include "stdafx.h" + +#include "ListPlug.h" + +HINSTANCE g_hInstance; +CAtlWinModule _Module; + +CAtlMap myList; // Onthouden om te kunnen terugvinden bij meerdere listers open + +int __stdcall ListNotificationReceived(HWND ListWin,int Message,WPARAM wParam,LPARAM lParam) +{ + return 0; +} + +int __stdcall ListSendCommand(HWND ListWin,int Command,int Parameter) +{ + ATLTRACE("ListSendCommand"); + CMainFrame *m_Frame; + switch (Command) + { + case lc_newparams: + { + if ((Parameter & lcp_fittowindow) == lcp_fittowindow) + { +// if (myList.Lookup(ListWin, m_Frame)) +// m_Frame->Zoom(1.0); + } + } + } + return LISTPLUGIN_OK; +} + +void __stdcall ListCloseWindow(HWND ListWin) +{ + CMainFrame *m_Frame; + if (myList.Lookup(ListWin, m_Frame)) + { + m_Frame->DestroyWindow(); + delete m_Frame; + } +} + +HWND __stdcall ListLoad(HWND ParentWin, char* FileToLoad, int ShowFlags) +{ + CMainFrame *m_Frame = new CMainFrame; // Wordt in ListCloseWindow vrijgegeven + + CRect rc; + GetClientRect(ParentWin, &rc); + + HWND m_hWndClient = m_Frame->Create(ParentWin, rc, NULL, WS_CHILD | WS_VISIBLE + | WS_CLIPSIBLINGS | WS_CLIPCHILDREN ); + + m_Frame->SetDWF(CString(FileToLoad)); + + // Onthouden om mettertijd weer te kunnen vrijgeven + myList[m_hWndClient] = m_Frame; + + return m_hWndClient; +} + +void __stdcall ListGetDetectString(char* DetectString,int maxlen) +{ + strncpy(DetectString, "EXT=\"DWF\"|EXT=\"W2D\"", maxlen); +} + +// Note: op termijn moeten we hier natuurlijk bij voorkeur de ingebakken bitmap gebruiken +// Verder moeten nog we de bitmap zo veel mogelijk 'croppen' +HBITMAP __stdcall ListGetPreviewBitmap(char* FileToLoad,int width,int height, + char* contentbuf,int contentbuflen) +{ + CWhip2DCImpl iWhip2DC; + + HDC pDC = ::GetDC(0); + HDC myDC = CreateCompatibleDC(pDC); + HBITMAP TmpBmp = CreateCompatibleBitmap ( pDC, width, height ); + HGDIOBJ TmpObj=SelectObject(myDC,TmpBmp); + CRect rc(0,0,width,height); + PaintToDC(myDC, CString (FileToLoad), 0, iWhip2DC, rc.Size()); // Altijd pagina 0 + +// Deze moet blijven DeleteObject(TmpBmp); + DeleteDC(myDC); + ReleaseDC( NULL, pDC ); //Do not forget! + + return TmpBmp; +} + +// Detect Memory Leaks +#ifdef _DEBUG +#include "memleakdetect.h" +//CMemLeakDetect memLeakDetect; +#endif + +BOOL APIENTRY DllMain( HINSTANCE hinst, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch ( ul_reason_for_call ) + { + case DLL_PROCESS_ATTACH: + { + g_hInstance = hinst; + char ModuleName[_MAX_PATH]; + GetModuleFileName(hinst, ModuleName, sizeof(ModuleName)); + + DisableThreadLibraryCalls(hinst); + + break; + } + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} diff --git a/WincmdViewer/WincmdViewer.def b/WincmdViewer/WincmdViewer.def new file mode 100644 index 0000000..ff5aede --- /dev/null +++ b/WincmdViewer/WincmdViewer.def @@ -0,0 +1,7 @@ +EXPORTS + ListLoad + ListGetDetectString + ListGetPreviewBitmap + ListCloseWindow + ListSendCommand + ListNotificationReceived \ No newline at end of file diff --git a/WincmdViewer/dbgint.h b/WincmdViewer/dbgint.h new file mode 100644 index 0000000..10fbde3 --- /dev/null +++ b/WincmdViewer/dbgint.h @@ -0,0 +1,308 @@ +/*** +*dbgint.h - Supports debugging features of the C runtime library. +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Support CRT debugging features. +* +* [Internal] +* +****/ + +#if _MSC_VER > 1000 +#pragma once +#endif /* _MSC_VER > 1000 */ + +#ifndef _INC_DBGINT +#define _INC_DBGINT + +#ifndef _CRTBLD +/* + * This is an internal C runtime header file. It is used when building + * the C runtimes only. It is not to be used as a public header file. + */ +#error ERROR: Use of C runtime library internal header file. +#endif /* _CRTBLD */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef _DEBUG + + /**************************************************************************** + * + * Debug OFF + * Debug OFF + * Debug OFF + * + ***************************************************************************/ + +#ifdef __cplusplus + +#define _new_crt new + +#endif /* __cplusplus */ + +#define _malloc_crt malloc +#define _calloc_crt calloc +#define _realloc_crt realloc +#define _expand_crt _expand +#define _free_crt free +#define _msize_crt _msize + + +#define _malloc_base malloc +#define _nh_malloc_base _nh_malloc +#define _nh_malloc_dbg(s, n, t, f, l) _nh_malloc(s, n) +#define _heap_alloc_base _heap_alloc +#define _heap_alloc_dbg(s, t, f, l) _heap_alloc(s) +#define _calloc_base calloc +#define _realloc_base realloc +#define _expand_base _expand +#define _free_base free +#define _msize_base _msize +#define _aligned_malloc_base _aligned_malloc +#define _aligned_realloc_base _aligned_realloc +#define _aligned_offset_malloc_base _aligned_offset_malloc +#define _aligned_offset_realloc_base _aligned_offset_realloc +#define _aligned_free_base _aligned_free + +#ifdef _MT + +#define _calloc_dbg_lk(c, s, t, f, l) _calloc_lk(c, s) +#define _realloc_dbg_lk(p, s, t, f, l) _realloc_lk(p, s) +#define _free_base_lk _free_lk +#define _free_dbg_lk(p, t) _free_lk(p) + +#else /* _MT */ + +#define _calloc_dbg_lk(c, s, t, f, l) calloc(c, s) +#define _realloc_dbg_lk(p, s, t, f, l) realloc(p, s) +#define _free_base_lk free +#define _free_dbg_lk(p, t) free(p) + +#endif /* _MT */ + + +#else /* _DEBUG */ + + + /**************************************************************************** + * + * Debug ON + * Debug ON + * Debug ON + * + ***************************************************************************/ + +#define _THISFILE __FILE__ + +#ifdef __cplusplus + +#define _new_crt new(_CRT_BLOCK, _THISFILE, __LINE__) + +#endif /* __cplusplus */ + +#define _malloc_crt(s) _malloc_dbg(s, _CRT_BLOCK, _THISFILE, __LINE__) +#define _calloc_crt(c, s) _calloc_dbg(c, s, _CRT_BLOCK, _THISFILE, __LINE__) +#define _realloc_crt(p, s) _realloc_dbg(p, s, _CRT_BLOCK, _THISFILE, __LINE__) +#define _expand_crt(p, s) _expand_dbg(p, s, _CRT_BLOCK) +#define _free_crt(p) _free_dbg(p, _CRT_BLOCK) +#define _msize_crt(p) _msize_dbg(p, _CRT_BLOCK) + +/* + * Prototypes for malloc, free, realloc, etc are in malloc.h + */ + +void * __cdecl _malloc_base( + size_t + ); + +void * __cdecl _nh_malloc_base ( + size_t, + int + ); + +void * __cdecl _nh_malloc_dbg ( + size_t, + int, + int, + const char *, + int + ); + +void * __cdecl _heap_alloc_base( + size_t + ); + +void * __cdecl _heap_alloc_dbg( + size_t, + int, + const char *, + int + ); + +void * __cdecl _calloc_base( + size_t, + size_t + ); + +void * __cdecl _realloc_base( + void *, + size_t + ); + +void * __cdecl _expand_base( + void *, + size_t + ); + +void __cdecl _free_base( + void * + ); + +size_t __cdecl _msize_base ( + void * + ); + +void __cdecl _aligned_free_base( + void * + ); + +void * __cdecl _aligned_malloc_base( + size_t, + size_t + ); + +void * __cdecl _aligned_offset_malloc_base( + size_t, + size_t, + size_t + ); + +void * __cdecl _aligned_realloc_base( + void *, + size_t, + size_t + ); + +void * __cdecl _aligned_offset_realloc_base( + void *, + size_t, + size_t, + size_t + ); + +#ifdef _MT + +/* + * Prototypes and macros for multi-thread support + */ + + +void * __cdecl _calloc_dbg_lk( + size_t, + size_t, + int, + char *, + int + ); + + +void * __cdecl _realloc_dbg_lk( + void *, + size_t, + int, + const char *, + int + ); + + +void __cdecl _free_base_lk( + void * + ); + +void __cdecl _free_dbg_lk( + void *, + int + ); + +#else /* _MT */ + +#define _calloc_dbg_lk _calloc_dbg +#define _realloc_dbg_lk _realloc_dbg +#define _free_base_lk _free_base +#define _free_dbg_lk _free_dbg + +#endif /* _MT */ + +/* + * For diagnostic purpose, blocks are allocated with extra information and + * stored in a doubly-linked list. This makes all blocks registered with + * how big they are, when they were allocated, and what they are used for. + */ + +#define nNoMansLandSize 4 + +typedef struct _CrtMemBlockHeader +{ + struct _CrtMemBlockHeader * pBlockHeaderNext; + struct _CrtMemBlockHeader * pBlockHeaderPrev; + char * szFileName; + int nLine; +#ifdef _WIN64 + /* These items are reversed on Win64 to eliminate gaps in the struct + * and ensure that sizeof(struct)%16 == 0, so 16-byte alignment is + * maintained in the debug heap. + */ + int nBlockUse; + size_t nDataSize; +#else /* _WIN64 */ + size_t nDataSize; + int nBlockUse; +#endif /* _WIN64 */ + long lRequest; + unsigned char gap[nNoMansLandSize]; + /* followed by: + * unsigned char data[nDataSize]; + * unsigned char anotherGap[nNoMansLandSize]; + */ +} _CrtMemBlockHeader; + +#define pbData(pblock) ((unsigned char *)((_CrtMemBlockHeader *)pblock + 1)) +#define pHdr(pbData) (((_CrtMemBlockHeader *)pbData)-1) + + +_CRTIMP void __cdecl _CrtSetDbgBlockType( + void *, + int + ); + +#define _BLOCK_TYPE_IS_VALID(use) (_BLOCK_TYPE(use) == _CLIENT_BLOCK || \ + (use) == _NORMAL_BLOCK || \ + _BLOCK_TYPE(use) == _CRT_BLOCK || \ + (use) == _IGNORE_BLOCK) + +extern _CRT_ALLOC_HOOK _pfnAllocHook; /* defined in dbghook.c */ + +int __cdecl _CrtDefaultAllocHook( + int, + void *, + size_t, + int, + long, + const unsigned char *, + int + ); + +#endif /* _DEBUG */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* _INC_DBGINT */ diff --git a/WincmdViewer/listplug.h b/WincmdViewer/listplug.h new file mode 100644 index 0000000..ea5386f --- /dev/null +++ b/WincmdViewer/listplug.h @@ -0,0 +1,47 @@ +/* Contents of file listplug.h */ + +#define lc_copy 1 +#define lc_newparams 2 +#define lc_selectall 3 +#define lc_setpercent 4 + +#define lcp_wraptext 1 +#define lcp_fittowindow 2 +#define lcp_ansi 4 +#define lcp_ascii 8 +#define lcp_variable 12 +#define lcp_forceshow 16 + +#define lcs_findfirst 1 +#define lcs_matchcase 2 +#define lcs_wholewords 4 +#define lcs_backwards 8 + +#define itm_percent 0xFFFE +#define itm_fontstyle 0xFFFD +#define itm_wrap 0xFFFC +#define itm_fit 0xFFFB +#define itm_next 0xFFFA + +#define LISTPLUGIN_OK 0 +#define LISTPLUGIN_ERROR 1 + +typedef struct { + int size; + DWORD PluginInterfaceVersionLow; + DWORD PluginInterfaceVersionHi; + char DefaultIniName[MAX_PATH]; +} ListDefaultParamStruct; + +HWND __stdcall ListLoad(HWND ParentWin,char* FileToLoad,int ShowFlags); +void __stdcall ListCloseWindow(HWND ListWin); +void __stdcall ListGetDetectString(char* DetectString,int maxlen); +int __stdcall ListSearchText(HWND ListWin,char* SearchString,int SearchParameter); +int __stdcall ListSendCommand(HWND ListWin,int Command,int Parameter); +int __stdcall ListPrint(HWND ListWin,char* FileToPrint,char* DefPrinter, + int PrintFlags,RECT* Margins); +int __stdcall ListNotificationReceived(HWND ListWin,int Message,WPARAM wParam,LPARAM lParam); +void __stdcall ListSetDefaultParams(ListDefaultParamStruct* dps); +HBITMAP __stdcall ListGetPreviewBitmap(char* FileToLoad,int width,int height, + char* contentbuf,int contentbuflen); + diff --git a/WincmdViewer/listplugin.hlp b/WincmdViewer/listplugin.hlp new file mode 100644 index 0000000..3aa6fbc Binary files /dev/null and b/WincmdViewer/listplugin.hlp differ diff --git a/WincmdViewer/res/.gitignore b/WincmdViewer/res/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/WincmdViewer/res/SLNKDWFViewer.ico b/WincmdViewer/res/SLNKDWFViewer.ico new file mode 100644 index 0000000..3b11c7a Binary files /dev/null and b/WincmdViewer/res/SLNKDWFViewer.ico differ diff --git a/WincmdViewer/res/Toolbar.bmp b/WincmdViewer/res/Toolbar.bmp new file mode 100644 index 0000000..a5cb458 Binary files /dev/null and b/WincmdViewer/res/Toolbar.bmp differ diff --git a/WincmdViewer/resource.h b/WincmdViewer/resource.h new file mode 100644 index 0000000..dd3e6e4 --- /dev/null +++ b/WincmdViewer/resource.h @@ -0,0 +1,32 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by SLNKDWFViewer.rc +// +#define IDD_ABOUTBOX 100 +#define IDR_MAINFRAME 128 +#define IDD_LAYERS 201 +#define IDC_LAYERLIST 1000 +#define IDC_DLLVERSION 1001 +#define IDC_DLLPATH 1002 +#define IDC_DLLBUILD 1003 +#define IDC_DLLBUILDTIME 1003 +#define IDC_WHIPVERSION 1004 +#define IDC_DWFVERSION 1005 +#define IDC_DWF2VERSION 1005 +#define ID_VIEW_LAYERS 32772 +#define ID_ZOOM_IN 32774 +#define ID_ZOOM_EXTENTS 32777 +#define ID_ZOOM_OUT 32782 +#define IDP_PLACEHOLDER 32783 +#define IDC_COMBO 32784 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 202 +#define _APS_NEXT_COMMAND_VALUE 32785 +#define _APS_NEXT_CONTROL_VALUE 1004 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/WincmdViewer/stdafx.cpp b/WincmdViewer/stdafx.cpp new file mode 100644 index 0000000..9888bd2 --- /dev/null +++ b/WincmdViewer/stdafx.cpp @@ -0,0 +1,9 @@ +// stdafx.cpp : source file that includes just the standard includes +// SLNKDWFViewer.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +#if (_ATL_VER < 0x0700) +#include +#endif //(_ATL_VER < 0x0700) diff --git a/WincmdViewer/stdafx.h b/WincmdViewer/stdafx.h new file mode 100644 index 0000000..c2ee6d5 --- /dev/null +++ b/WincmdViewer/stdafx.h @@ -0,0 +1,19 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +// Change these values to use different versions +//#define _WIN32_WINNT 0x0400 +#define _WIN32_IE 0x0400 +#define _RICHEDIT_VER 0x0100 + +#define _ATL_DEBUG_INTERFACES + +#include +#include + +//extern CAppModule _Module; gaf vage instabiliteit +#include "../Viewer/ViewerLib.h"